{ "def writeBoolean(self, n):\n \"\"\"\n Writes a Boolean to the stream.\n \"\"\"\n t = TYPE_BOOL_TRUE\n\n if n is False:\n t = TYPE_BOOL_FALSE\n\n self.stream.write(t)": 0, "def paste(xsel=False):\n \"\"\"Returns system clipboard contents.\"\"\"\n selection = \"primary\" if xsel else \"clipboard\"\n try:\n return subprocess.Popen([\"xclip\", \"-selection\", selection, \"-o\"], stdout=subprocess.PIPE).communicate()[0].decode(\"utf-8\")\n except OSError as why:\n raise XclipNotFound": 1, "def _format_json(data, theme):\n \"\"\"Pretty print a dict as a JSON, with colors if pygments is present.\"\"\"\n output = json.dumps(data, indent=2, sort_keys=True)\n\n if pygments and sys.stdout.isatty():\n style = get_style_by_name(theme)\n formatter = Terminal256Formatter(style=style)\n return pygments.highlight(output, JsonLexer(), formatter)\n\n return output": 2, "def create_path(path):\n \"\"\"Creates a absolute path in the file system.\n\n :param path: The path to be created\n \"\"\"\n import os\n if not os.path.exists(path):\n os.makedirs(path)": 3, "def _vector_or_scalar(x, type='row'):\n \"\"\"Convert an object to either a scalar or a row or column vector.\"\"\"\n if isinstance(x, (list, tuple)):\n x = np.array(x)\n if isinstance(x, np.ndarray):\n assert x.ndim == 1\n if type == 'column':\n x = x[:, None]\n return x": 4, "def experiment_property(prop):\n \"\"\"Get a property of the experiment by name.\"\"\"\n exp = experiment(session)\n p = getattr(exp, prop)\n return success_response(field=prop, data=p, request_type=prop)": 5, "def data_from_file(file):\n \"\"\"Return (first channel data, sample frequency, sample width) from a .wav\n file.\"\"\"\n fp = wave.open(file, 'r')\n data = fp.readframes(fp.getnframes())\n channels = fp.getnchannels()\n freq = fp.getframerate()\n bits = fp.getsampwidth()\n\n # Unpack bytes -- warning currently only tested with 16 bit wavefiles. 32\n # bit not supported.\n data = struct.unpack(('%sh' % fp.getnframes()) * channels, data)\n\n # Only use first channel\n channel1 = []\n n = 0\n for d in data:\n if n % channels == 0:\n channel1.append(d)\n n += 1\n fp.close()\n return (channel1, freq, bits)": 6, "def source_range(start, end, nr_var_dict):\n \"\"\"\n Given a range of source numbers, as well as a dictionary\n containing the numbers of each source, returns a dictionary\n containing tuples of the start and end index\n for each source variable type.\n \"\"\"\n\n return OrderedDict((k, e-s)\n for k, (s, e)\n in source_range_tuple(start, end, nr_var_dict).iteritems())": 7, "def timespan(start_time):\n \"\"\"Return time in milliseconds from start_time\"\"\"\n\n timespan = datetime.datetime.now() - start_time\n timespan_ms = timespan.total_seconds() * 1000\n return timespan_ms": 8, "def _convert_to_array(array_like, dtype):\n \"\"\"\n Convert Matrix attributes which are array-like or buffer to array.\n \"\"\"\n if isinstance(array_like, bytes):\n return np.frombuffer(array_like, dtype=dtype)\n return np.asarray(array_like, dtype=dtype)": 9, "def get_uniques(l):\n \"\"\" Returns a list with no repeated elements.\n \"\"\"\n result = []\n\n for i in l:\n if i not in result:\n result.append(i)\n\n return result": 10, "def interp(x, xp, *args, **kwargs):\n \"\"\"Wrap interpolate_1d for deprecated interp.\"\"\"\n return interpolate_1d(x, xp, *args, **kwargs)": 11, "def _array2cstr(arr):\n \"\"\" Serializes a numpy array to a compressed base64 string \"\"\"\n out = StringIO()\n np.save(out, arr)\n return b64encode(out.getvalue())": 12, "def percentile(values, k):\n \"\"\"Find the percentile of a list of values.\n\n :param list values: The list of values to find the percentile of\n :param int k: The percentile to find\n :rtype: float or int\n\n \"\"\"\n if not values:\n return None\n values.sort()\n index = (len(values) * (float(k) / 100)) - 1\n return values[int(math.ceil(index))]": 13, "def _string_hash(s):\n \"\"\"String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`).\"\"\"\n h = 5381\n for c in s:\n h = h * 33 + ord(c)\n return h": 14, "def transform_from_rot_trans(R, t):\n \"\"\"Transforation matrix from rotation matrix and translation vector.\"\"\"\n R = R.reshape(3, 3)\n t = t.reshape(3, 1)\n return np.vstack((np.hstack([R, t]), [0, 0, 0, 1]))": 15, "def _encode_bool(name, value, dummy0, dummy1):\n \"\"\"Encode a python boolean (True/False).\"\"\"\n return b\"\\x08\" + name + (value and b\"\\x01\" or b\"\\x00\")": 16, "def transform_to_3d(points,normal,z=0):\n \"\"\"Project points into 3d from 2d points.\"\"\"\n d = np.cross(normal, (0, 0, 1))\n M = rotation_matrix(d)\n transformed_points = M.dot(points.T).T + z\n return transformed_points": 17, "def _not(condition=None, **kwargs):\n \"\"\"\n Return the opposite of input condition.\n\n :param condition: condition to process.\n\n :result: not condition.\n :rtype: bool\n \"\"\"\n\n result = True\n\n if condition is not None:\n result = not run(condition, **kwargs)\n\n return result": 18, "def HttpResponse403(request, template=KEY_AUTH_403_TEMPLATE,\ncontent=KEY_AUTH_403_CONTENT, content_type=KEY_AUTH_403_CONTENT_TYPE):\n \"\"\"\n HTTP response for forbidden access (status code 403)\n \"\"\"\n return AccessFailedResponse(request, template, content, content_type, status=403)": 19, "def items(self, section_name):\n \"\"\":return: list((option, value), ...) pairs of all items in the given section\"\"\"\n return [(k, v) for k, v in super(GitConfigParser, self).items(section_name) if k != '__name__']": 20, "def mag(z):\n \"\"\"Get the magnitude of a vector.\"\"\"\n if isinstance(z[0], np.ndarray):\n return np.array(list(map(np.linalg.norm, z)))\n else:\n return np.linalg.norm(z)": 21, "def config_parser_to_dict(config_parser):\n \"\"\"\n Convert a ConfigParser to a dictionary.\n \"\"\"\n response = {}\n\n for section in config_parser.sections():\n for option in config_parser.options(section):\n response.setdefault(section, {})[option] = config_parser.get(section, option)\n\n return response": 22, "def __add__(self, other):\n \"\"\"Handle the `+` operator.\"\"\"\n return self._handle_type(other)(self.value + other.value)": 23, "def connect_mysql(host, port, user, password, database):\n \"\"\"Connect to MySQL with retries.\"\"\"\n return pymysql.connect(\n host=host, port=port,\n user=user, passwd=password,\n db=database\n )": 24, "def get_column(self, X, column):\n \"\"\"Return a column of the given matrix.\n\n Args:\n X: `numpy.ndarray` or `pandas.DataFrame`.\n column: `int` or `str`.\n\n Returns:\n np.ndarray: Selected column.\n \"\"\"\n if isinstance(X, pd.DataFrame):\n return X[column].values\n\n return X[:, column]": 25, "def connect(url, username, password):\n \"\"\"\n Return a connected Bitbucket session\n \"\"\"\n\n bb_session = stashy.connect(url, username, password)\n\n logger.info('Connected to: %s as %s', url, username)\n\n return bb_session": 26, "def add_blank_row(self, label):\n \"\"\"\n Add a blank row with only an index value to self.df.\n This is done inplace.\n \"\"\"\n col_labels = self.df.columns\n blank_item = pd.Series({}, index=col_labels, name=label)\n # use .loc to add in place (append won't do that)\n self.df.loc[blank_item.name] = blank_item\n return self.df": 27, "def teardown(self):\n \"\"\"\n Stop and remove the container if it exists.\n \"\"\"\n while self._http_clients:\n self._http_clients.pop().close()\n if self.created:\n self.halt()": 28, "def dumped(text, level, indent=2):\n \"\"\"Put curly brackets round an indented text\"\"\"\n return indented(\"{\\n%s\\n}\" % indented(text, level + 1, indent) or \"None\", level, indent) + \"\\n\"": 29, "def context(self):\n \"\"\"\n Create a context manager that ensures code runs within action's context.\n\n The action does NOT finish when the context is exited.\n \"\"\"\n parent = _ACTION_CONTEXT.set(self)\n try:\n yield self\n finally:\n _ACTION_CONTEXT.reset(parent)": 30, "def pformat(object, indent=1, width=80, depth=None):\n \"\"\"Format a Python object into a pretty-printed representation.\"\"\"\n return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object)": 31, "def replace_sys_args(new_args):\n \"\"\"Temporarily replace sys.argv with current arguments\n\n Restores sys.argv upon exit of the context manager.\n \"\"\"\n # Replace sys.argv arguments\n # for module import\n old_args = sys.argv\n sys.argv = new_args\n try:\n yield\n finally:\n sys.argv = old_args": 32, "def serialize(obj):\n \"\"\"Takes a object and produces a dict-like representation\n\n :param obj: the object to serialize\n \"\"\"\n if isinstance(obj, list):\n return [serialize(o) for o in obj]\n return GenericSerializer(ModelProviderImpl()).serialize(obj)": 33, "def advance_one_line(self):\n \"\"\"Advances to next line.\"\"\"\n\n current_line = self._current_token.line_number\n while current_line == self._current_token.line_number:\n self._current_token = ConfigParser.Token(*next(self._token_generator))": 34, "def generate_swagger_html(swagger_static_root, swagger_json_url):\n \"\"\"\n given a root directory for the swagger statics, and\n a swagger json path, return back a swagger html designed\n to use those values.\n \"\"\"\n tmpl = _get_template(\"swagger.html\")\n return tmpl.render(\n swagger_root=swagger_static_root, swagger_json_url=swagger_json_url\n )": 35, "def do_next(self, args):\n \"\"\"Step over the next statement\n \"\"\"\n self._do_print_from_last_cmd = True\n self._interp.step_over()\n return True": 36, "def __add__(self,other):\n \"\"\"\n If the number of columns matches, we can concatenate two LabeldMatrices\n with the + operator.\n \"\"\"\n assert self.matrix.shape[1] == other.matrix.shape[1]\n return LabeledMatrix(np.concatenate([self.matrix,other.matrix],axis=0),self.labels)": 37, "def get_line_flux(line_wave, wave, flux, **kwargs):\n \"\"\"Interpolated flux at a given wavelength (calls np.interp).\"\"\"\n return np.interp(line_wave, wave, flux, **kwargs)": 38, "def send(message, request_context=None, binary=False):\n \"\"\"Sends a message to websocket.\n\n :param str message: data to send\n\n :param request_context:\n\n :raises IOError: If unable to send a message.\n \"\"\"\n if binary:\n return uwsgi.websocket_send_binary(message, request_context)\n\n return uwsgi.websocket_send(message, request_context)": 39, "def get_number(s, cast=int):\n \"\"\"\n Try to get a number out of a string, and cast it.\n \"\"\"\n import string\n d = \"\".join(x for x in str(s) if x in string.digits)\n return cast(d)": 40, "def get_hline():\n \"\"\" gets a horiztonal line \"\"\"\n return Window(\n width=LayoutDimension.exact(1),\n height=LayoutDimension.exact(1),\n content=FillControl('-', token=Token.Line))": 41, "def parse_cookies_str(cookies):\n \"\"\"\n parse cookies str to dict\n :param cookies: cookies str\n :type cookies: str\n :return: cookie dict\n :rtype: dict\n \"\"\"\n cookie_dict = {}\n for record in cookies.split(\";\"):\n key, value = record.strip().split(\"=\", 1)\n cookie_dict[key] = value\n return cookie_dict": 42, "def to_snake_case(name):\n \"\"\" Given a name in camelCase return in snake_case \"\"\"\n s1 = FIRST_CAP_REGEX.sub(r'\\1_\\2', name)\n return ALL_CAP_REGEX.sub(r'\\1_\\2', s1).lower()": 43, "def populate_obj(obj, attrs):\n \"\"\"Populates an object's attributes using the provided dict\n \"\"\"\n for k, v in attrs.iteritems():\n setattr(obj, k, v)": 44, "def wordfreq(text, is_filename=False):\n \"\"\"Return a dictionary of words and word counts in a string.\"\"\"\n if is_filename:\n with open(text) as f:\n text = f.read()\n freqs = {}\n for word in text.split():\n lword = word.lower()\n freqs[lword] = freqs.get(lword, 0) + 1\n return freqs": 45, "def copyFile(input, output, replace=None):\n \"\"\"Copy a file whole from input to output.\"\"\"\n\n _found = findFile(output)\n if not _found or (_found and replace):\n shutil.copy2(input, output)": 46, "def push(h, x):\n \"\"\"Push a new value into heap.\"\"\"\n h.push(x)\n up(h, h.size()-1)": 47, "def yank(event):\n \"\"\"\n Paste before cursor.\n \"\"\"\n event.current_buffer.paste_clipboard_data(\n event.cli.clipboard.get_data(), count=event.arg, paste_mode=PasteMode.EMACS)": 48, "def filter_contour(imageFile, opFile):\n \"\"\" convert an image by applying a contour \"\"\"\n im = Image.open(imageFile)\n im1 = im.filter(ImageFilter.CONTOUR)\n im1.save(opFile)": 49, "def count(lines):\n \"\"\" Counts the word frequences in a list of sentences.\n\n Note:\n This is a helper function for parallel execution of `Vocabulary.from_text`\n method.\n \"\"\"\n words = [w for l in lines for w in l.strip().split()]\n return Counter(words)": 50, "def dictapply(d, fn):\n \"\"\"\n apply a function to all non-dict values in a dictionary\n \"\"\"\n for k, v in d.items():\n if isinstance(v, dict):\n v = dictapply(v, fn)\n else:\n d[k] = fn(v)\n return d": 51, "def count_replica(self, partition):\n \"\"\"Return count of replicas of given partition.\"\"\"\n return sum(1 for b in partition.replicas if b in self.brokers)": 52, "def visit_Name(self, node):\n \"\"\" Get range for parameters for examples or false branching. \"\"\"\n return self.add(node, self.result[node.id])": 53, "def mkdir(dir, enter):\n \"\"\"Create directory with template for topic of the current environment\n\n \"\"\"\n\n if not os.path.exists(dir):\n os.makedirs(dir)": 54, "def qrot(vector, quaternion):\n \"\"\"Rotate a 3D vector using quaternion algebra.\n\n Implemented by Vladimir Kulikovskiy.\n\n Parameters\n ----------\n vector: np.array\n quaternion: np.array\n\n Returns\n -------\n np.array\n\n \"\"\"\n t = 2 * np.cross(quaternion[1:], vector)\n v_rot = vector + quaternion[0] * t + np.cross(quaternion[1:], t)\n return v_rot": 55, "def _numpy_char_to_bytes(arr):\n \"\"\"Like netCDF4.chartostring, but faster and more flexible.\n \"\"\"\n # based on: http://stackoverflow.com/a/10984878/809705\n arr = np.array(arr, copy=False, order='C')\n dtype = 'S' + str(arr.shape[-1])\n return arr.view(dtype).reshape(arr.shape[:-1])": 56, "def csv_to_dicts(file, header=None):\n \"\"\"Reads a csv and returns a List of Dicts with keys given by header row.\"\"\"\n with open(file) as csvfile:\n return [row for row in csv.DictReader(csvfile, fieldnames=header)]": 57, "def get_tri_area(pts):\n \"\"\"\n Given a list of coords for 3 points,\n Compute the area of this triangle.\n\n Args:\n pts: [a, b, c] three points\n \"\"\"\n a, b, c = pts[0], pts[1], pts[2]\n v1 = np.array(b) - np.array(a)\n v2 = np.array(c) - np.array(a)\n area_tri = abs(sp.linalg.norm(sp.cross(v1, v2)) / 2)\n return area_tri": 58, "def one_hot(x, size, dtype=np.float32):\n \"\"\"Make a n+1 dim one-hot array from n dim int-categorical array.\"\"\"\n return np.array(x[..., np.newaxis] == np.arange(size), dtype)": 59, "def round_to_int(number, precision):\n \"\"\"Round a number to a precision\"\"\"\n precision = int(precision)\n rounded = (int(number) + precision / 2) // precision * precision\n return rounded": 60, "def create_object(cls, members):\n \"\"\"Promise an object of class `cls` with content `members`.\"\"\"\n obj = cls.__new__(cls)\n obj.__dict__ = members\n return obj": 61, "def to_unicode_repr( _letter ):\n \"\"\" helpful in situations where browser/app may recognize Unicode encoding\n in the \\u0b8e type syntax but not actual unicode glyph/code-point\"\"\"\n # Python 2-3 compatible\n return u\"u'\"+ u\"\".join( [ u\"\\\\u%04x\"%ord(l) for l in _letter ] ) + u\"'\"": 62, "def string_input(prompt=''):\n \"\"\"Python 3 input()/Python 2 raw_input()\"\"\"\n v = sys.version[0]\n if v == '3':\n return input(prompt)\n else:\n return raw_input(prompt)": 63, "def cfloat64_array_to_numpy(cptr, length):\n \"\"\"Convert a ctypes double pointer array to a numpy array.\"\"\"\n if isinstance(cptr, ctypes.POINTER(ctypes.c_double)):\n return np.fromiter(cptr, dtype=np.float64, count=length)\n else:\n raise RuntimeError('Expected double pointer')": 64, "def yn_prompt(msg, default=True):\n \"\"\"\n Prompts the user for yes or no.\n \"\"\"\n ret = custom_prompt(msg, [\"y\", \"n\"], \"y\" if default else \"n\")\n if ret == \"y\":\n return True\n return False": 65, "def _display(self, layout):\n \"\"\"launch layouts display\"\"\"\n print(file=self.out)\n TextWriter().format(layout, self.out)": 66, "def assert_list(self, putative_list, expected_type=string_types, key_arg=None):\n \"\"\"\n :API: public\n \"\"\"\n return assert_list(putative_list, expected_type, key_arg=key_arg,\n raise_type=lambda msg: TargetDefinitionException(self, msg))": 67, "def _xxrange(self, start, end, step_count):\n \"\"\"Generate n values between start and end.\"\"\"\n _step = (end - start) / float(step_count)\n return (start + (i * _step) for i in xrange(int(step_count)))": 68, "def assert_exactly_one_true(bool_list):\n \"\"\"This method asserts that only one value of the provided list is True.\n\n :param bool_list: List of booleans to check\n :return: True if only one value is True, False otherwise\n \"\"\"\n assert isinstance(bool_list, list)\n counter = 0\n for item in bool_list:\n if item:\n counter += 1\n return counter == 1": 69, "def _get_random_id():\n \"\"\" Get a random (i.e., unique) string identifier\"\"\"\n symbols = string.ascii_uppercase + string.ascii_lowercase + string.digits\n return ''.join(random.choice(symbols) for _ in range(15))": 70, "async def list(source):\n \"\"\"Generate a single list from an asynchronous sequence.\"\"\"\n result = []\n async with streamcontext(source) as streamer:\n async for item in streamer:\n result.append(item)\n yield result": 71, "def _attrprint(d, delimiter=', '):\n \"\"\"Print a dictionary of attributes in the DOT format\"\"\"\n return delimiter.join(('\"%s\"=\"%s\"' % item) for item in sorted(d.items()))": 72, "def get_next_scheduled_time(cron_string):\n \"\"\"Calculate the next scheduled time by creating a crontab object\n with a cron string\"\"\"\n itr = croniter.croniter(cron_string, datetime.utcnow())\n return itr.get_next(datetime)": 73, "def exit(exit_code=0):\n r\"\"\"A function to support exiting from exit hooks.\n\n Could also be used to exit from the calling scripts in a thread safe manner.\n \"\"\"\n core.processExitHooks()\n\n if state.isExitHooked and not hasattr(sys, 'exitfunc'): # The function is called from the exit hook\n sys.stderr.flush()\n sys.stdout.flush()\n os._exit(exit_code) #pylint: disable=W0212\n\n sys.exit(exit_code)": 74, "def dot_product(self, other):\n \"\"\" Return the dot product of the given vectors. \"\"\"\n return self.x * other.x + self.y * other.y": 75, "def reloader_thread(softexit=False):\n \"\"\"If ``soft_exit`` is True, we use sys.exit(); otherwise ``os_exit``\n will be used to end the process.\n \"\"\"\n while RUN_RELOADER:\n if code_changed():\n # force reload\n if softexit:\n sys.exit(3)\n else:\n os._exit(3)\n time.sleep(1)": 76, "def list_to_csv(value):\n \"\"\"\n Converts list to string with comma separated values. For string is no-op.\n \"\"\"\n if isinstance(value, (list, tuple, set)):\n value = \",\".join(value)\n return value": 77, "def average(iterator):\n \"\"\"Iterative mean.\"\"\"\n count = 0\n total = 0\n for num in iterator:\n count += 1\n total += num\n return float(total)/count": 78, "def cint32_array_to_numpy(cptr, length):\n \"\"\"Convert a ctypes int pointer array to a numpy array.\"\"\"\n if isinstance(cptr, ctypes.POINTER(ctypes.c_int32)):\n return np.fromiter(cptr, dtype=np.int32, count=length)\n else:\n raise RuntimeError('Expected int pointer')": 79, "def _aws_get_instance_by_tag(region, name, tag, raw):\n \"\"\"Get all instances matching a tag.\"\"\"\n client = boto3.session.Session().client('ec2', region)\n matching_reservations = client.describe_instances(Filters=[{'Name': tag, 'Values': [name]}]).get('Reservations', [])\n instances = []\n [[instances.append(_aws_instance_from_dict(region, instance, raw)) # pylint: disable=expression-not-assigned\n for instance in reservation.get('Instances')] for reservation in matching_reservations if reservation]\n return instances": 80, "def loganalytics_data_plane_client(cli_ctx, _):\n \"\"\"Initialize Log Analytics data client for use with CLI.\"\"\"\n from .vendored_sdks.loganalytics import LogAnalyticsDataClient\n from azure.cli.core._profile import Profile\n profile = Profile(cli_ctx=cli_ctx)\n cred, _, _ = profile.get_login_credentials(\n resource=\"https://api.loganalytics.io\")\n return LogAnalyticsDataClient(cred)": 81, "def cfloat32_array_to_numpy(cptr, length):\n \"\"\"Convert a ctypes float pointer array to a numpy array.\"\"\"\n if isinstance(cptr, ctypes.POINTER(ctypes.c_float)):\n return np.fromiter(cptr, dtype=np.float32, count=length)\n else:\n raise RuntimeError('Expected float pointer')": 82, "def underscore(text):\n \"\"\"Converts text that may be camelcased into an underscored format\"\"\"\n return UNDERSCORE[1].sub(r'\\1_\\2', UNDERSCORE[0].sub(r'\\1_\\2', text)).lower()": 83, "def cint8_array_to_numpy(cptr, length):\n \"\"\"Convert a ctypes int pointer array to a numpy array.\"\"\"\n if isinstance(cptr, ctypes.POINTER(ctypes.c_int8)):\n return np.fromiter(cptr, dtype=np.int8, count=length)\n else:\n raise RuntimeError('Expected int pointer')": 84, "def get_stoplist(language):\n \"\"\"Returns an built-in stop-list for the language as a set of words.\"\"\"\n file_path = os.path.join(\"stoplists\", \"%s.txt\" % language)\n try:\n stopwords = pkgutil.get_data(\"justext\", file_path)\n except IOError:\n raise ValueError(\n \"Stoplist for language '%s' is missing. \"\n \"Please use function 'get_stoplists' for complete list of stoplists \"\n \"and feel free to contribute by your own stoplist.\" % language\n )\n\n return frozenset(w.decode(\"utf8\").lower() for w in stopwords.splitlines())": 85, "def add_str(window, line_num, str):\n \"\"\" attempt to draw str on screen and ignore errors if they occur \"\"\"\n try:\n window.addstr(line_num, 0, str)\n except curses.error:\n pass": 86, "def relative_path(path):\n \"\"\"\n Return the given path relative to this file.\n \"\"\"\n return os.path.join(os.path.dirname(__file__), path)": 87, "def dictfetchall(cursor):\n \"\"\"Returns all rows from a cursor as a dict (rather than a headerless table)\n\n From Django Documentation: https://docs.djangoproject.com/en/dev/topics/db/sql/\n \"\"\"\n desc = cursor.description\n return [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()]": 88, "def xmltreefromfile(filename):\n \"\"\"Internal function to read an XML file\"\"\"\n try:\n return ElementTree.parse(filename, ElementTree.XMLParser(collect_ids=False))\n except TypeError:\n return ElementTree.parse(filename, ElementTree.XMLParser())": 89, "def _dictfetchall(self, cursor):\n \"\"\" Return all rows from a cursor as a dict. \"\"\"\n columns = [col[0] for col in cursor.description]\n return [\n dict(zip(columns, row))\n for row in cursor.fetchall()\n ]": 90, "def beta_pdf(x, a, b):\n \"\"\"Beta distirbution probability density function.\"\"\"\n bc = 1 / beta(a, b)\n fc = x ** (a - 1)\n sc = (1 - x) ** (b - 1)\n return bc * fc * sc": 91, "def filter_out(queryset, setting_name):\n \"\"\"\n Remove unwanted results from queryset\n \"\"\"\n kwargs = helpers.get_settings().get(setting_name, {}).get('FILTER_OUT', {})\n queryset = queryset.exclude(**kwargs)\n return queryset": 92, "def intToBin(i):\n \"\"\" Integer to two bytes \"\"\"\n # divide in two parts (bytes)\n i1 = i % 256\n i2 = int(i / 256)\n # make string (little endian)\n return i.to_bytes(2, byteorder='little')": 93, "def listlike(obj):\n \"\"\"Is an object iterable like a list (and not a string)?\"\"\"\n \n return hasattr(obj, \"__iter__\") \\\n and not issubclass(type(obj), str)\\\n and not issubclass(type(obj), unicode)": 94, "def table_top_abs(self):\n \"\"\"Returns the absolute position of table top\"\"\"\n table_height = np.array([0, 0, self.table_full_size[2]])\n return string_to_array(self.floor.get(\"pos\")) + table_height": 95, "def pdf(x, mu, std):\n \"\"\"Probability density function (normal distribution)\"\"\"\n return (1.0 / (std * sqrt(2 * pi))) * np.exp(-(x - mu) ** 2 / (2 * std ** 2))": 96, "def bytes_to_c_array(data):\n \"\"\"\n Make a C array using the given string.\n \"\"\"\n chars = [\n \"'{}'\".format(encode_escape(i))\n for i in decode_escape(data)\n ]\n return ', '.join(chars) + ', 0'": 97, "def gray2bgr(img):\n \"\"\"Convert a grayscale image to BGR image.\n\n Args:\n img (ndarray or str): The input image.\n\n Returns:\n ndarray: The converted BGR image.\n \"\"\"\n img = img[..., None] if img.ndim == 2 else img\n out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)\n return out_img": 98, "def mean_date(dt_list):\n \"\"\"Calcuate mean datetime from datetime list\n \"\"\"\n dt_list_sort = sorted(dt_list)\n dt_list_sort_rel = [dt - dt_list_sort[0] for dt in dt_list_sort]\n avg_timedelta = sum(dt_list_sort_rel, timedelta())/len(dt_list_sort_rel)\n return dt_list_sort[0] + avg_timedelta": 99, "def rotate_img(im, deg, mode=cv2.BORDER_CONSTANT, interpolation=cv2.INTER_AREA):\n \"\"\" Rotates an image by deg degrees\n\n Arguments:\n deg (float): degree to rotate.\n \"\"\"\n r,c,*_ = im.shape\n M = cv2.getRotationMatrix2D((c//2,r//2),deg,1)\n return cv2.warpAffine(im,M,(c,r), borderMode=mode, flags=cv2.WARP_FILL_OUTLIERS+interpolation)": 100, "def similarity(self, other):\n \"\"\"Calculates the cosine similarity between this vector and another\n vector.\"\"\"\n if self.magnitude == 0 or other.magnitude == 0:\n return 0\n\n return self.dot(other) / self.magnitude": 101, "def _calculate_distance(latlon1, latlon2):\n \"\"\"Calculates the distance between two points on earth.\n \"\"\"\n lat1, lon1 = latlon1\n lat2, lon2 = latlon2\n dlon = lon2 - lon1\n dlat = lat2 - lat1\n R = 6371 # radius of the earth in kilometers\n a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon / 2))**2\n c = 2 * np.pi * R * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) / 180\n return c": 102, "def screen_cv2(self):\n \"\"\"cv2 Image of current window screen\"\"\"\n pil_image = self.screen.convert('RGB')\n cv2_image = np.array(pil_image)\n pil_image.close()\n # Convert RGB to BGR \n cv2_image = cv2_image[:, :, ::-1]\n return cv2_image": 103, "def direct2dDistance(self, point):\n \"\"\"consider the distance between two mapPoints, ignoring all terrain, pathing issues\"\"\"\n if not isinstance(point, MapPoint): return 0.0\n return ((self.x-point.x)**2 + (self.y-point.y)**2)**(0.5) # simple distance formula": 104, "def _model_unique(ins):\n \"\"\" Get unique constraints info\n\n :type ins: sqlalchemy.orm.mapper.Mapper\n :rtype: list[tuple[str]]\n \"\"\"\n unique = []\n for t in ins.tables:\n for c in t.constraints:\n if isinstance(c, UniqueConstraint):\n unique.append(tuple(col.key for col in c.columns))\n return unique": 105, "def horz_dpi(self):\n \"\"\"\n Integer dots per inch for the width of this image. Defaults to 72\n when not present in the file, as is often the case.\n \"\"\"\n pHYs = self._chunks.pHYs\n if pHYs is None:\n return 72\n return self._dpi(pHYs.units_specifier, pHYs.horz_px_per_unit)": 106, "def parse(self, s):\n \"\"\"\n Parses a date string formatted like ``YYYY-MM-DD``.\n \"\"\"\n return datetime.datetime.strptime(s, self.date_format).date()": 107, "def estimate_complexity(self, x,y,z,n):\n \"\"\" \n calculates a rough guess of runtime based on product of parameters \n \"\"\"\n num_calculations = x * y * z * n\n run_time = num_calculations / 100000 # a 2014 PC does about 100k calcs in a second (guess based on prior logs)\n return self.show_time_as_short_string(run_time)": 108, "def weekly(date=datetime.date.today()):\n \"\"\"\n Weeks start are fixes at Monday for now.\n \"\"\"\n return date - datetime.timedelta(days=date.weekday())": 109, "def inh(table):\n \"\"\"\n inverse hyperbolic sine transformation\n \"\"\"\n t = []\n for i in table:\n t.append(np.ndarray.tolist(np.arcsinh(i)))\n return t": 110, "def daterange(start, end, delta=timedelta(days=1), lower=Interval.CLOSED, upper=Interval.OPEN):\n \"\"\"Returns a generator which creates the next value in the range on demand\"\"\"\n date_interval = Interval(lower=lower, lower_value=start, upper_value=end, upper=upper)\n current = start if start in date_interval else start + delta\n while current in date_interval:\n yield current\n current = current + delta": 111, "async def _thread_coro(self, *args):\n \"\"\" Coroutine called by MapAsync. It's wrapping the call of\n run_in_executor to run the synchronous function as thread \"\"\"\n return await self._loop.run_in_executor(\n self._executor, self._function, *args)": 112, "def start_of_month(val):\n \"\"\"\n Return a new datetime.datetime object with values that represent\n a start of a month.\n :param val: Date to ...\n :type val: datetime.datetime | datetime.date\n :rtype: datetime.datetime\n \"\"\"\n if type(val) == date:\n val = datetime.fromordinal(val.toordinal())\n return start_of_day(val).replace(day=1)": 113, "def check_output(args, env=None, sp=subprocess):\n \"\"\"Call an external binary and return its stdout.\"\"\"\n log.debug('calling %s with env %s', args, env)\n output = sp.check_output(args=args, env=env)\n log.debug('output: %r', output)\n return output": 114, "def datetime_to_ms(dt):\n \"\"\"\n Converts a datetime to a millisecond accuracy timestamp\n \"\"\"\n seconds = calendar.timegm(dt.utctimetuple())\n return seconds * 1000 + int(dt.microsecond / 1000)": 115, "def retry_on_signal(function):\n \"\"\"Retries function until it doesn't raise an EINTR error\"\"\"\n while True:\n try:\n return function()\n except EnvironmentError, e:\n if e.errno != errno.EINTR:\n raise": 116, "def datetime_to_timezone(date, tz=\"UTC\"):\n \"\"\" convert naive datetime to timezone-aware datetime \"\"\"\n if not date.tzinfo:\n date = date.replace(tzinfo=timezone(get_timezone()))\n return date.astimezone(timezone(tz))": 117, "def test(*args):\n \"\"\"\n Run unit tests.\n \"\"\"\n subprocess.call([\"py.test-2.7\"] + list(args))\n subprocess.call([\"py.test-3.4\"] + list(args))": 118, "def ToDatetime(self):\n \"\"\"Converts Timestamp to datetime.\"\"\"\n return datetime.utcfromtimestamp(\n self.seconds + self.nanos / float(_NANOS_PER_SECOND))": 119, "def sortable_title(instance):\n \"\"\"Uses the default Plone sortable_text index lower-case\n \"\"\"\n title = plone_sortable_title(instance)\n if safe_callable(title):\n title = title()\n return title.lower()": 120, "def localize(dt):\n \"\"\"Localize a datetime object to local time.\"\"\"\n if dt.tzinfo is UTC:\n return (dt + LOCAL_UTC_OFFSET).replace(tzinfo=None)\n # No TZ info so not going to assume anything, return as-is.\n return dt": 121, "def percent_cb(name, complete, total):\n \"\"\" Callback for updating target progress \"\"\"\n logger.debug(\n \"{}: {} transferred out of {}\".format(\n name, sizeof_fmt(complete), sizeof_fmt(total)\n )\n )\n progress.update_target(name, complete, total)": 122, "def now(self):\n\t\t\"\"\"\n\t\tReturn a :py:class:`datetime.datetime` instance representing the current time.\n\n\t\t:rtype: :py:class:`datetime.datetime`\n\t\t\"\"\"\n\t\tif self.use_utc:\n\t\t\treturn datetime.datetime.utcnow()\n\t\telse:\n\t\t\treturn datetime.datetime.now()": 123, "def to_pascal_case(s):\n \"\"\"Transform underscore separated string to pascal case\n\n \"\"\"\n return re.sub(r'(?!^)_([a-zA-Z])', lambda m: m.group(1).upper(), s.capitalize())": 124, "def _convert_date_to_dict(field_date):\n \"\"\"\n Convert native python ``datetime.date`` object to a format supported by the API\n \"\"\"\n return {DAY: field_date.day, MONTH: field_date.month, YEAR: field_date.year}": 125, "def convert_array(array):\n \"\"\"\n Converts an ARRAY string stored in the database back into a Numpy array.\n\n Parameters\n ----------\n array: ARRAY\n The array object to be converted back into a Numpy array.\n\n Returns\n -------\n array\n The converted Numpy array.\n\n \"\"\"\n out = io.BytesIO(array)\n out.seek(0)\n return np.load(out)": 126, "def parse_timestamp(timestamp):\n \"\"\"Parse ISO8601 timestamps given by github API.\"\"\"\n dt = dateutil.parser.parse(timestamp)\n return dt.astimezone(dateutil.tz.tzutc())": 127, "def add_to_js(self, name, var):\n \"\"\"Add an object to Javascript.\"\"\"\n frame = self.page().mainFrame()\n frame.addToJavaScriptWindowObject(name, var)": 128, "def fromtimestamp(cls, timestamp):\n \"\"\"Returns a datetime object of a given timestamp (in local tz).\"\"\"\n d = cls.utcfromtimestamp(timestamp)\n return d.astimezone(localtz())": 129, "def print_latex(o):\n \"\"\"A function to generate the latex representation of sympy\n expressions.\"\"\"\n if can_print_latex(o):\n s = latex(o, mode='plain')\n s = s.replace('\\\\dag','\\\\dagger')\n s = s.strip('$')\n return '$$%s$$' % s\n # Fallback to the string printer\n return None": 130, "def datetime64_to_datetime(dt):\n \"\"\" convert numpy's datetime64 to datetime \"\"\"\n dt64 = np.datetime64(dt)\n ts = (dt64 - np.datetime64('1970-01-01T00:00:00')) / np.timedelta64(1, 's')\n return datetime.datetime.utcfromtimestamp(ts)": 131, "def batch_tensor(self, name):\n \"\"\" A buffer of a given value in a 'flat' (minibatch-indexed) format \"\"\"\n if name in self.transition_tensors:\n return tensor_util.merge_first_two_dims(self.transition_tensors[name])\n else:\n return self.rollout_tensors[name]": 132, "def isInteractive():\n \"\"\"\n A basic check of if the program is running in interactive mode\n \"\"\"\n if sys.stdout.isatty() and os.name != 'nt':\n #Hopefully everything but ms supports '\\r'\n try:\n import threading\n except ImportError:\n return False\n else:\n return True\n else:\n return False": 133, "def create_symlink(source, link_name):\n \"\"\"\n Creates symbolic link for either operating system.\n\n http://stackoverflow.com/questions/6260149/os-symlink-support-in-windows\n \"\"\"\n os_symlink = getattr(os, \"symlink\", None)\n if isinstance(os_symlink, collections.Callable):\n os_symlink(source, link_name)\n else:\n import ctypes\n csl = ctypes.windll.kernel32.CreateSymbolicLinkW\n csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)\n csl.restype = ctypes.c_ubyte\n flags = 1 if os.path.isdir(source) else 0\n if csl(link_name, source, flags) == 0:\n raise ctypes.WinError()": 134, "def export(defn):\n \"\"\"Decorator to explicitly mark functions that are exposed in a lib.\"\"\"\n globals()[defn.__name__] = defn\n __all__.append(defn.__name__)\n return defn": 135, "def parse(source, remove_comments=True, **kw):\n \"\"\"Thin wrapper around ElementTree.parse\"\"\"\n return ElementTree.parse(source, SourceLineParser(), **kw)": 136, "def decorator(func):\n r\"\"\"Makes the passed decorators to support optional args.\n \"\"\"\n def wrapper(__decorated__=None, *Args, **KwArgs):\n if __decorated__ is None: # the decorator has some optional arguments.\n return lambda _func: func(_func, *Args, **KwArgs)\n\n else:\n return func(__decorated__, *Args, **KwArgs)\n\n return wrap(wrapper, func)": 137, "def show_image(self, key):\n \"\"\"Show image (item is a PIL image)\"\"\"\n data = self.model.get_data()\n data[key].show()": 138, "def get_default_args(func):\n \"\"\"\n returns a dictionary of arg_name:default_values for the input function\n \"\"\"\n args, varargs, keywords, defaults = getargspec_no_self(func)\n return dict(zip(args[-len(defaults):], defaults))": 139, "def _interval_to_bound_points(array):\n \"\"\"\n Helper function which returns an array\n with the Intervals' boundaries.\n \"\"\"\n\n array_boundaries = np.array([x.left for x in array])\n array_boundaries = np.concatenate(\n (array_boundaries, np.array([array[-1].right])))\n\n return array_boundaries": 140, "def closing_plugin(self, cancelable=False):\n \"\"\"Perform actions before parent main window is closed\"\"\"\n self.dialog_manager.close_all()\n self.shell.exit_interpreter()\n return True": 141, "def test(): \n \"\"\"Local test.\"\"\"\n from spyder.utils.qthelpers import qapplication\n app = qapplication()\n dlg = ProjectDialog(None)\n dlg.show()\n sys.exit(app.exec_())": 142, "def del_label(self, name):\n \"\"\"Delete a label by name.\"\"\"\n labels_tag = self.root[0]\n labels_tag.remove(self._find_label(name))": 143, "def mixedcase(path):\n \"\"\"Removes underscores and capitalizes the neighbouring character\"\"\"\n words = path.split('_')\n return words[0] + ''.join(word.title() for word in words[1:])": 144, "def delete_all_eggs(self):\n \"\"\" delete all the eggs in the directory specified \"\"\"\n path_to_delete = os.path.join(self.egg_directory, \"lib\", \"python\")\n if os.path.exists(path_to_delete):\n shutil.rmtree(path_to_delete)": 145, "def get_system_cpu_times():\n \"\"\"Return system CPU times as a namedtuple.\"\"\"\n user, nice, system, idle = _psutil_osx.get_system_cpu_times()\n return _cputimes_ntuple(user, nice, system, idle)": 146, "def remove(self, document_id, namespace, timestamp):\n \"\"\"Removes documents from Solr\n\n The input is a python dictionary that represents a mongo document.\n \"\"\"\n self.solr.delete(id=u(document_id),\n commit=(self.auto_commit_interval == 0))": 147, "def update_hash_from_str(hsh, str_input):\n \"\"\"\n Convert a str to object supporting buffer API and update a hash with it.\n \"\"\"\n byte_input = str(str_input).encode(\"UTF-8\")\n hsh.update(byte_input)": 148, "def make_regex(separator):\n \"\"\"Utility function to create regexp for matching escaped separators\n in strings.\n\n \"\"\"\n return re.compile(r'(?:' + re.escape(separator) + r')?((?:[^' +\n re.escape(separator) + r'\\\\]|\\\\.)+)')": 149, "def dictify(a_named_tuple):\n \"\"\"Transform a named tuple into a dictionary\"\"\"\n return dict((s, getattr(a_named_tuple, s)) for s in a_named_tuple._fields)": 150, "def _py2_and_3_joiner(sep, joinable):\n \"\"\"\n Allow '\\n'.join(...) statements to work in Py2 and Py3.\n :param sep:\n :param joinable:\n :return:\n \"\"\"\n if ISPY3:\n sep = bytes(sep, DEFAULT_ENCODING)\n joined = sep.join(joinable)\n return joined.decode(DEFAULT_ENCODING) if ISPY3 else joined": 151, "def c_str(string):\n \"\"\"\"Convert a python string to C string.\"\"\"\n if not isinstance(string, str):\n string = string.decode('ascii')\n return ctypes.c_char_p(string.encode('utf-8'))": 152, "def endline_semicolon_check(self, original, loc, tokens):\n \"\"\"Check for semicolons at the end of lines.\"\"\"\n return self.check_strict(\"semicolon at end of line\", original, loc, tokens)": 153, "def _datetime_to_date(arg):\n \"\"\"\n convert datetime/str to date\n :param arg:\n :return:\n \"\"\"\n _arg = parse(arg)\n if isinstance(_arg, datetime.datetime):\n _arg = _arg.date()\n return _arg": 154, "def get(self):\n \"\"\"Get the highest priority Processing Block from the queue.\"\"\"\n with self._mutex:\n entry = self._queue.pop()\n del self._block_map[entry[2]]\n return entry[2]": 155, "def center_text(text, width=80):\n \"\"\"Center all lines of the text.\n\n It is assumed that all lines width is smaller then B{width}, because the\n line width will not be checked.\n\n Args:\n text (str): Text to wrap.\n width (int): Maximum number of characters per line.\n\n Returns:\n str: Centered text.\n \"\"\"\n centered = []\n for line in text.splitlines():\n centered.append(line.center(width))\n return \"\\n\".join(centered)": 156, "def from_json(cls, json_str):\n \"\"\"Deserialize the object from a JSON string.\"\"\"\n d = json.loads(json_str)\n return cls.from_dict(d)": 157, "def update(kernel=False):\n \"\"\"\n Upgrade all packages, skip obsoletes if ``obsoletes=0`` in ``yum.conf``.\n\n Exclude *kernel* upgrades by default.\n \"\"\"\n manager = MANAGER\n cmds = {'yum -y --color=never': {False: '--exclude=kernel* update', True: 'update'}}\n cmd = cmds[manager][kernel]\n run_as_root(\"%(manager)s %(cmd)s\" % locals())": 158, "def guess_encoding(text, default=DEFAULT_ENCODING):\n \"\"\"Guess string encoding.\n\n Given a piece of text, apply character encoding detection to\n guess the appropriate encoding of the text.\n \"\"\"\n result = chardet.detect(text)\n return normalize_result(result, default=default)": 159, "def commajoin_as_strings(iterable):\n \"\"\" Join the given iterable with ',' \"\"\"\n return _(u',').join((six.text_type(i) for i in iterable))": 160, "def supports_color():\n \"\"\"\n Returns True if the running system's terminal supports color, and False\n otherwise.\n \"\"\"\n unsupported_platform = (sys.platform in ('win32', 'Pocket PC'))\n # isatty is not always implemented, #6223.\n is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()\n if unsupported_platform or not is_a_tty:\n return False\n return True": 161, "def seconds_to_hms(seconds):\n \"\"\"\n Converts seconds float to 'hh:mm:ss.ssssss' format.\n \"\"\"\n hours = int(seconds / 3600.0)\n minutes = int((seconds / 60.0) % 60.0)\n secs = float(seconds % 60.0)\n return \"{0:02d}:{1:02d}:{2:02.6f}\".format(hours, minutes, secs)": 162, "def __contains__(self, key):\n \"\"\"\n Invoked when determining whether a specific key is in the dictionary\n using `key in d`.\n\n The key is looked up case-insensitively.\n \"\"\"\n k = self._real_key(key)\n return k in self._data": 163, "def get_truetype(value):\n \"\"\"Convert a string to a pythonized parameter.\"\"\"\n if value in [\"true\", \"True\", \"y\", \"Y\", \"yes\"]:\n return True\n if value in [\"false\", \"False\", \"n\", \"N\", \"no\"]:\n return False\n if value.isdigit():\n return int(value)\n return str(value)": 164, "def Serializable(o):\n \"\"\"Make sure an object is JSON-serializable\n Use this to return errors and other info that does not need to be\n deserialized or does not contain important app data. Best for returning\n error info and such\"\"\"\n if isinstance(o, (str, dict, int)):\n return o\n else:\n try:\n json.dumps(o)\n return o\n except Exception:\n LOG.debug(\"Got a non-serilizeable object: %s\" % o)\n return o.__repr__()": 165, "def timed_rotating_file_handler(name, logname, filename, when='h',\n interval=1, backupCount=0,\n encoding=None, delay=False, utc=False):\n \"\"\"\n A Bark logging handler logging output to a named file. At\n intervals specified by the 'when', the file will be rotated, under\n control of 'backupCount'.\n\n Similar to logging.handlers.TimedRotatingFileHandler.\n \"\"\"\n\n return wrap_log_handler(logging.handlers.TimedRotatingFileHandler(\n filename, when=when, interval=interval, backupCount=backupCount,\n encoding=encoding, delay=delay, utc=utc))": 166, "def is_identifier(string):\n \"\"\"Check if string could be a valid python identifier\n\n :param string: string to be tested\n :returns: True if string can be a python identifier, False otherwise\n :rtype: bool\n \"\"\"\n matched = PYTHON_IDENTIFIER_RE.match(string)\n return bool(matched) and not keyword.iskeyword(string)": 167, "def uniform_iterator(sequence):\n \"\"\"Uniform (key, value) iteration on a `dict`,\n or (idx, value) on a `list`.\"\"\"\n\n if isinstance(sequence, abc.Mapping):\n return six.iteritems(sequence)\n else:\n return enumerate(sequence)": 168, "def _guess_type(val):\n \"\"\"Guess the input type of the parameter based off the default value, if unknown use text\"\"\"\n if isinstance(val, bool):\n return \"choice\"\n elif isinstance(val, int):\n return \"number\"\n elif isinstance(val, float):\n return \"number\"\n elif isinstance(val, str):\n return \"text\"\n elif hasattr(val, 'read'):\n return \"file\"\n else:\n return \"text\"": 169, "def _to_corrected_pandas_type(dt):\n \"\"\"\n When converting Spark SQL records to Pandas DataFrame, the inferred data type may be wrong.\n This method gets the corrected data type for Pandas if that type may be inferred uncorrectly.\n \"\"\"\n import numpy as np\n if type(dt) == ByteType:\n return np.int8\n elif type(dt) == ShortType:\n return np.int16\n elif type(dt) == IntegerType:\n return np.int32\n elif type(dt) == FloatType:\n return np.float32\n else:\n return None": 170, "def _platform_is_windows(platform=sys.platform):\n \"\"\"Is the current OS a Windows?\"\"\"\n matched = platform in ('cygwin', 'win32', 'win64')\n if matched:\n error_msg = \"Windows isn't supported yet\"\n raise OSError(error_msg)\n return matched": 171, "def _xls2col_widths(self, worksheet, tab):\n \"\"\"Updates col_widths in code_array\"\"\"\n\n for col in xrange(worksheet.ncols):\n try:\n xls_width = worksheet.colinfo_map[col].width\n pys_width = self.xls_width2pys_width(xls_width)\n self.code_array.col_widths[col, tab] = pys_width\n\n except KeyError:\n pass": 172, "def keys_to_snake_case(camel_case_dict):\n \"\"\"\n Make a copy of a dictionary with all keys converted to snake case. This is just calls to_snake_case on\n each of the keys in the dictionary and returns a new dictionary.\n\n :param camel_case_dict: Dictionary with the keys to convert.\n :type camel_case_dict: Dictionary.\n\n :return: Dictionary with the keys converted to snake case.\n \"\"\"\n return dict((to_snake_case(key), value) for (key, value) in camel_case_dict.items())": 173, "def _bytes_to_json(value):\n \"\"\"Coerce 'value' to an JSON-compatible representation.\"\"\"\n if isinstance(value, bytes):\n value = base64.standard_b64encode(value).decode(\"ascii\")\n return value": 174, "def dict_hash(dct):\n \"\"\"Return a hash of the contents of a dictionary\"\"\"\n dct_s = json.dumps(dct, sort_keys=True)\n\n try:\n m = md5(dct_s)\n except TypeError:\n m = md5(dct_s.encode())\n\n return m.hexdigest()": 175, "def int_to_date(date):\n \"\"\"\n Convert an int of form yyyymmdd to a python date object.\n \"\"\"\n\n year = date // 10**4\n month = date % 10**4 // 10**2\n day = date % 10**2\n\n return datetime.date(year, month, day)": 176, "def filter_dict(d, keys):\n \"\"\"\n Creates a new dict from an existing dict that only has the given keys\n \"\"\"\n return {k: v for k, v in d.items() if k in keys}": 177, "def hasattrs(object, *names):\n \"\"\"\n Takes in an object and a variable length amount of named attributes,\n and checks to see if the object has each property. If any of the\n attributes are missing, this returns false.\n\n :param object: an object that may or may not contain the listed attributes\n :param names: a variable amount of attribute names to check for\n :return: True if the object contains each named attribute, false otherwise\n \"\"\"\n for name in names:\n if not hasattr(object, name):\n return False\n return True": 178, "def dict_update_newkeys(dict_, dict2):\n \"\"\" Like dict.update, but does not overwrite items \"\"\"\n for key, val in six.iteritems(dict2):\n if key not in dict_:\n dict_[key] = val": 179, "def numpy_aware_eq(a, b):\n \"\"\"Return whether two objects are equal via recursion, using\n :func:`numpy.array_equal` for comparing numpy arays.\n \"\"\"\n if isinstance(a, np.ndarray) or isinstance(b, np.ndarray):\n return np.array_equal(a, b)\n if ((isinstance(a, Iterable) and isinstance(b, Iterable)) and\n not isinstance(a, str) and not isinstance(b, str)):\n if len(a) != len(b):\n return False\n return all(numpy_aware_eq(x, y) for x, y in zip(a, b))\n return a == b": 180, "def update(self, other_dict):\n \"\"\"update() extends rather than replaces existing key lists.\"\"\"\n for key, value in iter_multi_items(other_dict):\n MultiDict.add(self, key, value)": 181, "def _internet_on(address):\n \"\"\"\n Check to see if the internet is on by pinging a set address.\n :param address: the IP or address to hit\n :return: a boolean - true if can be reached, false if not.\n \"\"\"\n try:\n urllib2.urlopen(address, timeout=1)\n return True\n except urllib2.URLError as err:\n return False": 182, "def _defaultdict(dct, fallback=_illegal_character):\n \"\"\"Wraps the given dictionary such that the given fallback function will be called when a nonexistent key is\n accessed.\n \"\"\"\n out = defaultdict(lambda: fallback)\n for k, v in six.iteritems(dct):\n out[k] = v\n return out": 183, "def is_json_file(filename, show_warnings = False):\n \"\"\"Check configuration file type is JSON\n Return a boolean indicating wheather the file is JSON format or not\n \"\"\"\n try:\n config_dict = load_config(filename, file_type = \"json\")\n is_json = True\n except:\n is_json = False\n return(is_json)": 184, "def _remove_dict_keys_with_value(dict_, val):\n \"\"\"Removes `dict` keys which have have `self` as value.\"\"\"\n return {k: v for k, v in dict_.items() if v is not val}": 185, "def post_commit_hook(argv):\n \"\"\"Hook: for checking commit message.\"\"\"\n _, stdout, _ = run(\"git log -1 --format=%B HEAD\")\n message = \"\\n\".join(stdout)\n options = {\"allow_empty\": True}\n\n if not _check_message(message, options):\n click.echo(\n \"Commit message errors (fix with 'git commit --amend').\",\n file=sys.stderr)\n return 1 # it should not fail with exit\n return 0": 186, "def setdefaults(dct, defaults):\n \"\"\"Given a target dct and a dict of {key:default value} pairs,\n calls setdefault for all of those pairs.\"\"\"\n for key in defaults:\n dct.setdefault(key, defaults[key])\n\n return dct": 187, "def is_image_file_valid(file_path_name):\n \"\"\"\n Indicate whether the specified image file is valid or not.\n\n\n @param file_path_name: absolute path and file name of an image.\n\n\n @return: ``True`` if the image file is valid, ``False`` if the file is\n truncated or does not correspond to a supported image.\n \"\"\"\n # Image.verify is only implemented for PNG images, and it only verifies\n # the CRC checksum in the image. The only way to check from within\n # Pillow is to load the image in a try/except and check the error. If\n # as much info as possible is from the image is needed,\n # ``ImageFile.LOAD_TRUNCATED_IMAGES=True`` needs to bet set and it\n # will attempt to parse as much as possible.\n try:\n with Image.open(file_path_name) as image:\n image.load()\n except IOError:\n return False\n\n return True": 188, "def dict_to_html_attrs(dict_):\n \"\"\"\n Banana banana\n \"\"\"\n res = ' '.join('%s=\"%s\"' % (k, v) for k, v in dict_.items())\n return res": 189, "def is_binary(filename):\n \"\"\" Returns True if the file is binary\n\n \"\"\"\n with open(filename, 'rb') as fp:\n data = fp.read(1024)\n if not data:\n return False\n if b'\\0' in data:\n return True\n return False": 190, "def dict_to_querystring(dictionary):\n \"\"\"Converts a dict to a querystring suitable to be appended to a URL.\"\"\"\n s = u\"\"\n for d in dictionary.keys():\n s = unicode.format(u\"{0}{1}={2}&\", s, d, dictionary[d])\n return s[:-1]": 191, "def _check_elements_equal(lst):\n \"\"\"\n Returns true if all of the elements in the list are equal.\n \"\"\"\n assert isinstance(lst, list), \"Input value must be a list.\"\n return not lst or lst.count(lst[0]) == len(lst)": 192, "def nonull_dict(self):\n \"\"\"Like dict, but does not hold any null values.\n\n :return:\n\n \"\"\"\n return {k: v for k, v in six.iteritems(self.dict) if v and k != '_codes'}": 193, "def is_element_present(driver, selector, by=By.CSS_SELECTOR):\n \"\"\"\n Returns whether the specified element selector is present on the page.\n @Params\n driver - the webdriver object (required)\n selector - the locator that is used (required)\n by - the method to search for the locator (Default: By.CSS_SELECTOR)\n @Returns\n Boolean (is element present)\n \"\"\"\n try:\n driver.find_element(by=by, value=selector)\n return True\n except Exception:\n return False": 194, "def updateFromKwargs(self, properties, kwargs, collector, **unused):\n \"\"\"Primary entry point to turn 'kwargs' into 'properties'\"\"\"\n properties[self.name] = self.getFromKwargs(kwargs)": 195, "def is_callable(*p):\n \"\"\" True if all the args are functions and / or subroutines\n \"\"\"\n import symbols\n return all(isinstance(x, symbols.FUNCTION) for x in p)": 196, "async def disconnect(self):\n \"\"\" Disconnect from target. \"\"\"\n if not self.connected:\n return\n\n self.writer.close()\n self.reader = None\n self.writer = None": 197, "def is_dataframe(obj):\n \"\"\"\n Returns True if the given object is a Pandas Data Frame.\n\n Parameters\n ----------\n obj: instance\n The object to test whether or not is a Pandas DataFrame.\n \"\"\"\n try:\n # This is the best method of type checking\n from pandas import DataFrame\n return isinstance(obj, DataFrame)\n except ImportError:\n # Pandas is not a dependency, so this is scary\n return obj.__class__.__name__ == \"DataFrame\"": 198, "def test():\n \"\"\"Run the unit tests.\"\"\"\n import unittest\n tests = unittest.TestLoader().discover('tests')\n unittest.TextTestRunner(verbosity=2).run(tests)": 199, "def is_datetime_like(dtype):\n \"\"\"Check if a dtype is a subclass of the numpy datetime types\n \"\"\"\n return (np.issubdtype(dtype, np.datetime64) or\n np.issubdtype(dtype, np.timedelta64))": 200, "def serialize_json_string(self, value):\n \"\"\"\n Tries to load an encoded json string back into an object\n :param json_string:\n :return:\n \"\"\"\n\n # Check if the value might be a json string\n if not isinstance(value, six.string_types):\n return value\n\n # Make sure it starts with a brace\n if not value.startswith('{') or value.startswith('['):\n return value\n\n # Try to load the string\n try:\n return json.loads(value)\n except:\n return value": 201, "def is_defined(self, objtxt, force_import=False):\n \"\"\"Return True if object is defined\"\"\"\n return self.interpreter.is_defined(objtxt, force_import)": 202, "def group_exists(groupname):\n \"\"\"Check if a group exists\"\"\"\n try:\n grp.getgrnam(groupname)\n group_exists = True\n except KeyError:\n group_exists = False\n return group_exists": 203, "def sync(self, recursive=False):\n \"\"\"\n Syncs the information from this item to the tree and view.\n \"\"\"\n self.syncTree(recursive=recursive)\n self.syncView(recursive=recursive)": 204, "def is_same_shape(self, other_im, check_channels=False):\n \"\"\" Checks if two images have the same height and width (and optionally channels).\n\n Parameters\n ----------\n other_im : :obj:`Image`\n image to compare\n check_channels : bool\n whether or not to check equality of the channels\n\n Returns\n -------\n bool\n True if the images are the same shape, False otherwise\n \"\"\"\n if self.height == other_im.height and self.width == other_im.width:\n if check_channels and self.channels != other_im.channels:\n return False\n return True\n return False": 205, "def get_distance_between_two_points(self, one, two):\n \"\"\"Returns the distance between two XYPoints.\"\"\"\n dx = one.x - two.x\n dy = one.y - two.y\n return math.sqrt(dx * dx + dy * dy)": 206, "def post_process(self):\n \"\"\" Apply last 2D transforms\"\"\"\n self.image.putdata(self.pixels)\n self.image = self.image.transpose(Image.ROTATE_90)": 207, "def _not_none(items):\n \"\"\"Whether the item is a placeholder or contains a placeholder.\"\"\"\n if not isinstance(items, (tuple, list)):\n items = (items,)\n return all(item is not _none for item in items)": 208, "def delete_all_from_db():\n \"\"\"Clear the database.\n\n Used for testing and debugging.\n\n \"\"\"\n # The models.CASCADE property is set on all ForeignKey fields, so tables can\n # be deleted in any order without breaking constraints.\n for model in django.apps.apps.get_models():\n model.objects.all().delete()": 209, "def is_complex(dtype):\n \"\"\"Returns whether this is a complex floating point type.\"\"\"\n dtype = tf.as_dtype(dtype)\n if hasattr(dtype, 'is_complex'):\n return dtype.is_complex\n return np.issubdtype(np.dtype(dtype), np.complex)": 210, "def delete(build_folder):\n \"\"\"Delete build directory and all its contents.\n \"\"\"\n if _meta_.del_build in [\"on\", \"ON\"] and os.path.exists(build_folder):\n shutil.rmtree(build_folder)": 211, "def _stdin_ready_posix():\n \"\"\"Return True if there's something to read on stdin (posix version).\"\"\"\n infds, outfds, erfds = select.select([sys.stdin],[],[],0)\n return bool(infds)": 212, "def json_response(data, status=200):\n \"\"\"Return a JsonResponse. Make sure you have django installed first.\"\"\"\n from django.http import JsonResponse\n return JsonResponse(data=data, status=status, safe=isinstance(data, dict))": 213, "def _is_path(s):\n \"\"\"Return whether an object is a path.\"\"\"\n if isinstance(s, string_types):\n try:\n return op.exists(s)\n except (OSError, ValueError):\n return False\n else:\n return False": 214, "def see_doc(obj_with_doc):\n \"\"\"Copy docstring from existing object to the decorated callable.\"\"\"\n def decorator(fn):\n fn.__doc__ = obj_with_doc.__doc__\n return fn\n return decorator": 215, "def isToneCal(self):\n \"\"\"Whether the currently selected calibration stimulus type is the calibration curve\n\n :returns: boolean -- if the current combo box selection is calibration curve\n \"\"\"\n return self.ui.calTypeCmbbx.currentIndex() == self.ui.calTypeCmbbx.count() -1": 216, "def hmsToDeg(h, m, s):\n \"\"\"Convert RA hours, minutes, seconds into an angle in degrees.\"\"\"\n return h * degPerHMSHour + m * degPerHMSMin + s * degPerHMSSec": 217, "def is_date(thing):\n \"\"\"Checks if the given thing represents a date\n\n :param thing: The object to check if it is a date\n :type thing: arbitrary object\n :returns: True if we have a date object\n :rtype: bool\n \"\"\"\n # known date types\n date_types = (datetime.datetime,\n datetime.date,\n DateTime)\n return isinstance(thing, date_types)": 218, "def prepare(doc):\n \"\"\"Sets the caption_found and plot_found variables to False.\"\"\"\n doc.caption_found = False\n doc.plot_found = False\n doc.listings_counter = 0": 219, "def validate(key):\n \"\"\"Check that the key is a string or bytestring.\n\n That's the only valid type of key.\n \"\"\"\n if not isinstance(key, (str, bytes)):\n raise KeyError('Key must be of type str or bytes, found type {}'.format(type(key)))": 220, "def _normal_prompt(self):\n \"\"\"\n Flushes the prompt before requesting the input\n\n :return: The command line\n \"\"\"\n sys.stdout.write(self.__get_ps1())\n sys.stdout.flush()\n return safe_input()": 221, "def maxDepth(self, currentDepth=0):\n \"\"\"Compute the depth of the longest branch of the tree\"\"\"\n if not any((self.left, self.right)):\n return currentDepth\n result = 0\n for child in (self.left, self.right):\n if child:\n result = max(result, child.maxDepth(currentDepth + 1))\n return result": 222, "def from_rectangle(box):\n \"\"\" Create a vector randomly within the given rectangle. \"\"\"\n x = box.left + box.width * random.uniform(0, 1)\n y = box.bottom + box.height * random.uniform(0, 1)\n return Vector(x, y)": 223, "def launched():\n \"\"\"Test whether the current python environment is the correct lore env.\n\n :return: :any:`True` if the environment is launched\n :rtype: bool\n \"\"\"\n if not PREFIX:\n return False\n\n return os.path.realpath(sys.prefix) == os.path.realpath(PREFIX)": 224, "def hline(self, x, y, width, color):\n \"\"\"Draw a horizontal line up to a given length.\"\"\"\n self.rect(x, y, width, 1, color, fill=True)": 225, "def is_sequence(obj):\n \"\"\"Check if `obj` is a sequence, but not a string or bytes.\"\"\"\n return isinstance(obj, Sequence) and not (\n isinstance(obj, str) or BinaryClass.is_valid_type(obj))": 226, "def isnamedtuple(obj):\n \"\"\"Heuristic check if an object is a namedtuple.\"\"\"\n return isinstance(obj, tuple) \\\n and hasattr(obj, \"_fields\") \\\n and hasattr(obj, \"_asdict\") \\\n and callable(obj._asdict)": 227, "def starts_with_prefix_in_list(text, prefixes):\n \"\"\"\n Return True if the given string starts with one of the prefixes in the given list, otherwise\n return False.\n\n Arguments:\n text (str): Text to check for prefixes.\n prefixes (list): List of prefixes to check for.\n\n Returns:\n bool: True if the given text starts with any of the given prefixes, otherwise False.\n \"\"\"\n for prefix in prefixes:\n if text.startswith(prefix):\n return True\n return False": 228, "def print_yaml(o):\n \"\"\"Pretty print an object as YAML.\"\"\"\n print(yaml.dump(o, default_flow_style=False, indent=4, encoding='utf-8'))": 229, "def issuperset(self, other):\n \"\"\"Report whether this RangeSet contains another set.\"\"\"\n self._binary_sanity_check(other)\n return set.issuperset(self, other)": 230, "def deserialize_ndarray_npy(d):\n \"\"\"\n Deserializes a JSONified :obj:`numpy.ndarray` that was created using numpy's\n :obj:`save` function.\n\n Args:\n d (:obj:`dict`): A dictionary representation of an :obj:`ndarray` object, created\n using :obj:`numpy.save`.\n\n Returns:\n An :obj:`ndarray` object.\n \"\"\"\n with io.BytesIO() as f:\n f.write(json.loads(d['npy']).encode('latin-1'))\n f.seek(0)\n return np.load(f)": 231, "def check(text):\n \"\"\"Check the text.\"\"\"\n err = \"misc.currency\"\n msg = u\"Incorrect use of symbols in {}.\"\n\n symbols = [\n \"\\$[\\d]* ?(?:dollars|usd|us dollars)\"\n ]\n\n return existence_check(text, symbols, err, msg)": 232, "def required_header(header):\n \"\"\"Function that verify if the header parameter is a essential header\n\n :param header: A string represented a header\n :returns: A boolean value that represent if the header is required\n \"\"\"\n if header in IGNORE_HEADERS:\n return False\n\n if header.startswith('HTTP_') or header == 'CONTENT_TYPE':\n return True\n\n return False": 233, "def _map_table_name(self, model_names):\n \"\"\"\n Pre foregin_keys potrbejeme pre z nazvu tabulky zistit class,\n tak si to namapujme\n \"\"\"\n\n for model in model_names:\n if isinstance(model, tuple):\n model = model[0]\n\n try:\n model_cls = getattr(self.models, model)\n self.table_to_class[class_mapper(model_cls).tables[0].name] = model\n except AttributeError:\n pass": 234, "def service_available(service_name):\n \"\"\"Determine whether a system service is available\"\"\"\n try:\n subprocess.check_output(\n ['service', service_name, 'status'],\n stderr=subprocess.STDOUT).decode('UTF-8')\n except subprocess.CalledProcessError as e:\n return b'unrecognized service' not in e.output\n else:\n return True": 235, "def keys(self):\n \"\"\"Return a list of all keys in the dictionary.\n\n Returns:\n list of str: [key1,key2,...,keyN]\n \"\"\"\n all_keys = [k.decode('utf-8') for k,v in self.rdb.hgetall(self.session_hash).items()]\n return all_keys": 236, "def _valid_other_type(x, types):\n \"\"\"\n Do all elements of x have a type from types?\n \"\"\"\n return all(any(isinstance(el, t) for t in types) for el in np.ravel(x))": 237, "def escape_tex(value):\n \"\"\"\n Make text tex safe\n \"\"\"\n newval = value\n for pattern, replacement in LATEX_SUBS:\n newval = pattern.sub(replacement, newval)\n return newval": 238, "def _pip_exists(self):\n \"\"\"Returns True if pip exists inside the virtual environment. Can be\n used as a naive way to verify that the environment is installed.\"\"\"\n return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))": 239, "def update_index(index):\n \"\"\"Re-index every document in a named index.\"\"\"\n logger.info(\"Updating search index: '%s'\", index)\n client = get_client()\n responses = []\n for model in get_index_models(index):\n logger.info(\"Updating search index model: '%s'\", model.search_doc_type)\n objects = model.objects.get_search_queryset(index).iterator()\n actions = bulk_actions(objects, index=index, action=\"index\")\n response = helpers.bulk(client, actions, chunk_size=get_setting(\"chunk_size\"))\n responses.append(response)\n return responses": 240, "def hidden_cursor(self):\n \"\"\"Return a context manager that hides the cursor while inside it and\n makes it visible on leaving.\"\"\"\n self.stream.write(self.hide_cursor)\n try:\n yield\n finally:\n self.stream.write(self.normal_cursor)": 241, "def copy(doc, dest, src):\n \"\"\"Copy element from sequence, member from mapping.\n\n :param doc: the document base\n :param dest: the destination\n :type dest: Pointer\n :param src: the source\n :type src: Pointer\n :return: the new object\n \"\"\"\n\n return Target(doc).copy(dest, src).document": 242, "def is_string(val):\n \"\"\"Determines whether the passed value is a string, safe for 2/3.\"\"\"\n try:\n basestring\n except NameError:\n return isinstance(val, str)\n return isinstance(val, basestring)": 243, "def read_from_file(file_path, encoding=\"utf-8\"):\n \"\"\"\n Read helper method\n\n :type file_path: str|unicode\n :type encoding: str|unicode\n :rtype: str|unicode\n \"\"\"\n with codecs.open(file_path, \"r\", encoding) as f:\n return f.read()": 244, "def _is_root():\n \"\"\"Checks if the user is rooted.\"\"\"\n import os\n import ctypes\n try:\n return os.geteuid() == 0\n except AttributeError:\n return ctypes.windll.shell32.IsUserAnAdmin() != 0\n return False": 245, "def describe_enum_value(enum_value):\n \"\"\"Build descriptor for Enum instance.\n\n Args:\n enum_value: Enum value to provide descriptor for.\n\n Returns:\n Initialized EnumValueDescriptor instance describing the Enum instance.\n \"\"\"\n enum_value_descriptor = EnumValueDescriptor()\n enum_value_descriptor.name = six.text_type(enum_value.name)\n enum_value_descriptor.number = enum_value.number\n return enum_value_descriptor": 246, "def user_in_all_groups(user, groups):\n \"\"\"Returns True if the given user is in all given groups\"\"\"\n return user_is_superuser(user) or all(user_in_group(user, group) for group in groups)": 247, "def items(self):\n \"\"\"Return a list of the (name, value) pairs of the enum.\n\n These are returned in the order they were defined in the .proto file.\n \"\"\"\n return [(value_descriptor.name, value_descriptor.number)\n for value_descriptor in self._enum_type.values]": 248, "def n_choose_k(n, k):\n \"\"\" get the number of quartets as n-choose-k. This is used\n in equal splits to decide whether a split should be exhaustively sampled\n or randomly sampled. Edges near tips can be exhaustive while highly nested\n edges probably have too many quartets\n \"\"\"\n return int(reduce(MUL, (Fraction(n-i, i+1) for i in range(k)), 1))": 249, "def items(cls):\n \"\"\"\n All values for this enum\n :return: list of tuples\n\n \"\"\"\n return [\n cls.PRECIPITATION,\n cls.WIND,\n cls.TEMPERATURE,\n cls.PRESSURE\n ]": 250, "def revnet_164_cifar():\n \"\"\"Tiny hparams suitable for CIFAR/etc.\"\"\"\n hparams = revnet_cifar_base()\n hparams.bottleneck = True\n hparams.num_channels = [16, 32, 64]\n hparams.num_layers_per_block = [8, 8, 8]\n return hparams": 251, "def mtf_image_transformer_cifar_mp_4x():\n \"\"\"Data parallel CIFAR parameters.\"\"\"\n hparams = mtf_image_transformer_base_cifar()\n hparams.mesh_shape = \"model:4;batch:8\"\n hparams.layout = \"batch:batch;d_ff:model;heads:model\"\n hparams.batch_size = 32\n hparams.num_heads = 8\n hparams.d_ff = 8192\n return hparams": 252, "def image_set_aspect(aspect=1.0, axes=\"gca\"):\n \"\"\"\n sets the aspect ratio of the current zoom level of the imshow image\n \"\"\"\n if axes is \"gca\": axes = _pylab.gca()\n\n e = axes.get_images()[0].get_extent()\n axes.set_aspect(abs((e[1]-e[0])/(e[3]-e[2]))/aspect)": 253, "def Flush(self):\n \"\"\"Flush all items from cache.\"\"\"\n while self._age:\n node = self._age.PopLeft()\n self.KillObject(node.data)\n\n self._hash = dict()": 254, "def _propagate_mean(mean, linop, dist):\n \"\"\"Propagate a mean through linear Gaussian transformation.\"\"\"\n return linop.matmul(mean) + dist.mean()[..., tf.newaxis]": 255, "def invalidate_cache(cpu, address, size):\n \"\"\" remove decoded instruction from instruction cache \"\"\"\n cache = cpu.instruction_cache\n for offset in range(size):\n if address + offset in cache:\n del cache[address + offset]": 256, "def convertToBool():\n \"\"\" Convert a byte value to boolean (0 or 1) if\n the global flag strictBool is True\n \"\"\"\n if not OPTIONS.strictBool.value:\n return []\n\n REQUIRES.add('strictbool.asm')\n\n result = []\n result.append('pop af')\n result.append('call __NORMALIZE_BOOLEAN')\n result.append('push af')\n\n return result": 257, "def normalize(x, min_value, max_value):\n \"\"\"Normalize value between min and max values.\n It also clips the values, so that you cannot have values higher or lower\n than 0 - 1.\"\"\"\n x = (x - min_value) / (max_value - min_value)\n return clip(x, 0, 1)": 258, "def prepare_for_reraise(error, exc_info=None):\n \"\"\"Prepares the exception for re-raising with reraise method.\n\n This method attaches type and traceback info to the error object\n so that reraise can properly reraise it using this info.\n\n \"\"\"\n if not hasattr(error, \"_type_\"):\n if exc_info is None:\n exc_info = sys.exc_info()\n error._type_ = exc_info[0]\n error._traceback = exc_info[2]\n return error": 259, "def close_all_but_this(self):\n \"\"\"Close all files but the current one\"\"\"\n self.close_all_right()\n for i in range(0, self.get_stack_count()-1 ):\n self.close_file(0)": 260, "def eval_in_system_namespace(self, exec_str):\n \"\"\"\n Get Callable for specified string (for GUI-based editing)\n \"\"\"\n ns = self.cmd_namespace\n try:\n return eval(exec_str, ns)\n except Exception as e:\n self.logger.warning('Could not execute %s, gave error %s', exec_str, e)\n return None": 261, "def _close_socket(self):\n \"\"\"Shutdown and close the Socket.\n\n :return:\n \"\"\"\n try:\n self.socket.shutdown(socket.SHUT_RDWR)\n except (OSError, socket.error):\n pass\n self.socket.close()": 262, "def exec_function(ast, globals_map):\n \"\"\"Execute a python code object in the given environment.\n\n Args:\n globals_map: Dictionary to use as the globals context.\n Returns:\n locals_map: Dictionary of locals from the environment after execution.\n \"\"\"\n locals_map = globals_map\n exec ast in globals_map, locals_map\n return locals_map": 263, "def cleanup(self, app):\n \"\"\"Close all connections.\"\"\"\n if hasattr(self.database.obj, 'close_all'):\n self.database.close_all()": 264, "def get_unicode_str(obj):\n \"\"\"Makes sure obj is a unicode string.\"\"\"\n if isinstance(obj, six.text_type):\n return obj\n if isinstance(obj, six.binary_type):\n return obj.decode(\"utf-8\", errors=\"ignore\")\n return six.text_type(obj)": 265, "def exp_fit_fun(x, a, tau, c):\n \"\"\"Function used to fit the exponential decay.\"\"\"\n # pylint: disable=invalid-name\n return a * np.exp(-x / tau) + c": 266, "def _findNearest(arr, value):\n \"\"\" Finds the value in arr that value is closest to\n \"\"\"\n arr = np.array(arr)\n # find nearest value in array\n idx = (abs(arr-value)).argmin()\n return arr[idx]": 267, "def gauss_pdf(x, mu, sigma):\n \"\"\"Normalized Gaussian\"\"\"\n return 1 / np.sqrt(2 * np.pi) / sigma * np.exp(-(x - mu) ** 2 / 2. / sigma ** 2)": 268, "def remove_examples_all():\n \"\"\"remove arduino/examples/all directory.\n\n :rtype: None\n\n \"\"\"\n d = examples_all_dir()\n if d.exists():\n log.debug('remove %s', d)\n d.rmtree()\n else:\n log.debug('nothing to remove: %s', d)": 269, "def resources(self):\n \"\"\"Retrieve contents of each page of PDF\"\"\"\n return [self.pdf.getPage(i) for i in range(self.pdf.getNumPages())]": 270, "def cli_command_quit(self, msg):\n \"\"\"\\\n kills the child and exits\n \"\"\"\n if self.state == State.RUNNING and self.sprocess and self.sprocess.proc:\n self.sprocess.proc.kill()\n else:\n sys.exit(0)": 271, "def dot(self, w):\n \"\"\"Return the dotproduct between self and another vector.\"\"\"\n\n return sum([x * y for x, y in zip(self, w)])": 272, "def printc(cls, txt, color=colors.red):\n \"\"\"Print in color.\"\"\"\n print(cls.color_txt(txt, color))": 273, "def need_update(a, b):\n \"\"\"\n Check if file a is newer than file b and decide whether or not to update\n file b. Can generalize to two lists.\n \"\"\"\n a = listify(a)\n b = listify(b)\n\n return any((not op.exists(x)) for x in b) or \\\n all((os.stat(x).st_size == 0 for x in b)) or \\\n any(is_newer_file(x, y) for x in a for y in b)": 274, "def lengths( self ):\n \"\"\"\n The cell lengths.\n\n Args:\n None\n\n Returns:\n (np.array(a,b,c)): The cell lengths.\n \"\"\"\n return( np.array( [ math.sqrt( sum( row**2 ) ) for row in self.matrix ] ) )": 275, "def random_str(size=10):\n \"\"\"\n create random string of selected size\n\n :param size: int, length of the string\n :return: the string\n \"\"\"\n return ''.join(random.choice(string.ascii_lowercase) for _ in range(size))": 276, "def get_table_columns(dbconn, tablename):\n \"\"\"\n Return a list of tuples specifying the column name and type\n \"\"\"\n cur = dbconn.cursor()\n cur.execute(\"PRAGMA table_info('%s');\" % tablename)\n info = cur.fetchall()\n cols = [(i[1], i[2]) for i in info]\n return cols": 277, "def remove_duplicates(lst):\n \"\"\"\n Emulate what a Python ``set()`` does, but keeping the element's order.\n \"\"\"\n dset = set()\n return [l for l in lst if l not in dset and not dset.add(l)]": 278, "def _on_select(self, *args):\n \"\"\"\n Function bound to event of selection in the Combobox, calls callback if callable\n \n :param args: Tkinter event\n \"\"\"\n if callable(self.__callback):\n self.__callback(self.selection)": 279, "def fft_spectrum(frames, fft_points=512):\n \"\"\"This function computes the one-dimensional n-point discrete Fourier\n Transform (DFT) of a real-valued array by means of an efficient algorithm\n called the Fast Fourier Transform (FFT). Please refer to\n https://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.rfft.html\n for further details.\n\n Args:\n frames (array): The frame array in which each row is a frame.\n fft_points (int): The length of FFT. If fft_length is greater than frame_len, the frames will be zero-padded.\n\n Returns:\n array: The fft spectrum.\n If frames is an num_frames x sample_per_frame matrix, output\n will be num_frames x FFT_LENGTH.\n \"\"\"\n SPECTRUM_VECTOR = np.fft.rfft(frames, n=fft_points, axis=-1, norm=None)\n return np.absolute(SPECTRUM_VECTOR)": 280, "def isetdiff_flags(list1, list2):\n \"\"\"\n move to util_iter\n \"\"\"\n set2 = set(list2)\n return (item not in set2 for item in list1)": 281, "def guess_file_type(kind, filepath=None, youtube_id=None, web_url=None, encoding=None):\n \"\"\" guess_file_class: determines what file the content is\n Args:\n filepath (str): filepath of file to check\n Returns: string indicating file's class\n \"\"\"\n if youtube_id:\n return FileTypes.YOUTUBE_VIDEO_FILE\n elif web_url:\n return FileTypes.WEB_VIDEO_FILE\n elif encoding:\n return FileTypes.BASE64_FILE\n else:\n ext = os.path.splitext(filepath)[1][1:].lower()\n if kind in FILE_TYPE_MAPPING and ext in FILE_TYPE_MAPPING[kind]:\n return FILE_TYPE_MAPPING[kind][ext]\n return None": 282, "def is_same_dict(d1, d2):\n \"\"\"Test two dictionary is equal on values. (ignore order)\n \"\"\"\n for k, v in d1.items():\n if isinstance(v, dict):\n is_same_dict(v, d2[k])\n else:\n assert d1[k] == d2[k]\n\n for k, v in d2.items():\n if isinstance(v, dict):\n is_same_dict(v, d1[k])\n else:\n assert d1[k] == d2[k]": 283, "def file_writelines_flush_sync(path, lines):\n \"\"\"\n Fill file at @path with @lines then flush all buffers\n (Python and system buffers)\n \"\"\"\n fp = open(path, 'w')\n try:\n fp.writelines(lines)\n flush_sync_file_object(fp)\n finally:\n fp.close()": 284, "def make_kind_check(python_types, numpy_kind):\n \"\"\"\n Make a function that checks whether a scalar or array is of a given kind\n (e.g. float, int, datetime, timedelta).\n \"\"\"\n def check(value):\n if hasattr(value, 'dtype'):\n return value.dtype.kind == numpy_kind\n return isinstance(value, python_types)\n return check": 285, "def file_empty(fp):\n \"\"\"Determine if a file is empty or not.\"\"\"\n # for python 2 we need to use a homemade peek()\n if six.PY2:\n contents = fp.read()\n fp.seek(0)\n return not bool(contents)\n\n else:\n return not fp.peek()": 286, "def all_equal(arg1,arg2):\n \"\"\"\n Return a single boolean for arg1==arg2, even for numpy arrays\n using element-wise comparison.\n\n Uses all(arg1==arg2) for sequences, and arg1==arg2 otherwise.\n\n If both objects have an '_infinitely_iterable' attribute, they are\n not be zipped together and are compared directly instead.\n \"\"\"\n if all(hasattr(el, '_infinitely_iterable') for el in [arg1,arg2]):\n return arg1==arg2\n try:\n return all(a1 == a2 for a1, a2 in zip(arg1, arg2))\n except TypeError:\n return arg1==arg2": 287, "def get_file_size(filename):\n \"\"\"\n Get the file size of a given file\n\n :param filename: string: pathname of a file\n :return: human readable filesize\n \"\"\"\n if os.path.isfile(filename):\n return convert_size(os.path.getsize(filename))\n return None": 288, "def _check_for_int(x):\n \"\"\"\n This is a compatibility function that takes a C{float} and converts it to an\n C{int} if the values are equal.\n \"\"\"\n try:\n y = int(x)\n except (OverflowError, ValueError):\n pass\n else:\n # There is no way in AMF0 to distinguish between integers and floats\n if x == x and y == x:\n return y\n\n return x": 289, "def fill_form(form, data):\n \"\"\"Prefill form with data.\n\n :param form: The form to fill.\n :param data: The data to insert in the form.\n :returns: A pre-filled form.\n \"\"\"\n for (key, value) in data.items():\n if hasattr(form, key):\n if isinstance(value, dict):\n fill_form(getattr(form, key), value)\n else:\n getattr(form, key).data = value\n return form": 290, "def check_clang_apply_replacements_binary(args):\n \"\"\"Checks if invoking supplied clang-apply-replacements binary works.\"\"\"\n try:\n subprocess.check_call([args.clang_apply_replacements_binary, '--version'])\n except:\n print('Unable to run clang-apply-replacements. Is clang-apply-replacements '\n 'binary correctly specified?', file=sys.stderr)\n traceback.print_exc()\n sys.exit(1)": 291, "def _maybe_fill(arr, fill_value=np.nan):\n \"\"\"\n if we have a compatible fill_value and arr dtype, then fill\n \"\"\"\n if _isna_compat(arr, fill_value):\n arr.fill(fill_value)\n return arr": 292, "def extract_alzip (archive, compression, cmd, verbosity, interactive, outdir):\n \"\"\"Extract a ALZIP archive.\"\"\"\n return [cmd, '-d', outdir, archive]": 293, "def get_lons_from_cartesian(x__, y__):\n \"\"\"Get longitudes from cartesian coordinates.\n \"\"\"\n return rad2deg(arccos(x__ / sqrt(x__ ** 2 + y__ ** 2))) * sign(y__)": 294, "def filter_(stream_spec, filter_name, *args, **kwargs):\n \"\"\"Alternate name for ``filter``, so as to not collide with the\n built-in python ``filter`` operator.\n \"\"\"\n return filter(stream_spec, filter_name, *args, **kwargs)": 295, "def find_lt(a, x):\n \"\"\"Find rightmost value less than x.\"\"\"\n i = bs.bisect_left(a, x)\n if i: return i - 1\n raise ValueError": 296, "def get_stationary_distribution(self):\n \"\"\"Compute the stationary distribution of states.\n \"\"\"\n # The stationary distribution is proportional to the left-eigenvector\n # associated with the largest eigenvalue (i.e., 1) of the transition\n # matrix.\n check_is_fitted(self, \"transmat_\")\n eigvals, eigvecs = np.linalg.eig(self.transmat_.T)\n eigvec = np.real_if_close(eigvecs[:, np.argmax(eigvals)])\n return eigvec / eigvec.sum()": 297, "def apply_fit(xy,coeffs):\n \"\"\" Apply the coefficients from a linear fit to\n an array of x,y positions.\n\n The coeffs come from the 'coeffs' member of the\n 'fit_arrays()' output.\n \"\"\"\n x_new = coeffs[0][2] + coeffs[0][0]*xy[:,0] + coeffs[0][1]*xy[:,1]\n y_new = coeffs[1][2] + coeffs[1][0]*xy[:,0] + coeffs[1][1]*xy[:,1]\n\n return x_new,y_new": 298, "def _tf_squared_euclidean(X, Y):\n \"\"\"Squared Euclidean distance between the rows of `X` and `Y`.\n \"\"\"\n return tf.reduce_sum(tf.pow(tf.subtract(X, Y), 2), axis=1)": 299, "def euclidean(x, y):\n \"\"\"Standard euclidean distance.\n\n ..math::\n D(x, y) = \\sqrt{\\sum_i (x_i - y_i)^2}\n \"\"\"\n result = 0.0\n for i in range(x.shape[0]):\n result += (x[i] - y[i]) ** 2\n return np.sqrt(result)": 300, "def create_table_from_fits(fitsfile, hduname, colnames=None):\n \"\"\"Memory efficient function for loading a table from a FITS\n file.\"\"\"\n\n if colnames is None:\n return Table.read(fitsfile, hduname)\n\n cols = []\n with fits.open(fitsfile, memmap=True) as h:\n for k in colnames:\n data = h[hduname].data.field(k)\n cols += [Column(name=k, data=data)]\n return Table(cols)": 301, "def _gcd_array(X):\n \"\"\"\n Return the largest real value h such that all elements in x are integer\n multiples of h.\n \"\"\"\n greatest_common_divisor = 0.0\n for x in X:\n greatest_common_divisor = _gcd(greatest_common_divisor, x)\n\n return greatest_common_divisor": 302, "def lint(args):\n \"\"\"Run lint checks using flake8.\"\"\"\n application = get_current_application()\n if not args:\n args = [application.name, 'tests']\n args = ['flake8'] + list(args)\n run.main(args, standalone_mode=False)": 303, "def torecarray(*args, **kwargs):\n \"\"\"\n Convenient shorthand for ``toarray(*args, **kwargs).view(np.recarray)``.\n\n \"\"\"\n\n import numpy as np\n return toarray(*args, **kwargs).view(np.recarray)": 304, "def _type_bool(label,default=False):\n \"\"\"Shortcut fot boolean like fields\"\"\"\n return label, abstractSearch.nothing, abstractRender.boolen, default": 305, "def join_cols(cols):\n \"\"\"Join list of columns into a string for a SQL query\"\"\"\n return \", \".join([i for i in cols]) if isinstance(cols, (list, tuple, set)) else cols": 306, "def parse_form(self, req, name, field):\n \"\"\"Pull a form value from the request.\"\"\"\n return core.get_value(req.POST, name, field)": 307, "def type_converter(text):\n \"\"\" I convert strings into integers, floats, and strings! \"\"\"\n if text.isdigit():\n return int(text), int\n\n try:\n return float(text), float\n except ValueError:\n return text, STRING_TYPE": 308, "def cors_header(func):\n \"\"\" @cors_header decorator adds CORS headers \"\"\"\n\n @wraps(func)\n def wrapper(self, request, *args, **kwargs):\n res = func(self, request, *args, **kwargs)\n request.setHeader('Access-Control-Allow-Origin', '*')\n request.setHeader('Access-Control-Allow-Headers', 'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With')\n return res\n\n return wrapper": 309, "def handleFlaskPostRequest(flaskRequest, endpoint):\n \"\"\"\n Handles the specified flask request for one of the POST URLS\n Invokes the specified endpoint to generate a response.\n \"\"\"\n if flaskRequest.method == \"POST\":\n return handleHttpPost(flaskRequest, endpoint)\n elif flaskRequest.method == \"OPTIONS\":\n return handleHttpOptions()\n else:\n raise exceptions.MethodNotAllowedException()": 310, "def python_mime(fn):\n \"\"\"\n Decorator, which adds correct MIME type for python source to the decorated\n bottle API function.\n \"\"\"\n @wraps(fn)\n def python_mime_decorator(*args, **kwargs):\n response.content_type = \"text/x-python\"\n\n return fn(*args, **kwargs)\n\n return python_mime_decorator": 311, "def _spawn_kafka_consumer_thread(self):\n \"\"\"Spawns a kafka continuous consumer thread\"\"\"\n self.logger.debug(\"Spawn kafka consumer thread\"\"\")\n self._consumer_thread = Thread(target=self._consumer_loop)\n self._consumer_thread.setDaemon(True)\n self._consumer_thread.start()": 312, "def flatpages_link_list(request):\n \"\"\"\n Returns a HttpResponse whose content is a Javascript file representing a\n list of links to flatpages.\n \"\"\"\n from django.contrib.flatpages.models import FlatPage\n link_list = [(page.title, page.url) for page in FlatPage.objects.all()]\n return render_to_link_list(link_list)": 313, "def values(self):\n \"\"\"Gets the user enter max and min values of where the \n raster points should appear on the y-axis\n\n :returns: (float, float) -- (min, max) y-values to bound the raster plot by\n \"\"\"\n lower = float(self.lowerSpnbx.value())\n upper = float(self.upperSpnbx.value())\n return (lower, upper)": 314, "def sqlmany(self, stringname, *args):\n \"\"\"Wrapper for executing many SQL calls on my connection.\n\n First arg is the name of a query, either a key in the\n precompiled JSON or a method name in\n ``allegedb.alchemy.Alchemist``. Remaining arguments should be\n tuples of argument sequences to be passed to the query.\n\n \"\"\"\n if hasattr(self, 'alchemist'):\n return getattr(self.alchemist.many, stringname)(*args)\n s = self.strings[stringname]\n return self.connection.cursor().executemany(s, args)": 315, "def convolve_gaussian_2d(image, gaussian_kernel_1d):\n \"\"\"Convolve 2d gaussian.\"\"\"\n result = scipy.ndimage.filters.correlate1d(\n image, gaussian_kernel_1d, axis=0)\n result = scipy.ndimage.filters.correlate1d(\n result, gaussian_kernel_1d, axis=1)\n return result": 316, "def render_template_string(source, **context):\n \"\"\"Renders a template from the given template source string\n with the given context.\n\n :param source: the sourcecode of the template to be\n rendered\n :param context: the variables that should be available in the\n context of the template.\n \"\"\"\n ctx = _app_ctx_stack.top\n ctx.app.update_template_context(context)\n return _render(ctx.app.jinja_env.from_string(source),\n context, ctx.app)": 317, "def asynchronous(function, event):\n \"\"\"\n Runs the function asynchronously taking care of exceptions.\n \"\"\"\n thread = Thread(target=synchronous, args=(function, event))\n thread.daemon = True\n thread.start()": 318, "def default_static_path():\n \"\"\"\n Return the path to the javascript bundle\n \"\"\"\n fdir = os.path.dirname(__file__)\n return os.path.abspath(os.path.join(fdir, '../assets/'))": 319, "def count_list(the_list):\n \"\"\"\n Generates a count of the number of times each unique item appears in a list\n \"\"\"\n count = the_list.count\n result = [(item, count(item)) for item in set(the_list)]\n result.sort()\n return result": 320, "def round_to_float(number, precision):\n \"\"\"Round a float to a precision\"\"\"\n rounded = Decimal(str(floor((number + precision / 2) // precision))\n ) * Decimal(str(precision))\n return float(rounded)": 321, "def _calc_overlap_count(\n markers1: dict,\n markers2: dict,\n):\n \"\"\"Calculate overlap count between the values of two dictionaries\n\n Note: dict values must be sets\n \"\"\"\n overlaps=np.zeros((len(markers1), len(markers2)))\n\n j=0\n for marker_group in markers1:\n tmp = [len(markers2[i].intersection(markers1[marker_group])) for i in markers2.keys()]\n overlaps[j,:] = tmp\n j += 1\n\n return overlaps": 322, "def intround(value):\n \"\"\"Given a float returns a rounded int. Should give the same result on\n both Py2/3\n \"\"\"\n\n return int(decimal.Decimal.from_float(\n value).to_integral_value(decimal.ROUND_HALF_EVEN))": 323, "def focusInEvent(self, event):\n \"\"\"Reimplement Qt method to send focus change notification\"\"\"\n self.focus_changed.emit()\n return super(PageControlWidget, self).focusInEvent(event)": 324, "def _accumulate(sequence, func):\n \"\"\"\n Python2 accumulate implementation taken from\n https://docs.python.org/3/library/itertools.html#itertools.accumulate\n \"\"\"\n iterator = iter(sequence)\n total = next(iterator)\n yield total\n for element in iterator:\n total = func(total, element)\n yield total": 325, "def iter_finds(regex_obj, s):\n \"\"\"Generate all matches found within a string for a regex and yield each match as a string\"\"\"\n if isinstance(regex_obj, str):\n for m in re.finditer(regex_obj, s):\n yield m.group()\n else:\n for m in regex_obj.finditer(s):\n yield m.group()": 326, "def a2s(a):\n \"\"\"\n convert 3,3 a matrix to 6 element \"s\" list (see Tauxe 1998)\n \"\"\"\n s = np.zeros((6,), 'f') # make the a matrix\n for i in range(3):\n s[i] = a[i][i]\n s[3] = a[0][1]\n s[4] = a[1][2]\n s[5] = a[0][2]\n return s": 327, "def concat(cls, iterables):\n \"\"\"\n Similar to #itertools.chain.from_iterable().\n \"\"\"\n\n def generator():\n for it in iterables:\n for element in it:\n yield element\n return cls(generator())": 328, "def format_result(input):\n \"\"\"From: http://stackoverflow.com/questions/13062300/convert-a-dict-to-sorted-dict-in-python\n \"\"\"\n items = list(iteritems(input))\n return OrderedDict(sorted(items, key=lambda x: x[0]))": 329, "def bulk_query(self, query, *multiparams):\n \"\"\"Bulk insert or update.\"\"\"\n\n with self.get_connection() as conn:\n conn.bulk_query(query, *multiparams)": 330, "def Trie(S):\n \"\"\"\n :param S: set of words\n :returns: trie containing all words from S\n :complexity: linear in total word sizes from S\n \"\"\"\n T = None\n for w in S:\n T = add(T, w)\n return T": 331, "def __set__(self, instance, value):\n \"\"\" Set a related object for an instance. \"\"\"\n\n self.map[id(instance)] = (weakref.ref(instance), value)": 332, "def recarray(self):\n \"\"\"Returns data as :class:`numpy.recarray`.\"\"\"\n return numpy.rec.fromrecords(self.records, names=self.names)": 333, "def go_to_background():\n \"\"\" Daemonize the running process. \"\"\"\n try:\n if os.fork():\n sys.exit()\n except OSError as errmsg:\n LOGGER.error('Fork failed: {0}'.format(errmsg))\n sys.exit('Fork failed')": 334, "def generate_unique_host_id():\n \"\"\"Generate a unique ID, that is somewhat guaranteed to be unique among all\n instances running at the same time.\"\"\"\n host = \".\".join(reversed(socket.gethostname().split(\".\")))\n pid = os.getpid()\n return \"%s.%d\" % (host, pid)": 335, "def compress(self, data_list):\n \"\"\"\n Return the cleaned_data of the form, everything should already be valid\n \"\"\"\n data = {}\n if data_list:\n return dict(\n (f.name, data_list[i]) for i, f in enumerate(self.form))\n return data": 336, "def init_db():\n \"\"\"\n Drops and re-creates the SQL schema\n \"\"\"\n db.drop_all()\n db.configure_mappers()\n db.create_all()\n db.session.commit()": 337, "def safe_format(s, **kwargs):\n \"\"\"\n :type s str\n \"\"\"\n return string.Formatter().vformat(s, (), defaultdict(str, **kwargs))": 338, "def _init_unique_sets(self):\n \"\"\"Initialise sets used for uniqueness checking.\"\"\"\n\n ks = dict()\n for t in self._unique_checks:\n key = t[0]\n ks[key] = set() # empty set\n return ks": 339, "def straight_line_show(title, length=100, linestyle=\"=\", pad=0):\n \"\"\"Print a formatted straight line.\n \"\"\"\n print(StrTemplate.straight_line(\n title=title, length=length, linestyle=linestyle, pad=pad))": 340, "def make_executable(script_path):\n \"\"\"Make `script_path` executable.\n\n :param script_path: The file to change\n \"\"\"\n status = os.stat(script_path)\n os.chmod(script_path, status.st_mode | stat.S_IEXEC)": 341, "def make_html_code( self, lines ):\n \"\"\" convert a code sequence to HTML \"\"\"\n line = code_header + '\\n'\n for l in lines:\n line = line + html_quote( l ) + '\\n'\n\n return line + code_footer": 342, "def cross_product_matrix(vec):\n \"\"\"Returns a 3x3 cross-product matrix from a 3-element vector.\"\"\"\n return np.array([[0, -vec[2], vec[1]],\n [vec[2], 0, -vec[0]],\n [-vec[1], vec[0], 0]])": 343, "def index_nearest(value, array):\n \"\"\"\n expects a _n.array\n returns the global minimum of (value-array)^2\n \"\"\"\n\n a = (array-value)**2\n return index(a.min(), a)": 344, "def main(args=sys.argv):\n \"\"\"\n main entry point for the jardiff CLI\n \"\"\"\n\n parser = create_optparser(args[0])\n return cli(parser.parse_args(args[1:]))": 345, "def free(self):\n \"\"\"Free the underlying C array\"\"\"\n if self._ptr is None:\n return\n Gauged.array_free(self.ptr)\n FloatArray.ALLOCATIONS -= 1\n self._ptr = None": 346, "def from_points(cls, list_of_lists):\n \"\"\"\n Creates a *Polygon* instance out of a list of lists, each sublist being populated with\n `pyowm.utils.geo.Point` instances\n :param list_of_lists: list\n :type: list_of_lists: iterable_of_polygons\n :returns: a *Polygon* instance\n\n \"\"\"\n result = []\n for l in list_of_lists:\n curve = []\n for point in l:\n curve.append((point.lon, point.lat))\n result.append(curve)\n return Polygon(result)": 347, "def connect():\n \"\"\"Connect to FTP server, login and return an ftplib.FTP instance.\"\"\"\n ftp_class = ftplib.FTP if not SSL else ftplib.FTP_TLS\n ftp = ftp_class(timeout=TIMEOUT)\n ftp.connect(HOST, PORT)\n ftp.login(USER, PASSWORD)\n if SSL:\n ftp.prot_p() # secure data connection\n return ftp": 348, "def tmpfile(prefix, direc):\n \"\"\"Returns the path to a newly created temporary file.\"\"\"\n return tempfile.mktemp(prefix=prefix, suffix='.pdb', dir=direc)": 349, "def connect(host, port, username, password):\n \"\"\"Connect and login to an FTP server and return ftplib.FTP object.\"\"\"\n # Instantiate ftplib client\n session = ftplib.FTP()\n\n # Connect to host without auth\n session.connect(host, port)\n\n # Authenticate connection\n session.login(username, password)\n return session": 350, "def unique_list(lst):\n \"\"\"Make a list unique, retaining order of initial appearance.\"\"\"\n uniq = []\n for item in lst:\n if item not in uniq:\n uniq.append(item)\n return uniq": 351, "def All(sequence):\n \"\"\"\n :param sequence: Any sequence whose elements can be evaluated as booleans.\n :returns: true if all elements of the sequence satisfy True and x.\n \"\"\"\n return bool(reduce(lambda x, y: x and y, sequence, True))": 352, "def zero_state(self, batch_size):\n \"\"\" Initial state of the network \"\"\"\n return torch.zeros(batch_size, self.state_dim, dtype=torch.float32)": 353, "def _fullname(o):\n \"\"\"Return the fully-qualified name of a function.\"\"\"\n return o.__module__ + \".\" + o.__name__ if o.__module__ else o.__name__": 354, "def create_index(config):\n \"\"\"Create the root index.\"\"\"\n filename = pathlib.Path(config.cache_path) / \"index.json\"\n index = {\"version\": __version__}\n with open(filename, \"w\") as out:\n out.write(json.dumps(index, indent=2))": 355, "def issorted(list_, op=operator.le):\n \"\"\"\n Determines if a list is sorted\n\n Args:\n list_ (list):\n op (func): sorted operation (default=operator.le)\n\n Returns:\n bool : True if the list is sorted\n \"\"\"\n return all(op(list_[ix], list_[ix + 1]) for ix in range(len(list_) - 1))": 356, "def is_valid(number):\n \"\"\"determines whether the card number is valid.\"\"\"\n n = str(number)\n if not n.isdigit():\n return False\n return int(n[-1]) == get_check_digit(n[:-1])": 357, "def us2mc(string):\n \"\"\"Transform an underscore_case string to a mixedCase string\"\"\"\n return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), string)": 358, "def csv2yaml(in_file, out_file=None):\n \"\"\"Convert a CSV SampleSheet to YAML run_info format.\n \"\"\"\n if out_file is None:\n out_file = \"%s.yaml\" % os.path.splitext(in_file)[0]\n barcode_ids = _generate_barcode_ids(_read_input_csv(in_file))\n lanes = _organize_lanes(_read_input_csv(in_file), barcode_ids)\n with open(out_file, \"w\") as out_handle:\n out_handle.write(yaml.safe_dump(lanes, default_flow_style=False))\n return out_file": 359, "def get_average_length_of_string(strings):\n \"\"\"Computes average length of words\n\n :param strings: list of words\n :return: Average length of word on list\n \"\"\"\n if not strings:\n return 0\n\n return sum(len(word) for word in strings) / len(strings)": 360, "def cumsum(inlist):\n \"\"\"\nReturns a list consisting of the cumulative sum of the items in the\npassed list.\n\nUsage: lcumsum(inlist)\n\"\"\"\n newlist = copy.deepcopy(inlist)\n for i in range(1, len(newlist)):\n newlist[i] = newlist[i] + newlist[i - 1]\n return newlist": 361, "def good(txt):\n \"\"\"Print, emphasized 'good', the given 'txt' message\"\"\"\n\n print(\"%s# %s%s%s\" % (PR_GOOD_CC, get_time_stamp(), txt, PR_NC))\n sys.stdout.flush()": 362, "def move_to(self, ypos, xpos):\n \"\"\"\n move the cursor to the given co-ordinates. Co-ordinates are 1\n based, as listed in the status area of the terminal.\n \"\"\"\n # the screen's co-ordinates are 1 based, but the command is 0 based\n xpos -= 1\n ypos -= 1\n self.exec_command(\"MoveCursor({0}, {1})\".format(ypos, xpos).encode(\"ascii\"))": 363, "def dict_from_object(obj: object):\n \"\"\"Convert a object into dictionary with all of its readable attributes.\"\"\"\n\n # If object is a dict instance, no need to convert.\n return (obj if isinstance(obj, dict)\n else {attr: getattr(obj, attr)\n for attr in dir(obj) if not attr.startswith('_')})": 364, "def ensure_hbounds(self):\n \"\"\"Ensure the cursor is within horizontal screen bounds.\"\"\"\n self.cursor.x = min(max(0, self.cursor.x), self.columns - 1)": 365, "def strip_spaces(s):\n \"\"\" Strip excess spaces from a string \"\"\"\n return u\" \".join([c for c in s.split(u' ') if c])": 366, "def scatter(self, *args, **kwargs):\n \"\"\"Add a scatter plot.\"\"\"\n cls = _make_class(ScatterVisual,\n _default_marker=kwargs.pop('marker', None),\n )\n return self._add_item(cls, *args, **kwargs)": 367, "def download_file_from_bucket(self, bucket, file_path, key):\n \"\"\" Download file from S3 Bucket \"\"\"\n with open(file_path, 'wb') as data:\n self.__s3.download_fileobj(bucket, key, data)\n return file_path": 368, "def imdecode(image_path):\n \"\"\"Return BGR image read by opencv\"\"\"\n import os\n assert os.path.exists(image_path), image_path + ' not found'\n im = cv2.imread(image_path)\n return im": 369, "def ex(self, cmd):\n \"\"\"Execute a normal python statement in user namespace.\"\"\"\n with self.builtin_trap:\n exec cmd in self.user_global_ns, self.user_ns": 370, "def isbinary(*args):\n \"\"\"Checks if value can be part of binary/bitwise operations.\"\"\"\n return all(map(lambda c: isnumber(c) or isbool(c), args))": 371, "def split(s):\n \"\"\"Uses dynamic programming to infer the location of spaces in a string without spaces.\"\"\"\n l = [_split(x) for x in _SPLIT_RE.split(s)]\n return [item for sublist in l for item in sublist]": 372, "def dt2jd(dt):\n \"\"\"Convert datetime to julian date\n \"\"\"\n a = (14 - dt.month)//12\n y = dt.year + 4800 - a\n m = dt.month + 12*a - 3\n return dt.day + ((153*m + 2)//5) + 365*y + y//4 - y//100 + y//400 - 32045": 373, "def smooth_gaussian(image, sigma=1):\n \"\"\"Returns Gaussian smoothed image.\n\n :param image: numpy array or :class:`jicimagelib.image.Image`\n :param sigma: standard deviation\n :returns: :class:`jicimagelib.image.Image`\n \"\"\"\n return scipy.ndimage.filters.gaussian_filter(image, sigma=sigma, mode=\"nearest\")": 374, "def _time_to_json(value):\n \"\"\"Coerce 'value' to an JSON-compatible representation.\"\"\"\n if isinstance(value, datetime.time):\n value = value.isoformat()\n return value": 375, "def EvalGaussianPdf(x, mu, sigma):\n \"\"\"Computes the unnormalized PDF of the normal distribution.\n\n x: value\n mu: mean\n sigma: standard deviation\n \n returns: float probability density\n \"\"\"\n return scipy.stats.norm.pdf(x, mu, sigma)": 376, "def convert_timestamp(timestamp):\n \"\"\"\n Converts bokehJS timestamp to datetime64.\n \"\"\"\n datetime = dt.datetime.utcfromtimestamp(timestamp/1000.)\n return np.datetime64(datetime.replace(tzinfo=None))": 377, "def _make_cmd_list(cmd_list):\n \"\"\"\n Helper function to easily create the proper json formated string from a list of strs\n :param cmd_list: list of strings\n :return: str json formatted\n \"\"\"\n cmd = ''\n for i in cmd_list:\n cmd = cmd + '\"' + i + '\",'\n cmd = cmd[:-1]\n return cmd": 378, "def accuracy(self):\n \"\"\"\n Calculates the accuracy of the tree by comparing\n the model predictions to the dataset\n (TP + TN) / (TP + TN + FP + FN) == (T / (T + F))\n \"\"\"\n sub_observed = np.array([self.observed.metadata[i] for i in self.observed.arr])\n return float((self.model_predictions() == sub_observed).sum()) / self.data_size": 379, "def cli(yamlfile, format, context):\n \"\"\" Generate JSONLD file from biolink schema \"\"\"\n print(JSONLDGenerator(yamlfile, format).serialize(context=context))": 380, "def double_sha256(data):\n \"\"\"A standard compound hash.\"\"\"\n return bytes_as_revhex(hashlib.sha256(hashlib.sha256(data).digest()).digest())": 381, "def get_cantons(self):\n \"\"\"\n Return the list of unique cantons, sorted by name.\n \"\"\"\n return sorted(list(set([\n location.canton for location in self.get_locations().values()\n ])))": 382, "def get_method_name(method):\n \"\"\"\n Returns given method name.\n\n :param method: Method to retrieve the name.\n :type method: object\n :return: Method name.\n :rtype: unicode\n \"\"\"\n\n name = get_object_name(method)\n if name.startswith(\"__\") and not name.endswith(\"__\"):\n name = \"_{0}{1}\".format(get_object_name(method.im_class), name)\n return name": 383, "def _add_default_arguments(parser):\n \"\"\"Add the default arguments to the parser.\n\n :param argparse.ArgumentParser parser: The argument parser\n\n \"\"\"\n parser.add_argument('-c', '--config', action='store', dest='config',\n help='Path to the configuration file')\n parser.add_argument('-f', '--foreground', action='store_true', dest='foreground',\n help='Run the application interactively')": 384, "def get_methods(*objs):\n \"\"\" Return the names of all callable attributes of an object\"\"\"\n return set(\n attr\n for obj in objs\n for attr in dir(obj)\n if not attr.startswith('_') and callable(getattr(obj, attr))\n )": 385, "def computeDelaunayTriangulation(points):\n \"\"\" Takes a list of point objects (which must have x and y fields).\n Returns a list of 3-tuples: the indices of the points that form a\n Delaunay triangle.\n \"\"\"\n siteList = SiteList(points)\n context = Context()\n context.triangulate = True\n voronoi(siteList,context)\n return context.triangles": 386, "def get_keys_from_class(cc):\n \"\"\"Return list of the key property names for a class \"\"\"\n return [prop.name for prop in cc.properties.values() \\\n if 'key' in prop.qualifiers]": 387, "def rm(venv_name):\n \"\"\" Removes the venv by name \"\"\"\n inenv = InenvManager()\n venv = inenv.get_venv(venv_name)\n click.confirm(\"Delete dir {}\".format(venv.path))\n shutil.rmtree(venv.path)": 388, "def columns(self):\n \"\"\"Return names of all the addressable columns (including foreign keys) referenced in user supplied model\"\"\"\n res = [col['name'] for col in self.column_definitions]\n res.extend([col['name'] for col in self.foreign_key_definitions])\n return res": 389, "def remove_non_magic_cols(self):\n \"\"\"\n Remove all non-MagIC columns from all tables.\n \"\"\"\n for table_name in self.tables:\n table = self.tables[table_name]\n table.remove_non_magic_cols_from_table()": 390, "def get_obj(ref):\n \"\"\"Get object from string reference.\"\"\"\n oid = int(ref)\n return server.id2ref.get(oid) or server.id2obj[oid]": 391, "def _split_comma_separated(string):\n \"\"\"Return a set of strings.\"\"\"\n return set(text.strip() for text in string.split(',') if text.strip())": 392, "def angle(x0, y0, x1, y1):\n \"\"\" Returns the angle between two points.\n \"\"\"\n return degrees(atan2(y1-y0, x1-x0))": 393, "def delete_duplicates(seq):\n \"\"\"\n Remove duplicates from an iterable, preserving the order.\n\n Args:\n seq: Iterable of various type.\n\n Returns:\n list: List of unique objects.\n\n \"\"\"\n seen = set()\n seen_add = seen.add\n return [x for x in seq if not (x in seen or seen_add(x))]": 394, "def guess_extension(amimetype, normalize=False):\n \"\"\"\n Tries to guess extension for a mimetype.\n\n @param amimetype: name of a mimetype\n @time amimetype: string\n @return: the extension\n @rtype: string\n \"\"\"\n ext = _mimes.guess_extension(amimetype)\n if ext and normalize:\n # Normalize some common magic mis-interpreation\n ext = {'.asc': '.txt', '.obj': '.bin'}.get(ext, ext)\n from invenio.legacy.bibdocfile.api_normalizer import normalize_format\n return normalize_format(ext)\n return ext": 395, "def reset():\n \"\"\"Delete the session and clear temporary directories\n\n \"\"\"\n shutil.rmtree(session['img_input_dir'])\n shutil.rmtree(session['img_output_dir'])\n session.clear()\n return jsonify(ok='true')": 396, "def boolean(value):\n \"\"\"\n Configuration-friendly boolean type converter.\n\n Supports both boolean-valued and string-valued inputs (e.g. from env vars).\n\n \"\"\"\n if isinstance(value, bool):\n return value\n\n if value == \"\":\n return False\n\n return strtobool(value)": 397, "def detokenize(s):\n \"\"\" Detokenize a string by removing spaces before punctuation.\"\"\"\n print(s)\n s = re.sub(\"\\s+([;:,\\.\\?!])\", \"\\\\1\", s)\n s = re.sub(\"\\s+(n't)\", \"\\\\1\", s)\n return s": 398, "def get_colors(img):\n \"\"\"\n Returns a list of all the image's colors.\n \"\"\"\n w, h = img.size\n return [color[:3] for count, color in img.convert('RGB').getcolors(w * h)]": 399, "def pop(h):\n \"\"\"Pop the heap value from the heap.\"\"\"\n n = h.size() - 1\n h.swap(0, n)\n down(h, 0, n)\n return h.pop()": 400, "def memory():\n \"\"\"Determine memory specifications of the machine.\n\n Returns\n -------\n mem_info : dictonary\n Holds the current values for the total, free and used memory of the system.\n \"\"\"\n\n mem_info = dict()\n\n for k, v in psutil.virtual_memory()._asdict().items():\n mem_info[k] = int(v)\n \n return mem_info": 401, "def check_precomputed_distance_matrix(X):\n \"\"\"Perform check_array(X) after removing infinite values (numpy.inf) from the given distance matrix.\n \"\"\"\n tmp = X.copy()\n tmp[np.isinf(tmp)] = 1\n check_array(tmp)": 402, "def calculate_month(birth_date):\n \"\"\"\n Calculates and returns a month number basing on PESEL standard.\n \"\"\"\n year = int(birth_date.strftime('%Y'))\n month = int(birth_date.strftime('%m')) + ((int(year / 100) - 14) % 5) * 20\n\n return month": 403, "def linedelimited (inlist,delimiter):\n \"\"\"\nReturns a string composed of elements in inlist, with each element\nseparated by 'delimiter.' Used by function writedelimited. Use '\\t'\nfor tab-delimiting.\n\nUsage: linedelimited (inlist,delimiter)\n\"\"\"\n outstr = ''\n for item in inlist:\n if type(item) != StringType:\n item = str(item)\n outstr = outstr + item + delimiter\n outstr = outstr[0:-1]\n return outstr": 404, "def get_month_start_end_day():\n \"\"\"\n Get the month start date a nd end date\n \"\"\"\n t = date.today()\n n = mdays[t.month]\n return (date(t.year, t.month, 1), date(t.year, t.month, n))": 405, "def dequeue(self, block=True):\n \"\"\"Dequeue a record and return item.\"\"\"\n return self.queue.get(block, self.queue_get_timeout)": 406, "def return_value(self, *args, **kwargs):\n \"\"\"Extracts the real value to be returned from the wrapping callable.\n\n :return: The value the double should return when called.\n \"\"\"\n\n self._called()\n return self._return_value(*args, **kwargs)": 407, "def get_best_encoding(stream):\n \"\"\"Returns the default stream encoding if not found.\"\"\"\n rv = getattr(stream, 'encoding', None) or sys.getdefaultencoding()\n if is_ascii_encoding(rv):\n return 'utf-8'\n return rv": 408, "def relpath(self):\n \"\"\" Return this path as a relative path,\n based from the current working directory.\n \"\"\"\n cwd = self.__class__(os.getcwdu())\n return cwd.relpathto(self)": 409, "def we_are_in_lyon():\n \"\"\"Check if we are on a Lyon machine\"\"\"\n import socket\n try:\n hostname = socket.gethostname()\n ip = socket.gethostbyname(hostname)\n except socket.gaierror:\n return False\n return ip.startswith(\"134.158.\")": 410, "def skip_connection_distance(a, b):\n \"\"\"The distance between two skip-connections.\"\"\"\n if a[2] != b[2]:\n return 1.0\n len_a = abs(a[1] - a[0])\n len_b = abs(b[1] - b[0])\n return (abs(a[0] - b[0]) + abs(len_a - len_b)) / (max(a[0], b[0]) + max(len_a, len_b))": 411, "def eqstr(a, b):\n \"\"\"\n Determine whether two strings are equivalent.\n\n http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eqstr_c.html\n\n :param a: Arbitrary character string.\n :type a: str\n :param b: Arbitrary character string.\n :type b: str\n :return: True if A and B are equivalent.\n :rtype: bool\n \"\"\"\n return bool(libspice.eqstr_c(stypes.stringToCharP(a), stypes.stringToCharP(b)))": 412, "def get_by(self, name):\n \"\"\"get element by name\"\"\"\n return next((item for item in self if item.name == name), None)": 413, "def validate(self, *args, **kwargs): # pylint: disable=arguments-differ\n \"\"\"\n Validate a parameter dict against a parameter schema from an ocrd-tool.json\n\n Args:\n obj (dict):\n schema (dict):\n \"\"\"\n return super(ParameterValidator, self)._validate(*args, **kwargs)": 414, "def get_parent_dir(name):\n \"\"\"Get the parent directory of a filename.\"\"\"\n parent_dir = os.path.dirname(os.path.dirname(name))\n if parent_dir:\n return parent_dir\n return os.path.abspath('.')": 415, "def me(self):\n \"\"\"Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message contexts.\"\"\"\n return self.guild.me if self.guild is not None else self.bot.user": 416, "def get_size_in_bytes(self, handle):\n \"\"\"Return the size in bytes.\"\"\"\n fpath = self._fpath_from_handle(handle)\n return os.stat(fpath).st_size": 417, "def show_guestbook():\n \"\"\"Returns all existing guestbook records.\"\"\"\n cursor = flask.g.db.execute(\n 'SELECT name, message FROM entry ORDER BY id DESC;')\n entries = [{'name': row[0], 'message': row[1]} for row in cursor.fetchall()]\n return jinja2.Template(LAYOUT).render(entries=entries)": 418, "def get_month_start(day=None):\n \"\"\"Returns the first day of the given month.\"\"\"\n day = add_timezone(day or datetime.date.today())\n return day.replace(day=1)": 419, "def rank(idx, dim):\n \"\"\"Calculate the index rank according to Bertran's notation.\"\"\"\n idxm = multi_index(idx, dim)\n out = 0\n while idxm[-1:] == (0,):\n out += 1\n idxm = idxm[:-1]\n return out": 420, "def get_last_commit(git_path=None):\n \"\"\"\n Get the HEAD commit SHA1 of repository in current dir.\n \"\"\"\n if git_path is None: git_path = GIT_PATH\n line = get_last_commit_line(git_path)\n revision_id = line.split()[1]\n return revision_id": 421, "def csvpretty(csvfile: csvfile=sys.stdin):\n \"\"\" Pretty print a CSV file. \"\"\"\n shellish.tabulate(csv.reader(csvfile))": 422, "def array_dim(arr):\n \"\"\"Return the size of a multidimansional array.\n \"\"\"\n dim = []\n while True:\n try:\n dim.append(len(arr))\n arr = arr[0]\n except TypeError:\n return dim": 423, "def _split_str(s, n):\n \"\"\"\n split string into list of strings by specified number.\n \"\"\"\n length = len(s)\n return [s[i:i + n] for i in range(0, length, n)]": 424, "def qsize(self):\n \"\"\"Return the approximate size of the queue (not reliable!).\"\"\"\n self.mutex.acquire()\n n = self._qsize()\n self.mutex.release()\n return n": 425, "def is_static(self, filename):\n \"\"\"Check if a file is a static file (which should be copied, rather\n than compiled using Jinja2).\n\n A file is considered static if it lives in any of the directories\n specified in ``staticpaths``.\n\n :param filename: the name of the file to check\n\n \"\"\"\n if self.staticpaths is None:\n # We're not using static file support\n return False\n\n for path in self.staticpaths:\n if filename.startswith(path):\n return True\n return False": 426, "def serve_static(request, path, insecure=False, **kwargs):\n \"\"\"Collect and serve static files.\n\n This view serves up static files, much like Django's\n :py:func:`~django.views.static.serve` view, with the addition that it\n collects static files first (if enabled). This allows images, fonts, and\n other assets to be served up without first loading a page using the\n ``{% javascript %}`` or ``{% stylesheet %}`` template tags.\n\n You can use this view by adding the following to any :file:`urls.py`::\n\n urlpatterns += static('static/', view='pipeline.views.serve_static')\n \"\"\"\n # Follow the same logic Django uses for determining access to the\n # static-serving view.\n if not django_settings.DEBUG and not insecure:\n raise ImproperlyConfigured(\"The staticfiles view can only be used in \"\n \"debug mode or if the --insecure \"\n \"option of 'runserver' is used\")\n\n if not settings.PIPELINE_ENABLED and settings.PIPELINE_COLLECTOR_ENABLED:\n # Collect only the requested file, in order to serve the result as\n # fast as possible. This won't interfere with the template tags in any\n # way, as those will still cause Django to collect all media.\n default_collector.collect(request, files=[path])\n\n return serve(request, path, document_root=django_settings.STATIC_ROOT,\n **kwargs)": 427, "def go_to_new_line(self):\n \"\"\"Go to the end of the current line and create a new line\"\"\"\n self.stdkey_end(False, False)\n self.insert_text(self.get_line_separator())": 428, "def get_font_list():\n \"\"\"Returns a sorted list of all system font names\"\"\"\n\n font_map = pangocairo.cairo_font_map_get_default()\n font_list = [f.get_name() for f in font_map.list_families()]\n font_list.sort()\n\n return font_list": 429, "def has_parent(self, term):\n \"\"\"Return True if this GO object has a parent GO ID.\"\"\"\n for parent in self.parents:\n if parent.item_id == term or parent.has_parent(term):\n return True\n return False": 430, "def unique_list_dicts(dlist, key):\n \"\"\"Return a list of dictionaries which are sorted for only unique entries.\n\n :param dlist:\n :param key:\n :return list:\n \"\"\"\n\n return list(dict((val[key], val) for val in dlist).values())": 431, "def _get_local_ip():\n \"\"\"\n Get the local ip of this device\n\n :return: Ip of this computer\n :rtype: str\n \"\"\"\n return set([x[4][0] for x in socket.getaddrinfo(\n socket.gethostname(),\n 80,\n socket.AF_INET\n )]).pop()": 432, "def get_public_members(obj):\n \"\"\"\n Retrieves a list of member-like objects (members or properties) that are\n publically exposed.\n\n :param obj: The object to probe.\n :return: A list of strings.\n \"\"\"\n return {attr: getattr(obj, attr) for attr in dir(obj)\n if not attr.startswith(\"_\")\n and not hasattr(getattr(obj, attr), '__call__')}": 433, "def timer():\n \"\"\"\n Timer used for calculate time elapsed\n \"\"\"\n if sys.platform == \"win32\":\n default_timer = time.clock\n else:\n default_timer = time.time\n\n return default_timer()": 434, "def last_day(year=_year, month=_month):\n \"\"\"\n get the current month's last day\n :param year: default to current year\n :param month: default to current month\n :return: month's last day\n \"\"\"\n last_day = calendar.monthrange(year, month)[1]\n return datetime.date(year=year, month=month, day=last_day)": 435, "def unit_tangent(self, t):\n \"\"\"returns the unit tangent vector of the segment at t (centered at\n the origin and expressed as a complex number).\"\"\"\n dseg = self.derivative(t)\n return dseg/abs(dseg)": 436, "def get_obj_cols(df):\n \"\"\"\n Returns names of 'object' columns in the DataFrame.\n \"\"\"\n obj_cols = []\n for idx, dt in enumerate(df.dtypes):\n if dt == 'object' or is_category(dt):\n obj_cols.append(df.columns.values[idx])\n\n return obj_cols": 437, "def match_aspect_to_viewport(self):\n \"\"\"Updates Camera.aspect to match the viewport's aspect ratio.\"\"\"\n viewport = self.viewport\n self.aspect = float(viewport.width) / viewport.height": 438, "def get_property_by_name(pif, name):\n \"\"\"Get a property by name\"\"\"\n return next((x for x in pif.properties if x.name == name), None)": 439, "def _uniquify(_list):\n \"\"\"Remove duplicates in a list.\"\"\"\n seen = set()\n result = []\n for x in _list:\n if x not in seen:\n result.append(x)\n seen.add(x)\n return result": 440, "def fmt_duration(secs):\n \"\"\"Format a duration in seconds.\"\"\"\n return ' '.join(fmt.human_duration(secs, 0, precision=2, short=True).strip().split())": 441, "def get_module_path(modname):\n \"\"\"Return module *modname* base path\"\"\"\n return osp.abspath(osp.dirname(sys.modules[modname].__file__))": 442, "def np_hash(a):\n \"\"\"Return a hash of a NumPy array.\"\"\"\n if a is None:\n return hash(None)\n # Ensure that hashes are equal whatever the ordering in memory (C or\n # Fortran)\n a = np.ascontiguousarray(a)\n # Compute the digest and return a decimal int\n return int(hashlib.sha1(a.view(a.dtype)).hexdigest(), 16)": 443, "def get(s, delimiter='', format=\"diacritical\"):\n \"\"\"Return pinyin of string, the string must be unicode\n \"\"\"\n return delimiter.join(_pinyin_generator(u(s), format=format))": 444, "def center_eigenvalue_diff(mat):\n \"\"\"Compute the eigvals of mat and then find the center eigval difference.\"\"\"\n N = len(mat)\n evals = np.sort(la.eigvals(mat))\n diff = np.abs(evals[N/2] - evals[N/2-1])\n return diff": 445, "def get_file_size(fileobj):\n \"\"\"\n Returns the size of a file-like object.\n \"\"\"\n currpos = fileobj.tell()\n fileobj.seek(0, 2)\n total_size = fileobj.tell()\n fileobj.seek(currpos)\n return total_size": 446, "def array_bytes(array):\n \"\"\" Estimates the memory of the supplied array in bytes \"\"\"\n return np.product(array.shape)*np.dtype(array.dtype).itemsize": 447, "def clear_es():\n \"\"\"Clear all indexes in the es core\"\"\"\n # TODO: should receive a catalog slug.\n ESHypermap.es.indices.delete(ESHypermap.index_name, ignore=[400, 404])\n LOGGER.debug('Elasticsearch: Index cleared')": 448, "def get_idx_rect(index_list):\n \"\"\"Extract the boundaries from a list of indexes\"\"\"\n rows, cols = list(zip(*[(i.row(), i.column()) for i in index_list]))\n return ( min(rows), max(rows), min(cols), max(cols) )": 449, "def _get_node_parent(self, age, pos):\n \"\"\"Get the parent node of node, whch is located in tree's node list.\n\n Returns:\n object: The parent node.\n \"\"\"\n return self.nodes[age][int(pos / self.comp)]": 450, "def __repr__(self):\n \"\"\"Return list-lookalike of representation string of objects\"\"\"\n strings = []\n for currItem in self:\n strings.append(\"%s\" % currItem)\n return \"(%s)\" % (\", \".join(strings))": 451, "def dedup_list(l):\n \"\"\"Given a list (l) will removing duplicates from the list,\n preserving the original order of the list. Assumes that\n the list entrie are hashable.\"\"\"\n dedup = set()\n return [ x for x in l if not (x in dedup or dedup.add(x))]": 452, "def tf2():\n \"\"\"Provide the root module of a TF-2.0 API for use within TensorBoard.\n\n Returns:\n The root module of a TF-2.0 API, if available.\n\n Raises:\n ImportError: if a TF-2.0 API is not available.\n \"\"\"\n # Import the `tf` compat API from this file and check if it's already TF 2.0.\n if tf.__version__.startswith('2.'):\n return tf\n elif hasattr(tf, 'compat') and hasattr(tf.compat, 'v2'):\n # As a fallback, try `tensorflow.compat.v2` if it's defined.\n return tf.compat.v2\n raise ImportError('cannot import tensorflow 2.0 API')": 453, "def split_addresses(email_string_list):\n \"\"\"\n Converts a string containing comma separated email addresses\n into a list of email addresses.\n \"\"\"\n return [f for f in [s.strip() for s in email_string_list.split(\",\")] if f]": 454, "def size():\n \"\"\"Determines the height and width of the console window\n\n Returns:\n tuple of int: The height in lines, then width in characters\n \"\"\"\n try:\n assert os != 'nt' and sys.stdout.isatty()\n rows, columns = os.popen('stty size', 'r').read().split()\n except (AssertionError, AttributeError, ValueError):\n # in case of failure, use dimensions of a full screen 13\" laptop\n rows, columns = DEFAULT_HEIGHT, DEFAULT_WIDTH\n\n return int(rows), int(columns)": 455, "def get_list_index(lst, index_or_name):\n \"\"\"\n Return the index of an element in the list.\n\n Args:\n lst (list): The list.\n index_or_name (int or str): The value of the reference element, or directly its numeric index.\n\n Returns:\n (int) The index of the element in the list.\n \"\"\"\n if isinstance(index_or_name, six.integer_types):\n return index_or_name\n\n return lst.index(index_or_name)": 456, "def write_enum(fo, datum, schema):\n \"\"\"An enum is encoded by a int, representing the zero-based position of\n the symbol in the schema.\"\"\"\n index = schema['symbols'].index(datum)\n write_int(fo, index)": 457, "def get_bottomrect_idx(self, pos):\n \"\"\" Determine if cursor is on bottom right corner of a hot spot.\"\"\"\n for i, r in enumerate(self.link_bottom_rects):\n if r.Contains(pos):\n return i\n return -1": 458, "def _dt_to_epoch(dt):\n \"\"\"Convert datetime to epoch seconds.\"\"\"\n try:\n epoch = dt.timestamp()\n except AttributeError: # py2\n epoch = (dt - datetime(1970, 1, 1)).total_seconds()\n return epoch": 459, "def plot_epsilon_residuals(self):\n \"\"\"Plots the epsilon residuals for the variogram fit.\"\"\"\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.scatter(range(self.epsilon.size), self.epsilon, c='k', marker='*')\n ax.axhline(y=0.0)\n plt.show()": 460, "def _get_column_types(self, data):\n \"\"\"Get a list of the data types for each column in *data*.\"\"\"\n columns = list(zip_longest(*data))\n return [self._get_column_type(column) for column in columns]": 461, "def forceupdate(self, *args, **kw):\n \"\"\"Like a bulk :meth:`forceput`.\"\"\"\n self._update(False, self._ON_DUP_OVERWRITE, *args, **kw)": 462, "def get_nt_system_uid():\n \"\"\"Get the MachineGuid from\n HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Cryptography\\MachineGuid\n \"\"\"\n try:\n import _winreg as winreg\n except ImportError:\n import winreg\n lm = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)\n try:\n key = winreg.OpenKey(lm, r\"Software\\Microsoft\\Cryptography\")\n try:\n return winreg.QueryValueEx(key, \"MachineGuid\")[0]\n finally:\n key.Close()\n finally:\n lm.Close()": 463, "def _escape(s):\n \"\"\" Helper method that escapes parameters to a SQL query. \"\"\"\n e = s\n e = e.replace('\\\\', '\\\\\\\\')\n e = e.replace('\\n', '\\\\n')\n e = e.replace('\\r', '\\\\r')\n e = e.replace(\"'\", \"\\\\'\")\n e = e.replace('\"', '\\\\\"')\n return e": 464, "def get_element_with_id(self, id):\n \"\"\"Return the element with the specified ID.\"\"\"\n # Should we maintain a hashmap of ids to make this more efficient? Probably overkill.\n # TODO: Elements can contain nested elements (captions, footnotes, table cells, etc.)\n return next((el for el in self.elements if el.id == id), None)": 465, "def vector_distance(a, b):\n \"\"\"The Euclidean distance between two vectors.\"\"\"\n a = np.array(a)\n b = np.array(b)\n return np.linalg.norm(a - b)": 466, "def url(self):\n \"\"\" The url of this window \"\"\"\n with switch_window(self._browser, self.name):\n return self._browser.url": 467, "def euclidean(c1, c2):\n \"\"\"Square of the euclidean distance\"\"\"\n diffs = ((i - j) for i, j in zip(c1, c2))\n return sum(x * x for x in diffs)": 468, "def get_free_memory_win():\n \"\"\"Return current free memory on the machine for windows.\n\n Warning : this script is really not robust\n Return in MB unit\n \"\"\"\n stat = MEMORYSTATUSEX()\n ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat))\n return int(stat.ullAvailPhys / 1024 / 1024)": 469, "def xpathEvalExpression(self, str):\n \"\"\"Evaluate the XPath expression in the given context. \"\"\"\n ret = libxml2mod.xmlXPathEvalExpression(str, self._o)\n if ret is None:raise xpathError('xmlXPathEvalExpression() failed')\n return xpathObjectRet(ret)": 470, "def EnumValueName(self, enum, value):\n \"\"\"Returns the string name of an enum value.\n\n This is just a small helper method to simplify a common operation.\n\n Args:\n enum: string name of the Enum.\n value: int, value of the enum.\n\n Returns:\n string name of the enum value.\n\n Raises:\n KeyError if either the Enum doesn't exist or the value is not a valid\n value for the enum.\n \"\"\"\n return self.enum_types_by_name[enum].values_by_number[value].name": 471, "def is_in(self, point_x, point_y):\n \"\"\" Test if a point is within this polygonal region \"\"\"\n\n point_array = array(((point_x, point_y),))\n vertices = array(self.points)\n winding = self.inside_rule == \"winding\"\n result = points_in_polygon(point_array, vertices, winding)\n return result[0]": 472, "def extent_count(self):\n \"\"\"\n Returns the volume group extent count.\n \"\"\"\n self.open()\n count = lvm_vg_get_extent_count(self.handle)\n self.close()\n return count": 473, "def title(self):\n \"\"\" The title of this window \"\"\"\n with switch_window(self._browser, self.name):\n return self._browser.title": 474, "def visit_BoolOp(self, node):\n \"\"\" Return type may come from any boolop operand. \"\"\"\n return sum((self.visit(value) for value in node.values), [])": 475, "def __get_xml_text(root):\n \"\"\" Return the text for the given root node (xml.dom.minidom). \"\"\"\n txt = \"\"\n for e in root.childNodes:\n if (e.nodeType == e.TEXT_NODE):\n txt += e.data\n return txt": 476, "def runcode(code):\n\t\"\"\"Run the given code line by line with printing, as list of lines, and return variable 'ans'.\"\"\"\n\tfor line in code:\n\t\tprint('# '+line)\n\t\texec(line,globals())\n\tprint('# return ans')\n\treturn ans": 477, "def fetch_event(urls):\n \"\"\"\n This parallel fetcher uses gevent one uses gevent\n \"\"\"\n rs = (grequests.get(u) for u in urls)\n return [content.json() for content in grequests.map(rs)]": 478, "def get_order(self, codes):\n \"\"\"Return evidence codes in order shown in code2name.\"\"\"\n return sorted(codes, key=lambda e: [self.ev2idx.get(e)])": 479, "def equal(list1, list2):\n \"\"\" takes flags returns indexes of True values \"\"\"\n return [item1 == item2 for item1, item2 in broadcast_zip(list1, list2)]": 480, "def select(self, cmd, *args, **kwargs):\n \"\"\" Execute the SQL command and return the data rows as tuples\n \"\"\"\n self.cursor.execute(cmd, *args, **kwargs)\n return self.cursor.fetchall()": 481, "def go_to_parent_directory(self):\n \"\"\"Go to parent directory\"\"\"\n self.chdir(osp.abspath(osp.join(getcwd_or_home(), os.pardir)))": 482, "def _convert_to_float_if_possible(s):\n \"\"\"\n A small helper function to convert a string to a numeric value\n if appropriate\n\n :param s: the string to be converted\n :type s: str\n \"\"\"\n try:\n ret = float(s)\n except (ValueError, TypeError):\n ret = s\n return ret": 483, "def _top(self):\n \"\"\" g \"\"\"\n # Goto top of the list\n self.top.body.focus_position = 2 if self.compact is False else 0\n self.top.keypress(self.size, \"\")": 484, "def to_gtp(coord):\n \"\"\"Converts from a Minigo coordinate to a GTP coordinate.\"\"\"\n if coord is None:\n return 'pass'\n y, x = coord\n return '{}{}'.format(_GTP_COLUMNS[x], go.N - y)": 485, "def nb_to_python(nb_path):\n \"\"\"convert notebook to python script\"\"\"\n exporter = python.PythonExporter()\n output, resources = exporter.from_filename(nb_path)\n return output": 486, "def searchlast(self,n=10):\n \"\"\"Return the last n results (or possibly less if not found). Note that the last results are not necessarily the best ones! Depending on the search type.\"\"\" \n solutions = deque([], n)\n for solution in self:\n solutions.append(solution)\n return solutions": 487, "def to_json(df, state_index, color_index, fills):\n \"\"\"Transforms dataframe to json response\"\"\"\n records = {}\n for i, row in df.iterrows():\n\n records[row[state_index]] = {\n \"fillKey\": row[color_index]\n }\n\n return {\n \"data\": records,\n \"fills\": fills\n }": 488, "def _text_to_graphiz(self, text):\n \"\"\"create a graphviz graph from text\"\"\"\n dot = Source(text, format='svg')\n return dot.pipe().decode('utf-8')": 489, "def _round_half_hour(record):\n \"\"\"\n Round a time DOWN to half nearest half-hour.\n \"\"\"\n k = record.datetime + timedelta(minutes=-(record.datetime.minute % 30))\n return datetime(k.year, k.month, k.day, k.hour, k.minute, 0)": 490, "def get_X0(X):\n \"\"\" Return zero-th element of a one-element data container.\n \"\"\"\n if pandas_available and isinstance(X, pd.DataFrame):\n assert len(X) == 1\n x = np.array(X.iloc[0])\n else:\n x, = X\n return x": 491, "def threads_init(gtk=True):\n \"\"\"Enables multithreading support in Xlib and PyGTK.\n See the module docstring for more info.\n \n :Parameters:\n gtk : bool\n May be set to False to skip the PyGTK module.\n \"\"\"\n # enable X11 multithreading\n x11.XInitThreads()\n if gtk:\n from gtk.gdk import threads_init\n threads_init()": 492, "def security(self):\n \"\"\"Print security object information for a pdf document\"\"\"\n return {k: v for i in self.pdf.resolvedObjects.items() for k, v in i[1].items()}": 493, "def enable_gtk3(self, app=None):\n \"\"\"Enable event loop integration with Gtk3 (gir bindings).\n\n Parameters\n ----------\n app : ignored\n Ignored, it's only a placeholder to keep the call signature of all\n gui activation methods consistent, which simplifies the logic of\n supporting magics.\n\n Notes\n -----\n This methods sets the PyOS_InputHook for Gtk3, which allows\n the Gtk3 to integrate with terminal based applications like\n IPython.\n \"\"\"\n from pydev_ipython.inputhookgtk3 import create_inputhook_gtk3\n self.set_inputhook(create_inputhook_gtk3(self._stdin_file))\n self._current_gui = GUI_GTK": 494, "def dot(a, b):\n \"\"\"Take arrays `a` and `b` and form the dot product between the last axis\n of `a` and the first of `b`.\n \"\"\"\n b = numpy.asarray(b)\n return numpy.dot(a, b.reshape(b.shape[0], -1)).reshape(a.shape[:-1] + b.shape[1:])": 495, "def __gzip(filename):\n\t\t\"\"\" Compress a file returning the new filename (.gz)\n\t\t\"\"\"\n\t\tzipname = filename + '.gz'\n\t\tfile_pointer = open(filename,'rb')\n\t\tzip_pointer = gzip.open(zipname,'wb')\n\t\tzip_pointer.writelines(file_pointer)\n\t\tfile_pointer.close()\n\t\tzip_pointer.close()\n\t\treturn zipname": 496, "def create_h5py_with_large_cache(filename, cache_size_mb):\n \"\"\"\nAllows to open the hdf5 file with specified cache size\n \"\"\"\n # h5py does not allow to control the cache size from the high level\n # we employ the workaround\n # sources:\n #http://stackoverflow.com/questions/14653259/how-to-set-cache-settings-while-using-h5py-high-level-interface\n #https://groups.google.com/forum/#!msg/h5py/RVx1ZB6LpE4/KH57vq5yw2AJ\n propfaid = h5py.h5p.create(h5py.h5p.FILE_ACCESS)\n settings = list(propfaid.get_cache())\n settings[2] = 1024 * 1024 * cache_size_mb\n propfaid.set_cache(*settings)\n fid = h5py.h5f.create(filename, flags=h5py.h5f.ACC_EXCL, fapl=propfaid)\n fin = h5py.File(fid)\n return fin": 497, "def rfft2d_freqs(h, w):\n \"\"\"Computes 2D spectrum frequencies.\"\"\"\n\n fy = np.fft.fftfreq(h)[:, None]\n # when we have an odd input dimension we need to keep one additional\n # frequency and later cut off 1 pixel\n if w % 2 == 1:\n fx = np.fft.fftfreq(w)[: w // 2 + 2]\n else:\n fx = np.fft.fftfreq(w)[: w // 2 + 1]\n return np.sqrt(fx * fx + fy * fy)": 498, "def md5_hash_file(fh):\n \"\"\"Return the md5 hash of the given file-object\"\"\"\n md5 = hashlib.md5()\n while True:\n data = fh.read(8192)\n if not data:\n break\n md5.update(data)\n return md5.hexdigest()": 499, "def software_fibonacci(n):\n \"\"\" a normal old python function to return the Nth fibonacci number. \"\"\"\n a, b = 0, 1\n for i in range(n):\n a, b = b, a + b\n return a": 500, "def h5ToDict(h5, readH5pyDataset=True):\n \"\"\" Read a hdf5 file into a dictionary \"\"\"\n h = h5py.File(h5, \"r\")\n ret = unwrapArray(h, recursive=True, readH5pyDataset=readH5pyDataset)\n if readH5pyDataset: h.close()\n return ret": 501, "def current_zipfile():\n \"\"\"A function to vend the current zipfile, if any\"\"\"\n if zipfile.is_zipfile(sys.argv[0]):\n fd = open(sys.argv[0], \"rb\")\n return zipfile.ZipFile(fd)": 502, "def __unixify(self, s):\n \"\"\" stupid windows. converts the backslash to forwardslash for consistency \"\"\"\n return os.path.normpath(s).replace(os.sep, \"/\")": 503, "def __init__(self, encoding='utf-8'):\n \"\"\"Initializes an stdin input reader.\n\n Args:\n encoding (Optional[str]): input encoding.\n \"\"\"\n super(StdinInputReader, self).__init__(sys.stdin, encoding=encoding)": 504, "def _add_hash(source):\n \"\"\"Add a leading hash '#' at the beginning of every line in the source.\"\"\"\n source = '\\n'.join('# ' + line.rstrip()\n for line in source.splitlines())\n return source": 505, "def apply(f, obj, *args, **kwargs):\n \"\"\"Apply a function in parallel to each element of the input\"\"\"\n return vectorize(f)(obj, *args, **kwargs)": 506, "def drop_empty(rows):\n \"\"\"Transpose the columns into rows, remove all of the rows that are empty after the first cell, then\n transpose back. The result is that columns that have a header but no data in the body are removed, assuming\n the header is the first row. \"\"\"\n return zip(*[col for col in zip(*rows) if bool(filter(bool, col[1:]))])": 507, "def heappush_max(heap, item):\n \"\"\"Push item onto heap, maintaining the heap invariant.\"\"\"\n heap.append(item)\n _siftdown_max(heap, 0, len(heap) - 1)": 508, "def _heappush_max(heap, item):\n \"\"\" why is this not in heapq \"\"\"\n heap.append(item)\n heapq._siftdown_max(heap, 0, len(heap) - 1)": 509, "def _remove_keywords(d):\n \"\"\"\n copy the dict, filter_keywords\n\n Parameters\n ----------\n d : dict\n \"\"\"\n return { k:v for k, v in iteritems(d) if k not in RESERVED }": 510, "def _heapify_max(x):\n \"\"\"Transform list into a maxheap, in-place, in O(len(x)) time.\"\"\"\n n = len(x)\n for i in reversed(range(n//2)):\n _siftup_max(x, i)": 511, "def uniq(seq):\n \"\"\" Return a copy of seq without duplicates. \"\"\"\n seen = set()\n return [x for x in seq if str(x) not in seen and not seen.add(str(x))]": 512, "def replace_all(filepath, searchExp, replaceExp):\n \"\"\"\n Replace all the ocurrences (in a file) of a string with another value.\n \"\"\"\n for line in fileinput.input(filepath, inplace=1):\n if searchExp in line:\n line = line.replace(searchExp, replaceExp)\n sys.stdout.write(line)": 513, "def __call__(self, kind: Optional[str] = None, **kwargs):\n \"\"\"Use the plotter as callable.\"\"\"\n return plot(self.histogram, kind=kind, **kwargs)": 514, "def ci(a, which=95, axis=None):\n \"\"\"Return a percentile range from an array of values.\"\"\"\n p = 50 - which / 2, 50 + which / 2\n return percentiles(a, p, axis)": 515, "def dtype(self):\n \"\"\"Pixel data type.\"\"\"\n try:\n return self.data.dtype\n except AttributeError:\n return numpy.dtype('%s%d' % (self._sample_type, self._sample_bytes))": 516, "def tuple_search(t, i, v):\n \"\"\"\n Search tuple array by index and value\n :param t: tuple array\n :param i: index of the value in each tuple\n :param v: value\n :return: the first tuple in the array with the specific index / value\n \"\"\"\n for e in t:\n if e[i] == v:\n return e\n return None": 517, "def from_pairs_to_array_values(pairs):\n \"\"\"\n Like from pairs but combines duplicate key values into arrays\n :param pairs:\n :return:\n \"\"\"\n result = {}\n for pair in pairs:\n result[pair[0]] = concat(prop_or([], pair[0], result), [pair[1]])\n return result": 518, "def area(x,y):\n \"\"\"\n Calculate the area of a polygon given as x(...),y(...)\n Implementation of Shoelace formula\n \"\"\"\n # http://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates\n return 0.5 * np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1)))": 519, "def _getSuperFunc(self, s, func):\n \"\"\"Return the the super function.\"\"\"\n\n return getattr(super(self.cls(), s), func.__name__)": 520, "def val_to_bin(edges, x):\n \"\"\"Convert axis coordinate to bin index.\"\"\"\n ibin = np.digitize(np.array(x, ndmin=1), edges) - 1\n return ibin": 521, "def compare(dicts):\n \"\"\"Compare by iteration\"\"\"\n\n common_members = {}\n common_keys = reduce(lambda x, y: x & y, map(dict.keys, dicts))\n for k in common_keys:\n common_members[k] = list(\n reduce(lambda x, y: x & y, [set(d[k]) for d in dicts]))\n\n return common_members": 522, "def _get_compiled_ext():\n \"\"\"Official way to get the extension of compiled files (.pyc or .pyo)\"\"\"\n for ext, mode, typ in imp.get_suffixes():\n if typ == imp.PY_COMPILED:\n return ext": 523, "def list_add_capitalize(l):\n \"\"\"\n @type l: list\n @return: list\n \"\"\"\n nl = []\n\n for i in l:\n nl.append(i)\n\n if hasattr(i, \"capitalize\"):\n nl.append(i.capitalize())\n\n return list(set(nl))": 524, "def to_camel_case(text):\n \"\"\"Convert to camel case.\n\n :param str text:\n :rtype: str\n :return:\n \"\"\"\n split = text.split('_')\n return split[0] + \"\".join(x.title() for x in split[1:])": 525, "def median(lst):\n \"\"\" Calcuates the median value in a @lst \"\"\"\n #: http://stackoverflow.com/a/24101534\n sortedLst = sorted(lst)\n lstLen = len(lst)\n index = (lstLen - 1) // 2\n if (lstLen % 2):\n return sortedLst[index]\n else:\n return (sortedLst[index] + sortedLst[index + 1])/2.0": 526, "def _IsRetryable(error):\n \"\"\"Returns whether error is likely to be retryable.\"\"\"\n if not isinstance(error, MySQLdb.OperationalError):\n return False\n if not error.args:\n return False\n code = error.args[0]\n return code in _RETRYABLE_ERRORS": 527, "def pid_exists(pid):\n \"\"\" Determines if a system process identifer exists in process table.\n \"\"\"\n try:\n os.kill(pid, 0)\n except OSError as exc:\n return exc.errno == errno.EPERM\n else:\n return True": 528, "def getPrimeFactors(n):\n \"\"\"\n Get all the prime factor of given integer\n @param n integer\n @return list [1, ..., n]\n \"\"\"\n lo = [1]\n n2 = n // 2\n k = 2\n for k in range(2, n2 + 1):\n if (n // k)*k == n:\n lo.append(k)\n return lo + [n, ]": 529, "def _isstring(dtype):\n \"\"\"Given a numpy dtype, determines whether it is a string. Returns True\n if the dtype is string or unicode.\n \"\"\"\n return dtype.type == numpy.unicode_ or dtype.type == numpy.string_": 530, "def _is_override(meta, method):\n \"\"\"Checks whether given class or instance method has been marked\n with the ``@override`` decorator.\n \"\"\"\n from taipan.objective.modifiers import _OverriddenMethod\n return isinstance(method, _OverriddenMethod)": 531, "def should_skip_logging(func):\n \"\"\"\n Should we skip logging for this handler?\n\n \"\"\"\n disabled = strtobool(request.headers.get(\"x-request-nolog\", \"false\"))\n return disabled or getattr(func, SKIP_LOGGING, False)": 532, "def calc_cR(Q2, sigma):\n \"\"\"Returns the cR statistic for the variogram fit (see [1]).\"\"\"\n return Q2 * np.exp(np.sum(np.log(sigma**2))/sigma.shape[0])": 533, "def is_builtin_type(tp):\n \"\"\"Checks if the given type is a builtin one.\n \"\"\"\n return hasattr(__builtins__, tp.__name__) and tp is getattr(__builtins__, tp.__name__)": 534, "def forget_coords(self):\n \"\"\"Forget all loaded coordinates.\"\"\"\n self.w.ntotal.set_text('0')\n self.coords_dict.clear()\n self.redo()": 535, "def flat_list(lst):\n \"\"\"This function flatten given nested list.\n Argument:\n nested list\n Returns:\n flat list\n \"\"\"\n if isinstance(lst, list):\n for item in lst:\n for i in flat_list(item):\n yield i\n else:\n yield lst": 536, "def safe_exit(output):\n \"\"\"exit without breaking pipes.\"\"\"\n try:\n sys.stdout.write(output)\n sys.stdout.flush()\n except IOError:\n pass": 537, "def imflip(img, direction='horizontal'):\n \"\"\"Flip an image horizontally or vertically.\n\n Args:\n img (ndarray): Image to be flipped.\n direction (str): The flip direction, either \"horizontal\" or \"vertical\".\n\n Returns:\n ndarray: The flipped image.\n \"\"\"\n assert direction in ['horizontal', 'vertical']\n if direction == 'horizontal':\n return np.flip(img, axis=1)\n else:\n return np.flip(img, axis=0)": 538, "def get_order(self):\n \"\"\"\n Return a list of dicionaries. See `set_order`.\n \"\"\"\n return [dict(reverse=r[0], key=r[1]) for r in self.get_model()]": 539, "def hflip(img):\n \"\"\"Horizontally flip the given PIL Image.\n\n Args:\n img (PIL Image): Image to be flipped.\n\n Returns:\n PIL Image: Horizontall flipped image.\n \"\"\"\n if not _is_pil_image(img):\n raise TypeError('img should be PIL Image. Got {}'.format(type(img)))\n\n return img.transpose(Image.FLIP_LEFT_RIGHT)": 540, "def get_document_frequency(self, term):\n \"\"\"\n Returns the number of documents the specified term appears in.\n \"\"\"\n if term not in self._terms:\n raise IndexError(TERM_DOES_NOT_EXIST)\n else:\n return len(self._terms[term])": 541, "def destroy(self):\n \"\"\" Cleanup the activty lifecycle listener \"\"\"\n if self.widget:\n self.set_active(False)\n super(AndroidBarcodeView, self).destroy()": 542, "def one_for_all(self, deps):\n \"\"\"Because there are dependencies that depend on other\n dependencies are created lists into other lists.\n Thus creating this loop create one-dimensional list and\n remove double packages from dependencies.\n \"\"\"\n requires, dependencies = [], []\n deps.reverse()\n # Inverting the list brings the\n # dependencies in order to be installed.\n requires = Utils().dimensional_list(deps)\n dependencies = Utils().remove_dbs(requires)\n return dependencies": 543, "def trigger_fullscreen_action(self, fullscreen):\n \"\"\"\n Toggle fullscreen from outside the GUI,\n causes the GUI to updated and run all its actions.\n \"\"\"\n action = self.action_group.get_action('fullscreen')\n action.set_active(fullscreen)": 544, "def download_json(local_filename, url, clobber=False):\n \"\"\"Download the given JSON file, and pretty-print before we output it.\"\"\"\n with open(local_filename, 'w') as json_file:\n json_file.write(json.dumps(requests.get(url).json(), sort_keys=True, indent=2, separators=(',', ': ')))": 545, "def is_password_valid(password):\n \"\"\"\n Check if a password is valid\n \"\"\"\n pattern = re.compile(r\"^.{4,75}$\")\n return bool(pattern.match(password))": 546, "def drag_and_drop(self, droppable):\n \"\"\"\n Performs drag a element to another elmenet.\n\n Currently works only on Chrome driver.\n \"\"\"\n self.scroll_to()\n ActionChains(self.parent.driver).drag_and_drop(self._element, droppable._element).perform()": 547, "def url_encode(url):\n \"\"\"\n Convert special characters using %xx escape.\n\n :param url: str\n :return: str - encoded url\n \"\"\"\n if isinstance(url, text_type):\n url = url.encode('utf8')\n return quote(url, ':/%?&=')": 548, "def ExecuteRaw(self, position, command):\n \"\"\"Send a command string to gdb.\"\"\"\n self.EnsureGdbPosition(position[0], None, None)\n return gdb.execute(command, to_string=True)": 549, "def finish():\n \"\"\"Print warning about interrupt and empty the job queue.\"\"\"\n out.warn(\"Interrupted!\")\n for t in threads:\n t.stop()\n jobs.clear()\n out.warn(\"Waiting for download threads to finish.\")": 550, "def rlognormal(mu, tau, size=None):\n \"\"\"\n Return random lognormal variates.\n \"\"\"\n\n return np.random.lognormal(mu, np.sqrt(1. / tau), size)": 551, "def calculate_boundingbox(lng, lat, miles):\n \"\"\"\n Given a latitude, longitude and a distance in miles, calculate\n the co-ordinates of the bounding box 2*miles on long each side with the\n given co-ordinates at the center.\n \"\"\"\n\n latChange = change_in_latitude(miles)\n latSouth = lat - latChange\n latNorth = lat + latChange\n lngChange = change_in_longitude(lat, miles)\n lngWest = lng + lngChange\n lngEast = lng - lngChange\n return (lngWest, latSouth, lngEast, latNorth)": 552, "def uniqueID(size=6, chars=string.ascii_uppercase + string.digits):\n \"\"\"A quick and dirty way to get a unique string\"\"\"\n return ''.join(random.choice(chars) for x in xrange(size))": 553, "def toBase64(s):\n \"\"\"Represent string / bytes s as base64, omitting newlines\"\"\"\n if isinstance(s, str):\n s = s.encode(\"utf-8\")\n return binascii.b2a_base64(s)[:-1]": 554, "def _generate_key_map(entity_list, key, entity_class):\n \"\"\" Helper method to generate map from key to entity object for given list of dicts.\n\n Args:\n entity_list: List consisting of dict.\n key: Key in each dict which will be key in the map.\n entity_class: Class representing the entity.\n\n Returns:\n Map mapping key to entity object.\n \"\"\"\n\n key_map = {}\n for obj in entity_list:\n key_map[obj[key]] = entity_class(**obj)\n\n return key_map": 555, "def intersect(d1, d2):\n \"\"\"Intersect dictionaries d1 and d2 by key *and* value.\"\"\"\n return dict((k, d1[k]) for k in d1 if k in d2 and d1[k] == d2[k])": 556, "def _rndPointDisposition(dx, dy):\n \"\"\"Return random disposition point.\"\"\"\n x = int(random.uniform(-dx, dx))\n y = int(random.uniform(-dy, dy))\n return (x, y)": 557, "def sine_wave(frequency):\n \"\"\"Emit a sine wave at the given frequency.\"\"\"\n xs = tf.reshape(tf.range(_samples(), dtype=tf.float32), [1, _samples(), 1])\n ts = xs / FLAGS.sample_rate\n return tf.sin(2 * math.pi * frequency * ts)": 558, "def bitsToString(arr):\n \"\"\"Returns a string representing a numpy array of 0's and 1's\"\"\"\n s = array('c','.'*len(arr))\n for i in xrange(len(arr)):\n if arr[i] == 1:\n s[i]='*'\n return s": 559, "def find_nearest_index(arr, value):\n \"\"\"For a given value, the function finds the nearest value\n in the array and returns its index.\"\"\"\n arr = np.array(arr)\n index = (abs(arr-value)).argmin()\n return index": 560, "def make_file_read_only(file_path):\n \"\"\"\n Removes the write permissions for the given file for owner, groups and others.\n\n :param file_path: The file whose privileges are revoked.\n :raise FileNotFoundError: If the given file does not exist.\n \"\"\"\n old_permissions = os.stat(file_path).st_mode\n os.chmod(file_path, old_permissions & ~WRITE_PERMISSIONS)": 561, "def copy(self):\n \"\"\"\n Return a copy of the dictionary.\n\n This is a middle-deep copy; the copy is independent of the original in\n all attributes that have mutable types except for:\n\n * The values in the dictionary\n\n Note that the Python functions :func:`py:copy.copy` and\n :func:`py:copy.deepcopy` can be used to create completely shallow or\n completely deep copies of objects of this class.\n \"\"\"\n result = NocaseDict()\n result._data = self._data.copy() # pylint: disable=protected-access\n return result": 562, "def longest_run(da, dim='time'):\n \"\"\"Return the length of the longest consecutive run of True values.\n\n Parameters\n ----------\n arr : N-dimensional array (boolean)\n Input array\n dim : Xarray dimension (default = 'time')\n Dimension along which to calculate consecutive run\n\n Returns\n -------\n N-dimensional array (int)\n Length of longest run of True values along dimension\n \"\"\"\n\n d = rle(da, dim=dim)\n rl_long = d.max(dim=dim)\n\n return rl_long": 563, "def fopenat(base_fd, path):\n \"\"\"\n Does openat read-only, then does fdopen to get a file object\n \"\"\"\n\n return os.fdopen(openat(base_fd, path, os.O_RDONLY), 'rb')": 564, "def vars_class(cls):\n \"\"\"Return a dict of vars for the given class, including all ancestors.\n\n This differs from the usual behaviour of `vars` which returns attributes\n belonging to the given class and not its ancestors.\n \"\"\"\n return dict(chain.from_iterable(\n vars(cls).items() for cls in reversed(cls.__mro__)))": 565, "def flatten(l, types=(list, float)):\n \"\"\"\n Flat nested list of lists into a single list.\n \"\"\"\n l = [item if isinstance(item, types) else [item] for item in l]\n return [item for sublist in l for item in sublist]": 566, "def _ensure_element(tup, elem):\n \"\"\"\n Create a tuple containing all elements of tup, plus elem.\n\n Returns the new tuple and the index of elem in the new tuple.\n \"\"\"\n try:\n return tup, tup.index(elem)\n except ValueError:\n return tuple(chain(tup, (elem,))), len(tup)": 567, "def bitdepth(self):\n \"\"\"The number of bits per sample in the audio encoding (an int).\n Only available for certain file formats (zero where\n unavailable).\n \"\"\"\n if hasattr(self.mgfile.info, 'bits_per_sample'):\n return self.mgfile.info.bits_per_sample\n return 0": 568, "def to_python(self, value):\n \"\"\"\n Convert a string from a form into an Enum value.\n \"\"\"\n if value is None:\n return value\n if isinstance(value, self.enum):\n return value\n return self.enum[value]": 569, "def force_iterable(f):\n \"\"\"Will make any functions return an iterable objects by wrapping its result in a list.\"\"\"\n def wrapper(*args, **kwargs):\n r = f(*args, **kwargs)\n if hasattr(r, '__iter__'):\n return r\n else:\n return [r]\n return wrapper": 570, "def _read_date_from_string(str1):\n \"\"\"\n Reads the date from a string in the format YYYY/MM/DD and returns\n :class: datetime.date\n \"\"\"\n full_date = [int(x) for x in str1.split('/')]\n return datetime.date(full_date[0], full_date[1], full_date[2])": 571, "def wr_row_mergeall(self, worksheet, txtstr, fmt, row_idx):\n \"\"\"Merge all columns and place text string in widened cell.\"\"\"\n hdridxval = len(self.hdrs) - 1\n worksheet.merge_range(row_idx, 0, row_idx, hdridxval, txtstr, fmt)\n return row_idx + 1": 572, "def dates_in_range(start_date, end_date):\n \"\"\"Returns all dates between two dates.\n\n Inclusive of the start date but not the end date.\n\n Args:\n start_date (datetime.date)\n end_date (datetime.date)\n\n Returns:\n (list) of datetime.date objects\n \"\"\"\n return [\n start_date + timedelta(n)\n for n in range(int((end_date - start_date).days))\n ]": 573, "def unique(input_list):\n \"\"\"\n Return a list of unique items (similar to set functionality).\n\n Parameters\n ----------\n input_list : list\n A list containg some items that can occur more than once.\n\n Returns\n -------\n list\n A list with only unique occurances of an item.\n\n \"\"\"\n output = []\n for item in input_list:\n if item not in output:\n output.append(item)\n return output": 574, "def sort_fn_list(fn_list):\n \"\"\"Sort input filename list by datetime\n \"\"\"\n dt_list = get_dt_list(fn_list)\n fn_list_sort = [fn for (dt,fn) in sorted(zip(dt_list,fn_list))]\n return fn_list_sort": 575, "def fast_distinct(self):\n \"\"\"\n Because standard distinct used on the all fields are very slow and works only with PostgreSQL database\n this method provides alternative to the standard distinct method.\n :return: qs with unique objects\n \"\"\"\n return self.model.objects.filter(pk__in=self.values_list('pk', flat=True))": 576, "def Proxy(f):\n \"\"\"A helper to create a proxy method in a class.\"\"\"\n\n def Wrapped(self, *args):\n return getattr(self, f)(*args)\n\n return Wrapped": 577, "def metres2latlon(mx, my, origin_shift= 2 * pi * 6378137 / 2.0):\n \"\"\"Converts XY point from Spherical Mercator EPSG:900913 to lat/lon in\n WGS84 Datum\"\"\"\n lon = (mx / origin_shift) * 180.0\n lat = (my / origin_shift) * 180.0\n\n lat = 180 / pi * (2 * atan( exp( lat * pi / 180.0)) - pi / 2.0)\n return lat, lon": 578, "def next (self): # File-like object.\n\n \"\"\"This is to support iterators over a file-like object.\n \"\"\"\n\n result = self.readline()\n if result == self._empty_buffer:\n raise StopIteration\n return result": 579, "def _factor_generator(n):\n \"\"\"\n From a given natural integer, returns the prime factors and their multiplicity\n :param n: Natural integer\n :return:\n \"\"\"\n p = prime_factors(n)\n factors = {}\n for p1 in p:\n try:\n factors[p1] += 1\n except KeyError:\n factors[p1] = 1\n return factors": 580, "def unique(seq):\n \"\"\"Return the unique elements of a collection even if those elements are\n unhashable and unsortable, like dicts and sets\"\"\"\n cleaned = []\n for each in seq:\n if each not in cleaned:\n cleaned.append(each)\n return cleaned": 581, "def get_md5_for_file(file):\n \"\"\"Get the md5 hash for a file.\n\n :param file: the file to get the md5 hash for\n \"\"\"\n md5 = hashlib.md5()\n\n while True:\n data = file.read(md5.block_size)\n\n if not data:\n break\n\n md5.update(data)\n\n return md5.hexdigest()": 582, "def _rank(self, ranking, n):\n \"\"\" return the first n sentences with highest ranking \"\"\"\n return nlargest(n, ranking, key=ranking.get)": 583, "def drop_indexes(self):\n \"\"\"Delete all indexes for the database\"\"\"\n LOG.warning(\"Dropping all indexe\")\n for collection_name in INDEXES:\n LOG.warning(\"Dropping all indexes for collection name %s\", collection_name)\n self.db[collection_name].drop_indexes()": 584, "def last(self):\n \"\"\"Get the last object in file.\"\"\"\n # End of file\n self.__file.seek(0, 2)\n\n # Get the last struct\n data = self.get(self.length - 1)\n\n return data": 585, "def debug_src(src, pm=False, globs=None):\n \"\"\"Debug a single doctest docstring, in argument `src`'\"\"\"\n testsrc = script_from_examples(src)\n debug_script(testsrc, pm, globs)": 586, "def get_last_row(dbconn, tablename, n=1, uuid=None):\n \"\"\"\n Returns the last `n` rows in the table\n \"\"\"\n return fetch(dbconn, tablename, n, uuid, end=True)": 587, "def save(self, fname: str):\n \"\"\"\n Saves this training state to fname.\n \"\"\"\n with open(fname, \"wb\") as fp:\n pickle.dump(self, fp)": 588, "def display_len(text):\n \"\"\"\n Get the display length of a string. This can differ from the character\n length if the string contains wide characters.\n \"\"\"\n text = unicodedata.normalize('NFD', text)\n return sum(char_width(char) for char in text)": 589, "def isString(s):\n \"\"\"Convenience method that works with all 2.x versions of Python\n to determine whether or not something is stringlike.\"\"\"\n try:\n return isinstance(s, unicode) or isinstance(s, basestring)\n except NameError:\n return isinstance(s, str)": 590, "def rel_path(filename):\n \"\"\"\n Function that gets relative path to the filename\n \"\"\"\n return os.path.join(os.getcwd(), os.path.dirname(__file__), filename)": 591, "def const_rand(size, seed=23980):\n \"\"\" Generate a random array with a fixed seed.\n \"\"\"\n old_seed = np.random.seed()\n np.random.seed(seed)\n out = np.random.rand(size)\n np.random.seed(old_seed)\n return out": 592, "def get_action_methods(self):\n \"\"\"\n return a list of methods on this class for executing actions.\n methods are return as a list of (name, func) tuples\n \"\"\"\n return [(name, getattr(self, name))\n for name, _ in Action.get_command_types()]": 593, "def start():\n \"\"\"Starts the web server.\"\"\"\n global app\n bottle.run(app, host=conf.WebHost, port=conf.WebPort,\n debug=conf.WebAutoReload, reloader=conf.WebAutoReload,\n quiet=conf.WebQuiet)": 594, "async def sysinfo(dev: Device):\n \"\"\"Print out system information (version, MAC addrs).\"\"\"\n click.echo(await dev.get_system_info())\n click.echo(await dev.get_interface_information())": 595, "def count_(self):\n \"\"\"\n Returns the number of rows of the main dataframe\n \"\"\"\n try:\n num = len(self.df.index)\n except Exception as e:\n self.err(e, \"Can not count data\")\n return\n return num": 596, "def post_object_async(self, path, **kwds):\n \"\"\"POST to an object.\"\"\"\n return self.do_request_async(self.api_url + path, 'POST', **kwds)": 597, "def findfirst(f, coll):\n \"\"\"Return first occurrence matching f, otherwise None\"\"\"\n result = list(dropwhile(f, coll))\n return result[0] if result else None": 598, "def start(self):\n \"\"\"Create a background thread for httpd and serve 'forever'\"\"\"\n self._process = threading.Thread(target=self._background_runner)\n self._process.start()": 599, "def return_letters_from_string(text):\n \"\"\"Get letters from string only.\"\"\"\n out = \"\"\n for letter in text:\n if letter.isalpha():\n out += letter\n return out": 600, "def parse_querystring(self, req, name, field):\n \"\"\"Pull a querystring value from the request.\"\"\"\n return core.get_value(req.args, name, field)": 601, "def inject_into_urllib3():\n \"\"\"\n Monkey-patch urllib3 with SecureTransport-backed SSL-support.\n \"\"\"\n util.ssl_.SSLContext = SecureTransportContext\n util.HAS_SNI = HAS_SNI\n util.ssl_.HAS_SNI = HAS_SNI\n util.IS_SECURETRANSPORT = True\n util.ssl_.IS_SECURETRANSPORT = True": 602, "def strip_spaces(x):\n \"\"\"\n Strips spaces\n :param x:\n :return:\n \"\"\"\n x = x.replace(b' ', b'')\n x = x.replace(b'\\t', b'')\n return x": 603, "def argsort_indices(a, axis=-1):\n \"\"\"Like argsort, but returns an index suitable for sorting the\n the original array even if that array is multidimensional\n \"\"\"\n a = np.asarray(a)\n ind = list(np.ix_(*[np.arange(d) for d in a.shape]))\n ind[axis] = a.argsort(axis)\n return tuple(ind)": 604, "def file_or_default(path, default, function = None):\n \"\"\" Return a default value if a file does not exist \"\"\"\n try:\n result = file_get_contents(path)\n if function != None: return function(result)\n return result\n except IOError as e:\n if e.errno == errno.ENOENT: return default\n raise": 605, "def this_quarter():\n \"\"\" Return start and end date of this quarter. \"\"\"\n since = TODAY + delta(day=1)\n while since.month % 3 != 0:\n since -= delta(months=1)\n until = since + delta(months=3)\n return Date(since), Date(until)": 606, "def strToBool(val):\n \"\"\"\n Helper function to turn a string representation of \"true\" into\n boolean True.\n \"\"\"\n if isinstance(val, str):\n val = val.lower()\n\n return val in ['true', 'on', 'yes', True]": 607, "def clear_list_value(self, value):\n \"\"\"\n Clean the argument value to eliminate None or Falsy values if needed.\n \"\"\"\n # Don't go any further: this value is empty.\n if not value:\n return self.empty_value\n # Clean empty items if wanted\n if self.clean_empty:\n value = [v for v in value if v]\n return value or self.empty_value": 608, "def call_out(command):\n \"\"\"\n Run the given command (with shell=False) and return a tuple of\n (int returncode, str output). Strip the output of enclosing whitespace.\n \"\"\"\n # start external command process\n p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n # get outputs\n out, _ = p.communicate()\n\n return p.returncode, out.strip()": 609, "def run(self, value):\n \"\"\" Determines if value value is empty.\n Keyword arguments:\n value str -- the value of the associated field to compare\n \"\"\"\n if self.pass_ and not value.strip():\n return True\n\n if not value:\n return False\n return True": 610, "def _string_width(self, s):\n \"\"\"Get width of a string in the current font\"\"\"\n s = str(s)\n w = 0\n for i in s:\n w += self.character_widths[i]\n return w * self.font_size / 1000.0": 611, "def find_le(a, x):\n \"\"\"Find rightmost value less than or equal to x.\"\"\"\n i = bs.bisect_right(a, x)\n if i: return i - 1\n raise ValueError": 612, "def crop_box(im, box=False, **kwargs):\n \"\"\"Uses box coordinates to crop an image without resizing it first.\"\"\"\n if box:\n im = im.crop(box)\n return im": 613, "def datatype(dbtype, description, cursor):\n \"\"\"Google AppEngine Helper to convert a data type into a string.\"\"\"\n dt = cursor.db.introspection.get_field_type(dbtype, description)\n if type(dt) is tuple:\n return dt[0]\n else:\n return dt": 614, "def normalize(im, invert=False, scale=None, dtype=np.float64):\n \"\"\"\n Normalize a field to a (min, max) exposure range, default is (0, 255).\n (min, max) exposure values. Invert the image if requested.\n \"\"\"\n if dtype not in {np.float16, np.float32, np.float64}:\n raise ValueError('dtype must be numpy.float16, float32, or float64.')\n out = im.astype('float').copy()\n\n scale = scale or (0.0, 255.0)\n l, u = (float(i) for i in scale)\n out = (out - l) / (u - l)\n if invert:\n out = -out + (out.max() + out.min())\n return out.astype(dtype)": 615, "def end_index(self):\n \"\"\"Return the 1-based index of the last item on this page.\"\"\"\n paginator = self.paginator\n # Special case for the last page because there can be orphans.\n if self.number == paginator.num_pages:\n return paginator.count\n return (self.number - 1) * paginator.per_page + paginator.first_page": 616, "def filtered_image(self, im):\n \"\"\"Returns a filtered image after applying the Fourier-space filters\"\"\"\n q = np.fft.fftn(im)\n for k,v in self.filters:\n q[k] -= v\n return np.real(np.fft.ifftn(q))": 617, "def get_buffer(self, data_np, header, format, output=None):\n \"\"\"Get image as a buffer in (format).\n Format should be 'jpeg', 'png', etc.\n \"\"\"\n if not have_pil:\n raise Exception(\"Install PIL to use this method\")\n image = PILimage.fromarray(data_np)\n buf = output\n if buf is None:\n buf = BytesIO()\n image.save(buf, format)\n return buf": 618, "def uint32_to_uint8(cls, img):\n \"\"\"\n Cast uint32 RGB image to 4 uint8 channels.\n \"\"\"\n return np.flipud(img.view(dtype=np.uint8).reshape(img.shape + (4,)))": 619, "def get_user_by_id(self, id):\n \"\"\"Retrieve a User object by ID.\"\"\"\n return self.db_adapter.get_object(self.UserClass, id=id)": 620, "def reduce_fn(x):\n \"\"\"\n Aggregation function to get the first non-zero value.\n \"\"\"\n values = x.values if pd and isinstance(x, pd.Series) else x\n for v in values:\n if not is_nan(v):\n return v\n return np.NaN": 621, "def _EnforceProcessMemoryLimit(self, memory_limit):\n \"\"\"Enforces a process memory limit.\n\n Args:\n memory_limit (int): maximum number of bytes the process is allowed\n to allocate, where 0 represents no limit and None a default of\n 4 GiB.\n \"\"\"\n # Resource is not supported on Windows.\n if resource:\n if memory_limit is None:\n memory_limit = 4 * 1024 * 1024 * 1024\n elif memory_limit == 0:\n memory_limit = resource.RLIM_INFINITY\n\n resource.setrlimit(resource.RLIMIT_DATA, (memory_limit, memory_limit))": 622, "def check_many(self, domains):\n \"\"\"\n Check availability for a number of domains. Returns a dictionary\n mapping the domain names to their statuses as a string\n (\"active\"/\"free\").\n \"\"\"\n return dict((item.domain, item.status) for item in self.check_domain_request(domains))": 623, "def end_block(self):\n \"\"\"Ends an indentation block, leaving an empty line afterwards\"\"\"\n self.current_indent -= 1\n\n # If we did not add a new line automatically yet, now it's the time!\n if not self.auto_added_line:\n self.writeln()\n self.auto_added_line = True": 624, "def get_weights_from_kmodel(kmodel):\n \"\"\"\n Convert kmodel's weights to bigdl format.\n We are supposing the order is the same as the execution order.\n :param kmodel: keras model\n :return: list of ndarray\n \"\"\"\n layers_with_weights = [layer for layer in kmodel.layers if layer.weights]\n bweights = []\n for klayer in layers_with_weights:\n # bws would be [weights, bias] or [weights]\n bws = WeightsConverter.get_bigdl_weights_from_klayer(klayer)\n for w in bws:\n bweights.append(w)\n return bweights": 625, "def MultiArgMax(x):\n \"\"\"\n Get tuple (actually a generator) of indices where the max value of\n array x occurs. Requires that x have a max() method, as x.max()\n (in the case of NumPy) is much faster than max(x).\n For a simpler, faster argmax when there is only a single maximum entry,\n or when knowing only the first index where the maximum occurs,\n call argmax() on a NumPy array.\n\n :param x: Any sequence that has a max() method.\n :returns: Generator with the indices where the max value occurs.\n \"\"\"\n m = x.max()\n return (i for i, v in enumerate(x) if v == m)": 626, "def __init__(self, find, subcon):\n \"\"\"Initialize.\"\"\"\n Subconstruct.__init__(self, subcon)\n self.find = find": 627, "def value(self):\n \"\"\"Value of property.\"\"\"\n if self._prop.fget is None:\n raise AttributeError('Unable to read attribute')\n return self._prop.fget(self._obj)": 628, "def prepend_line(filepath, line):\n \"\"\"Rewrite a file adding a line to its beginning.\n \"\"\"\n with open(filepath) as f:\n lines = f.readlines()\n\n lines.insert(0, line)\n\n with open(filepath, 'w') as f:\n f.writelines(lines)": 629, "def find_coord_vars(ncds):\n \"\"\"\n Finds all coordinate variables in a dataset.\n\n A variable with the same name as a dimension is called a coordinate variable.\n \"\"\"\n coord_vars = []\n\n for d in ncds.dimensions:\n if d in ncds.variables and ncds.variables[d].dimensions == (d,):\n coord_vars.append(ncds.variables[d])\n\n return coord_vars": 630, "def get_func_posargs_name(f):\n \"\"\"Returns the name of the function f's keyword argument parameter if it exists, otherwise None\"\"\"\n sigparams = inspect.signature(f).parameters\n for p in sigparams:\n if sigparams[p].kind == inspect.Parameter.VAR_POSITIONAL:\n return sigparams[p].name\n return None": 631, "def check_git():\n \"\"\"Check if git command is available.\"\"\"\n try:\n with open(os.devnull, \"wb\") as devnull:\n subprocess.check_call([\"git\", \"--version\"], stdout=devnull, stderr=devnull)\n except:\n raise RuntimeError(\"Please make sure git is installed and on your path.\")": 632, "def as_list(self):\n \"\"\"Return all child objects in nested lists of strings.\"\"\"\n return [self.name, self.value, [x.as_list for x in self.children]]": 633, "def positive_integer(anon, obj, field, val):\n \"\"\"\n Returns a random positive integer (for a Django PositiveIntegerField)\n \"\"\"\n return anon.faker.positive_integer(field=field)": 634, "def method(func):\n \"\"\"Wrap a function as a method.\"\"\"\n attr = abc.abstractmethod(func)\n attr.__imethod__ = True\n return attr": 635, "def get_lines(handle, line):\n \"\"\"\n Get zero-indexed line from an open file-like.\n \"\"\"\n for i, l in enumerate(handle):\n if i == line:\n return l": 636, "def is_int(value):\n \"\"\"Return `True` if ``value`` is an integer.\"\"\"\n if isinstance(value, bool):\n return False\n try:\n int(value)\n return True\n except (ValueError, TypeError):\n return False": 637, "def norm(x, mu, sigma=1.0):\n \"\"\" Scipy norm function \"\"\"\n return stats.norm(loc=mu, scale=sigma).pdf(x)": 638, "def add_noise(Y, sigma):\n \"\"\"Adds noise to Y\"\"\"\n return Y + np.random.normal(0, sigma, Y.shape)": 639, "def spline_interpolate_by_datetime(datetime_axis, y_axis, datetime_new_axis):\n \"\"\"A datetime-version that takes datetime object list as x_axis\n \"\"\"\n numeric_datetime_axis = [\n totimestamp(a_datetime) for a_datetime in datetime_axis\n ]\n\n numeric_datetime_new_axis = [\n totimestamp(a_datetime) for a_datetime in datetime_new_axis\n ]\n\n return spline_interpolate(\n numeric_datetime_axis, y_axis, numeric_datetime_new_axis)": 640, "def _load_data(filepath):\n \"\"\"Loads the images and latent values into Numpy arrays.\"\"\"\n with h5py.File(filepath, \"r\") as h5dataset:\n image_array = np.array(h5dataset[\"images\"])\n # The 'label' data set in the hdf5 file actually contains the float values\n # and not the class labels.\n values_array = np.array(h5dataset[\"labels\"])\n return image_array, values_array": 641, "def invertDictMapping(d):\n \"\"\" Invert mapping of dictionary (i.e. map values to list of keys) \"\"\"\n inv_map = {}\n for k, v in d.items():\n inv_map[v] = inv_map.get(v, [])\n inv_map[v].append(k)\n return inv_map": 642, "def chunk_list(l, n):\n \"\"\"Return `n` size lists from a given list `l`\"\"\"\n return [l[i:i + n] for i in range(0, len(l), n)]": 643, "def is_valid_ip(ip_address):\n \"\"\"\n Check Validity of an IP address\n \"\"\"\n valid = True\n try:\n socket.inet_aton(ip_address.strip())\n except:\n valid = False\n return valid": 644, "def main(idle):\n \"\"\"Any normal python logic which runs a loop. Can take arguments.\"\"\"\n while True:\n\n LOG.debug(\"Sleeping for {0} seconds.\".format(idle))\n time.sleep(idle)": 645, "def unique(_list):\n \"\"\"\n Makes the list have unique items only and maintains the order\n\n list(set()) won't provide that\n\n :type _list list\n :rtype: list\n \"\"\"\n ret = []\n\n for item in _list:\n if item not in ret:\n ret.append(item)\n\n return ret": 646, "def is_a_sequence(var, allow_none=False):\n \"\"\" Returns True if var is a list or a tuple (but not a string!)\n \"\"\"\n return isinstance(var, (list, tuple)) or (var is None and allow_none)": 647, "def isin(elems, line):\n \"\"\"Check if an element from a list is in a string.\n\n :type elems: list\n :type line: str\n\n \"\"\"\n found = False\n for e in elems:\n if e in line.lower():\n found = True\n break\n return found": 648, "def _notnull(expr):\n \"\"\"\n Return a sequence or scalar according to the input indicating if the values are not null.\n\n :param expr: sequence or scalar\n :return: sequence or scalar\n \"\"\"\n\n if isinstance(expr, SequenceExpr):\n return NotNull(_input=expr, _data_type=types.boolean)\n elif isinstance(expr, Scalar):\n return NotNull(_input=expr, _value_type=types.boolean)": 649, "def conv_dict(self):\n \"\"\"dictionary of conversion\"\"\"\n return dict(integer=self.integer, real=self.real, no_type=self.no_type)": 650, "def _writable_dir(path):\n \"\"\"Whether `path` is a directory, to which the user has write access.\"\"\"\n return os.path.isdir(path) and os.access(path, os.W_OK)": 651, "def make_qs(n, m=None):\n \"\"\"Make sympy symbols q0, q1, ...\n \n Args:\n n(int), m(int, optional):\n If specified both n and m, returns [qn, q(n+1), ..., qm],\n Only n is specified, returns[q0, q1, ..., qn].\n\n Return:\n tuple(Symbol): Tuple of sympy symbols.\n \"\"\"\n try:\n import sympy\n except ImportError:\n raise ImportError(\"This function requires sympy. Please install it.\")\n if m is None:\n syms = sympy.symbols(\" \".join(f\"q{i}\" for i in range(n)))\n if isinstance(syms, tuple):\n return syms\n else:\n return (syms,)\n syms = sympy.symbols(\" \".join(f\"q{i}\" for i in range(n, m)))\n if isinstance(syms, tuple):\n return syms\n else:\n return (syms,)": 652, "def isdir(path, **kwargs):\n \"\"\"Check if *path* is a directory\"\"\"\n import os.path\n return os.path.isdir(path, **kwargs)": 653, "def batch(items, size):\n \"\"\"Batches a list into a list of lists, with sub-lists sized by a specified\n batch size.\"\"\"\n return [items[x:x + size] for x in xrange(0, len(items), size)]": 654, "def is_float_array(l):\n r\"\"\"Checks if l is a numpy array of floats (any dimension\n\n \"\"\"\n if isinstance(l, np.ndarray):\n if l.dtype.kind == 'f':\n return True\n return False": 655, "def myreplace(astr, thefind, thereplace):\n \"\"\"in string astr replace all occurences of thefind with thereplace\"\"\"\n alist = astr.split(thefind)\n new_s = alist.split(thereplace)\n return new_s": 656, "def is_iter_non_string(obj):\n \"\"\"test if object is a list or tuple\"\"\"\n if isinstance(obj, list) or isinstance(obj, tuple):\n return True\n return False": 657, "def round_to_x_digits(number, digits):\n \"\"\"\n Returns 'number' rounded to 'digits' digits.\n \"\"\"\n return round(number * math.pow(10, digits)) / math.pow(10, digits)": 658, "def __next__(self):\n \"\"\"Pop the head off the iterator and return it.\"\"\"\n res = self._head\n self._fill()\n if res is None:\n raise StopIteration()\n return res": 659, "def as_tuple(self, value):\n \"\"\"Utility function which converts lists to tuples.\"\"\"\n if isinstance(value, list):\n value = tuple(value)\n return value": 660, "def __reversed__(self):\n \"\"\"\n Return a reversed iterable over the items in the dictionary. Items are\n iterated over in their reverse sort order.\n\n Iterating views while adding or deleting entries in the dictionary may\n raise a RuntimeError or fail to iterate over all entries.\n \"\"\"\n _dict = self._dict\n return iter((key, _dict[key]) for key in reversed(self._list))": 661, "def register_modele(self, modele: Modele):\n \"\"\" Register a modele onto the lemmatizer\n\n :param modele: Modele to register\n \"\"\"\n self.lemmatiseur._modeles[modele.gr()] = modele": 662, "def split_every(n, iterable):\n \"\"\"Returns a generator that spits an iteratable into n-sized chunks. The last chunk may have\n less than n elements.\n\n See http://stackoverflow.com/a/22919323/503377.\"\"\"\n items = iter(iterable)\n return itertools.takewhile(bool, (list(itertools.islice(items, n)) for _ in itertools.count()))": 663, "def flatten(l):\n \"\"\"Flatten a nested list.\"\"\"\n return sum(map(flatten, l), []) \\\n if isinstance(l, list) or isinstance(l, tuple) else [l]": 664, "def directory_files(path):\n \"\"\"Yield directory file names.\"\"\"\n\n for entry in os.scandir(path):\n if not entry.name.startswith('.') and entry.is_file():\n yield entry.name": 665, "def read_array(path, mmap_mode=None):\n \"\"\"Read a .npy array.\"\"\"\n file_ext = op.splitext(path)[1]\n if file_ext == '.npy':\n return np.load(path, mmap_mode=mmap_mode)\n raise NotImplementedError(\"The file extension `{}` \".format(file_ext) +\n \"is not currently supported.\")": 666, "def group_by(iterable, key_func):\n \"\"\"Wrap itertools.groupby to make life easier.\"\"\"\n groups = (\n list(sub) for key, sub in groupby(iterable, key_func)\n )\n return zip(groups, groups)": 667, "def get_python():\n \"\"\"Determine the path to the virtualenv python\"\"\"\n if sys.platform == 'win32':\n python = path.join(VE_ROOT, 'Scripts', 'python.exe')\n else:\n python = path.join(VE_ROOT, 'bin', 'python')\n return python": 668, "def render_template(template_name, **context):\n \"\"\"Render a template into a response.\"\"\"\n tmpl = jinja_env.get_template(template_name)\n context[\"url_for\"] = url_for\n return Response(tmpl.render(context), mimetype=\"text/html\")": 669, "def selectnone(table, field, complement=False):\n \"\"\"Select rows where the given field is `None`.\"\"\"\n\n return select(table, field, lambda v: v is None, complement=complement)": 670, "def _join(verb):\n \"\"\"\n Join helper\n \"\"\"\n data = pd.merge(verb.x, verb.y, **verb.kwargs)\n\n # Preserve x groups\n if isinstance(verb.x, GroupedDataFrame):\n data.plydata_groups = list(verb.x.plydata_groups)\n return data": 671, "def stn(s, length, encoding, errors):\n \"\"\"Convert a string to a null-terminated bytes object.\n \"\"\"\n s = s.encode(encoding, errors)\n return s[:length] + (length - len(s)) * NUL": 672, "def join_images(img_files, out_file):\n \"\"\"Join the list of images into the out file\"\"\"\n images = [PIL.Image.open(f) for f in img_files]\n joined = PIL.Image.new(\n 'RGB',\n (sum(i.size[0] for i in images), max(i.size[1] for i in images))\n )\n left = 0\n for img in images:\n joined.paste(im=img, box=(left, 0))\n left = left + img.size[0]\n joined.save(out_file)": 673, "def _dict(content):\n \"\"\"\n Helper funcation that converts text-based get response\n to a python dictionary for additional manipulation.\n \"\"\"\n if _has_pandas:\n data = _data_frame(content).to_dict(orient='records')\n else:\n response = loads(content)\n key = [x for x in response.keys() if x in c.response_data][0]\n data = response[key]\n return data": 674, "def get_join_cols(by_entry):\n \"\"\" helper function used for joins\n builds left and right join list for join function\n \"\"\"\n left_cols = []\n right_cols = []\n for col in by_entry:\n if isinstance(col, str):\n left_cols.append(col)\n right_cols.append(col)\n else:\n left_cols.append(col[0])\n right_cols.append(col[1])\n return left_cols, right_cols": 675, "def IPYTHON_MAIN():\n \"\"\"Decide if the Ipython command line is running code.\"\"\"\n import pkg_resources\n\n runner_frame = inspect.getouterframes(inspect.currentframe())[-2]\n return (\n getattr(runner_frame, \"function\", None)\n == pkg_resources.load_entry_point(\"ipython\", \"console_scripts\", \"ipython\").__name__\n )": 676, "def flatten_dict_join_keys(dct, join_symbol=\" \"):\n \"\"\" Flatten dict with defined key join symbol.\n\n :param dct: dict to flatten\n :param join_symbol: default value is \" \"\n :return:\n \"\"\"\n return dict( flatten_dict(dct, join=lambda a,b:a+join_symbol+b) )": 677, "def hash_iterable(it):\n\t\"\"\"Perform a O(1) memory hash of an iterable of arbitrary length.\n\n\thash(tuple(it)) creates a temporary tuple containing all values from it\n\twhich could be a problem if it is large.\n\n\tSee discussion at:\n\thttps://groups.google.com/forum/#!msg/python-ideas/XcuC01a8SYs/e-doB9TbDwAJ\n\t\"\"\"\n\thash_value = hash(type(it))\n\tfor value in it:\n\t\thash_value = hash((hash_value, value))\n\treturn hash_value": 678, "def _to_diagonally_dominant(mat):\n \"\"\"Make matrix unweighted diagonally dominant using the Laplacian.\"\"\"\n mat += np.diag(np.sum(mat != 0, axis=1) + 0.01)\n return mat": 679, "def traverse_setter(obj, attribute, value):\n \"\"\"\n Traverses the object and sets the supplied attribute on the\n object. Supports Dimensioned and DimensionedPlot types.\n \"\"\"\n obj.traverse(lambda x: setattr(x, attribute, value))": 680, "def read_key(self, key, bucket_name=None):\n \"\"\"\n Reads a key from S3\n\n :param key: S3 key that will point to the file\n :type key: str\n :param bucket_name: Name of the bucket in which the file is stored\n :type bucket_name: str\n \"\"\"\n\n obj = self.get_key(key, bucket_name)\n return obj.get()['Body'].read().decode('utf-8')": 681, "def dump_json(obj):\n \"\"\"Dump Python object as JSON string.\"\"\"\n return simplejson.dumps(obj, ignore_nan=True, default=json_util.default)": 682, "def get_property(self, filename):\n \"\"\"Opens the file and reads the value\"\"\"\n\n with open(self.filepath(filename)) as f:\n return f.read().strip()": 683, "def pretty_dict_str(d, indent=2):\n \"\"\"shows JSON indented representation of d\"\"\"\n b = StringIO()\n write_pretty_dict_str(b, d, indent=indent)\n return b.getvalue()": 684, "def help_for_command(command):\n \"\"\"Get the help text (signature + docstring) for a command (function).\"\"\"\n help_text = pydoc.text.document(command)\n # remove backspaces\n return re.subn('.\\\\x08', '', help_text)[0]": 685, "def save(self, fname):\n \"\"\" Saves the dictionary in json format\n :param fname: file to save to\n \"\"\"\n with open(fname, 'wb') as f:\n json.dump(self, f)": 686, "def validate(raw_schema, target=None, **kwargs):\n \"\"\"\n Given the python representation of a JSONschema as defined in the swagger\n spec, validate that the schema complies to spec. If `target` is provided,\n that target will be validated against the provided schema.\n \"\"\"\n schema = schema_validator(raw_schema, **kwargs)\n if target is not None:\n validate_object(target, schema=schema, **kwargs)": 687, "def build_output(self, fout):\n \"\"\"Squash self.out into string.\n\n Join every line in self.out with a new line and write the\n result to the output file.\n \"\"\"\n fout.write('\\n'.join([s for s in self.out]))": 688, "def json_serial(obj):\n \"\"\"JSON serializer for objects not serializable by default json code\"\"\"\n if isinstance(obj, LegipyModel):\n return obj.to_json()\n elif isinstance(obj, (datetime.date, datetime.datetime)):\n return obj.isoformat()\n raise TypeError(\"Type {0} not serializable\".format(repr(type(obj))))": 689, "def generic_add(a, b):\n \"\"\"Simple function to add two numbers\"\"\"\n logger.debug('Called generic_add({}, {})'.format(a, b))\n return a + b": 690, "def _unjsonify(x, isattributes=False):\n \"\"\"Convert JSON string to an ordered defaultdict.\"\"\"\n if isattributes:\n obj = json.loads(x)\n return dict_class(obj)\n return json.loads(x)": 691, "def get_absolute_path(*args):\n \"\"\"Transform relative pathnames into absolute pathnames.\"\"\"\n directory = os.path.dirname(os.path.abspath(__file__))\n return os.path.join(directory, *args)": 692, "def graphql_queries_to_json(*queries):\n \"\"\"\n Queries should be a list of GraphQL objects\n \"\"\"\n rtn = {}\n for i, query in enumerate(queries):\n rtn[\"q{}\".format(i)] = query.value\n return json.dumps(rtn)": 693, "def synthesize(self, duration):\n \"\"\"\n Synthesize white noise\n\n Args:\n duration (numpy.timedelta64): The duration of the synthesized sound\n \"\"\"\n sr = self.samplerate.samples_per_second\n seconds = duration / Seconds(1)\n samples = np.random.uniform(low=-1., high=1., size=int(sr * seconds))\n return AudioSamples(samples, self.samplerate)": 694, "def _clean_dict(target_dict, whitelist=None):\n \"\"\" Convenience function that removes a dicts keys that have falsy values\n \"\"\"\n assert isinstance(target_dict, dict)\n return {\n ustr(k).strip(): ustr(v).strip()\n for k, v in target_dict.items()\n if v not in (None, Ellipsis, [], (), \"\")\n and (not whitelist or k in whitelist)\n }": 695, "def calculate_embedding(self, batch_image_bytes):\n \"\"\"Get the embeddings for a given JPEG image.\n\n Args:\n batch_image_bytes: As if returned from [ff.read() for ff in file_list].\n\n Returns:\n The Inception embeddings (bottleneck layer output)\n \"\"\"\n return self.tf_session.run(\n self.embedding, feed_dict={self.input_jpeg: batch_image_bytes})": 696, "def timeout_thread_handler(timeout, stop_event):\n \"\"\"A background thread to kill the process if it takes too long.\n\n Args:\n timeout (float): The number of seconds to wait before killing\n the process.\n stop_event (Event): An optional event to cleanly stop the background\n thread if required during testing.\n \"\"\"\n\n stop_happened = stop_event.wait(timeout)\n if stop_happened is False:\n print(\"Killing program due to %f second timeout\" % timeout)\n\n os._exit(2)": 697, "def copy_no_perm(src, dst):\n \"\"\"\n Copies a file from *src* to *dst* including meta data except for permission bits.\n \"\"\"\n shutil.copy(src, dst)\n perm = os.stat(dst).st_mode\n shutil.copystat(src, dst)\n os.chmod(dst, perm)": 698, "def iter_with_last(iterable):\n \"\"\"\n :return: generator of tuples (isLastFlag, item)\n \"\"\"\n # Ensure it's an iterator and get the first field\n iterable = iter(iterable)\n prev = next(iterable)\n for item in iterable:\n # Lag by one item so I know I'm not at the end\n yield False, prev\n prev = item\n # Last item\n yield True, prev": 699, "def store_data(data):\n \"\"\"Use this function to store data in a JSON file.\n\n This function is used for loading up a JSON file and appending additional\n data to the JSON file.\n\n :param data: the data to add to the JSON file.\n :type data: dict\n \"\"\"\n with open(url_json_path) as json_file:\n try:\n json_file_data = load(json_file)\n json_file_data.update(data)\n except (AttributeError, JSONDecodeError):\n json_file_data = data\n with open(url_json_path, 'w') as json_file:\n dump(json_file_data, json_file, indent=4, sort_keys=True)": 700, "def filename_addstring(filename, text):\n \"\"\"\n Add `text` to filename, keeping the extension in place\n For example when adding a timestamp to the filename\n \"\"\"\n fn, ext = os.path.splitext(filename)\n return fn + text + ext": 701, "def pop(self):\n \"\"\"\n return the last stack element and delete it from the list\n \"\"\"\n if not self.empty():\n val = self.stack[-1]\n del self.stack[-1]\n return val": 702, "def interpolate_logscale_single(start, end, coefficient):\n \"\"\" Cosine interpolation \"\"\"\n return np.exp(np.log(start) + (np.log(end) - np.log(start)) * coefficient)": 703, "def get_last_modified_timestamp(self):\n \"\"\"\n Looks at the files in a git root directory and grabs the last modified timestamp\n \"\"\"\n cmd = \"find . -print0 | xargs -0 stat -f '%T@ %p' | sort -n | tail -1 | cut -f2- -d' '\"\n ps = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)\n output = ps.communicate()[0]\n print output": 704, "def _stdin_(p):\n \"\"\"Takes input from user. Works for Python 2 and 3.\"\"\"\n _v = sys.version[0]\n return input(p) if _v is '3' else raw_input(p)": 705, "def get_list_dimensions(_list):\n \"\"\"\n Takes a nested list and returns the size of each dimension followed\n by the element type in the list\n \"\"\"\n if isinstance(_list, list) or isinstance(_list, tuple):\n return [len(_list)] + get_list_dimensions(_list[0])\n return []": 706, "def sort_filenames(filenames):\n \"\"\"\n sort a list of files by filename only, ignoring the directory names\n \"\"\"\n basenames = [os.path.basename(x) for x in filenames]\n indexes = [i[0] for i in sorted(enumerate(basenames), key=lambda x:x[1])]\n return [filenames[x] for x in indexes]": 707, "def levenshtein_distance_metric(a, b):\n \"\"\" 1 - farthest apart (same number of words, all diff). 0 - same\"\"\"\n return (levenshtein_distance(a, b) / (2.0 * max(len(a), len(b), 1)))": 708, "def wait_until_exit(self):\n \"\"\" Wait until thread exit\n\n Used for testing purpose only\n \"\"\"\n\n if self._timeout is None:\n raise Exception(\"Thread will never exit. Use stop or specify timeout when starting it!\")\n\n self._thread.join()\n self.stop()": 709, "def timed (log=sys.stderr, limit=2.0):\n \"\"\"Decorator to run a function with timing info.\"\"\"\n return lambda func: timeit(func, log, limit)": 710, "def dict_jsonp(param):\n \"\"\"Convert the parameter into a dictionary before calling jsonp, if it's not already one\"\"\"\n if not isinstance(param, dict):\n param = dict(param)\n return jsonp(param)": 711, "def txt_line_iterator(path):\n \"\"\"Iterate through lines of file.\"\"\"\n with tf.gfile.Open(path) as f:\n for line in f:\n yield line.strip()": 712, "def get_size(objects):\n \"\"\"Compute the total size of all elements in objects.\"\"\"\n res = 0\n for o in objects:\n try:\n res += _getsizeof(o)\n except AttributeError:\n print(\"IGNORING: type=%s; o=%s\" % (str(type(o)), str(o)))\n return res": 713, "def distinct(xs):\n \"\"\"Get the list of distinct values with preserving order.\"\"\"\n # don't use collections.OrderedDict because we do support Python 2.6\n seen = set()\n return [x for x in xs if x not in seen and not seen.add(x)]": 714, "def stderr(a):\n \"\"\"\n Calculate the standard error of a.\n \"\"\"\n return np.nanstd(a) / np.sqrt(sum(np.isfinite(a)))": 715, "def get_table_names(connection):\n\t\"\"\"\n\tReturn a list of the table names in the database.\n\t\"\"\"\n\tcursor = connection.cursor()\n\tcursor.execute(\"SELECT name FROM sqlite_master WHERE type == 'table'\")\n\treturn [name for (name,) in cursor]": 716, "def time(func, *args, **kwargs):\n \"\"\"\n Call the supplied function with the supplied arguments,\n and return the total execution time as a float in seconds.\n\n The precision of the returned value depends on the precision of\n `time.time()` on your platform.\n\n Arguments:\n func: the function to run.\n *args: positional arguments to pass into the function.\n **kwargs: keyword arguments to pass into the function.\n Returns:\n Execution time of the function as a float in seconds.\n \"\"\"\n start_time = time_module.time()\n func(*args, **kwargs)\n end_time = time_module.time()\n return end_time - start_time": 717, "def camel_case_from_underscores(string):\n \"\"\"generate a CamelCase string from an underscore_string.\"\"\"\n components = string.split('_')\n string = ''\n for component in components:\n string += component[0].upper() + component[1:]\n return string": 718, "def list_get(l, idx, default=None):\n \"\"\"\n Get from a list with an optional default value.\n \"\"\"\n try:\n if l[idx]:\n return l[idx]\n else:\n return default\n except IndexError:\n return default": 719, "def classnameify(s):\n \"\"\"\n Makes a classname\n \"\"\"\n return ''.join(w if w in ACRONYMS else w.title() for w in s.split('_'))": 720, "def dedupe_list(l):\n \"\"\"Remove duplicates from a list preserving the order.\n\n We might be tempted to use the list(set(l)) idiom, but it doesn't preserve\n the order, which hinders testability and does not work for lists with\n unhashable elements.\n \"\"\"\n result = []\n\n for el in l:\n if el not in result:\n result.append(el)\n\n return result": 721, "def force_to_string(unknown):\n \"\"\"\n converts and unknown type to string for display purposes.\n \n \"\"\"\n result = ''\n if type(unknown) is str:\n result = unknown\n if type(unknown) is int:\n result = str(unknown)\n if type(unknown) is float:\n result = str(unknown)\n if type(unknown) is dict:\n result = Dict2String(unknown)\n if type(unknown) is list:\n result = List2String(unknown)\n return result": 722, "def nan_pixels(self):\n \"\"\" Return an array of the NaN pixels.\n\n Returns\n -------\n :obj:`numpy.ndarray`\n Nx2 array of the NaN pixels\n \"\"\"\n nan_px = np.where(np.isnan(np.sum(self.raw_data, axis=2)))\n nan_px = np.c_[nan_px[0], nan_px[1]]\n return nan_px": 723, "def clean_error(err):\n \"\"\"\n Take stderr bytes returned from MicroPython and attempt to create a\n non-verbose error message.\n \"\"\"\n if err:\n decoded = err.decode('utf-8')\n try:\n return decoded.split('\\r\\n')[-2]\n except Exception:\n return decoded\n return 'There was an error.'": 724, "def downcaseTokens(s,l,t):\n \"\"\"Helper parse action to convert tokens to lower case.\"\"\"\n return [ tt.lower() for tt in map(_ustr,t) ]": 725, "def arr_to_vector(arr):\n \"\"\"Reshape a multidimensional array to a vector.\n \"\"\"\n dim = array_dim(arr)\n tmp_arr = []\n for n in range(len(dim) - 1):\n for inner in arr:\n for i in inner:\n tmp_arr.append(i)\n arr = tmp_arr\n tmp_arr = []\n return arr": 726, "def get_all_attributes(klass_or_instance):\n \"\"\"Get all attribute members (attribute, property style method).\n \"\"\"\n pairs = list()\n for attr, value in inspect.getmembers(\n klass_or_instance, lambda x: not inspect.isroutine(x)):\n if not (attr.startswith(\"__\") or attr.endswith(\"__\")):\n pairs.append((attr, value))\n return pairs": 727, "def session_to_epoch(timestamp):\n \"\"\" converts Synergy Timestamp for session to UTC zone seconds since epoch \"\"\"\n utc_timetuple = datetime.strptime(timestamp, SYNERGY_SESSION_PATTERN).replace(tzinfo=None).utctimetuple()\n return calendar.timegm(utc_timetuple)": 728, "def zero_pixels(self):\n \"\"\" Return an array of the zero pixels.\n\n Returns\n -------\n :obj:`numpy.ndarray`\n Nx2 array of the zero pixels\n \"\"\"\n zero_px = np.where(np.sum(self.raw_data, axis=2) == 0)\n zero_px = np.c_[zero_px[0], zero_px[1]]\n return zero_px": 729, "def end_table_header(self):\n r\"\"\"End the table header which will appear on every page.\"\"\"\n\n if self.header:\n msg = \"Table already has a header\"\n raise TableError(msg)\n\n self.header = True\n\n self.append(Command(r'endhead'))": 730, "def raise_os_error(_errno, path=None):\n \"\"\"\n Helper for raising the correct exception under Python 3 while still\n being able to raise the same common exception class in Python 2.7.\n \"\"\"\n\n msg = \"%s: '%s'\" % (strerror(_errno), path) if path else strerror(_errno)\n raise OSError(_errno, msg)": 731, "def get_mnist(data_type=\"train\", location=\"/tmp/mnist\"):\n \"\"\"\n Get mnist dataset with features and label as ndarray.\n Data would be downloaded automatically if it doesn't present at the specific location.\n\n :param data_type: \"train\" for training data and \"test\" for testing data.\n :param location: Location to store mnist dataset.\n :return: (features: ndarray, label: ndarray)\n \"\"\"\n X, Y = mnist.read_data_sets(location, data_type)\n return X, Y + 1": 732, "def _multiline_width(multiline_s, line_width_fn=len):\n \"\"\"Visible width of a potentially multiline content.\"\"\"\n return max(map(line_width_fn, re.split(\"[\\r\\n]\", multiline_s)))": 733, "def col_rename(df,col_name,new_col_name):\n \"\"\" Changes a column name in a DataFrame\n Parameters:\n df - DataFrame\n DataFrame to operate on\n col_name - string\n Name of column to change\n new_col_name - string\n New name of column\n \"\"\"\n col_list = list(df.columns)\n for index,value in enumerate(col_list):\n if value == col_name:\n col_list[index] = new_col_name\n break\n df.columns = col_list": 734, "def _include_yaml(loader, node):\n \"\"\"Load another YAML file and embeds it using the !include tag.\n\n Example:\n device_tracker: !include device_tracker.yaml\n \"\"\"\n return load_yaml(os.path.join(os.path.dirname(loader.name), node.value))": 735, "def comma_converter(float_string):\n \"\"\"Convert numbers to floats whether the decimal point is '.' or ','\"\"\"\n trans_table = maketrans(b',', b'.')\n return float(float_string.translate(trans_table))": 736, "def datetime_local_to_utc(local):\n \"\"\"\n Simple function to convert naive :std:`datetime.datetime` object containing\n local time to a naive :std:`datetime.datetime` object with UTC time.\n \"\"\"\n timestamp = time.mktime(local.timetuple())\n return datetime.datetime.utcfromtimestamp(timestamp)": 737, "def to_identifier(s):\n \"\"\"\n Convert snake_case to camel_case.\n \"\"\"\n if s.startswith('GPS'):\n s = 'Gps' + s[3:]\n return ''.join([i.capitalize() for i in s.split('_')]) if '_' in s else s": 738, "def lock(self, block=True):\n\t\t\"\"\"\n\t\tLock connection from being used else where\n\t\t\"\"\"\n\t\tself._locked = True\n\t\treturn self._lock.acquire(block)": 739, "def _validate_pos(df):\n \"\"\"Validates the returned positional object\n \"\"\"\n assert isinstance(df, pd.DataFrame)\n assert [\"seqname\", \"position\", \"strand\"] == df.columns.tolist()\n assert df.position.dtype == np.dtype(\"int64\")\n assert df.strand.dtype == np.dtype(\"O\")\n assert df.seqname.dtype == np.dtype(\"O\")\n return df": 740, "def lognorm(x, mu, sigma=1.0):\n \"\"\" Log-normal function from scipy \"\"\"\n return stats.lognorm(sigma, scale=mu).pdf(x)": 741, "def autoconvert(string):\n \"\"\"Try to convert variables into datatypes.\"\"\"\n for fn in (boolify, int, float):\n try:\n return fn(string)\n except ValueError:\n pass\n return string": 742, "def to_distribution_values(self, values):\n \"\"\"\n Returns numpy array of natural logarithms of ``values``.\n \"\"\"\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n # avoid RuntimeWarning: divide by zero encountered in log\n return numpy.log(values)": 743, "def find_console_handler(logger):\n \"\"\"Return a stream handler, if it exists.\"\"\"\n for handler in logger.handlers:\n if (isinstance(handler, logging.StreamHandler) and\n handler.stream == sys.stderr):\n return handler": 744, "def unicode_is_ascii(u_string):\n \"\"\"Determine if unicode string only contains ASCII characters.\n\n :param str u_string: unicode string to check. Must be unicode\n and not Python 2 `str`.\n :rtype: bool\n \"\"\"\n assert isinstance(u_string, str)\n try:\n u_string.encode('ascii')\n return True\n except UnicodeEncodeError:\n return False": 745, "def clog(color):\n \"\"\"Same to ``log``, but this one centralizes the message first.\"\"\"\n logger = log(color)\n return lambda msg: logger(centralize(msg).rstrip())": 746, "def is_defined(self, obj, force_import=False):\n \"\"\"Return True if object is defined in current namespace\"\"\"\n from spyder_kernels.utils.dochelpers import isdefined\n\n ns = self._get_current_namespace(with_magics=True)\n return isdefined(obj, force_import=force_import, namespace=ns)": 747, "def format(self, record, *args, **kwargs):\n \"\"\"\n Format a message in the log\n\n Act like the normal format, but indent anything that is a\n newline within the message.\n\n \"\"\"\n return logging.Formatter.format(\n self, record, *args, **kwargs).replace('\\n', '\\n' + ' ' * 8)": 748, "def is_delimiter(line):\n \"\"\" True if a line consists only of a single punctuation character.\"\"\"\n return bool(line) and line[0] in punctuation and line[0]*len(line) == line": 749, "def load_config(filename=\"logging.ini\", *args, **kwargs):\n \"\"\"\n Load logger config from file\n \n Keyword arguments:\n filename -- configuration filename (Default: \"logging.ini\")\n *args -- options passed to fileConfig\n **kwargs -- options passed to fileConfigg\n \n \"\"\"\n logging.config.fileConfig(filename, *args, **kwargs)": 750, "def is_parameter(self):\n \"\"\"Whether this is a function parameter.\"\"\"\n return (isinstance(self.scope, CodeFunction)\n and self in self.scope.parameters)": 751, "def print_log(value_color=\"\", value_noncolor=\"\"):\n \"\"\"set the colors for text.\"\"\"\n HEADER = '\\033[92m'\n ENDC = '\\033[0m'\n print(HEADER + value_color + ENDC + str(value_noncolor))": 752, "def is_seq(obj):\n \"\"\" Returns True if object is not a string but is iterable \"\"\"\n if not hasattr(obj, '__iter__'):\n return False\n if isinstance(obj, basestring):\n return False\n return True": 753, "def logger(message, level=10):\n \"\"\"Handle logging.\"\"\"\n logging.getLogger(__name__).log(level, str(message))": 754, "def is_listish(obj):\n \"\"\"Check if something quacks like a list.\"\"\"\n if isinstance(obj, (list, tuple, set)):\n return True\n return is_sequence(obj)": 755, "def isin(value, values):\n \"\"\" Check that value is in values \"\"\"\n for i, v in enumerate(value):\n if v not in np.array(values)[:, i]:\n return False\n return True": 756, "def is_non_empty_string(input_string):\n \"\"\"\n Validate if non empty string\n\n :param input_string: Input is a *str*.\n :return: True if input is string and non empty.\n Raise :exc:`Exception` otherwise.\n \"\"\"\n try:\n if not input_string.strip():\n raise ValueError()\n except AttributeError as error:\n raise TypeError(error)\n\n return True": 757, "def get_naive(dt):\n \"\"\"Gets a naive datetime from a datetime.\n\n datetime_tz objects can't just have tzinfo replaced with None, you need to\n call asdatetime.\n\n Args:\n dt: datetime object.\n\n Returns:\n datetime object without any timezone information.\n \"\"\"\n if not dt.tzinfo:\n return dt\n if hasattr(dt, \"asdatetime\"):\n return dt.asdatetime()\n return dt.replace(tzinfo=None)": 758, "def _match_literal(self, a, b=None):\n \"\"\"Match two names.\"\"\"\n\n return a.lower() == b if not self.case_sensitive else a == b": 759, "def make_symmetric(dict):\n \"\"\"Makes the given dictionary symmetric. Values are assumed to be unique.\"\"\"\n for key, value in list(dict.items()):\n dict[value] = key\n return dict": 760, "def isnumber(*args):\n \"\"\"Checks if value is an integer, long integer or float.\n\n NOTE: Treats booleans as numbers, where True=1 and False=0.\n \"\"\"\n return all(map(lambda c: isinstance(c, int) or isinstance(c, float), args))": 761, "def relpath(path):\n \"\"\"Path helper, gives you a path relative to this file\"\"\"\n return os.path.normpath(\n os.path.join(os.path.abspath(os.path.dirname(__file__)), path)\n )": 762, "def cudaDriverGetVersion():\n \"\"\"\n Get installed CUDA driver version.\n\n Return the version of the installed CUDA driver as an integer. If\n no driver is detected, 0 is returned.\n\n Returns\n -------\n version : int\n Driver version.\n\n \"\"\"\n\n version = ctypes.c_int()\n status = _libcudart.cudaDriverGetVersion(ctypes.byref(version))\n cudaCheckStatus(status)\n return version.value": 763, "def israw(self, **kwargs):\n \"\"\"\n Returns True if the PTY should operate in raw mode.\n\n If the container was not started with tty=True, this will return False.\n \"\"\"\n\n if self.raw is None:\n info = self._container_info()\n self.raw = self.stdout.isatty() and info['Config']['Tty']\n\n return self.raw": 764, "def html(header_rows):\n \"\"\"\n Convert a list of tuples describing a table into a HTML string\n \"\"\"\n name = 'table%d' % next(tablecounter)\n return HtmlTable([map(str, row) for row in header_rows], name).render()": 765, "def isSquare(matrix):\n \"\"\"Check that ``matrix`` is square.\n\n Returns\n =======\n is_square : bool\n ``True`` if ``matrix`` is square, ``False`` otherwise.\n\n \"\"\"\n try:\n try:\n dim1, dim2 = matrix.shape\n except AttributeError:\n dim1, dim2 = _np.array(matrix).shape\n except ValueError:\n return False\n if dim1 == dim2:\n return True\n return False": 766, "def ver_to_tuple(value):\n \"\"\"\n Convert version like string to a tuple of integers.\n \"\"\"\n return tuple(int(_f) for _f in re.split(r'\\D+', value) if _f)": 767, "def is_type(value):\n \"\"\"Determine if value is an instance or subclass of the class Type.\"\"\"\n if isinstance(value, type):\n return issubclass(value, Type)\n return isinstance(value, Type)": 768, "def _strvar(a, prec='{:G}'):\n r\"\"\"Return variable as a string to print, with given precision.\"\"\"\n return ' '.join([prec.format(i) for i in np.atleast_1d(a)])": 769, "def check_filename(filename):\n \"\"\"\n Returns a boolean stating if the filename is safe to use or not. Note that\n this does not test for \"legal\" names accepted, but a more restricted set of:\n Letters, numbers, spaces, hyphens, underscores and periods.\n\n :param filename: name of a file as a string\n :return: boolean if it is a safe file name\n \"\"\"\n if not isinstance(filename, str):\n raise TypeError(\"filename must be a string\")\n if regex.path.linux.filename.search(filename):\n return True\n return False": 770, "def GeneratePassphrase(length=20):\n \"\"\"Create a 20 char passphrase with easily typeable chars.\"\"\"\n valid_chars = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n valid_chars += \"0123456789 ,-_&$#\"\n return \"\".join(random.choice(valid_chars) for i in range(length))": 771, "def is_float(value):\n \"\"\"must be a float\"\"\"\n return isinstance(value, float) or isinstance(value, int) or isinstance(value, np.float64), float(value)": 772, "def _sub_patterns(patterns, text):\n \"\"\"\n Apply re.sub to bunch of (pattern, repl)\n \"\"\"\n for pattern, repl in patterns:\n text = re.sub(pattern, repl, text)\n return text": 773, "def on_source_directory_chooser_clicked(self):\n \"\"\"Autoconnect slot activated when tbSourceDir is clicked.\"\"\"\n\n title = self.tr('Set the source directory for script and scenario')\n self.choose_directory(self.source_directory, title)": 774, "def from_json_list(cls, api_client, data):\n \"\"\"Convert a list of JSON values to a list of models\n \"\"\"\n return [cls.from_json(api_client, item) for item in data]": 775, "def clean_all(self, args):\n \"\"\"Delete all build components; the package cache, package builds,\n bootstrap builds and distributions.\"\"\"\n self.clean_dists(args)\n self.clean_builds(args)\n self.clean_download_cache(args)": 776, "def _merge_maps(m1, m2):\n \"\"\"merge two Mapping objects, keeping the type of the first mapping\"\"\"\n return type(m1)(chain(m1.items(), m2.items()))": 777, "def strip(notebook):\n \"\"\"Remove outputs from a notebook.\"\"\"\n for cell in notebook.cells:\n if cell.cell_type == 'code':\n cell.outputs = []\n cell.execution_count = None": 778, "def find_whole_word(w):\n \"\"\"\n Scan through string looking for a location where this word produces a match,\n and return a corresponding MatchObject instance.\n Return None if no position in the string matches the pattern;\n note that this is different from finding a zero-length match at some point in the string.\n \"\"\"\n return re.compile(r'\\b({0})\\b'.format(w), flags=re.IGNORECASE).search": 779, "def __delitem__(self, resource):\n \"\"\"Remove resource instance from internal cache\"\"\"\n self.__caches[type(resource)].pop(resource.get_cache_internal_key(), None)": 780, "def autozoom(self, n=None):\n \"\"\"\n Auto-scales the axes to fit all the data in plot index n. If n == None,\n auto-scale everyone.\n \"\"\"\n if n==None:\n for p in self.plot_widgets: p.autoRange()\n else: self.plot_widgets[n].autoRange()\n\n return self": 781, "def color_to_hex(color):\n \"\"\"Convert matplotlib color code to hex color code\"\"\"\n if color is None or colorConverter.to_rgba(color)[3] == 0:\n return 'none'\n else:\n rgb = colorConverter.to_rgb(color)\n return '#{0:02X}{1:02X}{2:02X}'.format(*(int(255 * c) for c in rgb))": 782, "def erase_lines(n=1):\n \"\"\" Erases n lines from the screen and moves the cursor up to follow\n \"\"\"\n for _ in range(n):\n print(codes.cursor[\"up\"], end=\"\")\n print(codes.cursor[\"eol\"], end=\"\")": 783, "def horizontal_line(ax, scale, i, **kwargs):\n \"\"\"\n Draws the i-th horizontal line parallel to the lower axis.\n\n Parameters\n ----------\n ax: Matplotlib AxesSubplot\n The subplot to draw on.\n scale: float, 1.0\n Simplex scale size.\n i: float\n The index of the line to draw\n kwargs: Dictionary\n Any kwargs to pass through to Matplotlib.\n \"\"\"\n\n p1 = (0, i, scale - i)\n p2 = (scale - i, i, 0)\n line(ax, p1, p2, **kwargs)": 784, "def terminate(self):\n \"\"\"Terminate all workers and threads.\"\"\"\n for t in self._threads:\n t.quit()\n self._thread = []\n self._workers = []": 785, "def raise_figure_window(f=0):\n \"\"\"\n Raises the supplied figure number or figure window.\n \"\"\"\n if _fun.is_a_number(f): f = _pylab.figure(f)\n f.canvas.manager.window.raise_()": 786, "def linregress(x, y, return_stats=False):\n \"\"\"linear regression calculation\n\n Parameters\n ----\n x : independent variable (series)\n y : dependent variable (series)\n return_stats : returns statistical values as well if required (bool)\n \n\n Returns\n ----\n list of parameters (and statistics)\n \"\"\"\n a1, a0, r_value, p_value, stderr = scipy.stats.linregress(x, y)\n\n retval = a1, a0\n if return_stats:\n retval += r_value, p_value, stderr\n\n return retval": 787, "def clear_matplotlib_ticks(self, axis=\"both\"):\n \"\"\"Clears the default matplotlib ticks.\"\"\"\n ax = self.get_axes()\n plotting.clear_matplotlib_ticks(ax=ax, axis=axis)": 788, "def get_latex_table(self, parameters=None, transpose=False, caption=None,\n label=\"tab:model_params\", hlines=True, blank_fill=\"--\"): # pragma: no cover\n \"\"\" Generates a LaTeX table from parameter summaries.\n\n Parameters\n ----------\n parameters : list[str], optional\n A list of what parameters to include in the table. By default, includes all parameters\n transpose : bool, optional\n Defaults to False, which gives each column as a parameter, each chain (framework)\n as a row. You can swap it so that you have a parameter each row and a framework\n each column by setting this to True\n caption : str, optional\n If you want to generate a caption for the table through Python, use this.\n Defaults to an empty string\n label : str, optional\n If you want to generate a label for the table through Python, use this.\n Defaults to an empty string\n hlines : bool, optional\n Inserts ``\\\\hline`` before and after the header, and at the end of table.\n blank_fill : str, optional\n If a framework does not have a particular parameter, will fill that cell of\n the table with this string.\n\n Returns\n -------\n str\n the LaTeX table.\n \"\"\"\n if parameters is None:\n parameters = self.parent._all_parameters\n for p in parameters:\n assert isinstance(p, str), \\\n \"Generating a LaTeX table requires all parameters have labels\"\n num_parameters = len(parameters)\n num_chains = len(self.parent.chains)\n fit_values = self.get_summary(squeeze=False)\n if label is None:\n label = \"\"\n if caption is None:\n caption = \"\"\n\n end_text = \" \\\\\\\\ \\n\"\n if transpose:\n column_text = \"c\" * (num_chains + 1)\n else:\n column_text = \"c\" * (num_parameters + 1)\n\n center_text = \"\"\n hline_text = \"\\\\hline\\n\"\n if hlines:\n center_text += hline_text + \"\\t\\t\"\n if transpose:\n center_text += \" & \".join([\"Parameter\"] + [c.name for c in self.parent.chains]) + end_text\n if hlines:\n center_text += \"\\t\\t\" + hline_text\n for p in parameters:\n arr = [\"\\t\\t\" + p]\n for chain_res in fit_values:\n if p in chain_res:\n arr.append(self.get_parameter_text(*chain_res[p], wrap=True))\n else:\n arr.append(blank_fill)\n center_text += \" & \".join(arr) + end_text\n else:\n center_text += \" & \".join([\"Model\"] + parameters) + end_text\n if hlines:\n center_text += \"\\t\\t\" + hline_text\n for name, chain_res in zip([c.name for c in self.parent.chains], fit_values):\n arr = [\"\\t\\t\" + name]\n for p in parameters:\n if p in chain_res:\n arr.append(self.get_parameter_text(*chain_res[p], wrap=True))\n else:\n arr.append(blank_fill)\n center_text += \" & \".join(arr) + end_text\n if hlines:\n center_text += \"\\t\\t\" + hline_text\n final_text = get_latex_table_frame(caption, label) % (column_text, center_text)\n\n return final_text": 789, "def set_ylimits(self, row, column, min=None, max=None):\n \"\"\"Set y-axis limits of a subplot.\n\n :param row,column: specify the subplot.\n :param min: minimal axis value\n :param max: maximum axis value\n\n \"\"\"\n subplot = self.get_subplot_at(row, column)\n subplot.set_ylimits(min, max)": 790, "def _norm(self, x):\n \"\"\"Compute the safe norm.\"\"\"\n return tf.sqrt(tf.reduce_sum(tf.square(x), keepdims=True, axis=-1) + 1e-7)": 791, "def show(self, imgs, ax=None):\n \"\"\" Visualize the persistence image\n\n \"\"\"\n\n ax = ax or plt.gca()\n\n if type(imgs) is not list:\n imgs = [imgs]\n\n for i, img in enumerate(imgs):\n ax.imshow(img, cmap=plt.get_cmap(\"plasma\"))\n ax.axis(\"off\")": 792, "def cross_join(df1, df2):\n \"\"\"\n Return a dataframe that is a cross between dataframes\n df1 and df2\n\n ref: https://github.com/pydata/pandas/issues/5401\n \"\"\"\n if len(df1) == 0:\n return df2\n\n if len(df2) == 0:\n return df1\n\n # Add as lists so that the new index keeps the items in\n # the order that they are added together\n all_columns = pd.Index(list(df1.columns) + list(df2.columns))\n df1['key'] = 1\n df2['key'] = 1\n return pd.merge(df1, df2, on='key').loc[:, all_columns]": 793, "def downsample(array, k):\n \"\"\"Choose k random elements of array.\"\"\"\n length = array.shape[0]\n indices = random.sample(xrange(length), k)\n return array[indices]": 794, "def cmp_contents(filename1, filename2):\n \"\"\" Returns True if contents of the files are the same\n\n Parameters\n ----------\n filename1 : str\n filename of first file to compare\n filename2 : str\n filename of second file to compare\n\n Returns\n -------\n tf : bool\n True if binary contents of `filename1` is same as binary contents of\n `filename2`, False otherwise.\n \"\"\"\n with open_readable(filename1, 'rb') as fobj:\n contents1 = fobj.read()\n with open_readable(filename2, 'rb') as fobj:\n contents2 = fobj.read()\n return contents1 == contents2": 795, "def _digits(minval, maxval):\n \"\"\"Digits needed to comforatbly display values in [minval, maxval]\"\"\"\n if minval == maxval:\n return 3\n else:\n return min(10, max(2, int(1 + abs(np.log10(maxval - minval)))))": 796, "def compare(a, b):\n \"\"\"\n Compare items in 2 arrays. Returns sum(abs(a(i)-b(i)))\n \"\"\"\n s=0\n for i in range(len(a)):\n s=s+abs(a[i]-b[i])\n return s": 797, "def compare(left, right):\n \"\"\"\n yields EVENT,ENTRY pairs describing the differences between left\n and right, which are filenames for a pair of zip files\n \"\"\"\n\n with open_zip(left) as l:\n with open_zip(right) as r:\n return compare_zips(l, r)": 798, "def coverage():\n \"\"\"Run coverage tests.\"\"\"\n # Note: coverage options are controlled by .coveragerc file\n install()\n test_setup()\n sh(\"%s -m coverage run %s\" % (PYTHON, TEST_SCRIPT))\n sh(\"%s -m coverage report\" % PYTHON)\n sh(\"%s -m coverage html\" % PYTHON)\n sh(\"%s -m webbrowser -t htmlcov/index.html\" % PYTHON)": 799, "def m(name='', **kwargs):\n \"\"\"\n Print out memory usage at this point in time\n\n http://docs.python.org/2/library/resource.html\n http://stackoverflow.com/a/15448600/5006\n http://stackoverflow.com/questions/110259/which-python-memory-profiler-is-recommended\n \"\"\"\n with Reflect.context(**kwargs) as r:\n kwargs[\"name\"] = name\n instance = M_CLASS(r, stream, **kwargs)\n instance()": 800, "def cpp_prog_builder(build_context, target):\n \"\"\"Build a C++ binary executable\"\"\"\n yprint(build_context.conf, 'Build CppProg', target)\n workspace_dir = build_context.get_workspace('CppProg', target.name)\n build_cpp(build_context, target, target.compiler_config, workspace_dir)": 801, "def dictmerge(x, y):\n \"\"\"\n merge two dictionaries\n \"\"\"\n z = x.copy()\n z.update(y)\n return z": 802, "def merge(self, other):\n \"\"\" Merge another stats. \"\"\"\n Stats.merge(self, other)\n self.changes += other.changes": 803, "def _message_to_string(message, data=None):\n \"\"\" Gives a string representation of a PB2 message. \"\"\"\n if data is None:\n data = _json_from_message(message)\n\n return \"Message {} from {} to {}: {}\".format(\n message.namespace, message.source_id, message.destination_id, data)": 804, "def fn_min(self, a, axis=None):\n \"\"\"\n Return the minimum of an array, ignoring any NaNs.\n\n :param a: The array.\n :return: The minimum value of the array.\n \"\"\"\n\n return numpy.nanmin(self._to_ndarray(a), axis=axis)": 805, "def min_values(args):\n \"\"\" Return possible range for min function. \"\"\"\n return Interval(min(x.low for x in args), min(x.high for x in args))": 806, "def makedirs(path, mode=0o777, exist_ok=False):\n \"\"\"A wrapper of os.makedirs().\"\"\"\n os.makedirs(path, mode, exist_ok)": 807, "def _from_dict(cls, _dict):\n \"\"\"Initialize a ListCollectionsResponse object from a json dictionary.\"\"\"\n args = {}\n if 'collections' in _dict:\n args['collections'] = [\n Collection._from_dict(x) for x in (_dict.get('collections'))\n ]\n return cls(**args)": 808, "def most_common(items):\n \"\"\"\n Wanted functionality from Counters (new in Python 2.7).\n \"\"\"\n counts = {}\n for i in items:\n counts.setdefault(i, 0)\n counts[i] += 1\n return max(six.iteritems(counts), key=operator.itemgetter(1))": 809, "def find_one(cls, *args, **kwargs):\n \"\"\"Run a find_one on this model's collection. The arguments to\n ``Model.find_one`` are the same as to ``pymongo.Collection.find_one``.\"\"\"\n database, collection = cls._collection_key.split('.')\n return current()[database][collection].find_one(*args, **kwargs)": 810, "def indentsize(line):\n \"\"\"Return the indent size, in spaces, at the start of a line of text.\"\"\"\n expline = string.expandtabs(line)\n return len(expline) - len(string.lstrip(expline))": 811, "def mostCommonItem(lst):\n \"\"\"Choose the most common item from the list, or the first item if all\n items are unique.\"\"\"\n # This elegant solution from: http://stackoverflow.com/a/1518632/1760218\n lst = [l for l in lst if l]\n if lst:\n return max(set(lst), key=lst.count)\n else:\n return None": 812, "def make_env_key(app_name, key):\n \"\"\"Creates an environment key-equivalent for the given key\"\"\"\n key = key.replace('-', '_').replace(' ', '_')\n return str(\"_\".join((x.upper() for x in (app_name, key))))": 813, "def _go_to_line(editor, line):\n \"\"\"\n Move cursor to this line in the current buffer.\n \"\"\"\n b = editor.application.current_buffer\n b.cursor_position = b.document.translate_row_col_to_index(max(0, int(line) - 1), 0)": 814, "def touch():\n \"\"\"Create new bucket.\"\"\"\n from .models import Bucket\n bucket = Bucket.create()\n db.session.commit()\n click.secho(str(bucket), fg='green')": 815, "def align_file_position(f, size):\n \"\"\" Align the position in the file to the next block of specified size \"\"\"\n align = (size - 1) - (f.tell() % size)\n f.seek(align, 1)": 816, "def format_header_cell(val):\n \"\"\"\n Formats given header column. This involves changing '_Px_' to '(', '_xP_' to ')' and\n all other '_' to spaces.\n \"\"\"\n return re.sub('_', ' ', re.sub(r'(_Px_)', '(', re.sub(r'(_xP_)', ')', str(val) )))": 817, "def go_to_line(self, line):\n \"\"\"\n Moves the text cursor to given line.\n\n :param line: Line to go to.\n :type line: int\n :return: Method success.\n :rtype: bool\n \"\"\"\n\n cursor = self.textCursor()\n cursor.setPosition(self.document().findBlockByNumber(line - 1).position())\n self.setTextCursor(cursor)\n return True": 818, "def copy(self):\n \"\"\"Return a shallow copy of the sorted dictionary.\"\"\"\n return self.__class__(self._key, self._load, self._iteritems())": 819, "def singleton(class_):\n \"\"\"Singleton definition.\n\n Method 1 from\n https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python\n \"\"\"\n instances = {}\n\n def get_instance(*args, **kwargs):\n if class_ not in instances:\n instances[class_] = class_(*args, **kwargs)\n return instances[class_]\n return get_instance": 820, "def list_string_to_dict(string):\n \"\"\"Inputs ``['a', 'b', 'c']``, returns ``{'a': 0, 'b': 1, 'c': 2}``.\"\"\"\n dictionary = {}\n for idx, c in enumerate(string):\n dictionary.update({c: idx})\n return dictionary": 821, "def _match_space_at_line(line):\n \"\"\"Return a re.match object if an empty comment was found on line.\"\"\"\n regex = re.compile(r\"^{0}$\".format(_MDL_COMMENT))\n return regex.match(line)": 822, "def _comment(string):\n \"\"\"return string as a comment\"\"\"\n lines = [line.strip() for line in string.splitlines()]\n return \"# \" + (\"%s# \" % linesep).join(lines)": 823, "def count_generator(generator, memory_efficient=True):\n \"\"\"Count number of item in generator.\n\n memory_efficient=True, 3 times slower, but memory_efficient.\n memory_efficient=False, faster, but cost more memory.\n \"\"\"\n if memory_efficient:\n counter = 0\n for _ in generator:\n counter += 1\n return counter\n else:\n return len(list(generator))": 824, "def export_context(cls, context):\n\t\t\"\"\" Export the specified context to be capable context transferring\n\n\t\t:param context: context to export\n\t\t:return: tuple\n\t\t\"\"\"\n\t\tif context is None:\n\t\t\treturn\n\t\tresult = [(x.context_name(), x.context_value()) for x in context]\n\t\tresult.reverse()\n\t\treturn tuple(result)": 825, "def generate_matrices(dim = 40):\n \"\"\"\n Generates the matrices that positive and negative samples are multiplied\n with. The matrix for positive samples is randomly drawn from a uniform\n distribution, with elements in [-1, 1]. The matrix for negative examples\n is the sum of the positive matrix with a matrix drawn from a normal\n distribution with mean 0 variance 1.\n \"\"\"\n positive = numpy.random.uniform(-1, 1, (dim, dim))\n negative = positive + numpy.random.normal(0, 1, (dim, dim))\n return positive, negative": 826, "def qr(self,text):\n \"\"\" Print QR Code for the provided string \"\"\"\n qr_code = qrcode.QRCode(version=4, box_size=4, border=1)\n qr_code.add_data(text)\n qr_code.make(fit=True)\n qr_img = qr_code.make_image()\n im = qr_img._img.convert(\"RGB\")\n # Convert the RGB image in printable image\n self._convert_image(im)": 827, "def compute(args):\n x, y, params = args\n \"\"\"Callable function for the multiprocessing pool.\"\"\"\n return x, y, mandelbrot(x, y, params)": 828, "def clear_global(self):\n \"\"\"Clear only any cached global data.\n\n \"\"\"\n vname = self.varname\n logger.debug(f'global clearning {vname}')\n if vname in globals():\n logger.debug('removing global instance var: {}'.format(vname))\n del globals()[vname]": 829, "def get(self):\n \"\"\"retrieve a result from the pool\n\n if nothing is already completed when this method is called, it will\n block until something comes back\n\n if the pool's function exited via exception, that will come back as\n a result here as well, but will be re-raised in :meth:`get`.\n\n .. note::\n if there is nothing in the pool's output queue when this method is\n called, it will block until something is ready\n\n :returns:\n a return value from one of the function's invocations if it exited\n normally\n\n :raises:\n :class:`PoolClosed` if the pool was closed before a result could be\n produced for thie call\n\n :raises: any exception that was raised inside the worker function\n \"\"\"\n if self.closed:\n raise PoolClosed()\n\n while self._getcount not in self._cache:\n counter, result = self.outq.get()\n self._cache[counter] = result\n\n result, succeeded = self._cache.pop(self._getcount)\n self._getcount += 1\n\n if not succeeded:\n klass, exc, tb = result\n raise klass, exc, tb\n return result": 830, "def _release(self):\n \"\"\"Destroy self since closures cannot be called again.\"\"\"\n del self.funcs\n del self.variables\n del self.variable_values\n del self.satisfied": 831, "def compute_capture(args):\n x, y, w, h, params = args\n \"\"\"Callable function for the multiprocessing pool.\"\"\"\n return x, y, mandelbrot_capture(x, y, w, h, params)": 832, "def __delitem__(self, key):\n \"\"\"Remove a variable from this dataset.\n \"\"\"\n del self._variables[key]\n self._coord_names.discard(key)": 833, "def remove_columns(self, data, columns):\n \"\"\" This method removes columns in data\n\n :param data: original Pandas dataframe\n :param columns: list of columns to remove\n :type data: pandas.DataFrame\n :type columns: list of strings\n\n :returns: Pandas dataframe with removed columns\n :rtype: pandas.DataFrame\n \"\"\"\n\n for column in columns:\n if column in data.columns:\n data = data.drop(column, axis=1)\n\n return data": 834, "def _synced(method, self, args, kwargs):\n \"\"\"Underlying synchronized wrapper.\"\"\"\n with self._lock:\n return method(*args, **kwargs)": 835, "def _delete_local(self, filename):\n \"\"\"Deletes the specified file from the local filesystem.\"\"\"\n\n if os.path.exists(filename):\n os.remove(filename)": 836, "def remove_elements(target, indices):\n \"\"\"Remove multiple elements from a list and return result.\n This implementation is faster than the alternative below.\n Also note the creation of a new list to avoid altering the\n original. We don't have any current use for the original\n intact list, but may in the future...\"\"\"\n\n copied = list(target)\n\n for index in reversed(indices):\n del copied[index]\n return copied": 837, "def get_window(self): \n \"\"\"\n Returns the object's parent window. Returns None if no window found.\n \"\"\"\n x = self\n while not x._parent == None and \\\n not isinstance(x._parent, Window): \n x = x._parent\n return x._parent": 838, "def remove_bad(string):\n \"\"\"\n remove problem characters from string\n \"\"\"\n remove = [':', ',', '(', ')', ' ', '|', ';', '\\'']\n for c in remove:\n string = string.replace(c, '_')\n return string": 839, "def restore_scrollbar_position(self):\n \"\"\"Restoring scrollbar position after main window is visible\"\"\"\n scrollbar_pos = self.get_option('scrollbar_position', None)\n if scrollbar_pos is not None:\n self.explorer.treewidget.set_scrollbar_position(scrollbar_pos)": 840, "def rm_empty_indices(*args):\n \"\"\"\n Remove unwanted list indices. First argument is the list\n of indices to remove. Other elements are the lists\n to trim.\n \"\"\"\n rm_inds = args[0]\n\n if not rm_inds:\n return args[1:]\n\n keep_inds = [i for i in range(len(args[1])) if i not in rm_inds]\n\n return [[a[i] for i in keep_inds] for a in args[1:]]": 841, "def deprecate(func):\n \"\"\" A deprecation warning emmiter as a decorator. \"\"\"\n @wraps(func)\n def wrapper(*args, **kwargs):\n warn(\"Deprecated, this will be removed in the future\", DeprecationWarning)\n return func(*args, **kwargs)\n wrapper.__doc__ = \"Deprecated.\\n\" + (wrapper.__doc__ or \"\")\n return wrapper": 842, "def remove_node(self, node):\n \"\"\" Remove a node from this network. \"\"\"\n if _debug: Network._debug(\"remove_node %r\", node)\n\n self.nodes.remove(node)\n node.lan = None": 843, "def wordify(text):\n \"\"\"Generate a list of words given text, removing punctuation.\n\n Parameters\n ----------\n text : unicode\n A piece of english text.\n\n Returns\n -------\n words : list\n List of words.\n \"\"\"\n stopset = set(nltk.corpus.stopwords.words('english'))\n tokens = nltk.WordPunctTokenizer().tokenize(text)\n return [w for w in tokens if w not in stopset]": 844, "def is_admin(self):\n \"\"\"Is the user a system administrator\"\"\"\n return self.role == self.roles.administrator.value and self.state == State.approved": 845, "def start_connect(self):\n \"\"\"Tries to connect to the Heron Server\n\n ``loop()`` method needs to be called after this.\n \"\"\"\n Log.debug(\"In start_connect() of %s\" % self._get_classname())\n # TODO: specify buffer size, exception handling\n self.create_socket(socket.AF_INET, socket.SOCK_STREAM)\n\n # when ready, handle_connect is called\n self._connecting = True\n self.connect(self.endpoint)": 846, "def contains_empty(features):\n \"\"\"Check features data are not empty\n\n :param features: The features data to check.\n :type features: list of numpy arrays.\n\n :return: True if one of the array is empty, False else.\n\n \"\"\"\n if not features:\n return True\n for feature in features:\n if feature.shape[0] == 0:\n return True\n return False": 847, "def _api_type(self, value):\n \"\"\"\n Returns the API type of the given value based on its python type.\n\n \"\"\"\n if isinstance(value, six.string_types):\n return 'string'\n elif isinstance(value, six.integer_types):\n return 'integer'\n elif type(value) is datetime.datetime:\n return 'date'": 848, "def denorm(self,arr):\n \"\"\"Reverse the normalization done to a batch of images.\n\n Arguments:\n arr: of shape/size (N,3,sz,sz)\n \"\"\"\n if type(arr) is not np.ndarray: arr = to_np(arr)\n if len(arr.shape)==3: arr = arr[None]\n return self.transform.denorm(np.rollaxis(arr,1,4))": 849, "def is_seq(obj):\n \"\"\"\n Check if an object is a sequence.\n \"\"\"\n return (not is_str(obj) and not is_dict(obj) and\n (hasattr(obj, \"__getitem__\") or hasattr(obj, \"__iter__\")))": 850, "def isTestCaseDisabled(test_case_class, method_name):\n \"\"\"\n I check to see if a method on a TestCase has been disabled via nose's\n convention for disabling a TestCase. This makes it so that users can\n mix nose's parameterized tests with green as a runner.\n \"\"\"\n test_method = getattr(test_case_class, method_name)\n return getattr(test_method, \"__test__\", 'not nose') is False": 851, "def _histplot_bins(column, bins=100):\n \"\"\"Helper to get bins for histplot.\"\"\"\n col_min = np.min(column)\n col_max = np.max(column)\n return range(col_min, col_max + 2, max((col_max - col_min) // bins, 1))": 852, "def path_for_import(name):\n \"\"\"\n Returns the directory path for the given package or module.\n \"\"\"\n return os.path.dirname(os.path.abspath(import_module(name).__file__))": 853, "def as_float_array(a):\n \"\"\"View the quaternion array as an array of floats\n\n This function is fast (of order 1 microsecond) because no data is\n copied; the returned quantity is just a \"view\" of the original.\n\n The output view has one more dimension (of size 4) than the input\n array, but is otherwise the same shape.\n\n \"\"\"\n return np.asarray(a, dtype=np.quaternion).view((np.double, 4))": 854, "def tokenize(string):\n \"\"\"Match and yield all the tokens of the input string.\"\"\"\n for match in TOKENS_REGEX.finditer(string):\n yield Token(match.lastgroup, match.group().strip(), match.span())": 855, "def A(*a):\n \"\"\"convert iterable object into numpy array\"\"\"\n return np.array(a[0]) if len(a)==1 else [np.array(o) for o in a]": 856, "def chunked(l, n):\n \"\"\"Chunk one big list into few small lists.\"\"\"\n return [l[i:i + n] for i in range(0, len(l), n)]": 857, "def contains_all(self, array):\n \"\"\"Test if `array` is an array of real numbers.\"\"\"\n dtype = getattr(array, 'dtype', None)\n if dtype is None:\n dtype = np.result_type(*array)\n return is_real_dtype(dtype)": 858, "def quit(self):\n \"\"\" Exit the program due to user's choices.\n \"\"\"\n self.script.LOG.warn(\"Abort due to user choice!\")\n sys.exit(self.QUIT_RC)": 859, "def print_images(self, *printable_images):\n \"\"\"\n This method allows printing several images in one shot. This is useful if the client code does not want the\n printer to make pause during printing\n \"\"\"\n printable_image = reduce(lambda x, y: x.append(y), list(printable_images))\n self.print_image(printable_image)": 860, "def ma(self):\n \"\"\"Represent data as a masked array.\n\n The array is returned with column-first indexing, i.e. for a data file with\n columns X Y1 Y2 Y3 ... the array a will be a[0] = X, a[1] = Y1, ... .\n\n inf and nan are filtered via :func:`numpy.isfinite`.\n \"\"\"\n a = self.array\n return numpy.ma.MaskedArray(a, mask=numpy.logical_not(numpy.isfinite(a)))": 861, "def _divide(self, x1, x2, out):\n \"\"\"Raw pointwise multiplication of two elements.\"\"\"\n self.tspace._divide(x1.tensor, x2.tensor, out.tensor)": 862, "def _to_json(self):\n \"\"\" Gets a dict of this object's properties so that it can be used to send a dump to the client \"\"\"\n return dict(( (k, v) for k, v in self.__dict__.iteritems() if k != 'server'))": 863, "def _user_yes_no_query(self, question):\n \"\"\" Helper asking if the user want to download the file\n\n Note:\n Dowloading huge file can take a while\n\n \"\"\"\n sys.stdout.write('%s [y/n]\\n' % question)\n while True:\n try:\n return strtobool(raw_input().lower())\n except ValueError:\n sys.stdout.write('Please respond with \\'y\\' or \\'n\\'.\\n')": 864, "def json_datetime_serial(obj):\n \"\"\"JSON serializer for objects not serializable by default json code\"\"\"\n if isinstance(obj, (datetime, date)):\n serial = obj.isoformat()\n return serial\n\n if ObjectId is not None and isinstance(obj, ObjectId):\n # TODO: try to use bson.json_util instead\n return str(obj)\n\n raise TypeError(\"Type not serializable\")": 865, "def to_one_hot(dataY):\n \"\"\"Convert the vector of labels dataY into one-hot encoding.\n\n :param dataY: vector of labels\n :return: one-hot encoded labels\n \"\"\"\n nc = 1 + np.max(dataY)\n onehot = [np.zeros(nc, dtype=np.int8) for _ in dataY]\n for i, j in enumerate(dataY):\n onehot[i][j] = 1\n return onehot": 866, "def matrix_at_check(self, original, loc, tokens):\n \"\"\"Check for Python 3.5 matrix multiplication.\"\"\"\n return self.check_py(\"35\", \"matrix multiplication\", original, loc, tokens)": 867, "def glob_by_extensions(directory, extensions):\n \"\"\" Returns files matched by all extensions in the extensions list \"\"\"\n directorycheck(directory)\n files = []\n xt = files.extend\n for ex in extensions:\n xt(glob.glob('{0}/*.{1}'.format(directory, ex)))\n return files": 868, "def is_equal_strings_ignore_case(first, second):\n \"\"\"The function compares strings ignoring case\"\"\"\n if first and second:\n return first.upper() == second.upper()\n else:\n return not (first or second)": 869, "def _fix_up(self, cls, code_name):\n \"\"\"Internal helper called to tell the property its name.\n\n This is called by _fix_up_properties() which is called by\n MetaModel when finishing the construction of a Model subclass.\n The name passed in is the name of the class attribute to which the\n Property is assigned (a.k.a. the code name). Note that this means\n that each Property instance must be assigned to (at most) one\n class attribute. E.g. to declare three strings, you must call\n StringProperty() three times, you cannot write\n\n foo = bar = baz = StringProperty()\n \"\"\"\n self._code_name = code_name\n if self._name is None:\n self._name = code_name": 870, "def dot_v3(v, w):\n \"\"\"Return the dotproduct of two vectors.\"\"\"\n\n return sum([x * y for x, y in zip(v, w)])": 871, "def read_img(path):\n \"\"\" Reads image specified by path into numpy.ndarray\"\"\"\n img = cv2.resize(cv2.imread(path, 0), (80, 30)).astype(np.float32) / 255\n img = np.expand_dims(img.transpose(1, 0), 0)\n return img": 872, "def file_to_str(fname):\n \"\"\"\n Read a file into a string\n PRE: fname is a small file (to avoid hogging memory and its discontents)\n \"\"\"\n data = None\n # rU = read with Universal line terminator\n with open(fname, 'rU') as fd:\n data = fd.read()\n return data": 873, "def _download_py3(link, path, __hdr__):\n \"\"\"Download a file from a link in Python 3.\"\"\"\n try:\n req = urllib.request.Request(link, headers=__hdr__)\n u = urllib.request.urlopen(req)\n except Exception as e:\n raise Exception(' Download failed with the error:\\n{}'.format(e))\n\n with open(path, 'wb') as outf:\n for l in u:\n outf.write(l)\n u.close()": 874, "def to_dotfile(self):\n \"\"\" Writes a DOT graphviz file of the domain structure, and returns the filename\"\"\"\n domain = self.get_domain()\n filename = \"%s.dot\" % (self.__class__.__name__)\n nx.write_dot(domain, filename)\n return filename": 875, "def _openpyxl_read_xl(xl_path: str):\n \"\"\" Use openpyxl to read an Excel file. \"\"\"\n try:\n wb = load_workbook(filename=xl_path, read_only=True)\n except:\n raise\n else:\n return wb": 876, "def _drop_str_columns(df):\n \"\"\"\n\n Parameters\n ----------\n df : DataFrame\n\n Returns\n -------\n\n \"\"\"\n str_columns = filter(lambda pair: pair[1].char == 'S', df._gather_dtypes().items())\n str_column_names = list(map(lambda pair: pair[0], str_columns))\n\n return df.drop(str_column_names)": 877, "def upcaseTokens(s,l,t):\n \"\"\"Helper parse action to convert tokens to upper case.\"\"\"\n return [ tt.upper() for tt in map(_ustr,t) ]": 878, "def C_dict2array(C):\n \"\"\"Convert an OrderedDict containing C values to a 1D array.\"\"\"\n return np.hstack([np.asarray(C[k]).ravel() for k in C_keys])": 879, "def normalize_path(path):\n \"\"\"\n Convert a path to its canonical, case-normalized, absolute version.\n\n \"\"\"\n return os.path.normcase(os.path.realpath(os.path.expanduser(path)))": 880, "def haversine(x):\n \"\"\"Return the haversine of an angle\n\n haversine(x) = sin(x/2)**2, where x is an angle in radians\n \"\"\"\n y = .5*x\n y = np.sin(y)\n return y*y": 881, "def __get_float(section, name):\n \"\"\"Get the forecasted float from json section.\"\"\"\n try:\n return float(section[name])\n except (ValueError, TypeError, KeyError):\n return float(0)": 882, "def write_color(string, name, style='normal', when='auto'):\n \"\"\" Write the given colored string to standard out. \"\"\"\n write(color(string, name, style, when))": 883, "def close(self):\n \"\"\"Close port.\"\"\"\n os.close(self.in_d)\n os.close(self.out_d)": 884, "def extract_keywords_from_text(self, text):\n \"\"\"Method to extract keywords from the text provided.\n\n :param text: Text to extract keywords from, provided as a string.\n \"\"\"\n sentences = nltk.tokenize.sent_tokenize(text)\n self.extract_keywords_from_sentences(sentences)": 885, "def deserialize_date(string):\n \"\"\"\n Deserializes string to date.\n\n :param string: str.\n :type string: str\n :return: date.\n :rtype: date\n \"\"\"\n try:\n from dateutil.parser import parse\n return parse(string).date()\n except ImportError:\n return string": 886, "def get_soup(page=''):\n \"\"\"\n Returns a bs4 object of the page requested\n \"\"\"\n content = requests.get('%s/%s' % (BASE_URL, page)).text\n return BeautifulSoup(content)": 887, "def parse_date(s):\n \"\"\"\n Parse a date using dateutil.parser.parse if available,\n falling back to datetime.datetime.strptime if not\n \"\"\"\n if isinstance(s, (datetime.datetime, datetime.date)):\n return s\n try:\n from dateutil.parser import parse\n except ImportError:\n parse = lambda d: datetime.datetime.strptime(d, \"%Y-%m-%d\")\n return parse(s)": 888, "def clean_dataframe(df):\n \"\"\"Fill NaNs with the previous value, the next value or if all are NaN then 1.0\"\"\"\n df = df.fillna(method='ffill')\n df = df.fillna(0.0)\n return df": 889, "def fsliceafter(astr, sub):\n \"\"\"Return the slice after at sub in string astr\"\"\"\n findex = astr.find(sub)\n return astr[findex + len(sub):]": 890, "def map_wrap(f):\n \"\"\"Wrap standard function to easily pass into 'map' processing.\n \"\"\"\n @functools.wraps(f)\n def wrapper(*args, **kwargs):\n return f(*args, **kwargs)\n return wrapper": 891, "def list_formatter(handler, item, value):\n \"\"\"Format list.\"\"\"\n return u', '.join(str(v) for v in value)": 892, "def debug(self, text):\n\t\t\"\"\" Ajout d'un message de log de type DEBUG \"\"\"\n\t\tself.logger.debug(\"{}{}\".format(self.message_prefix, text))": 893, "def safe_int_conv(number):\n \"\"\"Safely convert a single number to integer.\"\"\"\n try:\n return int(np.array(number).astype(int, casting='safe'))\n except TypeError:\n raise ValueError('cannot safely convert {} to integer'.format(number))": 894, "def quote(self, s):\n \"\"\"Return a shell-escaped version of the string s.\"\"\"\n\n if six.PY2:\n from pipes import quote\n else:\n from shlex import quote\n\n return quote(s)": 895, "def translate_fourier(image, dx):\n \"\"\" Translate an image in fourier-space with plane waves \"\"\"\n N = image.shape[0]\n\n f = 2*np.pi*np.fft.fftfreq(N)\n kx,ky,kz = np.meshgrid(*(f,)*3, indexing='ij')\n kv = np.array([kx,ky,kz]).T\n\n q = np.fft.fftn(image)*np.exp(-1.j*(kv*dx).sum(axis=-1)).T\n return np.real(np.fft.ifftn(q))": 896, "def perform_pca(A):\n \"\"\"\n Computes eigenvalues and eigenvectors of covariance matrix of A.\n The rows of a correspond to observations, the columns to variables.\n \"\"\"\n # First subtract the mean\n M = (A-numpy.mean(A.T, axis=1)).T\n # Get eigenvectors and values of covariance matrix\n return numpy.linalg.eig(numpy.cov(M))": 897, "def main_func(args=None):\n \"\"\"Main funcion when executing this module as script\n\n :param args: commandline arguments\n :type args: list\n :returns: None\n :rtype: None\n :raises: None\n \"\"\"\n # we have to initialize a gui even if we dont need one right now.\n # as soon as you call maya.standalone.initialize(), a QApplication\n # with type Tty is created. This is the type for conosle apps.\n # Because i have not found a way to replace that, we just init the gui.\n guimain.init_gui()\n\n main.init()\n launcher = Launcher()\n parsed, unknown = launcher.parse_args(args)\n parsed.func(parsed, unknown)": 898, "def debug_on_error(type, value, tb):\n \"\"\"Code due to Thomas Heller - published in Python Cookbook (O'Reilley)\"\"\"\n traceback.print_exc(type, value, tb)\n print()\n pdb.pm()": 899, "def set_trace():\n \"\"\"Start a Pdb instance at the calling frame, with stdout routed to sys.__stdout__.\"\"\"\n # https://github.com/nose-devs/nose/blob/master/nose/tools/nontrivial.py\n pdb.Pdb(stdout=sys.__stdout__).set_trace(sys._getframe().f_back)": 900, "def _remove_duplicates(objects):\n \"\"\"Removes duplicate objects.\n\n http://www.peterbe.com/plog/uniqifiers-benchmark.\n \"\"\"\n seen, uniq = set(), []\n for obj in objects:\n obj_id = id(obj)\n if obj_id in seen:\n continue\n seen.add(obj_id)\n uniq.append(obj)\n return uniq": 901, "def to_camel_case(snake_case_string):\n \"\"\"\n Convert a string from snake case to camel case. For example, \"some_var\" would become \"someVar\".\n\n :param snake_case_string: Snake-cased string to convert to camel case.\n :returns: Camel-cased version of snake_case_string.\n \"\"\"\n parts = snake_case_string.lstrip('_').split('_')\n return parts[0] + ''.join([i.title() for i in parts[1:]])": 902, "def dimensions(self):\n \"\"\"Get width and height of a PDF\"\"\"\n size = self.pdf.getPage(0).mediaBox\n return {'w': float(size[2]), 'h': float(size[3])}": 903, "def do_history(self, line):\n \"\"\"history Display a list of commands that have been entered.\"\"\"\n self._split_args(line, 0, 0)\n for idx, item in enumerate(self._history):\n d1_cli.impl.util.print_info(\"{0: 3d} {1}\".format(idx, item))": 904, "def quote(s, unsafe='/'):\n \"\"\"Pass in a dictionary that has unsafe characters as the keys, and the percent\n encoded value as the value.\"\"\"\n res = s.replace('%', '%25')\n for c in unsafe:\n res = res.replace(c, '%' + (hex(ord(c)).upper())[2:])\n return res": 905, "def linearRegressionAnalysis(series):\n \"\"\"\n Returns factor and offset of linear regression function by least\n squares method.\n\n \"\"\"\n n = safeLen(series)\n sumI = sum([i for i, v in enumerate(series) if v is not None])\n sumV = sum([v for i, v in enumerate(series) if v is not None])\n sumII = sum([i * i for i, v in enumerate(series) if v is not None])\n sumIV = sum([i * v for i, v in enumerate(series) if v is not None])\n denominator = float(n * sumII - sumI * sumI)\n if denominator == 0:\n return None\n else:\n factor = (n * sumIV - sumI * sumV) / denominator / series.step\n offset = sumII * sumV - sumIV * sumI\n offset = offset / denominator - factor * series.start\n return factor, offset": 906, "def from_bytes(cls, b):\n\t\t\"\"\"Create :class:`PNG` from raw bytes.\n\t\t\n\t\t:arg bytes b: The raw bytes of the PNG file.\n\t\t:rtype: :class:`PNG`\n\t\t\"\"\"\n\t\tim = cls()\n\t\tim.chunks = list(parse_chunks(b))\n\t\tim.init()\n\t\treturn im": 907, "def less_strict_bool(x):\n \"\"\"Idempotent and None-safe version of strict_bool.\"\"\"\n if x is None:\n return False\n elif x is True or x is False:\n return x\n else:\n return strict_bool(x)": 908, "def _get_token(self, oauth_request, token_type='access'):\n \"\"\"Try to find the token for the provided request token key.\"\"\"\n token_field = oauth_request.get_parameter('oauth_token')\n token = self.data_store.lookup_token(token_type, token_field)\n if not token:\n raise OAuthError('Invalid %s token: %s' % (token_type, token_field))\n return token": 909, "def pause(self):\n \"\"\"Pause the music\"\"\"\n mixer.music.pause()\n self.pause_time = self.get_time()\n self.paused = True": 910, "def draw_image(self, ax, image):\n \"\"\"Process a matplotlib image object and call renderer.draw_image\"\"\"\n self.renderer.draw_image(imdata=utils.image_to_base64(image),\n extent=image.get_extent(),\n coordinates=\"data\",\n style={\"alpha\": image.get_alpha(),\n \"zorder\": image.get_zorder()},\n mplobj=image)": 911, "def cart2pol(x, y):\n \"\"\"Cartesian to Polar coordinates conversion.\"\"\"\n theta = np.arctan2(y, x)\n rho = np.hypot(x, y)\n return theta, rho": 912, "def get_column_keys_and_names(table):\n \"\"\"\n Return a generator of tuples k, c such that k is the name of the python attribute for\n the column and c is the name of the column in the sql table.\n \"\"\"\n ins = inspect(table)\n return ((k, c.name) for k, c in ins.mapper.c.items())": 913, "def asyncStarCmap(asyncCallable, iterable):\n \"\"\"itertools.starmap for deferred callables using cooperative multitasking\n \"\"\"\n results = []\n yield coopStar(asyncCallable, results.append, iterable)\n returnValue(results)": 914, "def _psutil_kill_pid(pid):\n \"\"\"\n http://stackoverflow.com/questions/1230669/subprocess-deleting-child-processes-in-windows\n \"\"\"\n try:\n parent = Process(pid)\n for child in parent.children(recursive=True):\n child.kill()\n parent.kill()\n except NoSuchProcess:\n return": 915, "def paint_cube(self, x, y):\n \"\"\"\n Paints a cube at a certain position a color.\n\n Parameters\n ----------\n x: int\n Horizontal position of the upper left corner of the cube.\n y: int\n Vertical position of the upper left corner of the cube.\n\n \"\"\"\n # get the color\n color = self.next_color()\n # calculate the position\n cube_pos = [x, y, x + self.cube_size, y + self.cube_size]\n # draw the cube\n draw = ImageDraw.Draw(im=self.image)\n draw.rectangle(xy=cube_pos, fill=color)": 916, "def onchange(self, value):\n \"\"\"Called when a new DropDownItem gets selected.\n \"\"\"\n log.debug('combo box. selected %s' % value)\n self.select_by_value(value)\n return (value, )": 917, "def p_postfix_expr(self, p):\n \"\"\"postfix_expr : left_hand_side_expr\n | left_hand_side_expr PLUSPLUS\n | left_hand_side_expr MINUSMINUS\n \"\"\"\n if len(p) == 2:\n p[0] = p[1]\n else:\n p[0] = ast.UnaryOp(op=p[2], value=p[1], postfix=True)": 918, "def phantomjs_retrieve(url, data=None):\n \"\"\"Retrieve the given URL using PhantomJS.\n PhantomJS will evaluate all scripts and return the HTML after body.onload.\n \n url - The page URL to retrieve\n data - The form data. TODO: Currently ignored.\n\n Returns a status code (e.g. 200) and the HTML as a unicode string.\n \"\"\"\n range_limit()\n print \"pGET\", url\n process = subprocess.Popen(['phantomjs', PHANTOM_SCRIPT, url], stdout=subprocess.PIPE)\n out = process.communicate()\n process.wait()\n response = out[0].decode('utf-8', 'ignore')\n status = response[:2]\n body = response[3:] # After the 'ok ' part.\n if status == 'ok':\n return 200, body\n else:\n return 404, body": 919, "def pprint_for_ordereddict():\n \"\"\"\n Context manager that causes pprint() to print OrderedDict objects as nicely\n as standard Python dictionary objects.\n \"\"\"\n od_saved = OrderedDict.__repr__\n try:\n OrderedDict.__repr__ = dict.__repr__\n yield\n finally:\n OrderedDict.__repr__ = od_saved": 920, "def getTypeStr(_type):\n r\"\"\"Gets the string representation of the given type.\n \"\"\"\n if isinstance(_type, CustomType):\n return str(_type)\n\n if hasattr(_type, '__name__'):\n return _type.__name__\n\n return ''": 921, "def iget_list_column_slice(list_, start=None, stop=None, stride=None):\n \"\"\" iterator version of get_list_column \"\"\"\n if isinstance(start, slice):\n slice_ = start\n else:\n slice_ = slice(start, stop, stride)\n return (row[slice_] for row in list_)": 922, "def pformat(o, indent=1, width=80, depth=None):\n \"\"\"Format a Python o into a pretty-printed representation.\"\"\"\n return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(o)": 923, "def print_trace(self):\n \"\"\"\n Prints stack trace for current exceptions chain.\n \"\"\"\n traceback.print_exc()\n for tb in self.tracebacks:\n print tb,\n print ''": 924, "def py(self, output):\n \"\"\"Output data as a nicely-formatted python data structure\"\"\"\n import pprint\n pprint.pprint(output, stream=self.outfile)": 925, "def pretty(obj, verbose=False, max_width=79, newline='\\n'):\n \"\"\"\n Pretty print the object's representation.\n \"\"\"\n stream = StringIO()\n printer = RepresentationPrinter(stream, verbose, max_width, newline)\n printer.pretty(obj)\n printer.flush()\n return stream.getvalue()": 926, "def file_length(file_obj):\n \"\"\"\n Returns the length in bytes of a given file object.\n Necessary because os.fstat only works on real files and not file-like\n objects. This works on more types of streams, primarily StringIO.\n \"\"\"\n file_obj.seek(0, 2)\n length = file_obj.tell()\n file_obj.seek(0)\n return length": 927, "def prnt(self):\n \"\"\"\n Prints DB data representation of the object.\n \"\"\"\n print(\"= = = =\\n\\n%s object key: \\033[32m%s\\033[0m\" % (self.__class__.__name__, self.key))\n pprnt(self._data or self.clean_value())": 928, "def timestamp_to_microseconds(timestamp):\n \"\"\"Convert a timestamp string into a microseconds value\n :param timestamp\n :return time in microseconds\n \"\"\"\n timestamp_str = datetime.datetime.strptime(timestamp, ISO_DATETIME_REGEX)\n epoch_time_secs = calendar.timegm(timestamp_str.timetuple())\n epoch_time_mus = epoch_time_secs * 1e6 + timestamp_str.microsecond\n return epoch_time_mus": 929, "def stdout_display():\n \"\"\" Print results straight to stdout \"\"\"\n if sys.version_info[0] == 2:\n yield SmartBuffer(sys.stdout)\n else:\n yield SmartBuffer(sys.stdout.buffer)": 930, "def start(self, timeout=None):\n \"\"\"\n Startup of the node.\n :param join: optionally wait for the process to end (default : True)\n :return: None\n \"\"\"\n\n assert super(PyrosBase, self).start(timeout=timeout)\n # Because we currently use this to setup connection\n return self.name": 931, "def filter_regex(names, regex):\n \"\"\"\n Return a tuple of strings that match the regular expression pattern.\n \"\"\"\n return tuple(name for name in names\n if regex.search(name) is not None)": 932, "def line_count(fn):\n \"\"\" Get line count of file\n\n Args:\n fn (str): Path to file\n\n Return:\n Number of lines in file (int)\n \"\"\"\n\n with open(fn) as f:\n for i, l in enumerate(f):\n pass\n return i + 1": 933, "def load(self):\n \"\"\"Load proxy list from configured proxy source\"\"\"\n self._list = self._source.load()\n self._list_iter = itertools.cycle(self._list)": 934, "def _get_points(self):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n return tuple([self._getitem__points(i)\n for i in range(self._len__points())])": 935, "def format_pylint_disables(error_names, tag=True):\n \"\"\"\n Format a list of error_names into a 'pylint: disable=' line.\n \"\"\"\n tag_str = \"lint-amnesty, \" if tag else \"\"\n if error_names:\n return u\" # {tag}pylint: disable={disabled}\".format(\n disabled=\", \".join(sorted(error_names)),\n tag=tag_str,\n )\n else:\n return \"\"": 936, "def qrandom(n):\n \"\"\"\n Creates an array of n true random numbers obtained from the quantum random\n number generator at qrng.anu.edu.au\n\n This function requires the package quantumrandom and an internet connection.\n\n Args:\n n (int):\n length of the random array\n\n Return:\n array of ints:\n array of truly random unsigned 16 bit int values\n \"\"\"\n import quantumrandom\n return np.concatenate([\n quantumrandom.get_data(data_type='uint16', array_length=1024)\n for i in range(int(np.ceil(n/1024.0)))\n ])[:n]": 937, "def clear_table(dbconn, table_name):\n \"\"\"\n Delete all rows from a table\n :param dbconn: data base connection\n :param table_name: name of the table\n :return:\n \"\"\"\n cur = dbconn.cursor()\n cur.execute(\"DELETE FROM '{name}'\".format(name=table_name))\n dbconn.commit()": 938, "def lowstrip(term):\n \"\"\"Convert to lowercase and strip spaces\"\"\"\n term = re.sub('\\s+', ' ', term)\n term = term.lower()\n return term": 939, "def chmod(self, mode):\n \"\"\"\n Change the mode (permissions) of this file. The permissions are\n unix-style and identical to those used by python's C{os.chmod}\n function.\n\n @param mode: new permissions\n @type mode: int\n \"\"\"\n self.sftp._log(DEBUG, 'chmod(%s, %r)' % (hexlify(self.handle), mode))\n attr = SFTPAttributes()\n attr.st_mode = mode\n self.sftp._request(CMD_FSETSTAT, self.handle, attr)": 940, "def region_from_segment(image, segment):\n \"\"\"given a segment (rectangle) and an image, returns it's corresponding subimage\"\"\"\n x, y, w, h = segment\n return image[y:y + h, x:x + w]": 941, "def test(ctx, all=False, verbose=False):\n \"\"\"Run the tests.\"\"\"\n cmd = 'tox' if all else 'py.test'\n if verbose:\n cmd += ' -v'\n return ctx.run(cmd, pty=True).return_code": 942, "def set_value(self, value):\n \"\"\"Set value of the checkbox.\n\n Parameters\n ----------\n value : bool\n value for the checkbox\n\n \"\"\"\n if value:\n self.setCheckState(Qt.Checked)\n else:\n self.setCheckState(Qt.Unchecked)": 943, "def show_xticklabels(self, row, column):\n \"\"\"Show the x-axis tick labels for a subplot.\n\n :param row,column: specify the subplot.\n\n \"\"\"\n subplot = self.get_subplot_at(row, column)\n subplot.show_xticklabels()": 944, "def resizeEvent(self, event):\n \"\"\"Reimplement Qt method\"\"\"\n if not self.isMaximized() and not self.fullscreen_flag:\n self.window_size = self.size()\n QMainWindow.resizeEvent(self, event)\n\n # To be used by the tour to be able to resize\n self.sig_resized.emit(event)": 945, "def PrintSummaryTable(self):\n \"\"\"Prints a summary table.\"\"\"\n print(\"\"\"\n\nAs of {0:s} the repository contains:\n\n| **File paths covered** | **{1:d}** |\n| :------------------ | ------: |\n| **Registry keys covered** | **{2:d}** |\n| **Total artifacts** | **{3:d}** |\n\"\"\".format(\n time.strftime('%Y-%m-%d'), self.path_count, self.reg_key_count,\n self.total_count))": 946, "def state(self):\n \"\"\"Returns the current LED state by querying the remote controller.\"\"\"\n ev = self._query_waiters.request(self.__do_query_state)\n ev.wait(1.0)\n return self._state": 947, "def refresh_swagger(self):\n \"\"\"\n Manually refresh the swagger document. This can help resolve errors communicate with the API.\n \"\"\"\n try:\n os.remove(self._get_swagger_filename(self.swagger_url))\n except EnvironmentError as e:\n logger.warn(os.strerror(e.errno))\n else:\n self.__init__()": 948, "def full(self):\n \"\"\"Return True if the queue is full\"\"\"\n if not self.size: return False\n return len(self.pq) == (self.size + self.removed_count)": 949, "def get_tablenames(cur):\n \"\"\" Conveinience: \"\"\"\n cur.execute(\"SELECT name FROM sqlite_master WHERE type='table'\")\n tablename_list_ = cur.fetchall()\n tablename_list = [str(tablename[0]) for tablename in tablename_list_ ]\n return tablename_list": 950, "def get_file_name(url):\n \"\"\"Returns file name of file at given url.\"\"\"\n return os.path.basename(urllib.parse.urlparse(url).path) or 'unknown_name'": 951, "def _quit(self, *args):\n \"\"\" quit crash \"\"\"\n self.logger.warn('Bye!')\n sys.exit(self.exit())": 952, "def sorted_index(values, x):\n \"\"\"\n For list, values, returns the index location of element x. If x does not exist will raise an error.\n\n :param values: list\n :param x: item\n :return: integer index\n \"\"\"\n i = bisect_left(values, x)\n j = bisect_right(values, x)\n return values[i:j].index(x) + i": 953, "def prepare(self):\n \"\"\"Prepare the handler, ensuring RabbitMQ is connected or start a new\n connection attempt.\n\n \"\"\"\n super(RabbitMQRequestHandler, self).prepare()\n if self._rabbitmq_is_closed:\n self._connect_to_rabbitmq()": 954, "def rnormal(mu, tau, size=None):\n \"\"\"\n Random normal variates.\n \"\"\"\n return np.random.normal(mu, 1. / np.sqrt(tau), size)": 955, "def _num_cpus_darwin():\n \"\"\"Return the number of active CPUs on a Darwin system.\"\"\"\n p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE)\n return p.stdout.read()": 956, "def endless_permutations(N, random_state=None):\n \"\"\"\n Generate an endless sequence of random integers from permutations of the\n set [0, ..., N).\n\n If we call this N times, we will sweep through the entire set without\n replacement, on the (N+1)th call a new permutation will be created, etc.\n\n Parameters\n ----------\n N: int\n the length of the set\n random_state: int or RandomState, optional\n random seed\n\n Yields\n ------\n int:\n a random int from the set [0, ..., N)\n \"\"\"\n generator = check_random_state(random_state)\n while True:\n batch_inds = generator.permutation(N)\n for b in batch_inds:\n yield b": 957, "def newest_file(file_iterable):\n \"\"\"\n Returns the name of the newest file given an iterable of file names.\n\n \"\"\"\n return max(file_iterable, key=lambda fname: os.path.getmtime(fname))": 958, "def timeit(output):\n \"\"\"\n If output is string, then print the string and also time used\n \"\"\"\n b = time.time()\n yield\n print output, 'time used: %.3fs' % (time.time()-b)": 959, "def read_string(buff, byteorder='big'):\n \"\"\"Read a string from a file-like object.\"\"\"\n length = read_numeric(USHORT, buff, byteorder)\n return buff.read(length).decode('utf-8')": 960, "def add_to_toolbar(self, toolbar, widget):\n \"\"\"Add widget actions to toolbar\"\"\"\n actions = widget.toolbar_actions\n if actions is not None:\n add_actions(toolbar, actions)": 961, "def load_data(filename):\n \"\"\"\n :rtype : numpy matrix\n \"\"\"\n data = pandas.read_csv(filename, header=None, delimiter='\\t', skiprows=9)\n return data.as_matrix()": 962, "def get_system_uid():\n \"\"\"Get a (probably) unique ID to identify a system.\n Used to differentiate votes.\n \"\"\"\n try:\n if os.name == 'nt':\n return get_nt_system_uid()\n if sys.platform == 'darwin':\n return get_osx_system_uid()\n except Exception:\n return get_mac_uid()\n else:\n return get_mac_uid()": 963, "def lines(input):\n \"\"\"Remove comments and empty lines\"\"\"\n for raw_line in input:\n line = raw_line.strip()\n if line and not line.startswith('#'):\n yield strip_comments(line)": 964, "def get_user_name():\n \"\"\"Get user name provide by operating system\n \"\"\"\n\n if sys.platform == 'win32':\n #user = os.getenv('USERPROFILE')\n user = os.getenv('USERNAME')\n else:\n user = os.getenv('LOGNAME')\n\n return user": 965, "def getlines(filename, module_globals=None):\n \"\"\"Get the lines for a file from the cache.\n Update the cache if it doesn't contain an entry for this file already.\"\"\"\n\n if filename in cache:\n return cache[filename][2]\n\n try:\n return updatecache(filename, module_globals)\n except MemoryError:\n clearcache()\n return []": 966, "def compute_y(self, coefficients, num_x):\n \"\"\" Return calculated y-values for the domain of x-values in [1, num_x]. \"\"\"\n y_vals = []\n\n for x in range(1, num_x + 1):\n y = sum([c * x ** i for i, c in enumerate(coefficients[::-1])])\n y_vals.append(y)\n\n return y_vals": 967, "def _readuntil(f, end=_TYPE_END):\n\t\"\"\"Helper function to read bytes until a certain end byte is hit\"\"\"\n\tbuf = bytearray()\n\tbyte = f.read(1)\n\twhile byte != end:\n\t\tif byte == b'':\n\t\t\traise ValueError('File ended unexpectedly. Expected end byte {}.'.format(end))\n\t\tbuf += byte\n\t\tbyte = f.read(1)\n\treturn buf": 968, "def _add_pos1(token):\n \"\"\"\n Adds a 'pos1' element to a frog token.\n \"\"\"\n result = token.copy()\n result['pos1'] = _POSMAP[token['pos'].split(\"(\")[0]]\n return result": 969, "def read_string_from_file(path, encoding=\"utf8\"):\n \"\"\"\n Read entire contents of file into a string.\n \"\"\"\n with codecs.open(path, \"rb\", encoding=encoding) as f:\n value = f.read()\n return value": 970, "def getfirstline(file, default):\n \"\"\"\n Returns the first line of a file.\n \"\"\"\n with open(file, 'rb') as fh:\n content = fh.readlines()\n if len(content) == 1:\n return content[0].decode('utf-8').strip('\\n')\n\n return default": 971, "def page_guiref(arg_s=None):\n \"\"\"Show a basic reference about the GUI Console.\"\"\"\n from IPython.core import page\n page.page(gui_reference, auto_html=True)": 972, "def _read_stdin():\n \"\"\"\n Generator for reading from standard input in nonblocking mode.\n\n Other ways of reading from ``stdin`` in python waits, until the buffer is\n big enough, or until EOF character is sent.\n\n This functions yields immediately after each line.\n \"\"\"\n line = sys.stdin.readline()\n while line:\n yield line\n line = sys.stdin.readline()": 973, "def save_excel(self, fd):\n \"\"\" Saves the case as an Excel spreadsheet.\n \"\"\"\n from pylon.io.excel import ExcelWriter\n ExcelWriter(self).write(fd)": 974, "async def async_input(prompt):\n \"\"\"\n Python's ``input()`` is blocking, which means the event loop we set\n above can't be running while we're blocking there. This method will\n let the loop run while we wait for input.\n \"\"\"\n print(prompt, end='', flush=True)\n return (await loop.run_in_executor(None, sys.stdin.readline)).rstrip()": 975, "def set_font_size(self, size):\n \"\"\"Convenience method for just changing font size.\"\"\"\n if self.font.font_size == size:\n pass\n else:\n self.font._set_size(size)": 976, "def open_json(file_name):\n \"\"\"\n returns json contents as string\n \"\"\"\n with open(file_name, \"r\") as json_data:\n data = json.load(json_data)\n return data": 977, "def is_read_only(object):\n \"\"\"\n Returns if given object is read only ( built-in or extension ).\n\n :param object: Object.\n :type object: object\n :return: Is object read only.\n :rtype: bool\n \"\"\"\n\n try:\n attribute = \"_trace__read__\"\n setattr(object, attribute, True)\n delattr(object, attribute)\n return False\n except (TypeError, AttributeError):\n return True": 978, "def draw_header(self, stream, header):\n \"\"\"Draw header with underline\"\"\"\n stream.writeln('=' * (len(header) + 4))\n stream.writeln('| ' + header + ' |')\n stream.writeln('=' * (len(header) + 4))\n stream.writeln()": 979, "def url_read_text(url, verbose=True):\n r\"\"\"\n Directly reads text data from url\n \"\"\"\n data = url_read(url, verbose)\n text = data.decode('utf8')\n return text": 980, "def get_xy_grids(ds, stride=1, getval=False):\n \"\"\"Return 2D arrays of x and y map coordinates for input GDAL Dataset \n \"\"\"\n gt = ds.GetGeoTransform()\n #stride = stride_m/gt[1]\n pX = np.arange(0, ds.RasterXSize, stride)\n pY = np.arange(0, ds.RasterYSize, stride)\n psamp = np.meshgrid(pX, pY)\n mX, mY = pixelToMap(psamp[0], psamp[1], gt)\n return mX, mY": 981, "def _parse_config(config_file_path):\n \"\"\" Parse Config File from yaml file. \"\"\"\n config_file = open(config_file_path, 'r')\n config = yaml.load(config_file)\n config_file.close()\n return config": 982, "def json_iter (path):\n \"\"\"\n iterator for JSON-per-line in a file pattern\n \"\"\"\n with open(path, 'r') as f:\n for line in f.readlines():\n yield json.loads(line)": 983, "def mouse_move_event(self, event):\n \"\"\"\n Forward mouse cursor position events to the example\n \"\"\"\n self.example.mouse_position_event(event.x(), event.y())": 984, "def exit(self):\n \"\"\"\n Closes the connection\n \"\"\"\n self.pubsub.unsubscribe()\n self.client.connection_pool.disconnect()\n\n logger.info(\"Connection to Redis closed\")": 985, "def get_var_type(self, name):\n \"\"\"\n Return type string, compatible with numpy.\n \"\"\"\n name = create_string_buffer(name)\n type_ = create_string_buffer(MAXSTRLEN)\n self.library.get_var_type.argtypes = [c_char_p, c_char_p]\n self.library.get_var_type(name, type_)\n return type_.value": 986, "def acquire_node(self, node):\n \"\"\"\n acquire a single redis node\n \"\"\"\n try:\n return node.set(self.resource, self.lock_key, nx=True, px=self.ttl)\n except (redis.exceptions.ConnectionError, redis.exceptions.TimeoutError):\n return False": 987, "def java_version():\n \"\"\"Call java and return version information.\n\n :return unicode: Java version string\n \"\"\"\n result = subprocess.check_output(\n [c.JAVA, '-version'], stderr=subprocess.STDOUT\n )\n first_line = result.splitlines()[0]\n return first_line.decode()": 988, "def expireat(self, key, when):\n \"\"\"Emulate expireat\"\"\"\n expire_time = datetime.fromtimestamp(when)\n key = self._encode(key)\n if key in self.redis:\n self.timeouts[key] = expire_time\n return True\n return False": 989, "def init_checks_registry():\n \"\"\"Register all globally visible functions.\n\n The first argument name is either 'physical_line' or 'logical_line'.\n \"\"\"\n mod = inspect.getmodule(register_check)\n for (name, function) in inspect.getmembers(mod, inspect.isfunction):\n register_check(function)": 990, "def find_root(self):\n \"\"\" Traverse parent refs to top. \"\"\"\n cmd = self\n while cmd.parent:\n cmd = cmd.parent\n return cmd": 991, "def _load_texture(file_name, resolver):\n \"\"\"\n Load a texture from a file into a PIL image.\n \"\"\"\n file_data = resolver.get(file_name)\n image = PIL.Image.open(util.wrap_as_stream(file_data))\n return image": 992, "def _tuple_repr(data):\n \"\"\"Return a repr() for a list/tuple\"\"\"\n if len(data) == 1:\n return \"(%s,)\" % rpr(data[0])\n else:\n return \"(%s)\" % \", \".join([rpr(x) for x in data])": 993, "def Load(file):\n \"\"\" Loads a model from specified file \"\"\"\n with open(file, 'rb') as file:\n model = dill.load(file)\n return model": 994, "def make_bintree(levels):\n \"\"\"Make a symmetrical binary tree with @levels\"\"\"\n G = nx.DiGraph()\n root = '0'\n G.add_node(root)\n add_children(G, root, levels, 2)\n return G": 995, "def is_valid_regex(string):\n \"\"\"\n Checks whether the re module can compile the given regular expression.\n\n Parameters\n ----------\n string: str\n\n Returns\n -------\n boolean\n \"\"\"\n try:\n re.compile(string)\n is_valid = True\n except re.error:\n is_valid = False\n return is_valid": 996, "def _makes_clone(_func, *args, **kw):\n \"\"\"\n A decorator that returns a clone of the current object so that\n we can re-use the object for similar requests.\n \"\"\"\n self = args[0]._clone()\n _func(self, *args[1:], **kw)\n return self": 997, "def validate_multiindex(self, obj):\n \"\"\"validate that we can store the multi-index; reset and return the\n new object\n \"\"\"\n levels = [l if l is not None else \"level_{0}\".format(i)\n for i, l in enumerate(obj.index.names)]\n try:\n return obj.reset_index(), levels\n except ValueError:\n raise ValueError(\"duplicate names/columns in the multi-index when \"\n \"storing as a table\")": 998, "def alert(text='', title='', button=OK_TEXT, root=None, timeout=None):\n \"\"\"Displays a simple message box with text and a single OK button. Returns the text of the button clicked on.\"\"\"\n assert TKINTER_IMPORT_SUCCEEDED, 'Tkinter is required for pymsgbox'\n return _buttonbox(msg=text, title=title, choices=[str(button)], root=root, timeout=timeout)": 999, "def cmd_reindex():\n \"\"\"Uses CREATE INDEX CONCURRENTLY to create a duplicate index, then tries to swap the new index for the original.\n\n The index swap is done using a short lock timeout to prevent it from interfering with running queries. Retries until\n the rename succeeds.\n \"\"\"\n db = connect(args.database)\n for idx in args.indexes:\n pg_reindex(db, idx)": 1000, "def update_redirect(self):\n \"\"\"\n Call it on your own endpoint's to update the back history navigation.\n If you bypass it, the next submit or back will go over it.\n \"\"\"\n page_history = Stack(session.get(\"page_history\", []))\n page_history.push(request.url)\n session[\"page_history\"] = page_history.to_json()": 1001, "def filter_dict_by_key(d, keys):\n \"\"\"Filter the dict *d* to remove keys not in *keys*.\"\"\"\n return {k: v for k, v in d.items() if k in keys}": 1002, "def sent2features(sentence, template):\n \"\"\" extract features in a sentence\n\n :type sentence: list of token, each token is a list of tag\n \"\"\"\n return [word2features(sentence, i, template) for i in range(len(sentence))]": 1003, "def handle_whitespace(text):\n r\"\"\"Handles whitespace cleanup.\n\n Tabs are \"smartly\" retabbed (see sub_retab). Lines that contain\n only whitespace are truncated to a single newline.\n \"\"\"\n text = re_retab.sub(sub_retab, text)\n text = re_whitespace.sub('', text).strip()\n return text": 1004, "def get_table(ports):\n \"\"\"\n This function returns a pretty table used to display the port results.\n\n :param ports: list of found ports\n :return: the table to display\n \"\"\"\n table = PrettyTable([\"Name\", \"Port\", \"Protocol\", \"Description\"])\n table.align[\"Name\"] = \"l\"\n table.align[\"Description\"] = \"l\"\n table.padding_width = 1\n\n for port in ports:\n table.add_row(port)\n\n return table": 1005, "def _remove_blank(l):\n \"\"\" Removes trailing zeros in the list of integers and returns a new list of integers\"\"\"\n ret = []\n for i, _ in enumerate(l):\n if l[i] == 0:\n break\n ret.append(l[i])\n return ret": 1006, "def auto():\n\t\"\"\"set colouring on if STDOUT is a terminal device, off otherwise\"\"\"\n\ttry:\n\t\tStyle.enabled = False\n\t\tStyle.enabled = sys.stdout.isatty()\n\texcept (AttributeError, TypeError):\n\t\tpass": 1007, "def Fsphere(q, R):\n \"\"\"Scattering form-factor amplitude of a sphere normalized to F(q=0)=V\n\n Inputs:\n -------\n ``q``: independent variable\n ``R``: sphere radius\n\n Formula:\n --------\n ``4*pi/q^3 * (sin(qR) - qR*cos(qR))``\n \"\"\"\n return 4 * np.pi / q ** 3 * (np.sin(q * R) - q * R * np.cos(q * R))": 1008, "def figsize(x=8, y=7., aspect=1.):\n \"\"\" manually set the default figure size of plots\n ::Arguments::\n x (float): x-axis size\n y (float): y-axis size\n aspect (float): aspect ratio scalar\n \"\"\"\n # update rcparams with adjusted figsize params\n mpl.rcParams.update({'figure.figsize': (x*aspect, y)})": 1009, "def vowels(self):\n \"\"\"\n Return a new IPAString, containing only the vowels in the current string.\n\n :rtype: IPAString\n \"\"\"\n return IPAString(ipa_chars=[c for c in self.ipa_chars if c.is_vowel])": 1010, "def prune(self, n):\n \"\"\"prune all but the first (=best) n items\"\"\"\n if self.minimize:\n self.data = self.data[:n]\n else:\n self.data = self.data[-1 * n:]": 1011, "def submitbutton(self, request, tag):\n \"\"\"\n Render an INPUT element of type SUBMIT which will post this form to the\n server.\n \"\"\"\n return tags.input(type='submit',\n name='__submit__',\n value=self._getDescription())": 1012, "def rrmdir(directory):\n \"\"\"\n Recursivly delete a directory\n\n :param directory: directory to remove\n \"\"\"\n for root, dirs, files in os.walk(directory, topdown=False):\n for name in files:\n os.remove(os.path.join(root, name))\n for name in dirs:\n os.rmdir(os.path.join(root, name))\n os.rmdir(directory)": 1013, "def flatten_list(l):\n \"\"\" Nested lists to single-level list, does not split strings\"\"\"\n return list(chain.from_iterable(repeat(x,1) if isinstance(x,str) else x for x in l))": 1014, "def rm_keys_from_dict(d, keys):\n \"\"\"\n Given a dictionary and a key list, remove any data in the dictionary with the given keys.\n\n :param dict d: Metadata\n :param list keys: Keys to be removed\n :return dict d: Metadata\n \"\"\"\n # Loop for each key given\n for key in keys:\n # Is the key in the dictionary?\n if key in d:\n try:\n d.pop(key, None)\n except KeyError:\n # Not concerned with an error. Keep going.\n pass\n return d": 1015, "def create_ellipse(width,height,angle):\n \"\"\"Create parametric ellipse from 200 points.\"\"\"\n angle = angle / 180.0 * np.pi\n thetas = np.linspace(0,2*np.pi,200)\n a = width / 2.0\n b = height / 2.0\n\n x = a*np.cos(thetas)*np.cos(angle) - b*np.sin(thetas)*np.sin(angle)\n y = a*np.cos(thetas)*np.sin(angle) + b*np.sin(thetas)*np.cos(angle)\n z = np.zeros(thetas.shape)\n return np.vstack((x,y,z)).T": 1016, "def purge_dict(idict):\n \"\"\"Remove null items from a dictionary \"\"\"\n odict = {}\n for key, val in idict.items():\n if is_null(val):\n continue\n odict[key] = val\n return odict": 1017, "def set_color(self, fg=None, bg=None, intensify=False, target=sys.stdout):\n \"\"\"Set foreground- and background colors and intensity.\"\"\"\n raise NotImplementedError": 1018, "def pop(self, index=-1):\n\t\t\"\"\"Remove and return the item at index.\"\"\"\n\t\tvalue = self._list.pop(index)\n\t\tdel self._dict[value]\n\t\treturn value": 1019, "def selecttrue(table, field, complement=False):\n \"\"\"Select rows where the given field evaluates `True`.\"\"\"\n\n return select(table, field, lambda v: bool(v), complement=complement)": 1020, "def unaccentuate(s):\n \"\"\" Replace accentuated chars in string by their non accentuated equivalent. \"\"\"\n return \"\".join(c for c in unicodedata.normalize(\"NFKD\", s) if not unicodedata.combining(c))": 1021, "def subn_filter(s, find, replace, count=0):\n \"\"\"A non-optimal implementation of a regex filter\"\"\"\n return re.gsub(find, replace, count, s)": 1022, "def multi_replace(instr, search_list=[], repl_list=None):\n \"\"\"\n Does a string replace with a list of search and replacements\n\n TODO: rename\n \"\"\"\n repl_list = [''] * len(search_list) if repl_list is None else repl_list\n for ser, repl in zip(search_list, repl_list):\n instr = instr.replace(ser, repl)\n return instr": 1023, "def configure_relation(graph, ns, mappings):\n \"\"\"\n Register relation endpoint(s) between two resources.\n\n \"\"\"\n convention = RelationConvention(graph)\n convention.configure(ns, mappings)": 1024, "def _replace_nan(a, val):\n \"\"\"\n replace nan in a by val, and returns the replaced array and the nan\n position\n \"\"\"\n mask = isnull(a)\n return where_method(val, mask, a), mask": 1025, "def cprint(string, fg=None, bg=None, end='\\n', target=sys.stdout):\n \"\"\"Print a colored string to the target handle.\n\n fg and bg specify foreground- and background colors, respectively. The\n remaining keyword arguments are the same as for Python's built-in print\n function. Colors are returned to their defaults before the function\n returns.\n\n \"\"\"\n _color_manager.set_color(fg, bg)\n target.write(string + end)\n target.flush() # Needed for Python 3.x\n _color_manager.set_defaults()": 1026, "def http_request_json(*args, **kwargs):\n \"\"\"\n\n See: http_request\n \"\"\"\n ret, status = http_request(*args, **kwargs)\n return json.loads(ret), status": 1027, "def stdoutwriteline(*args):\n \"\"\"\n @type args: tuple\n @return: None\n \"\"\"\n s = \"\"\n\n for i in args:\n s += str(i) + \" \"\n\n s = s.strip()\n sys.stdout.write(str(s) + \"\\n\")\n sys.stdout.flush()\n\n return s": 1028, "def copy_user_agent_from_driver(self):\n \"\"\" Updates requests' session user-agent with the driver's user agent\n\n This method will start the browser process if its not already running.\n \"\"\"\n selenium_user_agent = self.driver.execute_script(\"return navigator.userAgent;\")\n self.headers.update({\"user-agent\": selenium_user_agent})": 1029, "def _show(self, message, indent=0, enable_verbose=True): # pragma: no cover\n \"\"\"Message printer.\n \"\"\"\n if enable_verbose:\n print(\" \" * indent + message)": 1030, "def save_session_to_file(self, sessionfile):\n \"\"\"Not meant to be used directly, use :meth:`Instaloader.save_session_to_file`.\"\"\"\n pickle.dump(requests.utils.dict_from_cookiejar(self._session.cookies), sessionfile)": 1031, "def is_http_running_on(port):\n \"\"\" Check if an http server runs on a given port.\n\n Args:\n The port to check.\n Returns:\n True if it is used by an http server. False otherwise.\n \"\"\"\n try:\n conn = httplib.HTTPConnection('127.0.0.1:' + str(port))\n conn.connect()\n conn.close()\n return True\n except Exception:\n return False": 1032, "def download(url, encoding='utf-8'):\n \"\"\"Returns the text fetched via http GET from URL, read as `encoding`\"\"\"\n import requests\n response = requests.get(url)\n response.encoding = encoding\n return response.text": 1033, "def clear(self):\n \"\"\" clear plot \"\"\"\n self.axes.cla()\n self.conf.ntrace = 0\n self.conf.xlabel = ''\n self.conf.ylabel = ''\n self.conf.title = ''": 1034, "def __init__(self, pos, cell, motion, cellmotion):\n self.pos = pos\n \"\"\"(x, y) position of the mouse on the screen.\n type: (int, int)\"\"\"\n self.cell = cell\n \"\"\"(x, y) position of the mouse snapped to a cell on the root console.\n type: (int, int)\"\"\"\n self.motion = motion\n \"\"\"(x, y) motion of the mouse on the screen.\n type: (int, int)\"\"\"\n self.cellmotion = cellmotion\n \"\"\"(x, y) mostion of the mouse moving over cells on the root console.\n type: (int, int)\"\"\"": 1035, "def resize(self, size):\n\t\t\"\"\" Resize current array. If size is None, then array became nonfixed-length array. If new size is\n\t\tless then current size and value, then value will be truncated (lesser significant bits will be\n\t\ttruncated).\n\n\t\t:param size:\n\t\t:return:\n\t\t\"\"\"\n\t\tif size is not None:\n\t\t\tself.__value = int(WBinArray(self.__value)[:size])\n\t\tself.__size = size": 1036, "def print_out(self, *lst):\n \"\"\" Print list of strings to the predefined stdout. \"\"\"\n self.print2file(self.stdout, True, True, *lst)": 1037, "def raise_for_not_ok_status(response):\n \"\"\"\n Raises a `requests.exceptions.HTTPError` if the response has a non-200\n status code.\n \"\"\"\n if response.code != OK:\n raise HTTPError('Non-200 response code (%s) for url: %s' % (\n response.code, uridecode(response.request.absoluteURI)))\n\n return response": 1038, "def disable_busy_cursor():\n \"\"\"Disable the hourglass cursor and listen for layer changes.\"\"\"\n while QgsApplication.instance().overrideCursor() is not None and \\\n QgsApplication.instance().overrideCursor().shape() == \\\n QtCore.Qt.WaitCursor:\n QgsApplication.instance().restoreOverrideCursor()": 1039, "async def json_or_text(response):\n \"\"\"Turns response into a properly formatted json or text object\"\"\"\n text = await response.text()\n if response.headers['Content-Type'] == 'application/json; charset=utf-8':\n return json.loads(text)\n return text": 1040, "def get_auth():\n \"\"\"Get authentication.\"\"\"\n import getpass\n user = input(\"User Name: \") # noqa\n pswd = getpass.getpass('Password: ')\n return Github(user, pswd)": 1041, "def http(self, *args, **kwargs):\n \"\"\"Starts the process of building a new HTTP route linked to this API instance\"\"\"\n kwargs['api'] = self.api\n return http(*args, **kwargs)": 1042, "def ILIKE(pattern):\n \"\"\"Unix shell-style wildcards. Case-insensitive\"\"\"\n return P(lambda x: fnmatch.fnmatch(x.lower(), pattern.lower()))": 1043, "def documentation(self):\n \"\"\"\n Get the documentation that the server sends for the API.\n \"\"\"\n newclient = self.__class__(self.session, self.root_url)\n return newclient.get_raw('/')": 1044, "def _add_indent(string, indent):\n \"\"\"Add indent of ``indent`` spaces to ``string.split(\"\\n\")[1:]``\n\n Useful for formatting in strings to already indented blocks\n \"\"\"\n lines = string.split(\"\\n\")\n first, lines = lines[0], lines[1:]\n lines = [\"{indent}{s}\".format(indent=\" \" * indent, s=s)\n for s in lines]\n lines = [first] + lines\n return \"\\n\".join(lines)": 1045, "def get_key_goids(self, goids):\n \"\"\"Given GO IDs, return key GO IDs.\"\"\"\n go2obj = self.go2obj\n return set(go2obj[go].id for go in goids)": 1046, "def requests_post(url, data=None, json=None, **kwargs):\n \"\"\"Requests-mock requests.post wrapper.\"\"\"\n return requests_request('post', url, data=data, json=json, **kwargs)": 1047, "def find_start_point(self):\n \"\"\"\n Find the first location in our array that is not empty\n \"\"\"\n for i, row in enumerate(self.data):\n for j, _ in enumerate(row):\n if self.data[i, j] != 0: # or not np.isfinite(self.data[i,j]):\n return i, j": 1048, "def uniquify_list(L):\n \"\"\"Same order unique list using only a list compression.\"\"\"\n return [e for i, e in enumerate(L) if L.index(e) == i]": 1049, "def norm_vec(vector):\n \"\"\"Normalize the length of a vector to one\"\"\"\n assert len(vector) == 3\n v = np.array(vector)\n return v/np.sqrt(np.sum(v**2))": 1050, "def get_file_string(filepath):\n \"\"\"Get string from file.\"\"\"\n with open(os.path.abspath(filepath)) as f:\n return f.read()": 1051, "def _get_sql(filename):\n \"\"\"Returns the contents of the sql file from the given ``filename``.\"\"\"\n with open(os.path.join(SQL_DIR, filename), 'r') as f:\n return f.read()": 1052, "def out_shape_from_array(arr):\n \"\"\"Get the output shape from an array.\"\"\"\n arr = np.asarray(arr)\n if arr.ndim == 1:\n return arr.shape\n else:\n return (arr.shape[1],)": 1053, "def parse_s3_url(url):\n \"\"\"\n Parses S3 URL.\n\n Returns bucket (domain) and file (full path).\n \"\"\"\n bucket = ''\n path = ''\n if url:\n result = urlparse(url)\n bucket = result.netloc\n path = result.path.strip('/')\n return bucket, path": 1054, "def pickle_load(fname):\n \"\"\"return the contents of a pickle file\"\"\"\n assert type(fname) is str and os.path.exists(fname)\n print(\"loaded\",fname)\n return pickle.load(open(fname,\"rb\"))": 1055, "def get_key_by_value(dictionary, search_value):\n \"\"\"\n searchs a value in a dicionary and returns the key of the first occurrence\n\n :param dictionary: dictionary to search in\n :param search_value: value to search for\n \"\"\"\n for key, value in dictionary.iteritems():\n if value == search_value:\n return ugettext(key)": 1056, "def plot_dist_normal(s, mu, sigma):\n \"\"\"\n plot distribution\n \"\"\"\n import matplotlib.pyplot as plt\n count, bins, ignored = plt.hist(s, 30, normed=True)\n plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) \\\n * np.exp( - (bins - mu)**2 / (2 * sigma**2) ), \\\n linewidth = 2, color = 'r')\n plt.show()": 1057, "def _pdf_at_peak(self):\n \"\"\"Pdf evaluated at the peak.\"\"\"\n return (self.peak - self.low) / (self.high - self.low)": 1058, "def _dict_to_proto(py_dict, proto):\n \"\"\"\n Converts a python dictionary to the proto supplied\n\n :param py_dict: The dictionary to convert\n :type py_dict: dict\n :param proto: The proto object to merge with dictionary\n :type proto: protobuf\n :return: A parsed python dictionary in provided proto format\n :raises:\n ParseError: On JSON parsing problems.\n \"\"\"\n dict_json_str = json.dumps(py_dict)\n return json_format.Parse(dict_json_str, proto)": 1059, "def round_to_n(x, n):\n \"\"\"\n Round to sig figs\n \"\"\"\n return round(x, -int(np.floor(np.log10(x))) + (n - 1))": 1060, "def trigger(self, target: str, trigger: str, parameters: Dict[str, Any]={}):\n\t\t\"\"\"Calls the specified Trigger of another Area with the optionally given parameters.\n\n\t\tArgs:\n\t\t\ttarget: The name of the target Area.\n\t\t\ttrigger: The name of the Trigger.\n\t\t\tparameters: The parameters of the function call.\n\t\t\"\"\"\n\t\tpass": 1061, "def get_rounded(self, digits):\n \"\"\" Return a vector with the elements rounded to the given number of digits. \"\"\"\n result = self.copy()\n result.round(digits)\n return result": 1062, "def open_with_encoding(filename, encoding, mode='r'):\n \"\"\"Return opened file with a specific encoding.\"\"\"\n return io.open(filename, mode=mode, encoding=encoding,\n newline='')": 1063, "def call_and_exit(self, cmd, shell=True):\n \"\"\"Run the *cmd* and exit with the proper exit code.\"\"\"\n sys.exit(subprocess.call(cmd, shell=shell))": 1064, "def merge(left, right, how='inner', key=None, left_key=None, right_key=None,\n left_as='left', right_as='right'):\n \"\"\" Performs a join using the union join function. \"\"\"\n return join(left, right, how, key, left_key, right_key,\n join_fn=make_union_join(left_as, right_as))": 1065, "async def result_processor(tasks):\n \"\"\"An async result aggregator that combines all the results\n This gets executed in unsync.loop and unsync.thread\"\"\"\n output = {}\n for task in tasks:\n num, res = await task\n output[num] = res\n return output": 1066, "def add_text(text, x=0.01, y=0.01, axes=\"gca\", draw=True, **kwargs):\n \"\"\"\n Adds text to the axes at the specified position.\n\n **kwargs go to the axes.text() function.\n \"\"\"\n if axes==\"gca\": axes = _pylab.gca()\n axes.text(x, y, text, transform=axes.transAxes, **kwargs)\n if draw: _pylab.draw()": 1067, "def safe_quotes(text, escape_single_quotes=False):\n \"\"\"htmlify string\"\"\"\n if isinstance(text, str):\n safe_text = text.replace('\"', \""\")\n if escape_single_quotes:\n safe_text = safe_text.replace(\"'\", \"\'\")\n return safe_text.replace('True', 'true')\n return text": 1068, "def make_post_request(self, url, auth, json_payload):\n \"\"\"This function executes the request with the provided\n json payload and return the json response\"\"\"\n response = requests.post(url, auth=auth, json=json_payload)\n return response.json()": 1069, "def fig2x(figure, format):\n \"\"\"Returns svg from matplotlib chart\"\"\"\n\n # Save svg to file like object svg_io\n io = StringIO()\n figure.savefig(io, format=format)\n\n # Rewind the file like object\n io.seek(0)\n\n data = io.getvalue()\n io.close()\n\n return data": 1070, "def error(*args):\n \"\"\"Display error message via stderr or GUI.\"\"\"\n if sys.stdin.isatty():\n print('ERROR:', *args, file=sys.stderr)\n else:\n notify_error(*args)": 1071, "def close(*args, **kwargs):\n r\"\"\"Close last created figure, alias to ``plt.close()``.\"\"\"\n _, plt, _ = _import_plt()\n plt.close(*args, **kwargs)": 1072, "def head(filename, n=10):\n \"\"\" prints the top `n` lines of a file \"\"\"\n with freader(filename) as fr:\n for _ in range(n):\n print(fr.readline().strip())": 1073, "def format_exc(limit=None):\n \"\"\"Like print_exc() but return a string. Backport for Python 2.3.\"\"\"\n try:\n etype, value, tb = sys.exc_info()\n return ''.join(traceback.format_exception(etype, value, tb, limit))\n finally:\n etype = value = tb = None": 1074, "def conv1x1(in_planes, out_planes, stride=1):\n \"\"\"1x1 convolution\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)": 1075, "def _get_name(self, key):\n \"\"\" get display name for a key, or mangle for display \"\"\"\n if key in self.display_names:\n return self.display_names[key]\n\n return key.capitalize()": 1076, "def scipy_sparse_to_spmatrix(A):\n \"\"\"Efficient conversion from scipy sparse matrix to cvxopt sparse matrix\"\"\"\n coo = A.tocoo()\n SP = spmatrix(coo.data.tolist(), coo.row.tolist(), coo.col.tolist(), size=A.shape)\n return SP": 1077, "def _screen(self, s, newline=False):\n \"\"\"Print something on screen when self.verbose == True\"\"\"\n if self.verbose:\n if newline:\n print(s)\n else:\n print(s, end=' ')": 1078, "def _stdout_raw(self, s):\n \"\"\"Writes the string to stdout\"\"\"\n print(s, end='', file=sys.stdout)\n sys.stdout.flush()": 1079, "def write_wav(path, samples, sr=16000):\n \"\"\"\n Write to given samples to a wav file.\n The samples are expected to be floating point numbers\n in the range of -1.0 to 1.0.\n\n Args:\n path (str): The path to write the wav to.\n samples (np.array): A float array .\n sr (int): The sampling rate.\n \"\"\"\n max_value = np.abs(np.iinfo(np.int16).min)\n data = (samples * max_value).astype(np.int16)\n scipy.io.wavfile.write(path, sr, data)": 1080, "def string_to_identity(identity_str):\n \"\"\"Parse string into Identity dictionary.\"\"\"\n m = _identity_regexp.match(identity_str)\n result = m.groupdict()\n log.debug('parsed identity: %s', result)\n return {k: v for k, v in result.items() if v}": 1081, "def mouse_out(self):\n \"\"\"\n Performs a mouse out the element.\n\n Currently works only on Chrome driver.\n \"\"\"\n self.scroll_to()\n ActionChains(self.parent.driver).move_by_offset(0, 0).click().perform()": 1082, "def _set_scroll_v(self, *args):\n \"\"\"Scroll both categories Canvas and scrolling container\"\"\"\n self._canvas_categories.yview(*args)\n self._canvas_scroll.yview(*args)": 1083, "def bash(filename):\n \"\"\"Runs a bash script in the local directory\"\"\"\n sys.stdout.flush()\n subprocess.call(\"bash {}\".format(filename), shell=True)": 1084, "def stdin_readable():\n \"\"\"Determine whether stdin has any data to read.\"\"\"\n if not WINDOWS:\n try:\n return bool(select([sys.stdin], [], [], 0)[0])\n except Exception:\n logger.log_exc()\n try:\n return not sys.stdin.isatty()\n except Exception:\n logger.log_exc()\n return False": 1085, "def execute_in_background(self):\n \"\"\"Executes a (shell) command in the background\n\n :return: the process' pid\n \"\"\"\n # http://stackoverflow.com/questions/1605520\n args = shlex.split(self.cmd)\n p = Popen(args)\n return p.pid": 1086, "def ratio_and_percentage(current, total, time_remaining):\n \"\"\"Returns the progress ratio and percentage.\"\"\"\n return \"{} / {} ({}% completed)\".format(current, total, int(current / total * 100))": 1087, "def ask_dir(self):\n\t\t\"\"\"\n\t\tdialogue box for choosing directory\n\t\t\"\"\"\n\t\targs ['directory'] = askdirectory(**self.dir_opt) \n\t\tself.dir_text.set(args ['directory'])": 1088, "def numpy(self):\n \"\"\" Grabs image data and converts it to a numpy array \"\"\"\n # load GDCM's image reading functionality\n image_reader = gdcm.ImageReader()\n image_reader.SetFileName(self.fname)\n if not image_reader.Read():\n raise IOError(\"Could not read DICOM image\")\n pixel_array = self._gdcm_to_numpy(image_reader.GetImage())\n return pixel_array": 1089, "def selectgt(table, field, value, complement=False):\n \"\"\"Select rows where the given field is greater than the given value.\"\"\"\n\n value = Comparable(value)\n return selectop(table, field, value, operator.gt, complement=complement)": 1090, "def read_utf8(fh, byteorder, dtype, count, offsetsize):\n \"\"\"Read tag data from file and return as unicode string.\"\"\"\n return fh.read(count).decode('utf-8')": 1091, "def selectnotnone(table, field, complement=False):\n \"\"\"Select rows where the given field is not `None`.\"\"\"\n\n return select(table, field, lambda v: v is not None,\n complement=complement)": 1092, "def ReadManyFromPath(filepath):\n \"\"\"Reads a Python object stored in a specified YAML file.\n\n Args:\n filepath: A filepath to the YAML file.\n\n Returns:\n A Python data structure corresponding to the YAML in the given file.\n \"\"\"\n with io.open(filepath, mode=\"r\", encoding=\"utf-8\") as filedesc:\n return ReadManyFromFile(filedesc)": 1093, "def find_first_number(ll):\n \"\"\" Returns nr of first entry parseable to float in ll, None otherwise\"\"\"\n for nr, entry in enumerate(ll):\n try:\n float(entry)\n except (ValueError, TypeError) as e:\n pass\n else:\n return nr\n return None": 1094, "def filter_by_ids(original_list, ids_to_filter):\n \"\"\"Filter a list of dicts by IDs using an id key on each dict.\"\"\"\n if not ids_to_filter:\n return original_list\n\n return [i for i in original_list if i['id'] in ids_to_filter]": 1095, "def load_yaml(filepath):\n \"\"\"Convenience function for loading yaml-encoded data from disk.\"\"\"\n with open(filepath) as f:\n txt = f.read()\n return yaml.load(txt)": 1096, "def __init__(self):\n \"\"\"Initializes an attribute container identifier.\"\"\"\n super(AttributeContainerIdentifier, self).__init__()\n self._identifier = id(self)": 1097, "async def readline(self):\n \"\"\"\n This is an asyncio adapted version of pyserial read.\n It provides a non-blocking read and returns a line of data read.\n\n :return: A line of data\n \"\"\"\n future = asyncio.Future()\n data_available = False\n while True:\n if not data_available:\n if not self.my_serial.inWaiting():\n await asyncio.sleep(self.sleep_tune)\n else:\n data_available = True\n data = self.my_serial.readline()\n future.set_result(data)\n else:\n if not future.done():\n await asyncio.sleep(self.sleep_tune)\n else:\n return future.result()": 1098, "def _trim(image):\n \"\"\"Trim a PIL image and remove white space.\"\"\"\n background = PIL.Image.new(image.mode, image.size, image.getpixel((0, 0)))\n diff = PIL.ImageChops.difference(image, background)\n diff = PIL.ImageChops.add(diff, diff, 2.0, -100)\n bbox = diff.getbbox()\n if bbox:\n image = image.crop(bbox)\n return image": 1099, "def remove_series(self, series):\n \"\"\"Removes a :py:class:`.Series` from the chart.\n\n :param Series series: The :py:class:`.Series` to remove.\n :raises ValueError: if you try to remove the last\\\n :py:class:`.Series`.\"\"\"\n\n if len(self.all_series()) == 1:\n raise ValueError(\"Cannot remove last series from %s\" % str(self))\n self._all_series.remove(series)\n series._chart = None": 1100, "def del_Unnamed(df):\n \"\"\"\n Deletes all the unnamed columns\n\n :param df: pandas dataframe\n \"\"\"\n cols_del=[c for c in df.columns if 'Unnamed' in c]\n return df.drop(cols_del,axis=1)": 1101, "def get_header(request, header_service):\n \"\"\"Return request's 'X_POLYAXON_...:' header, as a bytestring.\n\n Hide some test client ickyness where the header can be unicode.\n \"\"\"\n service = request.META.get('HTTP_{}'.format(header_service), b'')\n if isinstance(service, str):\n # Work around django test client oddness\n service = service.encode(HTTP_HEADER_ENCODING)\n return service": 1102, "def _removeTags(tags, objects):\n \"\"\" Removes tags from objects \"\"\"\n for t in tags:\n for o in objects:\n o.tags.remove(t)\n\n return True": 1103, "def fix_datagrepper_message(message):\n \"\"\"\n See if a message is (probably) a datagrepper message and attempt to mutate\n it to pass signature validation.\n\n Datagrepper adds the 'source_name' and 'source_version' keys. If messages happen\n to use those keys, they will fail message validation. Additionally, a 'headers'\n dictionary is present on all responses, regardless of whether it was in the\n original message or not. This is deleted if it's null, which won't be correct in\n all cases. Finally, datagrepper turns the 'timestamp' field into a float, but it\n might have been an integer when the message was signed.\n\n A copy of the dictionary is made and returned if altering the message is necessary.\n\n I'm so sorry.\n\n Args:\n message (dict): A message to clean up.\n\n Returns:\n dict: A copy of the provided message, with the datagrepper-related keys removed\n if they were present.\n \"\"\"\n if not ('source_name' in message and 'source_version' in message):\n return message\n\n # Don't mutate the original message\n message = message.copy()\n\n del message['source_name']\n del message['source_version']\n # datanommer adds the headers field to the message in all cases.\n # This is a huge problem because if the signature was generated with a 'headers'\n # key set and we delete it here, messages will fail validation, but if we don't\n # messages will fail validation if they didn't have a 'headers' key set.\n #\n # There's no way to know whether or not the headers field was part of the signed\n # message or not. Generally, the problem is datanommer is mutating messages.\n if 'headers' in message and not message['headers']:\n del message['headers']\n if 'timestamp' in message:\n message['timestamp'] = int(message['timestamp'])\n\n return message": 1104, "def set_time(filename, mod_time):\n\t\"\"\"\n\tSet the modified time of a file\n\t\"\"\"\n\tlog.debug('Setting modified time to %s', mod_time)\n\tmtime = calendar.timegm(mod_time.utctimetuple())\n\t# utctimetuple discards microseconds, so restore it (for consistency)\n\tmtime += mod_time.microsecond / 1000000\n\tatime = os.stat(filename).st_atime\n\tos.utime(filename, (atime, mtime))": 1105, "def get_var(name, factory=None):\n \"\"\"Gets a global variable given its name.\n\n If factory is not None and the variable is not set, factory\n is a callable that will set the variable.\n\n If not set, returns None.\n \"\"\"\n if name not in _VARS and factory is not None:\n _VARS[name] = factory()\n return _VARS.get(name)": 1106, "def turn(self):\n \"\"\"Turn the ring for a single position.\n For example, [a, b, c, d] becomes [b, c, d, a].\"\"\"\n first = self._data.pop(0)\n self._data.append(first)": 1107, "def clean_axis(axis):\n \"\"\"Remove ticks, tick labels, and frame from axis\"\"\"\n axis.get_xaxis().set_ticks([])\n axis.get_yaxis().set_ticks([])\n for spine in list(axis.spines.values()):\n spine.set_visible(False)": 1108, "def set_log_level(logger_name: str, log_level: str, propagate: bool = False):\n \"\"\"Set the log level of the specified logger.\"\"\"\n log = logging.getLogger(logger_name)\n log.propagate = propagate\n log.setLevel(log_level)": 1109, "def split_comma_argument(comma_sep_str):\n \"\"\"Split a comma separated option into a list.\"\"\"\n terms = []\n for term in comma_sep_str.split(','):\n if term:\n terms.append(term)\n return terms": 1110, "def set_pivot_keys(self, foreign_key, other_key):\n \"\"\"\n Set the key names for the pivot model instance\n \"\"\"\n self.__foreign_key = foreign_key\n self.__other_key = other_key\n\n return self": 1111, "def mock_add_spec(self, spec, spec_set=False):\n \"\"\"Add a spec to a mock. `spec` can either be an object or a\n list of strings. Only attributes on the `spec` can be fetched as\n attributes from the mock.\n\n If `spec_set` is True then only attributes on the spec can be set.\"\"\"\n self._mock_add_spec(spec, spec_set)\n self._mock_set_magics()": 1112, "def fmt_subst(regex, subst):\n \"\"\"Replace regex with string.\"\"\"\n return lambda text: re.sub(regex, subst, text) if text else text": 1113, "def discard(self, element):\n \"\"\"Remove element from the RangeSet if it is a member.\n\n If the element is not a member, do nothing.\n \"\"\"\n try:\n i = int(element)\n set.discard(self, i)\n except ValueError:\n pass": 1114, "def median(self):\n \"\"\"Computes the median of a log-normal distribution built with the stats data.\"\"\"\n mu = self.mean()\n ret_val = math.exp(mu)\n if math.isnan(ret_val):\n ret_val = float(\"inf\")\n return ret_val": 1115, "def load_file(self, filename):\n \"\"\"Read in file contents and set the current string.\"\"\"\n with open(filename, 'r') as sourcefile:\n self.set_string(sourcefile.read())": 1116, "def normalise_string(string):\n \"\"\" Strips trailing whitespace from string, lowercases it and replaces\n spaces with underscores\n \"\"\"\n string = (string.strip()).lower()\n return re.sub(r'\\W+', '_', string)": 1117, "def to_utc(self, dt):\n \"\"\"Convert any timestamp to UTC (with tzinfo).\"\"\"\n if dt.tzinfo is None:\n return dt.replace(tzinfo=self.utc)\n return dt.astimezone(self.utc)": 1118, "def dashrepl(value):\n \"\"\"\n Replace any non-word characters with a dash.\n \"\"\"\n patt = re.compile(r'\\W', re.UNICODE)\n return re.sub(patt, '-', value)": 1119, "def im2mat(I):\n \"\"\"Converts and image to matrix (one pixel per line)\"\"\"\n return I.reshape((I.shape[0] * I.shape[1], I.shape[2]))": 1120, "def check_str(obj):\n \"\"\" Returns a string for various input types \"\"\"\n if isinstance(obj, str):\n return obj\n if isinstance(obj, float):\n return str(int(obj))\n else:\n return str(obj)": 1121, "async def restart(request):\n \"\"\"\n Returns OK, then waits approximately 1 second and restarts container\n \"\"\"\n def wait_and_restart():\n log.info('Restarting server')\n sleep(1)\n os.system('kill 1')\n Thread(target=wait_and_restart).start()\n return web.json_response({\"message\": \"restarting\"})": 1122, "def get_jsonparsed_data(url):\n \"\"\"Receive the content of ``url``, parse it as JSON and return the\n object.\n \"\"\"\n response = urlopen(url)\n data = response.read().decode('utf-8')\n return json.loads(data)": 1123, "def feed_eof(self):\n \"\"\"Send a potentially \"ragged\" EOF.\n\n This method will raise an SSL_ERROR_EOF exception if the EOF is\n unexpected.\n \"\"\"\n self._incoming.write_eof()\n ssldata, appdata = self.feed_ssldata(b'')\n assert appdata == [] or appdata == [b'']": 1124, "def bounds_to_poly(bounds):\n \"\"\"\n Constructs a shapely Polygon from the provided bounds tuple.\n\n Parameters\n ----------\n bounds: tuple\n Tuple representing the (left, bottom, right, top) coordinates\n\n Returns\n -------\n polygon: shapely.geometry.Polygon\n Shapely Polygon geometry of the bounds\n \"\"\"\n x0, y0, x1, y1 = bounds\n return Polygon([(x0, y0), (x1, y0), (x1, y1), (x0, y1)])": 1125, "def reset(self):\n\t\t\"\"\"\n\t\tResets the iterator to the start.\n\n\t\tAny remaining values in the current iteration are discarded.\n\t\t\"\"\"\n\t\tself.__iterator, self.__saved = itertools.tee(self.__saved)": 1126, "def format_exc(*exc_info):\n \"\"\"Show exception with traceback.\"\"\"\n typ, exc, tb = exc_info or sys.exc_info()\n error = traceback.format_exception(typ, exc, tb)\n return \"\".join(error)": 1127, "def _saferound(value, decimal_places):\n \"\"\"\n Rounds a float value off to the desired precision\n \"\"\"\n try:\n f = float(value)\n except ValueError:\n return ''\n format = '%%.%df' % decimal_places\n return format % f": 1128, "def _shuffle(data, idx):\n \"\"\"Shuffle the data.\"\"\"\n shuffle_data = []\n\n for idx_k, idx_v in data:\n shuffle_data.append((idx_k, mx.ndarray.array(idx_v.asnumpy()[idx], idx_v.context)))\n\n return shuffle_data": 1129, "def lowPass(self, *args):\n \"\"\"\n Creates a copy of the signal with the low pass applied, args specifed are passed through to _butter. \n :return: \n \"\"\"\n return Signal(self._butter(self.samples, 'low', *args), fs=self.fs)": 1130, "def begin_stream_loop(stream, poll_interval):\n \"\"\"Start and maintain the streaming connection...\"\"\"\n while should_continue():\n try:\n stream.start_polling(poll_interval)\n except Exception as e:\n # Infinite restart\n logger.error(\"Exception while polling. Restarting in 1 second.\", exc_info=True)\n time.sleep(1)": 1131, "def readTuple(self, line, n=3):\n \"\"\" Reads a tuple of numbers. e.g. vertices, normals or teture coords.\n \"\"\"\n numbers = [num for num in line.split(' ') if num]\n return [float(num) for num in numbers[1:n + 1]]": 1132, "def stub_main():\n \"\"\"setuptools blah: it still can't run a module as a script entry_point\"\"\"\n from google.apputils import run_script_module\n import butcher.main\n run_script_module.RunScriptModule(butcher.main)": 1133, "def _nbytes(buf):\n \"\"\"Return byte-size of a memoryview or buffer.\"\"\"\n if isinstance(buf, memoryview):\n if PY3:\n # py3 introduces nbytes attribute\n return buf.nbytes\n else:\n # compute nbytes on py2\n size = buf.itemsize\n for dim in buf.shape:\n size *= dim\n return size\n else:\n # not a memoryview, raw bytes/ py2 buffer\n return len(buf)": 1134, "def save(variable, filename):\n \"\"\"Save variable on given path using Pickle\n \n Args:\n variable: what to save\n path (str): path of the output\n \"\"\"\n fileObj = open(filename, 'wb')\n pickle.dump(variable, fileObj)\n fileObj.close()": 1135, "def _skip_frame(self):\n \"\"\"Skip the next time frame\"\"\"\n for line in self._f:\n if line == 'ITEM: ATOMS\\n':\n break\n for i in range(self.num_atoms):\n next(self._f)": 1136, "def skip(self, n):\n \"\"\"Skip the specified number of elements in the list.\n\n If the number skipped is greater than the number of elements in\n the list, hasNext() becomes false and available() returns zero\n as there are no more elements to retrieve.\n\n arg: n (cardinal): the number of elements to skip\n *compliance: mandatory -- This method must be implemented.*\n\n \"\"\"\n try:\n self._iter_object.skip(n)\n except AttributeError:\n for i in range(0, n):\n self.next()": 1137, "def write_fits(self, fitsfile):\n \"\"\"Write the ROI model to a FITS file.\"\"\"\n\n tab = self.create_table()\n hdu_data = fits.table_to_hdu(tab)\n hdus = [fits.PrimaryHDU(), hdu_data]\n fits_utils.write_hdus(hdus, fitsfile)": 1138, "def getbyteslice(self, start, end):\n \"\"\"Direct access to byte data.\"\"\"\n c = self._rawarray[start:end]\n return c": 1139, "def pickle_save(thing,fname):\n \"\"\"save something to a pickle file\"\"\"\n pickle.dump(thing, open(fname,\"wb\"),pickle.HIGHEST_PROTOCOL)\n return thing": 1140, "def is_full_slice(obj, l):\n \"\"\"\n We have a full length slice.\n \"\"\"\n return (isinstance(obj, slice) and obj.start == 0 and obj.stop == l and\n obj.step is None)": 1141, "def resize_image(self, data, size):\n \"\"\" Resizes the given image to fit inside a box of the given size. \"\"\"\n from machina.core.compat import PILImage as Image\n image = Image.open(BytesIO(data))\n\n # Resize!\n image.thumbnail(size, Image.ANTIALIAS)\n\n string = BytesIO()\n image.save(string, format='PNG')\n return string.getvalue()": 1142, "def stop(self, dummy_signum=None, dummy_frame=None):\n \"\"\" Shutdown process (this method is also a signal handler) \"\"\"\n logging.info('Shutting down ...')\n self.socket.close()\n sys.exit(0)": 1143, "def stop(self):\n \"\"\"Stops the background synchronization thread\"\"\"\n with self.synclock:\n if self.syncthread is not None:\n self.syncthread.cancel()\n self.syncthread = None": 1144, "def symlink_remove(link):\n \"\"\"Remove a symlink. Used for model shortcut links.\n\n link (unicode / Path): The path to the symlink.\n \"\"\"\n # https://stackoverflow.com/q/26554135/6400719\n if os.path.isdir(path2str(link)) and is_windows:\n # this should only be on Py2.7 and windows\n os.rmdir(path2str(link))\n else:\n os.unlink(path2str(link))": 1145, "def split_strings_in_list_retain_spaces(orig_list):\n \"\"\"\n Function to split every line in a list, and retain spaces for a rejoin\n :param orig_list: Original list\n :return:\n A List with split lines\n\n \"\"\"\n temp_list = list()\n for line in orig_list:\n line_split = __re.split(r'(\\s+)', line)\n temp_list.append(line_split)\n\n return temp_list": 1146, "def transcript_sort_key(transcript):\n \"\"\"\n Key function used to sort transcripts. Taking the negative of\n protein sequence length and nucleotide sequence length so that\n the transcripts with longest sequences come first in the list. This couldn't\n be accomplished with `reverse=True` since we're also sorting by\n transcript name (which places TP53-001 before TP53-002).\n \"\"\"\n return (\n -len(transcript.protein_sequence),\n -len(transcript.sequence),\n transcript.name\n )": 1147, "def getdefaultencoding():\n \"\"\"Return IPython's guess for the default encoding for bytes as text.\n\n Asks for stdin.encoding first, to match the calling Terminal, but that\n is often None for subprocesses. Fall back on locale.getpreferredencoding()\n which should be a sensible platform default (that respects LANG environment),\n and finally to sys.getdefaultencoding() which is the most conservative option,\n and usually ASCII.\n \"\"\"\n enc = get_stream_enc(sys.stdin)\n if not enc or enc=='ascii':\n try:\n # There are reports of getpreferredencoding raising errors\n # in some cases, which may well be fixed, but let's be conservative here.\n enc = locale.getpreferredencoding()\n except Exception:\n pass\n return enc or sys.getdefaultencoding()": 1148, "def _config_win32_domain(self, domain):\n \"\"\"Configure a Domain registry entry.\"\"\"\n # we call str() on domain to convert it from unicode to ascii\n self.domain = dns.name.from_text(str(domain))": 1149, "def _dict_values_sorted_by_key(dictionary):\n # This should be a yield from instead.\n \"\"\"Internal helper to return the values of a dictionary, sorted by key.\n \"\"\"\n for _, value in sorted(dictionary.iteritems(), key=operator.itemgetter(0)):\n yield value": 1150, "def get_neg_infinity(dtype):\n \"\"\"Return an appropriate positive infinity for this dtype.\n\n Parameters\n ----------\n dtype : np.dtype\n\n Returns\n -------\n fill_value : positive infinity value corresponding to this dtype.\n \"\"\"\n if issubclass(dtype.type, (np.floating, np.integer)):\n return -np.inf\n\n if issubclass(dtype.type, np.complexfloating):\n return -np.inf - 1j * np.inf\n\n return NINF": 1151, "def chmod_add_excute(filename):\n \"\"\"\n Adds execute permission to file.\n :param filename:\n :return:\n \"\"\"\n st = os.stat(filename)\n os.chmod(filename, st.st_mode | stat.S_IEXEC)": 1152, "def _removeStopwords(text_list):\n \"\"\"\n Removes stopwords contained in a list of words.\n\n :param text_string: A list of strings.\n :type text_string: list.\n\n :returns: The input ``text_list`` with stopwords removed.\n :rtype: list\n \"\"\"\n\n output_list = []\n\n for word in text_list:\n if word.lower() not in _stopwords:\n output_list.append(word)\n\n return output_list": 1153, "def GetPythonLibraryDirectoryPath():\n \"\"\"Retrieves the Python library directory path.\"\"\"\n path = sysconfig.get_python_lib(True)\n _, _, path = path.rpartition(sysconfig.PREFIX)\n\n if path.startswith(os.sep):\n path = path[1:]\n\n return path": 1154, "def lspearmanr(x,y):\n \"\"\"\nCalculates a Spearman rank-order correlation coefficient. Taken\nfrom Heiman's Basic Statistics for the Behav. Sci (1st), p.192.\n\nUsage: lspearmanr(x,y) where x and y are equal-length lists\nReturns: Spearman's r, two-tailed p-value\n\"\"\"\n TINY = 1e-30\n if len(x) != len(y):\n raise ValueError('Input values not paired in spearmanr. Aborting.')\n n = len(x)\n rankx = rankdata(x)\n ranky = rankdata(y)\n dsq = sumdiffsquared(rankx,ranky)\n rs = 1 - 6*dsq / float(n*(n**2-1))\n t = rs * math.sqrt((n-2) / ((rs+1.0)*(1.0-rs)))\n df = n-2\n probrs = betai(0.5*df,0.5,df/(df+t*t)) # t already a float\n# probability values for rs are from part 2 of the spearman function in\n# Numerical Recipies, p.510. They are close to tables, but not exact. (?)\n return rs, probrs": 1155, "def _python_rpath(self):\n \"\"\"The relative path (from environment root) to python.\"\"\"\n # Windows virtualenv installation installs pip to the [Ss]cripts\n # folder. Here's a simple check to support:\n if sys.platform == 'win32':\n return os.path.join('Scripts', 'python.exe')\n return os.path.join('bin', 'python')": 1156, "def setValue(self, p_float):\n \"\"\"Override method to set a value to show it as 0 to 100.\n\n :param p_float: The float number that want to be set.\n :type p_float: float\n \"\"\"\n p_float = p_float * 100\n\n super(PercentageSpinBox, self).setValue(p_float)": 1157, "def expand_args(cmd_args):\n \"\"\"split command args to args list\n returns a list of args\n\n :param cmd_args: command args, can be tuple, list or str\n \"\"\"\n if isinstance(cmd_args, (tuple, list)):\n args_list = list(cmd_args)\n else:\n args_list = shlex.split(cmd_args)\n return args_list": 1158, "def datetime_from_timestamp(timestamp, content):\n \"\"\"\n Helper function to add timezone information to datetime,\n so that datetime is comparable to other datetime objects in recent versions\n that now also have timezone information.\n \"\"\"\n return set_date_tzinfo(\n datetime.fromtimestamp(timestamp),\n tz_name=content.settings.get('TIMEZONE', None))": 1159, "def split_on(s, sep=\" \"):\n \"\"\"Split s by sep, unless it's inside a quote.\"\"\"\n pattern = '''((?:[^%s\"']|\"[^\"]*\"|'[^']*')+)''' % sep\n\n return [_strip_speechmarks(t) for t in re.split(pattern, s)[1::2]]": 1160, "def SetValue(self, row, col, value):\n \"\"\"\n Set value in the pandas DataFrame\n \"\"\"\n self.dataframe.iloc[row, col] = value": 1161, "def extract_args(argv):\n \"\"\"\n take sys.argv that is used to call a command-line script and return a correctly split list of arguments\n for example, this input: [\"eqarea.py\", \"-f\", \"infile\", \"-F\", \"outfile\", \"-A\"]\n will return this output: [['f', 'infile'], ['F', 'outfile'], ['A']]\n \"\"\"\n string = \" \".join(argv)\n string = string.split(' -')\n program = string[0]\n arguments = [s.split() for s in string[1:]]\n return arguments": 1162, "def move_to(x, y):\n \"\"\"Moves the brush to a particular position.\n\n Arguments:\n x - a number between -250 and 250.\n y - a number between -180 and 180.\n \"\"\"\n _make_cnc_request(\"coord/{0}/{1}\".format(x, y))\n state['turtle'].goto(x, y)": 1163, "def stopwatch_now():\n \"\"\"Get a timevalue for interval comparisons\n\n When possible it is a monotonic clock to prevent backwards time issues.\n \"\"\"\n if six.PY2:\n now = time.time()\n else:\n now = time.monotonic()\n return now": 1164, "def case_us2mc(x):\n \"\"\" underscore to mixed case notation \"\"\"\n return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), x)": 1165, "def file_found(filename,force):\n \"\"\"Check if a file exists\"\"\"\n if os.path.exists(filename) and not force:\n logger.info(\"Found %s; skipping...\"%filename)\n return True\n else:\n return False": 1166, "def restart(self, reset=False):\n \"\"\"\n Quit and Restart Spyder application.\n\n If reset True it allows to reset spyder on restart.\n \"\"\"\n # Get start path to use in restart script\n spyder_start_directory = get_module_path('spyder')\n restart_script = osp.join(spyder_start_directory, 'app', 'restart.py')\n\n # Get any initial argument passed when spyder was started\n # Note: Variables defined in bootstrap.py and spyder/app/start.py\n env = os.environ.copy()\n bootstrap_args = env.pop('SPYDER_BOOTSTRAP_ARGS', None)\n spyder_args = env.pop('SPYDER_ARGS')\n\n # Get current process and python running spyder\n pid = os.getpid()\n python = sys.executable\n\n # Check if started with bootstrap.py\n if bootstrap_args is not None:\n spyder_args = bootstrap_args\n is_bootstrap = True\n else:\n is_bootstrap = False\n\n # Pass variables as environment variables (str) to restarter subprocess\n env['SPYDER_ARGS'] = spyder_args\n env['SPYDER_PID'] = str(pid)\n env['SPYDER_IS_BOOTSTRAP'] = str(is_bootstrap)\n env['SPYDER_RESET'] = str(reset)\n\n if DEV:\n if os.name == 'nt':\n env['PYTHONPATH'] = ';'.join(sys.path)\n else:\n env['PYTHONPATH'] = ':'.join(sys.path)\n\n # Build the command and popen arguments depending on the OS\n if os.name == 'nt':\n # Hide flashing command prompt\n startupinfo = subprocess.STARTUPINFO()\n startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW\n shell = False\n else:\n startupinfo = None\n shell = True\n\n command = '\"{0}\" \"{1}\"'\n command = command.format(python, restart_script)\n\n try:\n if self.closing(True):\n subprocess.Popen(command, shell=shell, env=env,\n startupinfo=startupinfo)\n self.console.quit()\n except Exception as error:\n # If there is an error with subprocess, Spyder should not quit and\n # the error can be inspected in the internal console\n print(error) # spyder: test-skip\n print(command)": 1167, "def MatrixSolve(a, rhs, adj):\n \"\"\"\n Matrix solve op.\n \"\"\"\n return np.linalg.solve(a if not adj else _adjoint(a), rhs),": 1168, "def _bindingsToDict(self, bindings):\n \"\"\"\n Given a binding from the sparql query result,\n create a dict of plain text\n \"\"\"\n myDict = {}\n for key, val in bindings.iteritems():\n myDict[key.toPython().replace('?', '')] = val.toPython()\n return myDict": 1169, "def createdb():\n \"\"\"Create database tables from sqlalchemy models\"\"\"\n manager.db.engine.echo = True\n manager.db.create_all()\n set_alembic_revision()": 1170, "def algo_exp(x, m, t, b):\n \"\"\"mono-exponential curve.\"\"\"\n return m*np.exp(-t*x)+b": 1171, "def sort_dict(d, key=None, reverse=False):\n \"\"\"\n Sorts a dict by value.\n\n Args:\n d: Input dictionary\n key: Function which takes an tuple (key, object) and returns a value to\n compare and sort by. By default, the function compares the values\n of the dict i.e. key = lambda t : t[1]\n reverse: Allows to reverse sort order.\n\n Returns:\n OrderedDict object whose keys are ordered according to their value.\n \"\"\"\n kv_items = [kv for kv in d.items()]\n\n # Sort kv_items according to key.\n if key is None:\n kv_items.sort(key=lambda t: t[1], reverse=reverse)\n else:\n kv_items.sort(key=key, reverse=reverse)\n\n # Build ordered dict.\n return collections.OrderedDict(kv_items)": 1172, "def commit(self, session=None):\n \"\"\"Merge modified objects into parent transaction.\n\n Once commited a transaction object is not usable anymore\n\n :param:session: current sqlalchemy Session\n \"\"\"\n if self.__cleared:\n return\n\n if self._parent:\n # nested transaction\n self._commit_parent()\n else:\n self._commit_repository()\n self._clear()": 1173, "def arglexsort(arrays):\n \"\"\"\n Returns the indices of the lexicographical sorting\n order of the supplied arrays.\n \"\"\"\n dtypes = ','.join(array.dtype.str for array in arrays)\n recarray = np.empty(len(arrays[0]), dtype=dtypes)\n for i, array in enumerate(arrays):\n recarray['f%s' % i] = array\n return recarray.argsort()": 1174, "def __init__(self):\n \"\"\"Initializes the database file object.\"\"\"\n super(Sqlite3DatabaseFile, self).__init__()\n self._connection = None\n self._cursor = None\n self.filename = None\n self.read_only = None": 1175, "def _shutdown_transport(self):\n \"\"\"Unwrap a Python 2.6 SSL socket, so we can call shutdown()\"\"\"\n if self.sock is not None:\n try:\n unwrap = self.sock.unwrap\n except AttributeError:\n return\n try:\n self.sock = unwrap()\n except ValueError:\n # Failure within SSL might mean unwrap exists but socket is not\n # deemed wrapped\n pass": 1176, "def sort_nicely(l):\n \"\"\"Sort the given list in the way that humans expect.\"\"\"\n convert = lambda text: int(text) if text.isdigit() else text\n alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]\n l.sort(key=alphanum_key)": 1177, "def weighted_std(values, weights):\n \"\"\" Calculate standard deviation weighted by errors \"\"\"\n average = np.average(values, weights=weights)\n variance = np.average((values-average)**2, weights=weights)\n return np.sqrt(variance)": 1178, "def _std(self,x):\n \"\"\"\n Compute standard deviation with ddof degrees of freedom\n \"\"\"\n return np.nanstd(x.values,ddof=self._ddof)": 1179, "def sort_data(data, cols):\n \"\"\"Sort `data` rows and order columns\"\"\"\n return data.sort_values(cols)[cols + ['value']].reset_index(drop=True)": 1180, "def get_function_class(function_name):\n \"\"\"\n Return the type for the requested function\n\n :param function_name: the function to return\n :return: the type for that function (i.e., this is a class, not an instance)\n \"\"\"\n\n if function_name in _known_functions:\n\n return _known_functions[function_name]\n\n else:\n\n raise UnknownFunction(\"Function %s is not known. Known functions are: %s\" %\n (function_name, \",\".join(_known_functions.keys())))": 1181, "def safe_call(cls, method, *args):\n \"\"\" Call a remote api method but don't raise if an error occurred.\"\"\"\n return cls.call(method, *args, safe=True)": 1182, "def text_width(string, font_name, font_size):\n \"\"\"Determine with width in pixels of string.\"\"\"\n return stringWidth(string, fontName=font_name, fontSize=font_size)": 1183, "def is_static(*p):\n \"\"\" A static value (does not change at runtime)\n which is known at compile time\n \"\"\"\n return all(is_CONST(x) or\n is_number(x) or\n is_const(x)\n for x in p)": 1184, "def incidence(boundary):\n \"\"\"\n given an Nxm matrix containing boundary info between simplices,\n compute indidence info matrix\n not very reusable; should probably not be in this lib\n \"\"\"\n return GroupBy(boundary).split(np.arange(boundary.size) // boundary.shape[1])": 1185, "def _update_staticmethod(self, oldsm, newsm):\n \"\"\"Update a staticmethod update.\"\"\"\n # While we can't modify the staticmethod object itself (it has no\n # mutable attributes), we *can* extract the underlying function\n # (by calling __get__(), which returns it) and update it in-place.\n # We don't have the class available to pass to __get__() but any\n # object except None will do.\n self._update(None, None, oldsm.__get__(0), newsm.__get__(0))": 1186, "def column_stack_2d(data):\n \"\"\"Perform column-stacking on a list of 2d data blocks.\"\"\"\n return list(list(itt.chain.from_iterable(_)) for _ in zip(*data))": 1187, "def disconnect(self):\n \"\"\"Gracefully close connection to stomp server.\"\"\"\n if self._connected:\n self._connected = False\n self._conn.disconnect()": 1188, "def _configure_logger():\n \"\"\"Configure the logging module.\"\"\"\n if not app.debug:\n _configure_logger_for_production(logging.getLogger())\n elif not app.testing:\n _configure_logger_for_debugging(logging.getLogger())": 1189, "def _StopStatusUpdateThread(self):\n \"\"\"Stops the status update thread.\"\"\"\n self._status_update_active = False\n if self._status_update_thread.isAlive():\n self._status_update_thread.join()\n self._status_update_thread = None": 1190, "def to_binary(s, encoding='utf8'):\n \"\"\"Portable cast function.\n\n In python 2 the ``str`` function which is used to coerce objects to bytes does not\n accept an encoding argument, whereas python 3's ``bytes`` function requires one.\n\n :param s: object to be converted to binary_type\n :return: binary_type instance, representing s.\n \"\"\"\n if PY3: # pragma: no cover\n return s if isinstance(s, binary_type) else binary_type(s, encoding=encoding)\n return binary_type(s)": 1191, "def stop_button_click_handler(self):\n \"\"\"Method to handle what to do when the stop button is pressed\"\"\"\n self.stop_button.setDisabled(True)\n # Interrupt computations or stop debugging\n if not self.shellwidget._reading:\n self.interrupt_kernel()\n else:\n self.shellwidget.write_to_stdin('exit')": 1192, "def md5_string(s):\n \"\"\"\n Shortcut to create md5 hash\n :param s:\n :return:\n \"\"\"\n m = hashlib.md5()\n m.update(s)\n return str(m.hexdigest())": 1193, "def disown(cmd):\n \"\"\"Call a system command in the background,\n disown it and hide it's output.\"\"\"\n subprocess.Popen(cmd,\n stdout=subprocess.DEVNULL,\n stderr=subprocess.DEVNULL)": 1194, "def _validate_date_str(str_):\n \"\"\"Validate str as a date and return string version of date\"\"\"\n\n if not str_:\n return None\n\n # Convert to datetime so we can validate it's a real date that exists then\n # convert it back to the string.\n try:\n date = datetime.strptime(str_, DATE_FMT)\n except ValueError:\n msg = 'Invalid date format, should be YYYY-MM-DD'\n raise argparse.ArgumentTypeError(msg)\n\n return date.strftime(DATE_FMT)": 1195, "def magnitude(X):\n \"\"\"Magnitude of a complex matrix.\"\"\"\n r = np.real(X)\n i = np.imag(X)\n return np.sqrt(r * r + i * i);": 1196, "def loads(s, model=None, parser=None):\n \"\"\"Deserialize s (a str) to a Python object.\"\"\"\n with StringIO(s) as f:\n return load(f, model=model, parser=parser)": 1197, "def _serialize_json(obj, fp):\n \"\"\" Serialize ``obj`` as a JSON formatted stream to ``fp`` \"\"\"\n json.dump(obj, fp, indent=4, default=serialize)": 1198, "def is_valid_url(url):\n \"\"\"Checks if a given string is an url\"\"\"\n pieces = urlparse(url)\n return all([pieces.scheme, pieces.netloc])": 1199, "def bytesize(arr):\n \"\"\"\n Returns the memory byte size of a Numpy array as an integer.\n \"\"\"\n byte_size = np.prod(arr.shape) * np.dtype(arr.dtype).itemsize\n return byte_size": 1200, "def format_float(value): # not used\n \"\"\"Modified form of the 'g' format specifier.\n \"\"\"\n string = \"{:g}\".format(value).replace(\"e+\", \"e\")\n string = re.sub(\"e(-?)0*(\\d+)\", r\"e\\1\\2\", string)\n return string": 1201, "def random_int(maximum_value):\n\t\"\"\" Random generator (PyCrypto getrandbits wrapper). The result is a non-negative value.\n\n\t:param maximum_value: maximum integer value\n\t:return: int\n\t\"\"\"\n\tif maximum_value == 0:\n\t\treturn 0\n\telif maximum_value == 1:\n\t\treturn random_bits(1)\n\n\tbits = math.floor(math.log2(maximum_value))\n\tresult = random_bits(bits) + random_int(maximum_value - ((2 ** bits) - 1))\n\treturn result": 1202, "def covstr(s):\n \"\"\" convert string to int or float. \"\"\"\n try:\n ret = int(s)\n except ValueError:\n ret = float(s)\n return ret": 1203, "def _system_parameters(**kwargs):\n \"\"\"\n Returns system keyword arguments removing Nones.\n\n Args:\n kwargs: system keyword arguments.\n\n Returns:\n dict: system keyword arguments.\n \"\"\"\n return {key: value for key, value in kwargs.items()\n if (value is not None or value == {})}": 1204, "def _from_bytes(bytes, byteorder=\"big\", signed=False):\n \"\"\"This is the same functionality as ``int.from_bytes`` in python 3\"\"\"\n return int.from_bytes(bytes, byteorder=byteorder, signed=signed)": 1205, "def lcumsum (inlist):\n \"\"\"\nReturns a list consisting of the cumulative sum of the items in the\npassed list.\n\nUsage: lcumsum(inlist)\n\"\"\"\n newlist = copy.deepcopy(inlist)\n for i in range(1,len(newlist)):\n newlist[i] = newlist[i] + newlist[i-1]\n return newlist": 1206, "def is_hex_string(string):\n \"\"\"Check if the string is only composed of hex characters.\"\"\"\n pattern = re.compile(r'[A-Fa-f0-9]+')\n if isinstance(string, six.binary_type):\n string = str(string)\n return pattern.match(string) is not None": 1207, "def local_accuracy(X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model):\n \"\"\" The how well do the features plus a constant base rate sum up to the model output.\n \"\"\"\n\n X_train, X_test = to_array(X_train, X_test)\n\n # how many features to mask\n assert X_train.shape[1] == X_test.shape[1]\n\n # keep nkeep top features and re-train the model for each test explanation\n yp_test = trained_model.predict(X_test)\n\n return metric(yp_test, strip_list(attr_test).sum(1))": 1208, "def doc_to_html(doc, doc_format=\"ROBOT\"):\n \"\"\"Convert documentation to HTML\"\"\"\n from robot.libdocpkg.htmlwriter import DocToHtml\n return DocToHtml(doc_format)(doc)": 1209, "def replace(scope, strings, source, dest):\n \"\"\"\n Returns a copy of the given string (or list of strings) in which all\n occurrences of the given source are replaced by the given dest.\n\n :type strings: string\n :param strings: A string, or a list of strings.\n :type source: string\n :param source: What to replace.\n :type dest: string\n :param dest: What to replace it with.\n :rtype: string\n :return: The resulting string, or list of strings.\n \"\"\"\n return [s.replace(source[0], dest[0]) for s in strings]": 1210, "def parse_datetime(dt_str):\n \"\"\"Parse datetime.\"\"\"\n date_format = \"%Y-%m-%dT%H:%M:%S %z\"\n dt_str = dt_str.replace(\"Z\", \" +0000\")\n return datetime.datetime.strptime(dt_str, date_format)": 1211, "def pack_triples_numpy(triples):\n \"\"\"Packs a list of triple indexes into a 2D numpy array.\"\"\"\n if len(triples) == 0:\n return np.array([], dtype=np.int64)\n return np.stack(list(map(_transform_triple_numpy, triples)), axis=0)": 1212, "def str2bytes(x):\n \"\"\"Convert input argument to bytes\"\"\"\n if type(x) is bytes:\n return x\n elif type(x) is str:\n return bytes([ ord(i) for i in x ])\n else:\n return str2bytes(str(x))": 1213, "def visit_Str(self, node):\n \"\"\" Set the pythonic string type. \"\"\"\n self.result[node] = self.builder.NamedType(pytype_to_ctype(str))": 1214, "def string_list_to_array(l):\n \"\"\"\n Turns a Python unicode string list into a Java String array.\n\n :param l: the string list\n :type: list\n :rtype: java string array\n :return: JB_Object\n \"\"\"\n result = javabridge.get_env().make_object_array(len(l), javabridge.get_env().find_class(\"java/lang/String\"))\n for i in range(len(l)):\n javabridge.get_env().set_object_array_element(result, i, javabridge.get_env().new_string_utf(l[i]))\n return result": 1215, "def coerce(self, value):\n \"\"\"Convert from whatever is given to a list of scalars for the lookup_field.\"\"\"\n if isinstance(value, dict):\n value = [value]\n if not isiterable_notstring(value):\n value = [value]\n return [coerce_single_instance(self.lookup_field, v) for v in value]": 1216, "def drop_bad_characters(text):\n \"\"\"Takes a text and drops all non-printable and non-ascii characters and\n also any whitespace characters that aren't space.\n\n :arg str text: the text to fix\n\n :returns: text with all bad characters dropped\n\n \"\"\"\n # Strip all non-ascii and non-printable characters\n text = ''.join([c for c in text if c in ALLOWED_CHARS])\n return text": 1217, "def removeFromRegistery(obj) :\n\t\"\"\"Removes an object/rabalist from registery. This is useful if you want to allow the garbage collector to free the memory\n\ttaken by the objects you've already loaded. Be careful might cause some discrepenties in your scripts. For objects,\n\tcascades to free the registeries of related rabalists also\"\"\"\n\t\n\tif isRabaObject(obj) :\n\t\t_unregisterRabaObjectInstance(obj)\n\telif isRabaList(obj) :\n\t\t_unregisterRabaListInstance(obj)": 1218, "def filter_none(list_of_points):\n \"\"\"\n \n :param list_of_points: \n :return: list_of_points with None's removed\n \"\"\"\n remove_elementnone = filter(lambda p: p is not None, list_of_points)\n remove_sublistnone = filter(lambda p: not contains_none(p), remove_elementnone)\n return list(remove_sublistnone)": 1219, "def _unzip_handle(handle):\n \"\"\"Transparently unzip the file handle\"\"\"\n if isinstance(handle, basestring):\n handle = _gzip_open_filename(handle)\n else:\n handle = _gzip_open_handle(handle)\n return handle": 1220, "def _update_texttuple(self, x, y, s, cs, d):\n \"\"\"Update the text tuple at `x` and `y` with the given `s` and `d`\"\"\"\n pos = (x, y, cs)\n for i, (old_x, old_y, old_s, old_cs, old_d) in enumerate(self.value):\n if (old_x, old_y, old_cs) == pos:\n self.value[i] = (old_x, old_y, s, old_cs, d)\n return\n raise ValueError(\"No text tuple found at {0}!\".format(pos))": 1221, "def authenticate(self, transport, account_name, password=None):\n \"\"\"\n Authenticates account using soap method.\n \"\"\"\n Authenticator.authenticate(self, transport, account_name, password)\n\n if password == None:\n return self.pre_auth(transport, account_name)\n else:\n return self.auth(transport, account_name, password)": 1222, "def _wait_for_response(self):\n\t\t\"\"\"\n\t\tWait until the user accepted or rejected the request\n\t\t\"\"\"\n\t\twhile not self.server.response_code:\n\t\t\ttime.sleep(2)\n\t\ttime.sleep(5)\n\t\tself.server.shutdown()": 1223, "def copy_and_update(dictionary, update):\n \"\"\"Returns an updated copy of the dictionary without modifying the original\"\"\"\n newdict = dictionary.copy()\n newdict.update(update)\n return newdict": 1224, "def _do_auto_predict(machine, X, *args):\n \"\"\"Performs an automatic prediction for the specified machine and returns\n the predicted values.\n \"\"\"\n if auto_predict and hasattr(machine, \"predict\"):\n return machine.predict(X)": 1225, "def row_to_dict(row):\n \"\"\"Convert a table row to a dictionary.\"\"\"\n o = {}\n for colname in row.colnames:\n\n if isinstance(row[colname], np.string_) and row[colname].dtype.kind in ['S', 'U']:\n o[colname] = str(row[colname])\n else:\n o[colname] = row[colname]\n\n return o": 1226, "def color_string(color, string):\n \"\"\"\n Colorizes a given string, if coloring is available.\n \"\"\"\n if not color_available:\n return string\n\n return color + string + colorama.Fore.RESET": 1227, "def execute(self, env, args):\n \"\"\" Starts a new task.\n\n `env`\n Runtime ``Environment`` instance.\n `args`\n Arguments object from arg parser.\n \"\"\"\n\n # start the task\n if env.task.start(args.task_name):\n env.io.success(u'Task Loaded.')": 1228, "def create_tmpfile(self, content):\n \"\"\" Utility method to create temp files. These are cleaned at the end of the test \"\"\"\n # Not using a context manager to avoid unneccessary identation in test code\n tmpfile, tmpfilepath = tempfile.mkstemp()\n self.tmpfiles.append(tmpfilepath)\n with os.fdopen(tmpfile, \"w\") as f:\n f.write(content)\n return tmpfilepath": 1229, "def aandb(a, b):\n \"\"\"Return a matrix of logic comparison of A or B\"\"\"\n return matrix(np.logical_and(a, b).astype('float'), a.size)": 1230, "def json_template(data, template_name, template_context):\n \"\"\"Old style, use JSONTemplateResponse instead of this.\n \"\"\"\n html = render_to_string(template_name, template_context)\n data = data or {}\n data['html'] = html\n return HttpResponse(json_encode(data), content_type='application/json')": 1231, "def find(self, *args, **kwargs):\n \"\"\"Same as :meth:`pymongo.collection.Collection.find`, except\n it returns the right document class.\n \"\"\"\n return Cursor(self, *args, wrap=self.document_class, **kwargs)": 1232, "def unfolding(tens, i):\n \"\"\"Compute the i-th unfolding of a tensor.\"\"\"\n return reshape(tens.full(), (np.prod(tens.n[0:(i+1)]), -1))": 1233, "def members(self, uid=\"*\", objects=False):\n \"\"\" members() issues an ldap query for all users, and returns a dict\n for each matching entry. This can be quite slow, and takes roughly\n 3s to complete. You may optionally restrict the scope by specifying\n a uid, which is roughly equivalent to a search(uid='foo')\n \"\"\"\n entries = self.search(uid='*')\n if objects:\n return self.memberObjects(entries)\n result = []\n for entry in entries:\n result.append(entry[1])\n return result": 1234, "def flatten_all_but_last(a):\n \"\"\"Flatten all dimensions of a except the last.\"\"\"\n ret = tf.reshape(a, [-1, tf.shape(a)[-1]])\n if not tf.executing_eagerly():\n ret.set_shape([None] + a.get_shape().as_list()[-1:])\n return ret": 1235, "def list_move_to_front(l,value='other'):\n \"\"\"if the value is in the list, move it to the front and return it.\"\"\"\n l=list(l)\n if value in l:\n l.remove(value)\n l.insert(0,value)\n return l": 1236, "def afx_small():\n \"\"\"Small transformer model with small batch size for fast step times.\"\"\"\n hparams = transformer.transformer_tpu()\n hparams.filter_size = 1024\n hparams.num_heads = 4\n hparams.num_hidden_layers = 3\n hparams.batch_size = 512\n return hparams": 1237, "def get_span_char_width(span, column_widths):\n \"\"\"\n Sum the widths of the columns that make up the span, plus the extra.\n\n Parameters\n ----------\n span : list of lists of int\n list of [row, column] pairs that make up the span\n column_widths : list of int\n The widths of the columns that make up the table\n\n Returns\n -------\n total_width : int\n The total width of the span\n \"\"\"\n\n start_column = span[0][1]\n column_count = get_span_column_count(span)\n total_width = 0\n\n for i in range(start_column, start_column + column_count):\n total_width += column_widths[i]\n\n total_width += column_count - 1\n\n return total_width": 1238, "def has_attribute(module_name, attribute_name):\n \"\"\"Is this attribute present?\"\"\"\n init_file = '%s/__init__.py' % module_name\n return any(\n [attribute_name in init_line for init_line in open(init_file).readlines()]\n )": 1239, "def sort_genomic_ranges(rngs):\n \"\"\"sort multiple ranges\"\"\"\n return sorted(rngs, key=lambda x: (x.chr, x.start, x.end))": 1240, "def is_square_matrix(mat):\n \"\"\"Test if an array is a square matrix.\"\"\"\n mat = np.array(mat)\n if mat.ndim != 2:\n return False\n shape = mat.shape\n return shape[0] == shape[1]": 1241, "def save_session(self, sid, session, namespace=None):\n \"\"\"Store the user session for a client.\n\n The only difference with the :func:`socketio.Server.save_session`\n method is that when the ``namespace`` argument is not given the\n namespace associated with the class is used.\n \"\"\"\n return self.server.save_session(\n sid, session, namespace=namespace or self.namespace)": 1242, "def is_connected(self):\n \"\"\"\n Return true if the socket managed by this connection is connected\n\n :rtype: bool\n \"\"\"\n try:\n return self.socket is not None and self.socket.getsockname()[1] != 0 and BaseTransport.is_connected(self)\n except socket.error:\n return False": 1243, "def show(config):\n \"\"\"Show revision list\"\"\"\n with open(config, 'r'):\n main.show(yaml.load(open(config)))": 1244, "def _validate_type_scalar(self, value):\n \"\"\" Is not a list or a dict \"\"\"\n if isinstance(\n value, _int_types + (_str_type, float, date, datetime, bool)\n ):\n return True": 1245, "def encode_dataset(dataset, vocabulary):\n \"\"\"Encode from strings to token ids.\n\n Args:\n dataset: a tf.data.Dataset with string values.\n vocabulary: a mesh_tensorflow.transformer.Vocabulary\n Returns:\n a tf.data.Dataset with integer-vector values ending in EOS=1\n \"\"\"\n def encode(features):\n return {k: vocabulary.encode_tf(v) for k, v in features.items()}\n return dataset.map(encode, num_parallel_calls=tf.data.experimental.AUTOTUNE)": 1246, "def generate_write_yaml_to_file(file_name):\n \"\"\" generate a method to write the configuration in yaml to the method desired \"\"\"\n def write_yaml(config):\n with open(file_name, 'w+') as fh:\n fh.write(yaml.dump(config))\n return write_yaml": 1247, "def Stop(self):\n \"\"\"Stops the process status RPC server.\"\"\"\n self._Close()\n\n if self._rpc_thread.isAlive():\n self._rpc_thread.join()\n self._rpc_thread = None": 1248, "def is_valid_ipv6(ip_str):\n \"\"\"\n Check the validity of an IPv6 address\n \"\"\"\n try:\n socket.inet_pton(socket.AF_INET6, ip_str)\n except socket.error:\n return False\n return True": 1249, "def flush():\n \"\"\"Try to flush all stdio buffers, both from python and from C.\"\"\"\n try:\n sys.stdout.flush()\n sys.stderr.flush()\n except (AttributeError, ValueError, IOError):\n pass # unsupported\n try:\n libc.fflush(None)\n except (AttributeError, ValueError, IOError):\n pass": 1250, "def get_list_representation(self):\n \"\"\"Returns this subset's representation as a list of indices.\"\"\"\n if self.is_list:\n return self.list_or_slice\n else:\n return self[list(range(self.num_examples))]": 1251, "def join(self):\n\t\t\"\"\"Note that the Executor must be close()'d elsewhere,\n\t\tor join() will never return.\n\t\t\"\"\"\n\t\tself.inputfeeder_thread.join()\n\t\tself.pool.join()\n\t\tself.resulttracker_thread.join()\n\t\tself.failuretracker_thread.join()": 1252, "def write_tsv_line_from_list(linelist, outfp):\n \"\"\"Utility method to convert list to tsv line with carriage return\"\"\"\n line = '\\t'.join(linelist)\n outfp.write(line)\n outfp.write('\\n')": 1253, "def _make_sentence(txt):\n \"\"\"Make a sentence from a piece of text.\"\"\"\n #Make sure first letter is capitalized\n txt = txt.strip(' ')\n txt = txt[0].upper() + txt[1:] + '.'\n return txt": 1254, "def make_directory(path):\n \"\"\"\n Make a directory and any intermediate directories that don't already\n exist. This function handles the case where two threads try to create\n a directory at once.\n \"\"\"\n if not os.path.exists(path):\n # concurrent writes that try to create the same dir can fail\n try:\n os.makedirs(path)\n\n except OSError as e:\n if e.errno == errno.EEXIST:\n pass\n else:\n raise e": 1255, "def csv_matrix_print(classes, table):\n \"\"\"\n Return matrix as csv data.\n\n :param classes: classes list\n :type classes:list\n :param table: table\n :type table:dict\n :return:\n \"\"\"\n result = \"\"\n classes.sort()\n for i in classes:\n for j in classes:\n result += str(table[i][j]) + \",\"\n result = result[:-1] + \"\\n\"\n return result[:-1]": 1256, "def quaternion_to_rotation_matrix(quaternion):\n \"\"\"Compute the rotation matrix representated by the quaternion\"\"\"\n c, x, y, z = quaternion\n return np.array([\n [c*c + x*x - y*y - z*z, 2*x*y - 2*c*z, 2*x*z + 2*c*y ],\n [2*x*y + 2*c*z, c*c - x*x + y*y - z*z, 2*y*z - 2*c*x ],\n [2*x*z - 2*c*y, 2*y*z + 2*c*x, c*c - x*x - y*y + z*z]\n ], float)": 1257, "def write_file(filename, content):\n \"\"\"Create the file with the given content\"\"\"\n print 'Generating {0}'.format(filename)\n with open(filename, 'wb') as out_f:\n out_f.write(content)": 1258, "def ms_to_datetime(ms):\n \"\"\"\n Converts a millisecond accuracy timestamp to a datetime\n \"\"\"\n dt = datetime.datetime.utcfromtimestamp(ms / 1000)\n return dt.replace(microsecond=(ms % 1000) * 1000).replace(tzinfo=pytz.utc)": 1259, "def retry_test(func):\n \"\"\"Retries the passed function 3 times before failing\"\"\"\n success = False\n ex = Exception(\"Unknown\")\n for i in six.moves.range(3):\n try:\n result = func()\n except Exception as e:\n time.sleep(1)\n ex = e\n else:\n success = True\n break\n if not success:\n raise ex\n assert success\n return result": 1260, "def get_own_ip():\n \"\"\"Get the host's ip number.\n \"\"\"\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n try:\n sock.connect((\"8.8.8.8\", 80))\n except socket.gaierror:\n ip_ = \"127.0.0.1\"\n else:\n ip_ = sock.getsockname()[0]\n finally:\n sock.close()\n return ip_": 1261, "def make_aware(dt):\n \"\"\"Appends tzinfo and assumes UTC, if datetime object has no tzinfo already.\"\"\"\n return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)": 1262, "def timestamp_to_datetime(timestamp):\n \"\"\"Convert an ARF timestamp to a datetime.datetime object (naive local time)\"\"\"\n from datetime import datetime, timedelta\n obj = datetime.fromtimestamp(timestamp[0])\n return obj + timedelta(microseconds=int(timestamp[1]))": 1263, "def yview(self, *args):\n \"\"\"Update inplace widgets position when doing vertical scroll\"\"\"\n self.after_idle(self.__updateWnds)\n ttk.Treeview.yview(self, *args)": 1264, "def is_gzipped_fastq(file_name):\n \"\"\"\n Determine whether indicated file appears to be a gzipped FASTQ.\n\n :param str file_name: Name/path of file to check as gzipped FASTQ.\n :return bool: Whether indicated file appears to be in gzipped FASTQ format.\n \"\"\"\n _, ext = os.path.splitext(file_name)\n return file_name.endswith(\".fastq.gz\") or file_name.endswith(\".fq.gz\")": 1265, "def get_pg_connection(host, user, port, password, database, ssl={}):\n \"\"\" PostgreSQL connection \"\"\"\n\n return psycopg2.connect(host=host,\n user=user,\n port=port,\n password=password,\n dbname=database,\n sslmode=ssl.get('sslmode', None),\n sslcert=ssl.get('sslcert', None),\n sslkey=ssl.get('sslkey', None),\n sslrootcert=ssl.get('sslrootcert', None),\n )": 1266, "def defvalkey(js, key, default=None, take_none=True):\n \"\"\"\n Returns js[key] if set, otherwise default. Note js[key] can be None.\n :param js:\n :param key:\n :param default:\n :param take_none:\n :return:\n \"\"\"\n if js is None:\n return default\n if key not in js:\n return default\n if js[key] is None and not take_none:\n return default\n return js[key]": 1267, "def get_python_dict(scala_map):\n \"\"\"Return a dict from entries in a scala.collection.immutable.Map\"\"\"\n python_dict = {}\n keys = get_python_list(scala_map.keys().toList())\n for key in keys:\n python_dict[key] = scala_map.apply(key)\n return python_dict": 1268, "def resize_image_to_fit_width(image, dest_w):\n \"\"\"\n Resize and image to fit the passed in width, keeping the aspect ratio the same\n\n :param image: PIL.Image\n :param dest_w: The desired width\n \"\"\"\n scale_factor = dest_w / image.size[0]\n dest_h = image.size[1] * scale_factor\n \n scaled_image = image.resize((int(dest_w), int(dest_h)), PIL.Image.ANTIALIAS)\n\n return scaled_image": 1269, "def list(self):\n \"\"\"position in 3d space\"\"\"\n return [self._pos3d.x, self._pos3d.y, self._pos3d.z]": 1270, "def GetAttributeNs(self, localName, namespaceURI):\n \"\"\"Provides the value of the specified attribute \"\"\"\n ret = libxml2mod.xmlTextReaderGetAttributeNs(self._o, localName, namespaceURI)\n return ret": 1271, "def find_geom(geom, geoms):\n \"\"\"\n Returns the index of a geometry in a list of geometries avoiding\n expensive equality checks of `in` operator.\n \"\"\"\n for i, g in enumerate(geoms):\n if g is geom:\n return i": 1272, "def _using_stdout(self):\n \"\"\"\n Return whether the handler is using sys.stdout.\n \"\"\"\n if WINDOWS and colorama:\n # Then self.stream is an AnsiToWin32 object.\n return self.stream.wrapped is sys.stdout\n\n return self.stream is sys.stdout": 1273, "def _linearInterpolationTransformMatrix(matrix1, matrix2, value):\n \"\"\" Linear, 'oldstyle' interpolation of the transform matrix.\"\"\"\n return tuple(_interpolateValue(matrix1[i], matrix2[i], value) for i in range(len(matrix1)))": 1274, "def is_unix_style(flags):\n \"\"\"Check if we should use Unix style.\"\"\"\n\n return (util.platform() != \"windows\" or (not bool(flags & REALPATH) and get_case(flags))) and not flags & _FORCEWIN": 1275, "def start(args):\n \"\"\"Run server with provided command line arguments.\n \"\"\"\n application = tornado.web.Application([(r\"/run\", run.get_handler(args)),\n (r\"/status\", run.StatusHandler)])\n application.runmonitor = RunMonitor()\n application.listen(args.port)\n tornado.ioloop.IOLoop.instance().start()": 1276, "def generic_div(a, b):\n \"\"\"Simple function to divide two numbers\"\"\"\n logger.debug('Called generic_div({}, {})'.format(a, b))\n return a / b": 1277, "def mean(inlist):\n \"\"\"\nReturns the arithematic mean of the values in the passed list.\nAssumes a '1D' list, but will function on the 1st dim of an array(!).\n\nUsage: lmean(inlist)\n\"\"\"\n sum = 0\n for item in inlist:\n sum = sum + item\n return sum / float(len(inlist))": 1278, "def _frombuffer(ptr, frames, channels, dtype):\n \"\"\"Create NumPy array from a pointer to some memory.\"\"\"\n framesize = channels * dtype.itemsize\n data = np.frombuffer(ffi.buffer(ptr, frames * framesize), dtype=dtype)\n data.shape = -1, channels\n return data": 1279, "def _single_page_pdf(page):\n \"\"\"Construct a single page PDF from the provided page in memory\"\"\"\n pdf = Pdf.new()\n pdf.pages.append(page)\n bio = BytesIO()\n pdf.save(bio)\n bio.seek(0)\n return bio.read()": 1280, "def query_fetch_one(self, query, values):\n \"\"\"\n Executes a db query, gets the first value, and closes the connection.\n \"\"\"\n self.cursor.execute(query, values)\n retval = self.cursor.fetchone()\n self.__close_db()\n return retval": 1281, "def walk_tree(root):\n \"\"\"Pre-order depth-first\"\"\"\n yield root\n\n for child in root.children:\n for el in walk_tree(child):\n yield el": 1282, "def __consistent_isoformat_utc(datetime_val):\n \"\"\"\n Function that does what isoformat does but it actually does the same\n every time instead of randomly doing different things on some systems\n and also it represents that time as the equivalent UTC time.\n \"\"\"\n isotime = datetime_val.astimezone(pytz.utc).strftime(\"%Y-%m-%dT%H:%M:%S%z\")\n if isotime[-2] != \":\":\n isotime = isotime[:-2] + \":\" + isotime[-2:]\n return isotime": 1283, "def __iter__(self):\n\t\t\"\"\"Iterate through all elements.\n\n\t\tMultiple copies will be returned if they exist.\n\t\t\"\"\"\n\t\tfor value, count in self.counts():\n\t\t\tfor _ in range(count):\n\t\t\t\tyield value": 1284, "def eintr_retry(exc_type, f, *args, **kwargs):\n \"\"\"Calls a function. If an error of the given exception type with\n interrupted system call (EINTR) occurs calls the function again.\n \"\"\"\n while True:\n try:\n return f(*args, **kwargs)\n except exc_type as exc:\n if exc.errno != EINTR:\n raise\n else:\n break": 1285, "def dt_to_ts(value):\n \"\"\" If value is a datetime, convert to timestamp \"\"\"\n if not isinstance(value, datetime):\n return value\n return calendar.timegm(value.utctimetuple()) + value.microsecond / 1000000.0": 1286, "def itervalues(d, **kw):\n \"\"\"Return an iterator over the values of a dictionary.\"\"\"\n if not PY2:\n return iter(d.values(**kw))\n return d.itervalues(**kw)": 1287, "def norm_slash(name):\n \"\"\"Normalize path slashes.\"\"\"\n\n if isinstance(name, str):\n return name.replace('/', \"\\\\\") if not is_case_sensitive() else name\n else:\n return name.replace(b'/', b\"\\\\\") if not is_case_sensitive() else name": 1288, "def get_java_path():\n \"\"\"Get the path of java executable\"\"\"\n java_home = os.environ.get(\"JAVA_HOME\")\n return os.path.join(java_home, BIN_DIR, \"java\")": 1289, "def excel_key(index):\n \"\"\"create a key for index by converting index into a base-26 number, using A-Z as the characters.\"\"\"\n X = lambda n: ~n and X((n // 26)-1) + chr(65 + (n % 26)) or ''\n return X(int(index))": 1290, "def test_python_java_rt():\n \"\"\" Run Python test cases against Java runtime classes. \"\"\"\n sub_env = {'PYTHONPATH': _build_dir()}\n\n log.info('Executing Python unit tests (against Java runtime classes)...')\n return jpyutil._execute_python_scripts(python_java_rt_tests,\n env=sub_env)": 1291, "def split_into_sentences(s):\n \"\"\"Split text into list of sentences.\"\"\"\n s = re.sub(r\"\\s+\", \" \", s)\n s = re.sub(r\"[\\\\.\\\\?\\\\!]\", \"\\n\", s)\n return s.split(\"\\n\")": 1292, "def get_attributes(var):\n \"\"\"\n Given a varaible, return the list of attributes that are available inside\n of a template\n \"\"\"\n is_valid = partial(is_valid_in_template, var)\n return list(filter(is_valid, dir(var)))": 1293, "def _sim_fill(r1, r2, imsize):\n \"\"\"\n calculate the fill similarity over the image\n \"\"\"\n bbsize = (\n (max(r1[\"max_x\"], r2[\"max_x\"]) - min(r1[\"min_x\"], r2[\"min_x\"]))\n * (max(r1[\"max_y\"], r2[\"max_y\"]) - min(r1[\"min_y\"], r2[\"min_y\"]))\n )\n return 1.0 - (bbsize - r1[\"size\"] - r2[\"size\"]) / imsize": 1294, "def delimited(items, character='|'):\n \"\"\"Returns a character delimited version of the provided list as a Python string\"\"\"\n return '|'.join(items) if type(items) in (list, tuple, set) else items": 1295, "def _timestamp_to_json_row(value):\n \"\"\"Coerce 'value' to an JSON-compatible representation.\n\n This version returns floating-point seconds value used in row data.\n \"\"\"\n if isinstance(value, datetime.datetime):\n value = _microseconds_from_datetime(value) * 1e-6\n return value": 1296, "def istype(obj, check):\n \"\"\"Like isinstance(obj, check), but strict.\n\n This won't catch subclasses.\n \"\"\"\n if isinstance(check, tuple):\n for cls in check:\n if type(obj) is cls:\n return True\n return False\n else:\n return type(obj) is check": 1297, "def parse_json_date(value):\n \"\"\"\n Parses an ISO8601 formatted datetime from a string value\n \"\"\"\n if not value:\n return None\n\n return datetime.datetime.strptime(value, JSON_DATETIME_FORMAT).replace(tzinfo=pytz.UTC)": 1298, "def _to_numeric(val):\n \"\"\"\n Helper function for conversion of various data types into numeric representation.\n \"\"\"\n if isinstance(val, (int, float, datetime.datetime, datetime.timedelta)):\n return val\n return float(val)": 1299, "def read_json(location):\n \"\"\"Open and load JSON from file.\n\n location (Path): Path to JSON file.\n RETURNS (dict): Loaded JSON content.\n \"\"\"\n location = ensure_path(location)\n with location.open('r', encoding='utf8') as f:\n return ujson.load(f)": 1300, "def json_serialize(obj):\n \"\"\"\n Simple generic JSON serializer for common objects.\n \"\"\"\n if isinstance(obj, datetime):\n return obj.isoformat()\n\n if hasattr(obj, 'id'):\n return jsonify(obj.id)\n\n if hasattr(obj, 'name'):\n return jsonify(obj.name)\n\n raise TypeError('{0} is not JSON serializable'.format(obj))": 1301, "def load_schema(schema_path):\n \"\"\"Prepare the api specification for request and response validation.\n\n :returns: a mapping from :class:`RequestMatcher` to :class:`ValidatorMap`\n for every operation in the api specification.\n :rtype: dict\n \"\"\"\n with open(schema_path, 'r') as schema_file:\n schema = simplejson.load(schema_file)\n resolver = RefResolver('', '', schema.get('models', {}))\n return build_request_to_validator_map(schema, resolver)": 1302, "def __init__(self, testnet=False, dryrun=False):\n \"\"\"TODO doc string\"\"\"\n self.testnet = testnet\n self.dryrun = dryrun": 1303, "def unique(iterable):\n \"\"\" Returns a list copy in which each item occurs only once (in-order).\n \"\"\"\n seen = set()\n return [x for x in iterable if x not in seen and not seen.add(x)]": 1304, "def test():\n \"\"\" Run all Tests [nose] \"\"\"\n\n command = 'nosetests --with-coverage --cover-package=pwnurl'\n status = subprocess.call(shlex.split(command))\n sys.exit(status)": 1305, "def kill_process_children(pid):\n \"\"\"Find and kill child processes of a process.\n\n :param pid: PID of parent process (process ID)\n :return: Nothing\n \"\"\"\n if sys.platform == \"darwin\":\n kill_process_children_osx(pid)\n elif sys.platform == \"linux\":\n kill_process_children_unix(pid)\n else:\n pass": 1306, "def assert_is_not(expected, actual, message=None, extra=None):\n \"\"\"Raises an AssertionError if expected is actual.\"\"\"\n assert expected is not actual, _assert_fail_message(\n message, expected, actual, \"is\", extra\n )": 1307, "def sigterm(self, signum, frame):\n \"\"\"\n These actions will be done after SIGTERM.\n \"\"\"\n self.logger.warning(\"Caught signal %s. Stopping daemon.\" % signum)\n sys.exit(0)": 1308, "def guess_url(url):\n \"\"\"Guess if URL is a http or ftp URL.\n @param url: the URL to check\n @ptype url: unicode\n @return: url with http:// or ftp:// prepended if it's detected as\n a http respective ftp URL.\n @rtype: unicode\n \"\"\"\n if url.lower().startswith(\"www.\"):\n # syntactic sugar\n return \"http://%s\" % url\n elif url.lower().startswith(\"ftp.\"):\n # syntactic sugar\n return \"ftp://%s\" % url\n return url": 1309, "def normalize(v, axis=None, eps=1e-10):\n \"\"\"L2 Normalize along specified axes.\"\"\"\n return v / max(anorm(v, axis=axis, keepdims=True), eps)": 1310, "def finish_plot():\n \"\"\"Helper for plotting.\"\"\"\n plt.legend()\n plt.grid(color='0.7')\n plt.xlabel('x')\n plt.ylabel('y')\n plt.show()": 1311, "def s3(ctx, bucket_name, data_file, region):\n \"\"\"Use the S3 SWAG backend.\"\"\"\n if not ctx.data_file:\n ctx.data_file = data_file\n\n if not ctx.bucket_name:\n ctx.bucket_name = bucket_name\n\n if not ctx.region:\n ctx.region = region\n\n ctx.type = 's3'": 1312, "def is_safe_url(url, host=None):\n \"\"\"Return ``True`` if the url is a safe redirection.\n\n The safe redirection means that it doesn't point to a different host.\n Always returns ``False`` on an empty url.\n \"\"\"\n if not url:\n return False\n netloc = urlparse.urlparse(url)[1]\n return not netloc or netloc == host": 1313, "def tail(self, n=10):\n \"\"\"\n Get an SArray that contains the last n elements in the SArray.\n\n Parameters\n ----------\n n : int\n The number of elements to fetch\n\n Returns\n -------\n out : SArray\n A new SArray which contains the last n rows of the current SArray.\n \"\"\"\n with cython_context():\n return SArray(_proxy=self.__proxy__.tail(n))": 1314, "def get_url_args(url):\n \"\"\" Returns a dictionary from a URL params \"\"\"\n url_data = urllib.parse.urlparse(url)\n arg_dict = urllib.parse.parse_qs(url_data.query)\n return arg_dict": 1315, "def colorbar(height, length, colormap):\n \"\"\"Return the channels of a colorbar.\n \"\"\"\n cbar = np.tile(np.arange(length) * 1.0 / (length - 1), (height, 1))\n cbar = (cbar * (colormap.values.max() - colormap.values.min())\n + colormap.values.min())\n\n return colormap.colorize(cbar)": 1316, "def set_empty(self, row, column):\n \"\"\"Keep one of the subplots completely empty.\n\n :param row,column: specify the subplot.\n\n \"\"\"\n subplot = self.get_subplot_at(row, column)\n subplot.set_empty()": 1317, "def fromDict(cls, _dict):\n \"\"\" Builds instance from dictionary of properties. \"\"\"\n obj = cls()\n obj.__dict__.update(_dict)\n return obj": 1318, "def _requiredSize(shape, dtype):\n\t\"\"\"\n\tDetermines the number of bytes required to store a NumPy array with\n\tthe specified shape and datatype.\n\t\"\"\"\n\treturn math.floor(np.prod(np.asarray(shape, dtype=np.uint64)) * np.dtype(dtype).itemsize)": 1319, "def normalized(vector):\n \"\"\"\n Get unit vector for a given one.\n\n :param vector:\n Numpy vector as coordinates in Cartesian space, or an array of such.\n :returns:\n Numpy array of the same shape and structure where all vectors are\n normalized. That is, each coordinate component is divided by its\n vector's length.\n \"\"\"\n length = numpy.sum(vector * vector, axis=-1)\n length = numpy.sqrt(length.reshape(length.shape + (1, )))\n return vector / length": 1320, "def static_method(cls, f):\n \"\"\"Decorator which dynamically binds static methods to the model for later use.\"\"\"\n setattr(cls, f.__name__, staticmethod(f))\n return f": 1321, "def align_to_mmap(num, round_up):\n \"\"\"\n Align the given integer number to the closest page offset, which usually is 4096 bytes.\n\n :param round_up: if True, the next higher multiple of page size is used, otherwise\n the lower page_size will be used (i.e. if True, 1 becomes 4096, otherwise it becomes 0)\n :return: num rounded to closest page\"\"\"\n res = (num // ALLOCATIONGRANULARITY) * ALLOCATIONGRANULARITY\n if round_up and (res != num):\n res += ALLOCATIONGRANULARITY\n # END handle size\n return res": 1322, "def set(self, f):\n \"\"\"Call a function after a delay, unless another function is set\n in the meantime.\"\"\"\n self.stop()\n self._create_timer(f)\n self.start()": 1323, "def close(self):\n\t\t\"\"\"\n\t\tSend a terminate request and then disconnect from the serial device.\n\t\t\"\"\"\n\t\tif self._initialized:\n\t\t\tself.stop()\n\t\tself.logged_in = False\n\t\treturn self.serial_h.close()": 1324, "def test():\n \"\"\"Interactive test run.\"\"\"\n try:\n while 1:\n x, digs = input('Enter (x, digs): ')\n print x, fix(x, digs), sci(x, digs)\n except (EOFError, KeyboardInterrupt):\n pass": 1325, "def get_flat_size(self):\n \"\"\"Returns the total length of all of the flattened variables.\n\n Returns:\n The length of all flattened variables concatenated.\n \"\"\"\n return sum(\n np.prod(v.get_shape().as_list()) for v in self.variables.values())": 1326, "def read_credentials(fname):\n \"\"\"\n read a simple text file from a private location to get\n username and password\n \"\"\"\n with open(fname, 'r') as f:\n username = f.readline().strip('\\n')\n password = f.readline().strip('\\n')\n return username, password": 1327, "def b2u(string):\n \"\"\" bytes to unicode \"\"\"\n if (isinstance(string, bytes) or\n (PY2 and isinstance(string, str))):\n return string.decode('utf-8')\n return string": 1328, "def validate_int(value):\n \"\"\" Integer validator \"\"\"\n\n if value and not isinstance(value, int):\n try:\n int(str(value))\n except (TypeError, ValueError):\n raise ValidationError('not a valid number')\n return value": 1329, "def list2dict(list_of_options):\n \"\"\"Transforms a list of 2 element tuples to a dictionary\"\"\"\n d = {}\n for key, value in list_of_options:\n d[key] = value\n return d": 1330, "def _values(self):\n \"\"\"Getter for series values (flattened)\"\"\"\n return [\n val for serie in self.series for val in serie.values\n if val is not None\n ]": 1331, "def check_X_y(X, y):\n \"\"\"\n tool to ensure input and output data have the same number of samples\n\n Parameters\n ----------\n X : array-like\n y : array-like\n\n Returns\n -------\n None\n \"\"\"\n if len(X) != len(y):\n raise ValueError('Inconsistent input and output data shapes. '\\\n 'found X: {} and y: {}'.format(X.shape, y.shape))": 1332, "def AsPrimitiveProto(self):\n \"\"\"Return an old style protocol buffer object.\"\"\"\n if self.protobuf:\n result = self.protobuf()\n result.ParseFromString(self.SerializeToString())\n return result": 1333, "def sav_to_pandas_rpy2(input_file):\n \"\"\"\n SPSS .sav files to Pandas DataFrame through Rpy2\n\n :param input_file: string\n\n :return:\n \"\"\"\n import pandas.rpy.common as com\n\n w = com.robj.r('foreign::read.spss(\"%s\", to.data.frame=TRUE)' % input_file)\n return com.convert_robj(w)": 1334, "def is_timestamp(instance):\n \"\"\"Validates data is a timestamp\"\"\"\n if not isinstance(instance, (int, str)):\n return True\n return datetime.fromtimestamp(int(instance))": 1335, "def ln_norm(x, mu, sigma=1.0):\n \"\"\" Natural log of scipy norm function truncated at zero \"\"\"\n return np.log(stats.norm(loc=mu, scale=sigma).pdf(x))": 1336, "def iter_except_top_row_tcs(self):\n \"\"\"Generate each `a:tc` element in non-first rows of range.\"\"\"\n for tr in self._tbl.tr_lst[self._top + 1:self._bottom]:\n for tc in tr.tc_lst[self._left:self._right]:\n yield tc": 1337, "def web(host, port):\n \"\"\"Start web application\"\"\"\n from .webserver.web import get_app\n get_app().run(host=host, port=port)": 1338, "def get_type(self):\n \"\"\"Get the type of the item.\n\n :return: the type of the item.\n :returntype: `unicode`\"\"\"\n item_type = self.xmlnode.prop(\"type\")\n if not item_type:\n item_type = \"?\"\n return item_type.decode(\"utf-8\")": 1339, "def _is_osx_107():\n \"\"\"\n :return:\n A bool if the current machine is running OS X 10.7\n \"\"\"\n\n if sys.platform != 'darwin':\n return False\n version = platform.mac_ver()[0]\n return tuple(map(int, version.split('.')))[0:2] == (10, 7)": 1340, "def close_other_windows(self):\n \"\"\"\n Closes all not current windows. Useful for tests - after each test you\n can automatically close all windows.\n \"\"\"\n main_window_handle = self.current_window_handle\n for window_handle in self.window_handles:\n if window_handle == main_window_handle:\n continue\n self.switch_to_window(window_handle)\n self.close()\n self.switch_to_window(main_window_handle)": 1341, "def swap_memory():\n \"\"\"Swap system memory as a (total, used, free, sin, sout) tuple.\"\"\"\n mem = _psutil_mswindows.get_virtual_mem()\n total = mem[2]\n free = mem[3]\n used = total - free\n percent = usage_percent(used, total, _round=1)\n return nt_swapmeminfo(total, used, free, percent, 0, 0)": 1342, "def from_pb(cls, pb):\n \"\"\"Instantiate the object from a protocol buffer.\n\n Args:\n pb (protobuf)\n\n Save a reference to the protocol buffer on the object.\n \"\"\"\n obj = cls._from_pb(pb)\n obj._pb = pb\n return obj": 1343, "def _write_json(file, contents):\n \"\"\"Write a dict to a JSON file.\"\"\"\n with open(file, 'w') as f:\n return json.dump(contents, f, indent=2, sort_keys=True)": 1344, "def dedupe(items):\n \"\"\"Remove duplicates from a sequence (of hashable items) while maintaining\n order. NOTE: This only works if items in the list are hashable types.\n\n Taken from the Python Cookbook, 3rd ed. Such a great book!\n\n \"\"\"\n seen = set()\n for item in items:\n if item not in seen:\n yield item\n seen.add(item)": 1345, "def set_property(self, key, value):\n \"\"\"\n Update only one property in the dict\n \"\"\"\n self.properties[key] = value\n self.sync_properties()": 1346, "def _write_color_colorama (fp, text, color):\n \"\"\"Colorize text with given color.\"\"\"\n foreground, background, style = get_win_color(color)\n colorama.set_console(foreground=foreground, background=background,\n style=style)\n fp.write(text)\n colorama.reset_console()": 1347, "def zeros(self, name, **kwargs):\n \"\"\"Create an array. Keyword arguments as per\n :func:`zarr.creation.zeros`.\"\"\"\n return self._write_op(self._zeros_nosync, name, **kwargs)": 1348, "def save_dict_to_file(filename, dictionary):\n \"\"\"Saves dictionary as CSV file.\"\"\"\n with open(filename, 'w') as f:\n writer = csv.writer(f)\n for k, v in iteritems(dictionary):\n writer.writerow([str(k), str(v)])": 1349, "def average_gradient(data, *kwargs):\n \"\"\" Compute average gradient norm of an image\n \"\"\"\n return np.average(np.array(np.gradient(data))**2)": 1350, "def safe_dump(data, stream=None, **kwds):\n \"\"\"implementation of safe dumper using Ordered Dict Yaml Dumper\"\"\"\n return yaml.dump(data, stream=stream, Dumper=ODYD, **kwds)": 1351, "def add_plot(x, y, xl, yl, fig, ax, LATEX=False, linestyle=None, **kwargs):\n \"\"\"Add plots to an existing plot\"\"\"\n if LATEX:\n xl_data = xl[1] # NOQA\n yl_data = yl[1]\n else:\n xl_data = xl[0] # NOQA\n yl_data = yl[0]\n\n for idx in range(len(y)):\n ax.plot(x, y[idx], label=yl_data[idx], linestyle=linestyle)\n\n ax.legend(loc='upper right')\n ax.set_ylim(auto=True)": 1352, "def load_yaml_file(file_path: str):\n \"\"\"Load a YAML file from path\"\"\"\n with codecs.open(file_path, 'r') as f:\n return yaml.safe_load(f)": 1353, "def safe_unicode(string):\n \"\"\"If Python 2, replace non-ascii characters and return encoded string.\"\"\"\n if not PY3:\n uni = string.replace(u'\\u2019', \"'\")\n return uni.encode('utf-8')\n \n return string": 1354, "def yaml_to_param(obj, name):\n\t\"\"\"\n\tReturn the top-level element of a document sub-tree containing the\n\tYAML serialization of a Python object.\n\t\"\"\"\n\treturn from_pyvalue(u\"yaml:%s\" % name, unicode(yaml.dump(obj)))": 1355, "def url_fix_common_typos (url):\n \"\"\"Fix common typos in given URL like forgotten colon.\"\"\"\n if url.startswith(\"http//\"):\n url = \"http://\" + url[6:]\n elif url.startswith(\"https//\"):\n url = \"https://\" + url[7:]\n return url": 1356, "def yaml(self):\n \"\"\"\n returns the yaml output of the dict.\n \"\"\"\n return ordered_dump(OrderedDict(self),\n Dumper=yaml.SafeDumper,\n default_flow_style=False)": 1357, "def matshow(*args, **kwargs):\n \"\"\"\n imshow without interpolation like as matshow\n :param args:\n :param kwargs:\n :return:\n \"\"\"\n kwargs['interpolation'] = kwargs.pop('interpolation', 'none')\n return plt.imshow(*args, **kwargs)": 1358, "def extract_all(zipfile, dest_folder):\n \"\"\"\n reads the zip file, determines compression\n and unzips recursively until source files \n are extracted \n \"\"\"\n z = ZipFile(zipfile)\n print(z)\n z.extract(dest_folder)": 1359, "def handle_m2m(self, sender, instance, **kwargs):\n \"\"\" Handle many to many relationships \"\"\"\n self.handle_save(instance.__class__, instance)": 1360, "def extract(self, destination):\n \"\"\"Extract the archive.\"\"\"\n with zipfile.ZipFile(self.archive, 'r') as zip_ref:\n zip_ref.extractall(destination)": 1361, "def compress(data, **kwargs):\n \"\"\"zlib.compress(data, **kwargs)\n \n \"\"\" + zopfli.__COMPRESSOR_DOCSTRING__ + \"\"\"\n Returns:\n String containing a zlib container\n \"\"\"\n kwargs['gzip_mode'] = 0\n return zopfli.zopfli.compress(data, **kwargs)": 1362, "def init_mq(self):\n \"\"\"Init connection and consumer with openstack mq.\"\"\"\n mq = self.init_connection()\n self.init_consumer(mq)\n return mq.connection": 1363, "def is_real_floating_dtype(dtype):\n \"\"\"Return ``True`` if ``dtype`` is a real floating point type.\"\"\"\n dtype = np.dtype(dtype)\n return np.issubsctype(getattr(dtype, 'base', None), np.floating)": 1364, "def max(self):\n \"\"\"\n Returns the maximum value of the domain.\n\n :rtype: `float` or `np.inf`\n \"\"\"\n return int(self._max) if not np.isinf(self._max) else self._max": 1365, "def log_loss(preds, labels):\n \"\"\"Logarithmic loss with non-necessarily-binary labels.\"\"\"\n log_likelihood = np.sum(labels * np.log(preds)) / len(preds)\n return -log_likelihood": 1366, "def list_of_lists_to_dict(l):\n \"\"\" Convert list of key,value lists to dict\n\n [['id', 1], ['id', 2], ['id', 3], ['foo': 4]]\n {'id': [1, 2, 3], 'foo': [4]}\n \"\"\"\n d = {}\n for key, val in l:\n d.setdefault(key, []).append(val)\n return d": 1367, "def longest_run_1d(arr):\n \"\"\"Return the length of the longest consecutive run of identical values.\n\n Parameters\n ----------\n arr : bool array\n Input array\n\n Returns\n -------\n int\n Length of longest run.\n \"\"\"\n v, rl = rle_1d(arr)[:2]\n return np.where(v, rl, 0).max()": 1368, "def simulate(self):\n \"\"\"Generates a random integer in the available range.\"\"\"\n min_ = (-sys.maxsize - 1) if self._min is None else self._min\n max_ = sys.maxsize if self._max is None else self._max\n return random.randint(min_, max_)": 1369, "def in_directory(path):\n \"\"\"Context manager (with statement) that changes the current directory\n during the context.\n \"\"\"\n curdir = os.path.abspath(os.curdir)\n os.chdir(path)\n yield\n os.chdir(curdir)": 1370, "def median(data):\n \"\"\"Calculate the median of a list.\"\"\"\n data.sort()\n num_values = len(data)\n half = num_values // 2\n if num_values % 2:\n return data[half]\n return 0.5 * (data[half-1] + data[half])": 1371, "def append_pdf(input_pdf: bytes, output_writer: PdfFileWriter):\n \"\"\"\n Appends a PDF to a pyPDF writer. Legacy interface.\n \"\"\"\n append_memory_pdf_to_writer(input_pdf=input_pdf,\n writer=output_writer)": 1372, "def date_to_timestamp(date):\n \"\"\"\n date to unix timestamp in milliseconds\n \"\"\"\n date_tuple = date.timetuple()\n timestamp = calendar.timegm(date_tuple) * 1000\n return timestamp": 1373, "def FindMethodByName(self, name):\n \"\"\"Searches for the specified method, and returns its descriptor.\"\"\"\n for method in self.methods:\n if name == method.name:\n return method\n return None": 1374, "def mock_decorator(*args, **kwargs):\n \"\"\"Mocked decorator, needed in the case we need to mock a decorator\"\"\"\n def _called_decorator(dec_func):\n @wraps(dec_func)\n def _decorator(*args, **kwargs):\n return dec_func()\n return _decorator\n return _called_decorator": 1375, "def add_matplotlib_cmap(cm, name=None):\n \"\"\"Add a matplotlib colormap.\"\"\"\n global cmaps\n cmap = matplotlib_to_ginga_cmap(cm, name=name)\n cmaps[cmap.name] = cmap": 1376, "def to_bytes(value):\n \"\"\" str to bytes (py3k) \"\"\"\n vtype = type(value)\n\n if vtype == bytes or vtype == type(None):\n return value\n\n try:\n return vtype.encode(value)\n except UnicodeEncodeError:\n pass\n return value": 1377, "def find_one(self, query):\n \"\"\"Find one wrapper with conversion to dictionary\n\n :param dict query: A Mongo query\n \"\"\"\n mongo_response = yield self.collection.find_one(query)\n raise Return(self._obj_cursor_to_dictionary(mongo_response))": 1378, "def loadb(b):\n \"\"\"Deserialize ``b`` (instance of ``bytes``) to a Python object.\"\"\"\n assert isinstance(b, (bytes, bytearray))\n return std_json.loads(b.decode('utf-8'))": 1379, "def test_replace_colon():\n \"\"\"py.test for replace_colon\"\"\"\n data = ((\"zone:aap\", '@', \"zone@aap\"),# s, r, replaced\n ) \n for s, r, replaced in data:\n result = replace_colon(s, r)\n assert result == replaced": 1380, "def init_rotating_logger(level, logfile, max_files, max_bytes):\n \"\"\"Initializes a rotating logger\n\n It also makes sure that any StreamHandler is removed, so as to avoid stdout/stderr\n constipation issues\n \"\"\"\n logging.basicConfig()\n\n root_logger = logging.getLogger()\n log_format = \"[%(asctime)s] [%(levelname)s] %(filename)s: %(message)s\"\n\n root_logger.setLevel(level)\n handler = RotatingFileHandler(logfile, maxBytes=max_bytes, backupCount=max_files)\n handler.setFormatter(logging.Formatter(fmt=log_format, datefmt=date_format))\n root_logger.addHandler(handler)\n\n for handler in root_logger.handlers:\n root_logger.debug(\"Associated handlers - \" + str(handler))\n if isinstance(handler, logging.StreamHandler):\n root_logger.debug(\"Removing StreamHandler: \" + str(handler))\n root_logger.handlers.remove(handler)": 1381, "def main(ctx, connection):\n \"\"\"Command line interface for PyBEL.\"\"\"\n ctx.obj = Manager(connection=connection)\n ctx.obj.bind()": 1382, "def maybeparens(lparen, item, rparen):\n \"\"\"Wrap an item in optional parentheses, only applying them if necessary.\"\"\"\n return item | lparen.suppress() + item + rparen.suppress()": 1383, "def now(timezone=None):\n \"\"\"\n Return a naive datetime object for the given ``timezone``. A ``timezone``\n is any pytz- like or datetime.tzinfo-like timezone object. If no timezone\n is given, then UTC is assumed.\n\n This method is best used with pytz installed::\n\n pip install pytz\n \"\"\"\n d = datetime.datetime.utcnow()\n if not timezone:\n return d\n\n return to_timezone(d, timezone).replace(tzinfo=None)": 1384, "def matrixTimesVector(MM, aa):\n \"\"\"\n\n :param MM: A matrix of size 3x3\n :param aa: A vector of size 3\n :return: A vector of size 3 which is the product of the matrix by the vector\n \"\"\"\n bb = np.zeros(3, np.float)\n for ii in range(3):\n bb[ii] = np.sum(MM[ii, :] * aa)\n return bb": 1385, "def redirect_stdout(new_stdout):\n \"\"\"Redirect the stdout\n\n Args:\n new_stdout (io.StringIO): New stdout to use instead\n \"\"\"\n old_stdout, sys.stdout = sys.stdout, new_stdout\n try:\n yield None\n finally:\n sys.stdout = old_stdout": 1386, "def _check_and_convert_bools(self):\n \"\"\"Replace boolean variables by the characters 'F'/'T'\n \"\"\"\n replacements = {\n True: 'T',\n False: 'F',\n }\n\n for key in self.bools:\n if isinstance(self[key], bool):\n self[key] = replacements[self[key]]": 1387, "def __exit__(self, *exc):\n \"\"\"Exit the runtime context. This will end the transaction.\"\"\"\n if exc[0] is None and exc[1] is None and exc[2] is None:\n self.commit()\n else:\n self.rollback()": 1388, "def stringify_dict_contents(dct):\n \"\"\"Turn dict keys and values into native strings.\"\"\"\n return {\n str_if_nested_or_str(k): str_if_nested_or_str(v)\n for k, v in dct.items()\n }": 1389, "def up(self):\n \n \"\"\"Moves the layer up in the stacking order.\n \n \"\"\"\n \n i = self.index()\n if i != None:\n del self.canvas.layers[i]\n i = min(len(self.canvas.layers), i+1)\n self.canvas.layers.insert(i, self)": 1390, "def pretty_dict_string(d, indent=0):\n \"\"\"Pretty output of nested dictionaries.\n \"\"\"\n s = ''\n for key, value in sorted(d.items()):\n s += ' ' * indent + str(key)\n if isinstance(value, dict):\n s += '\\n' + pretty_dict_string(value, indent+1)\n else:\n s += '=' + str(value) + '\\n'\n return s": 1391, "def set_locale(request):\n \"\"\"Return locale from GET lang param or automatically.\"\"\"\n return request.query.get('lang', app.ps.babel.select_locale_by_request(request))": 1392, "def is_power_of_2(num):\n \"\"\"Return whether `num` is a power of two\"\"\"\n log = math.log2(num)\n return int(log) == float(log)": 1393, "def _qrcode_to_file(qrcode, out_filepath):\n \"\"\" Save a `qrcode` object into `out_filepath`.\n Parameters\n ----------\n qrcode: qrcode object\n\n out_filepath: str\n Path to the output file.\n \"\"\"\n try:\n qrcode.save(out_filepath)\n except Exception as exc:\n raise IOError('Error trying to save QR code file {}.'.format(out_filepath)) from exc\n else:\n return qrcode": 1394, "def copy(obj):\n def copy(self):\n \"\"\"\n Copy self to a new object.\n \"\"\"\n from copy import deepcopy\n\n return deepcopy(self)\n obj.copy = copy\n return obj": 1395, "def shot_noise(x, severity=1):\n \"\"\"Shot noise corruption to images.\n\n Args:\n x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].\n severity: integer, severity of corruption.\n\n Returns:\n numpy array, image with uint8 pixels in [0,255]. Added shot noise.\n \"\"\"\n c = [60, 25, 12, 5, 3][severity - 1]\n x = np.array(x) / 255.\n x_clip = np.clip(np.random.poisson(x * c) / float(c), 0, 1) * 255\n return around_and_astype(x_clip)": 1396, "def _normalize(image):\n \"\"\"Normalize the image to zero mean and unit variance.\"\"\"\n offset = tf.constant(MEAN_RGB, shape=[1, 1, 3])\n image -= offset\n\n scale = tf.constant(STDDEV_RGB, shape=[1, 1, 3])\n image /= scale\n return image": 1397, "def sometimesish(fn):\n \"\"\"\n Has a 50/50 chance of calling a function\n \"\"\"\n def wrapped(*args, **kwargs):\n if random.randint(1, 2) == 1:\n return fn(*args, **kwargs)\n\n return wrapped": 1398, "def log_normalize(data):\n \"\"\"Perform log transform log(x + 1).\n \n Parameters\n ----------\n data : array_like\n \n \"\"\"\n if sp.issparse(data):\n data = data.copy()\n data.data = np.log2(data.data + 1)\n return data\n\n return np.log2(data.astype(np.float64) + 1)": 1399, "def runiform(lower, upper, size=None):\n \"\"\"\n Random uniform variates.\n \"\"\"\n return np.random.uniform(lower, upper, size)": 1400, "def decode_arr(data):\n \"\"\"Extract a numpy array from a base64 buffer\"\"\"\n data = data.encode('utf-8')\n return frombuffer(base64.b64decode(data), float64)": 1401, "def input(self,pin):\n \"\"\"Read the specified pin and return HIGH/true if the pin is pulled high,\n or LOW/false if pulled low.\n \"\"\"\n return self.mraa_gpio.Gpio.read(self.mraa_gpio.Gpio(pin))": 1402, "def _iter_keys(key):\n \"\"\"! Iterate over subkeys of a key\n \"\"\"\n for i in range(winreg.QueryInfoKey(key)[0]):\n yield winreg.OpenKey(key, winreg.EnumKey(key, i))": 1403, "def shape(self):\n \"\"\"Compute the shape of the dataset as (rows, cols).\"\"\"\n if not self.data:\n return (0, 0)\n return (len(self.data), len(self.dimensions))": 1404, "def one_hot2string(arr, vocab):\n \"\"\"Convert a one-hot encoded array back to string\n \"\"\"\n tokens = one_hot2token(arr)\n indexToLetter = _get_index_dict(vocab)\n\n return [''.join([indexToLetter[x] for x in row]) for row in tokens]": 1405, "def lambda_from_file(python_file):\n \"\"\"\n Reads a python file and returns a awslambda.Code object\n :param python_file:\n :return:\n \"\"\"\n lambda_function = []\n with open(python_file, 'r') as f:\n lambda_function.extend(f.read().splitlines())\n\n return awslambda.Code(ZipFile=(Join('\\n', lambda_function)))": 1406, "def reverse_code_map(self):\n \"\"\"Return a map from a code ( usually a string ) to the shorter numeric value\"\"\"\n\n return {c.value: (c.ikey if c.ikey else c.key) for c in self.codes}": 1407, "def html_to_text(content):\n \"\"\" Converts html content to plain text \"\"\"\n text = None\n h2t = html2text.HTML2Text()\n h2t.ignore_links = False\n text = h2t.handle(content)\n return text": 1408, "def _loadfilepath(self, filepath, **kwargs):\n \"\"\"This loads a geojson file into a geojson python\n dictionary using the json module.\n \n Note: to load with a different text encoding use the encoding argument.\n \"\"\"\n with open(filepath, \"r\") as f:\n data = json.load(f, **kwargs)\n return data": 1409, "def get(url):\n \"\"\"Recieving the JSON file from uulm\"\"\"\n response = urllib.request.urlopen(url)\n data = response.read()\n data = data.decode(\"utf-8\")\n data = json.loads(data)\n return data": 1410, "def cli(yamlfile, root, format):\n \"\"\" Generate CSV/TSV file from biolink model \"\"\"\n print(CsvGenerator(yamlfile, format).serialize(classes=root))": 1411, "def dimensions(path):\n \"\"\"Get width and height of a PDF\"\"\"\n pdf = PdfFileReader(path)\n size = pdf.getPage(0).mediaBox\n return {'w': float(size[2]), 'h': float(size[3])}": 1412, "def list_apis(awsclient):\n \"\"\"List APIs in account.\"\"\"\n client_api = awsclient.get_client('apigateway')\n\n apis = client_api.get_rest_apis()['items']\n\n for api in apis:\n print(json2table(api))": 1413, "def execfile(fname, variables):\n \"\"\" This is builtin in python2, but we have to roll our own on py3. \"\"\"\n with open(fname) as f:\n code = compile(f.read(), fname, 'exec')\n exec(code, variables)": 1414, "def get_code(module):\n \"\"\"\n Compile and return a Module's code object.\n \"\"\"\n fp = open(module.path)\n try:\n return compile(fp.read(), str(module.name), 'exec')\n finally:\n fp.close()": 1415, "def aux_insertTree(childTree, parentTree):\n\t\"\"\"This a private (You shouldn't have to call it) recursive function that inserts a child tree into a parent tree.\"\"\"\n\tif childTree.x1 != None and childTree.x2 != None :\n\t\tparentTree.insert(childTree.x1, childTree.x2, childTree.name, childTree.referedObject)\n\n\tfor c in childTree.children:\n\t\taux_insertTree(c, parentTree)": 1416, "def do_serial(self, p):\n\t\t\"\"\"Set the serial port, e.g.: /dev/tty.usbserial-A4001ib8\"\"\"\n\t\ttry:\n\t\t\tself.serial.port = p\n\t\t\tself.serial.open()\n\t\t\tprint 'Opening serial port: %s' % p\n\t\texcept Exception, e:\n\t\t\tprint 'Unable to open serial port: %s' % p": 1417, "def get_feature_order(dataset, features):\n \"\"\" Returns a list with the order that features requested appear in\n dataset \"\"\"\n all_features = dataset.get_feature_names()\n\n i = [all_features.index(f) for f in features]\n\n return i": 1418, "def circ_permutation(items):\n \"\"\"Calculate the circular permutation for a given list of items.\"\"\"\n permutations = []\n for i in range(len(items)):\n permutations.append(items[i:] + items[:i])\n return permutations": 1419, "def _format_list(result):\n \"\"\"Format list responses into a table.\"\"\"\n\n if not result:\n return result\n\n if isinstance(result[0], dict):\n return _format_list_objects(result)\n\n table = Table(['value'])\n for item in result:\n table.add_row([iter_to_table(item)])\n return table": 1420, "def redirect(view=None, url=None, **kwargs):\n \"\"\"Redirects to the specified view or url\n \"\"\"\n if view:\n if url:\n kwargs[\"url\"] = url\n url = flask.url_for(view, **kwargs)\n current_context.exit(flask.redirect(url))": 1421, "def zero_pad(m, n=1):\n \"\"\"Pad a matrix with zeros, on all sides.\"\"\"\n return np.pad(m, (n, n), mode='constant', constant_values=[0])": 1422, "def get(self, key): \n \"\"\" get a set of keys from redis \"\"\"\n res = self.connection.get(key)\n print(res)\n return res": 1423, "def format_screen(strng):\n \"\"\"Format a string for screen printing.\n\n This removes some latex-type format codes.\"\"\"\n # Paragraph continue\n par_re = re.compile(r'\\\\$',re.MULTILINE)\n strng = par_re.sub('',strng)\n return strng": 1424, "def old_pad(s):\n \"\"\"\n Pads an input string to a given block size.\n :param s: string\n :returns: The padded string.\n \"\"\"\n if len(s) % OLD_BLOCK_SIZE == 0:\n return s\n\n return Padding.appendPadding(s, blocksize=OLD_BLOCK_SIZE)": 1425, "def path(self):\n \"\"\"Return the project path (aka project root)\n\n If ``package.__file__`` is ``/foo/foo/__init__.py``, then project.path\n should be ``/foo``.\n \"\"\"\n return pathlib.Path(self.package.__file__).resolve().parent.parent": 1426, "def get_max(qs, field):\n \"\"\"\n get max for queryset.\n\n qs: queryset\n field: The field name to max.\n \"\"\"\n max_field = '%s__max' % field\n num = qs.aggregate(Max(field))[max_field]\n return num if num else 0": 1427, "def remove(self, path):\n \"\"\"Remove remote file\n Return:\n bool: true or false\"\"\"\n p = self.cmd('shell', 'rm', path)\n stdout, stderr = p.communicate()\n if stdout or stderr:\n return False\n else:\n return True": 1428, "def parse(self):\n \"\"\"\n Parse file specified by constructor.\n \"\"\"\n f = open(self.parse_log_path, \"r\")\n self.parse2(f)\n f.close()": 1429, "def parse_obj(o):\n \"\"\"\n Parses a given dictionary with the key being the OBD PID and the value its\n returned value by the OBD interface\n :param dict o:\n :return:\n \"\"\"\n r = {}\n for k, v in o.items():\n if is_unable_to_connect(v):\n r[k] = None\n\n try:\n r[k] = parse_value(k, v)\n except (ObdPidParserUnknownError, AttributeError, TypeError):\n r[k] = None\n return r": 1430, "def remove_list_duplicates(lista, unique=False):\n \"\"\"\n Remove duplicated elements in a list.\n Args:\n lista: List with elements to clean duplicates.\n \"\"\"\n result = []\n allready = []\n\n for elem in lista:\n if elem not in result:\n result.append(elem)\n else:\n allready.append(elem)\n\n if unique:\n for elem in allready:\n result = list(filter((elem).__ne__, result))\n\n return result": 1431, "def arg_default(*args, **kwargs):\n \"\"\"Return default argument value as given by argparse's add_argument().\n\n The argument is passed through a mocked-up argument parser. This way, we\n get default parameters even if the feature is called directly and not\n through the CLI.\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(*args, **kwargs)\n args = vars(parser.parse_args([]))\n _, default = args.popitem()\n return default": 1432, "def def_linear(fun):\n \"\"\"Flags that a function is linear wrt all args\"\"\"\n defjvp_argnum(fun, lambda argnum, g, ans, args, kwargs:\n fun(*subval(args, argnum, g), **kwargs))": 1433, "def add_to_parser(self, parser):\n \"\"\"\n Adds the argument to an argparse.ArgumentParser instance\n\n @param parser An argparse.ArgumentParser instance\n \"\"\"\n kwargs = self._get_kwargs()\n args = self._get_args()\n parser.add_argument(*args, **kwargs)": 1434, "def random_choice(sequence):\n \"\"\" Same as :meth:`random.choice`, but also supports :class:`set` type to be passed as sequence. \"\"\"\n return random.choice(tuple(sequence) if isinstance(sequence, set) else sequence)": 1435, "def unescape(str):\n \"\"\"Undoes the effects of the escape() function.\"\"\"\n out = ''\n prev_backslash = False\n for char in str:\n if not prev_backslash and char == '\\\\':\n prev_backslash = True\n continue\n out += char\n prev_backslash = False\n return out": 1436, "def strip_columns(tab):\n \"\"\"Strip whitespace from string columns.\"\"\"\n for colname in tab.colnames:\n if tab[colname].dtype.kind in ['S', 'U']:\n tab[colname] = np.core.defchararray.strip(tab[colname])": 1437, "def export_all(self):\n\t\tquery = \"\"\"\n\t\t\tSELECT quote, library, logid\n\t\t\tfrom quotes\n\t\t\tleft outer join quote_log on quotes.quoteid = quote_log.quoteid\n\t\t\t\"\"\"\n\t\tfields = 'text', 'library', 'log_id'\n\t\treturn (dict(zip(fields, res)) for res in self.db.execute(query))": 1438, "def seq_to_str(obj, sep=\",\"):\n \"\"\"\n Given a sequence convert it to a comma separated string.\n If, however, the argument is a single object, return its string\n representation.\n \"\"\"\n if isinstance(obj, string_classes):\n return obj\n elif isinstance(obj, (list, tuple)):\n return sep.join([str(x) for x in obj])\n else:\n return str(obj)": 1439, "def _precision_recall(y_true, y_score, ax=None):\n \"\"\"\n Plot precision-recall curve.\n\n Parameters\n ----------\n y_true : array-like, shape = [n_samples]\n Correct target values (ground truth).\n y_score : array-like, shape = [n_samples]\n Target scores (estimator predictions).\n ax : matplotlib Axes\n Axes object to draw the plot onto, otherwise uses current Axes\n\n Returns\n -------\n ax: matplotlib Axes\n Axes containing the plot\n\n \"\"\"\n precision, recall, _ = precision_recall_curve(y_true, y_score)\n average_precision = average_precision_score(y_true, y_score)\n\n if ax is None:\n ax = plt.gca()\n\n ax.plot(recall, precision, label=('Precision-Recall curve: AUC={0:0.2f}'\n .format(average_precision)))\n _set_ax_settings(ax)\n return ax": 1440, "def remove_dups(seq):\n \"\"\"remove duplicates from a sequence, preserving order\"\"\"\n seen = set()\n seen_add = seen.add\n return [x for x in seq if not (x in seen or seen_add(x))]": 1441, "def format_prettytable(table):\n \"\"\"Converts SoftLayer.CLI.formatting.Table instance to a prettytable.\"\"\"\n for i, row in enumerate(table.rows):\n for j, item in enumerate(row):\n table.rows[i][j] = format_output(item)\n\n ptable = table.prettytable()\n ptable.hrules = prettytable.FRAME\n ptable.horizontal_char = '.'\n ptable.vertical_char = ':'\n ptable.junction_char = ':'\n return ptable": 1442, "def _RemoveIllegalXMLCharacters(self, xml_string):\n \"\"\"Removes illegal characters for XML.\n\n If the input is not a string it will be returned unchanged.\n\n Args:\n xml_string (str): XML with possible illegal characters.\n\n Returns:\n str: XML where all illegal characters have been removed.\n \"\"\"\n if not isinstance(xml_string, py2to3.STRING_TYPES):\n return xml_string\n\n return self._ILLEGAL_XML_RE.sub('\\ufffd', xml_string)": 1443, "def pylog(self, *args, **kwargs):\n \"\"\"Display all available logging information.\"\"\"\n printerr(self.name, args, kwargs, traceback.format_exc())": 1444, "def strip_accents(s):\n \"\"\"\n Strip accents to prepare for slugification.\n \"\"\"\n nfkd = unicodedata.normalize('NFKD', unicode(s))\n return u''.join(ch for ch in nfkd if not unicodedata.combining(ch))": 1445, "def indented_show(text, howmany=1):\n \"\"\"Print a formatted indented text.\n \"\"\"\n print(StrTemplate.pad_indent(text=text, howmany=howmany))": 1446, "def key_to_metric(self, key):\n \"\"\"Replace all non-letter characters with underscores\"\"\"\n return ''.join(l if l in string.letters else '_' for l in key)": 1447, "def get_ram(self, format_ = \"nl\"):\n\t\t\"\"\"\n\t\t\treturn a string representations of the ram\n\t\t\"\"\"\n\t\tram = [self.ram.read(i) for i in range(self.ram.size)]\n\t\treturn self._format_mem(ram, format_)": 1448, "def strip_querystring(url):\n \"\"\"Remove the querystring from the end of a URL.\"\"\"\n p = six.moves.urllib.parse.urlparse(url)\n return p.scheme + \"://\" + p.netloc + p.path": 1449, "def dedupe_list(seq):\n \"\"\"\n Utility function to remove duplicates from a list\n :param seq: The sequence (list) to deduplicate\n :return: A list with original duplicates removed\n \"\"\"\n seen = set()\n return [x for x in seq if not (x in seen or seen.add(x))]": 1450, "def to_str(s):\n \"\"\"\n Convert bytes and non-string into Python 3 str\n \"\"\"\n if isinstance(s, bytes):\n s = s.decode('utf-8')\n elif not isinstance(s, str):\n s = str(s)\n return s": 1451, "def printOut(value, end='\\n'):\n \"\"\"\n This function prints the given String immediately and flushes the output.\n \"\"\"\n sys.stdout.write(value)\n sys.stdout.write(end)\n sys.stdout.flush()": 1452, "def normalize_value(text):\n \"\"\"\n This removes newlines and multiple spaces from a string.\n \"\"\"\n result = text.replace('\\n', ' ')\n result = re.subn('[ ]{2,}', ' ', result)[0]\n return result": 1453, "def IndexOfNth(s, value, n):\n \"\"\"Gets the index of Nth occurance of a given character in a string\n\n :param str s:\n Input string\n :param char value:\n Input char to be searched.\n :param int n:\n Nth occurrence of char to be searched.\n\n :return:\n Index of the Nth occurrence in the string.\n :rtype: int\n\n \"\"\"\n remaining = n\n for i in xrange(0, len(s)):\n if s[i] == value:\n remaining -= 1\n if remaining == 0:\n return i\n return -1": 1454, "def remove_file_from_s3(awsclient, bucket, key):\n \"\"\"Remove a file from an AWS S3 bucket.\n\n :param awsclient:\n :param bucket:\n :param key:\n :return:\n \"\"\"\n client_s3 = awsclient.get_client('s3')\n response = client_s3.delete_object(Bucket=bucket, Key=key)": 1455, "def get_trace_id_from_flask():\n \"\"\"Get trace_id from flask request headers.\n\n :rtype: str\n :returns: TraceID in HTTP request headers.\n \"\"\"\n if flask is None or not flask.request:\n return None\n\n header = flask.request.headers.get(_FLASK_TRACE_HEADER)\n\n if header is None:\n return None\n\n trace_id = header.split(\"/\", 1)[0]\n\n return trace_id": 1456, "def current_memory_usage():\n \"\"\"\n Returns this programs current memory usage in bytes\n \"\"\"\n import psutil\n proc = psutil.Process(os.getpid())\n #meminfo = proc.get_memory_info()\n meminfo = proc.memory_info()\n rss = meminfo[0] # Resident Set Size / Mem Usage\n vms = meminfo[1] # Virtual Memory Size / VM Size # NOQA\n return rss": 1457, "def _idx_col2rowm(d):\n \"\"\"Generate indexes to change from col-major to row-major ordering\"\"\"\n if 0 == len(d):\n return 1\n if 1 == len(d):\n return np.arange(d[0])\n # order='F' indicates column-major ordering\n idx = np.array(np.arange(np.prod(d))).reshape(d, order='F').T\n return idx.flatten(order='F')": 1458, "def get_memory_usage():\n \"\"\"Gets RAM memory usage\n\n :return: MB of memory used by this process\n \"\"\"\n process = psutil.Process(os.getpid())\n mem = process.memory_info().rss\n return mem / (1024 * 1024)": 1459, "def _replace_token_range(tokens, start, end, replacement):\n \"\"\"For a range indicated from start to end, replace with replacement.\"\"\"\n tokens = tokens[:start] + replacement + tokens[end:]\n return tokens": 1460, "def parse(self):\n \"\"\"Parses data in table\n\n :return: List of list of values in table\n \"\"\"\n data = [] # add name of section\n\n for row in self.soup.find_all(\"tr\"): # cycle through all rows\n parsed = self._parse_row(row)\n if parsed:\n data.append(parsed)\n\n return data": 1461, "def stringify_col(df, col_name):\n \"\"\"\n Take a dataframe and string-i-fy a column of values.\n Turn nan/None into \"\" and all other values into strings.\n\n Parameters\n ----------\n df : dataframe\n col_name : string\n \"\"\"\n df = df.copy()\n df[col_name] = df[col_name].fillna(\"\")\n df[col_name] = df[col_name].astype(str)\n return df": 1462, "def add_0x(string):\n \"\"\"Add 0x to string at start.\n \"\"\"\n if isinstance(string, bytes):\n string = string.decode('utf-8')\n return '0x' + str(string)": 1463, "def parse_form(self, req, name, field):\n \"\"\"Pull a form value from the request.\"\"\"\n return get_value(req.body_arguments, name, field)": 1464, "def warn_deprecated(message, stacklevel=2): # pragma: no cover\n \"\"\"Warn deprecated.\"\"\"\n\n warnings.warn(\n message,\n category=DeprecationWarning,\n stacklevel=stacklevel\n )": 1465, "def resize_by_area(img, size):\n \"\"\"image resize function used by quite a few image problems.\"\"\"\n return tf.to_int64(\n tf.image.resize_images(img, [size, size], tf.image.ResizeMethod.AREA))": 1466, "def raw_print(*args, **kw):\n \"\"\"Raw print to sys.__stdout__, otherwise identical interface to print().\"\"\"\n\n print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\\n'),\n file=sys.__stdout__)\n sys.__stdout__.flush()": 1467, "def popup(self, title, callfn, initialdir=None):\n \"\"\"Let user select a directory.\"\"\"\n super(DirectorySelection, self).popup(title, callfn, initialdir)": 1468, "def command_py2to3(args):\n \"\"\"\n Apply '2to3' tool (Python2 to Python3 conversion tool) to Python sources.\n \"\"\"\n from lib2to3.main import main\n sys.exit(main(\"lib2to3.fixes\", args=args.sources))": 1469, "def __is_bound_method(method):\n \"\"\"Return ``True`` if the `method` is a bound method (attached to an class\n instance.\n\n Args:\n method: A method or function type object.\n \"\"\"\n if not(hasattr(method, \"__func__\") and hasattr(method, \"__self__\")):\n return False\n\n # Bound methods have a __self__ attribute pointing to the owner instance\n return six.get_method_self(method) is not None": 1470, "def clean_url(url):\n \"\"\"URL Validation function\"\"\"\n if not url.startswith(('http://', 'https://')):\n url = f'http://{url}'\n\n if not URL_RE.match(url):\n raise BadURLException(f'{url} is not valid')\n\n return url": 1471, "def stft_magnitude(signal, fft_length,\n hop_length=None,\n window_length=None):\n \"\"\"Calculate the short-time Fourier transform magnitude.\n\n Args:\n signal: 1D np.array of the input time-domain signal.\n fft_length: Size of the FFT to apply.\n hop_length: Advance (in samples) between each frame passed to FFT.\n window_length: Length of each block of samples to pass to FFT.\n\n Returns:\n 2D np.array where each row contains the magnitudes of the fft_length/2+1\n unique values of the FFT for the corresponding frame of input samples.\n \"\"\"\n frames = frame(signal, window_length, hop_length)\n # Apply frame window to each frame. We use a periodic Hann (cosine of period\n # window_length) instead of the symmetric Hann of np.hanning (period\n # window_length-1).\n window = periodic_hann(window_length)\n windowed_frames = frames * window\n return np.abs(np.fft.rfft(windowed_frames, int(fft_length)))": 1472, "def make_unique_ngrams(s, n):\n \"\"\"Make a set of unique n-grams from a string.\"\"\"\n return set(s[i:i + n] for i in range(len(s) - n + 1))": 1473, "def module_name(self):\n \"\"\"\n The module where this route's view function was defined.\n \"\"\"\n if not self.view_func:\n return None\n elif self._controller_cls:\n rv = inspect.getmodule(self._controller_cls).__name__\n return rv\n return inspect.getmodule(self.view_func).__name__": 1474, "def _is_leap_year(year):\n \"\"\"Determine if a year is leap year.\n\n Parameters\n ----------\n year : numeric\n\n Returns\n -------\n isleap : array of bools\n \"\"\"\n isleap = ((np.mod(year, 4) == 0) &\n ((np.mod(year, 100) != 0) | (np.mod(year, 400) == 0)))\n return isleap": 1475, "def first_sunday(self, year, month):\n \"\"\"Get the first sunday of a month.\"\"\"\n date = datetime(year, month, 1, 0)\n days_until_sunday = 6 - date.weekday()\n\n return date + timedelta(days=days_until_sunday)": 1476, "def series_index(self, series):\n \"\"\"\n Return the integer index of *series* in this sequence.\n \"\"\"\n for idx, s in enumerate(self):\n if series is s:\n return idx\n raise ValueError('series not in chart data object')": 1477, "def right_outer(self):\n \"\"\"\n Performs Right Outer Join\n :return right_outer: dict\n \"\"\"\n self.get_collections_data()\n right_outer_join = self.merge_join_docs(\n set(self.collections_data['right'].keys()))\n return right_outer_join": 1478, "def input_int_default(question=\"\", default=0):\n \"\"\"A function that works for both, Python 2.x and Python 3.x.\n It asks the user for input and returns it as a string.\n \"\"\"\n answer = input_string(question)\n if answer == \"\" or answer == \"yes\":\n return default\n else:\n return int(answer)": 1479, "def to_dict(dictish):\n \"\"\"\n Given something that closely resembles a dictionary, we attempt\n to coerce it into a propery dictionary.\n \"\"\"\n if hasattr(dictish, 'iterkeys'):\n m = dictish.iterkeys\n elif hasattr(dictish, 'keys'):\n m = dictish.keys\n else:\n raise ValueError(dictish)\n\n return dict((k, dictish[k]) for k in m())": 1480, "def shallow_reverse(g):\n \"\"\"\n Make a shallow copy of a directional graph and reverse the edges. This is a workaround to solve the issue that one\n cannot easily make a shallow reversed copy of a graph in NetworkX 2, since networkx.reverse(copy=False) now returns\n a GraphView, and GraphViews are always read-only.\n\n :param networkx.DiGraph g: The graph to reverse.\n :return: A new networkx.DiGraph that has all nodes and all edges of the original graph, with\n edges reversed.\n \"\"\"\n\n new_g = networkx.DiGraph()\n\n new_g.add_nodes_from(g.nodes())\n for src, dst, data in g.edges(data=True):\n new_g.add_edge(dst, src, **data)\n\n return new_g": 1481, "def __matches(s1, s2, ngrams_fn, n=3):\n \"\"\"\n Returns the n-grams that match between two sequences\n\n See also: SequenceMatcher.get_matching_blocks\n\n Args:\n s1: a string\n s2: another string\n n: an int for the n in n-gram\n\n Returns:\n set:\n \"\"\"\n ngrams1, ngrams2 = set(ngrams_fn(s1, n=n)), set(ngrams_fn(s2, n=n))\n return ngrams1.intersection(ngrams2)": 1482, "def sf01(arr):\n \"\"\"\n swap and then flatten axes 0 and 1\n \"\"\"\n s = arr.shape\n return arr.swapaxes(0, 1).reshape(s[0] * s[1], *s[2:])": 1483, "def _rotate(n, x, y, rx, ry):\n \"\"\"Rotate and flip a quadrant appropriately\n\n Based on the implementation here:\n https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503\n\n \"\"\"\n if ry == 0:\n if rx == 1:\n x = n - 1 - x\n y = n - 1 - y\n return y, x\n return x, y": 1484, "def redirect_output(fileobj):\n \"\"\"Redirect standard out to file.\"\"\"\n old = sys.stdout\n sys.stdout = fileobj\n try:\n yield fileobj\n finally:\n sys.stdout = old": 1485, "def Slice(a, begin, size):\n \"\"\"\n Slicing op.\n \"\"\"\n return np.copy(a)[[slice(*tpl) for tpl in zip(begin, begin+size)]],": 1486, "def round_array(array_in):\n \"\"\"\n arr_out = round_array(array_in)\n\n Rounds an array and recasts it to int. Also works on scalars.\n \"\"\"\n if isinstance(array_in, ndarray):\n return np.round(array_in).astype(int)\n else:\n return int(np.round(array_in))": 1487, "def normalize(self, string):\n \"\"\"Normalize the string according to normalization list\"\"\"\n return ''.join([self._normalize.get(x, x) for x in nfd(string)])": 1488, "def lower_ext(abspath):\n \"\"\"Convert file extension to lowercase.\n \"\"\"\n fname, ext = os.path.splitext(abspath)\n return fname + ext.lower()": 1489, "def _linear_interpolation(x, X, Y):\n \"\"\"Given two data points [X,Y], linearly interpolate those at x.\n \"\"\"\n return (Y[1] * (x - X[0]) + Y[0] * (X[1] - x)) / (X[1] - X[0])": 1490, "def __call__(self, func, *args, **kwargs):\n \"\"\"Shorcut for self.run.\"\"\"\n return self.run(func, *args, **kwargs)": 1491, "def abort(err):\n \"\"\"Abort everything, everywhere.\"\"\"\n if _debug: abort._debug(\"abort %r\", err)\n global local_controllers\n\n # tell all the local controllers to abort\n for controller in local_controllers.values():\n controller.abort(err)": 1492, "def test(): # pragma: no cover\n \"\"\"Execute the unit tests on an installed copy of unyt.\n\n Note that this function requires pytest to run. If pytest is not\n installed this function will raise ImportError.\n \"\"\"\n import pytest\n import os\n\n pytest.main([os.path.dirname(os.path.abspath(__file__))])": 1493, "def storeByteArray(self, context, page, len, data, returnError):\n \"\"\"please override\"\"\"\n returnError.contents.value = self.IllegalStateError\n raise NotImplementedError(\"You must override this method.\")": 1494, "def array(self):\n \"\"\"\n return the underlying numpy array\n \"\"\"\n return np.arange(self.start, self.stop, self.step)": 1495, "def test(nose_argsuments):\n \"\"\" Run application tests \"\"\"\n from nose import run\n\n params = ['__main__', '-c', 'nose.ini']\n params.extend(nose_argsuments)\n run(argv=params)": 1496, "def _save_file(self, filename, contents):\n \"\"\"write the html file contents to disk\"\"\"\n with open(filename, 'w') as f:\n f.write(contents)": 1497, "def resetScale(self):\n \"\"\"Resets the scale on this image. Correctly aligns time scale, undoes manual scaling\"\"\"\n self.img.scale(1./self.imgScale[0], 1./self.imgScale[1])\n self.imgScale = (1.,1.)": 1498, "def compile_filter(bpf_filter, iface=None):\n \"\"\"Asks Tcpdump to parse the filter, then build the matching\n BPF bytecode using get_bpf_pointer.\n \"\"\"\n if not TCPDUMP:\n raise Scapy_Exception(\"tcpdump is not available. Cannot use filter !\")\n try:\n process = subprocess.Popen([\n conf.prog.tcpdump,\n \"-p\",\n \"-i\", (conf.iface if iface is None else iface),\n \"-ddd\",\n \"-s\", str(MTU),\n bpf_filter],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE\n )\n except OSError as ex:\n raise Scapy_Exception(\"Failed to attach filter: %s\" % ex)\n lines, err = process.communicate()\n ret = process.returncode\n if ret:\n raise Scapy_Exception(\n \"Failed to attach filter: tcpdump returned: %s\" % err\n )\n lines = lines.strip().split(b\"\\n\")\n return get_bpf_pointer(lines)": 1499, "def setdefault(obj, field, default):\n \"\"\"Set an object's field to default if it doesn't have a value\"\"\"\n setattr(obj, field, getattr(obj, field, default))": 1500, "def plot_target(target, ax):\n \"\"\"Ajoute la target au plot\"\"\"\n ax.scatter(target[0], target[1], target[2], c=\"red\", s=80)": 1501, "def append(self, item):\n \"\"\" append item and print it to stdout \"\"\"\n print(item)\n super(MyList, self).append(item)": 1502, "def get_duckduckgo_links(limit, params, headers):\n\t\"\"\"\n\tfunction to fetch links equal to limit\n\n\tduckduckgo pagination is not static, so there is a limit on\n\tmaximum number of links that can be scraped\n\t\"\"\"\n\tresp = s.get('https://duckduckgo.com/html', params = params, headers = headers)\n\tlinks = scrape_links(resp.content, engine = 'd')\n\treturn links[:limit]": 1503, "def __dir__(self):\n u\"\"\"Returns a list of children and available helper methods.\"\"\"\n return sorted(self.keys() | {m for m in dir(self.__class__) if m.startswith('to_')})": 1504, "def add_argument(self, dest, nargs=1, obj=None):\n \"\"\"Adds a positional argument named `dest` to the parser.\n\n The `obj` can be used to identify the option in the order list\n that is returned from the parser.\n \"\"\"\n if obj is None:\n obj = dest\n self._args.append(Argument(dest=dest, nargs=nargs, obj=obj))": 1505, "def get_last(self, table=None):\n \"\"\"Just the last entry.\"\"\"\n if table is None: table = self.main_table\n query = 'SELECT * FROM \"%s\" ORDER BY ROWID DESC LIMIT 1;' % table\n return self.own_cursor.execute(query).fetchone()": 1506, "def Min(a, axis, keep_dims):\n \"\"\"\n Min reduction op.\n \"\"\"\n return np.amin(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),\n keepdims=keep_dims),": 1507, "def build_parser():\n \"\"\"Build argument parsers.\"\"\"\n\n parser = argparse.ArgumentParser(\"Release packages to pypi\")\n parser.add_argument('--check', '-c', action=\"store_true\", help=\"Do a dry run without uploading\")\n parser.add_argument('component', help=\"The component to release as component-version\")\n return parser": 1508, "def send_email_message(self, recipient, subject, html_message, text_message, sender_email, sender_name):\n \"\"\" Send email message via Flask-Sendmail.\n\n Args:\n recipient: Email address or tuple of (Name, Email-address).\n subject: Subject line.\n html_message: The message body in HTML.\n text_message: The message body in plain text.\n \"\"\"\n\n if not current_app.testing: # pragma: no cover\n\n # Prepare email message\n from flask_sendmail import Message\n message = Message(\n subject,\n recipients=[recipient],\n html=html_message,\n body=text_message)\n\n # Send email message\n self.mail.send(message)": 1509, "async def _send_plain_text(self, request: Request, stack: Stack):\n \"\"\"\n Sends plain text using `_send_text()`.\n \"\"\"\n\n await self._send_text(request, stack, None)": 1510, "def chunks(arr, size):\n \"\"\"Splits a list into chunks\n\n :param arr: list to split\n :type arr: :class:`list`\n :param size: number of elements in each chunk\n :type size: :class:`int`\n :return: generator object\n :rtype: :class:`generator`\n \"\"\"\n for i in _range(0, len(arr), size):\n yield arr[i:i+size]": 1511, "def yield_connections(sock):\n \"\"\"Run a server on the specified socket.\"\"\"\n while True:\n log.debug('waiting for connection on %s', sock.getsockname())\n try:\n conn, _ = sock.accept()\n except KeyboardInterrupt:\n return\n conn.settimeout(None)\n log.debug('accepted connection on %s', sock.getsockname())\n yield conn": 1512, "def to_dicts(recarray):\n \"\"\"convert record array to a dictionaries\"\"\"\n for rec in recarray:\n yield dict(zip(recarray.dtype.names, rec.tolist()))": 1513, "def set_if_empty(self, param, default):\n \"\"\" Set the parameter to the default if it doesn't exist \"\"\"\n if not self.has(param):\n self.set(param, default)": 1514, "def is_scalar(value):\n \"\"\"Test if the given value is a scalar.\n\n This function also works with memory mapped array values, in contrast to the numpy is_scalar method.\n\n Args:\n value: the value to test for being a scalar value\n\n Returns:\n boolean: if the given value is a scalar or not\n \"\"\"\n return np.isscalar(value) or (isinstance(value, np.ndarray) and (len(np.squeeze(value).shape) == 0))": 1515, "def set_xlimits_widgets(self, set_min=True, set_max=True):\n \"\"\"Populate axis limits GUI with current plot values.\"\"\"\n xmin, xmax = self.tab_plot.ax.get_xlim()\n if set_min:\n self.w.x_lo.set_text('{0}'.format(xmin))\n if set_max:\n self.w.x_hi.set_text('{0}'.format(xmax))": 1516, "def barray(iterlines):\n \"\"\"\n Array of bytes\n \"\"\"\n lst = [line.encode('utf-8') for line in iterlines]\n arr = numpy.array(lst)\n return arr": 1517, "def setPixel(self, x, y, color):\n \"\"\"Set the pixel at (x,y) to the integers in sequence 'color'.\"\"\"\n return _fitz.Pixmap_setPixel(self, x, y, color)": 1518, "def _assert_is_type(name, value, value_type):\n \"\"\"Assert that a value must be a given type.\"\"\"\n if not isinstance(value, value_type):\n if type(value_type) is tuple:\n types = ', '.join(t.__name__ for t in value_type)\n raise ValueError('{0} must be one of ({1})'.format(name, types))\n else:\n raise ValueError('{0} must be {1}'\n .format(name, value_type.__name__))": 1519, "def StringIO(*args, **kwargs):\n \"\"\"StringIO constructor shim for the async wrapper.\"\"\"\n raw = sync_io.StringIO(*args, **kwargs)\n return AsyncStringIOWrapper(raw)": 1520, "def _zerosamestates(self, A):\n \"\"\"\n zeros out states that should be identical\n\n REQUIRED ARGUMENTS\n\n A: the matrix whose entries are to be zeroed.\n\n \"\"\"\n\n for pair in self.samestates:\n A[pair[0], pair[1]] = 0\n A[pair[1], pair[0]] = 0": 1521, "def get_attribute_name_id(attr):\n \"\"\"\n Return the attribute name identifier\n \"\"\"\n return attr.value.id if isinstance(attr.value, ast.Name) else None": 1522, "def __iand__(self, other):\n \"\"\"Intersect this flag with ``other`` in-place.\n \"\"\"\n self.known &= other.known\n self.active &= other.active\n return self": 1523, "def get_raw_input(description, default=False):\n \"\"\"Get user input from the command line via raw_input / input.\n\n description (unicode): Text to display before prompt.\n default (unicode or False/None): Default value to display with prompt.\n RETURNS (unicode): User input.\n \"\"\"\n additional = ' (default: %s)' % default if default else ''\n prompt = ' %s%s: ' % (description, additional)\n user_input = input_(prompt)\n return user_input": 1524, "def setup(app):\n \"\"\"\n Just connects the docstring pre_processor and should_skip functions to be\n applied on all docstrings.\n\n \"\"\"\n app.connect('autodoc-process-docstring',\n lambda *args: pre_processor(*args, namer=audiolazy_namer))\n app.connect('autodoc-skip-member', should_skip)": 1525, "def log_y_cb(self, w, val):\n \"\"\"Toggle linear/log scale for Y-axis.\"\"\"\n self.tab_plot.logy = val\n self.plot_two_columns()": 1526, "def convert_camel_case_to_snake_case(name):\n \"\"\"Convert CamelCase to snake_case.\"\"\"\n s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', name)\n return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()": 1527, "def array_size(x, axis):\n \"\"\"Calculate the size of `x` along `axis` dimensions only.\"\"\"\n axis_shape = x.shape if axis is None else tuple(x.shape[a] for a in axis)\n return max(numpy.prod(axis_shape), 1)": 1528, "def _mean_dict(dict_list):\n \"\"\"Compute the mean value across a list of dictionaries\n \"\"\"\n return {k: np.array([d[k] for d in dict_list]).mean()\n for k in dict_list[0].keys()}": 1529, "def average(arr):\n \"\"\"average of the values, must have more than 0 entries.\n\n :param arr: list of numbers\n :type arr: number[] a number array\n :return: average\n :rtype: float\n\n \"\"\"\n if len(arr) == 0:\n sys.stderr.write(\"ERROR: no content in array to take average\\n\")\n sys.exit()\n if len(arr) == 1: return arr[0]\n return float(sum(arr))/float(len(arr))": 1530, "def _aggr_mean(inList):\n \"\"\" Returns mean of non-None elements of the list\n \"\"\"\n aggrSum = 0\n nonNone = 0\n for elem in inList:\n if elem != SENTINEL_VALUE_FOR_MISSING_DATA:\n aggrSum += elem\n nonNone += 1\n if nonNone != 0:\n return aggrSum / nonNone\n else:\n return None": 1531, "def help(self):\n \"\"\"Prints discovered resources and their associated methods. Nice when\n noodling in the terminal to wrap your head around Magento's insanity.\n \"\"\"\n\n print('Resources:')\n print('')\n for name in sorted(self._resources.keys()):\n methods = sorted(self._resources[name]._methods.keys())\n print('{}: {}'.format(bold(name), ', '.join(methods)))": 1532, "def _repr(obj):\n \"\"\"Show the received object as precise as possible.\"\"\"\n vals = \", \".join(\"{}={!r}\".format(\n name, getattr(obj, name)) for name in obj._attribs)\n if vals:\n t = \"{}(name={}, {})\".format(obj.__class__.__name__, obj.name, vals)\n else:\n t = \"{}(name={})\".format(obj.__class__.__name__, obj.name)\n return t": 1533, "def out(self, output, newline=True):\n \"\"\"Outputs a string to the console (stdout).\"\"\"\n click.echo(output, nl=newline)": 1534, "def encode_batch(self, inputBatch):\n \"\"\"Encodes a whole batch of input arrays, without learning.\"\"\"\n X = inputBatch\n encode = self.encode\n Y = np.array([ encode(x) for x in X])\n return Y": 1535, "def parse(el, typ):\n \"\"\"\n Parse a ``BeautifulSoup`` element as the given type.\n \"\"\"\n if not el:\n return typ()\n txt = text(el)\n if not txt:\n return typ()\n return typ(txt)": 1536, "def as_tree(context):\n \"\"\"Return info about an object's members as JSON\"\"\"\n\n tree = _build_tree(context, 2, 1)\n if type(tree) == dict:\n tree = [tree] \n \n return Response(content_type='application/json', body=json.dumps(tree))": 1537, "def QA_util_datetime_to_strdate(dt):\n \"\"\"\n :param dt: pythone datetime.datetime\n :return: 1999-02-01 string type\n \"\"\"\n strdate = \"%04d-%02d-%02d\" % (dt.year, dt.month, dt.day)\n return strdate": 1538, "def filter_useless_pass(source):\n \"\"\"Yield code with useless \"pass\" lines removed.\"\"\"\n try:\n marked_lines = frozenset(useless_pass_line_numbers(source))\n except (SyntaxError, tokenize.TokenError):\n marked_lines = frozenset()\n\n sio = io.StringIO(source)\n for line_number, line in enumerate(sio.readlines(), start=1):\n if line_number not in marked_lines:\n yield line": 1539, "def get_bin_indices(self, values):\n \"\"\"Returns index tuple in histogram of bin which contains value\"\"\"\n return tuple([self.get_axis_bin_index(values[ax_i], ax_i)\n for ax_i in range(self.dimensions)])": 1540, "def register_view(self, view):\n \"\"\"Register callbacks for button press events and selection changed\"\"\"\n super(ListViewController, self).register_view(view)\n self.tree_view.connect('button_press_event', self.mouse_click)": 1541, "def Bernstein(n, k):\n \"\"\"Bernstein polynomial.\n\n \"\"\"\n coeff = binom(n, k)\n\n def _bpoly(x):\n return coeff * x ** k * (1 - x) ** (n - k)\n\n return _bpoly": 1542, "def abbreviate_dashed(s):\n \"\"\"Abbreviates each part of string that is delimited by a '-'.\"\"\"\n r = []\n for part in s.split('-'):\n r.append(abbreviate(part))\n return '-'.join(r)": 1543, "def maskIndex(self):\n \"\"\" Returns a boolean index with True if the value is masked.\n\n Always has the same shape as the maksedArray.data, event if the mask is a single boolan.\n \"\"\"\n if isinstance(self.mask, bool):\n return np.full(self.data.shape, self.mask, dtype=np.bool)\n else:\n return self.mask": 1544, "def _split(string, splitters):\n \"\"\"Splits a string into parts at multiple characters\"\"\"\n part = ''\n for character in string:\n if character in splitters:\n yield part\n part = ''\n else:\n part += character\n yield part": 1545, "def split_into_words(s):\n \"\"\"Split a sentence into list of words.\"\"\"\n s = re.sub(r\"\\W+\", \" \", s)\n s = re.sub(r\"[_0-9]+\", \" \", s)\n return s.split()": 1546, "def get_as_bytes(self, s3_path):\n \"\"\"\n Get the contents of an object stored in S3 as bytes\n\n :param s3_path: URL for target S3 location\n :return: File contents as pure bytes\n \"\"\"\n (bucket, key) = self._path_to_bucket_and_key(s3_path)\n obj = self.s3.Object(bucket, key)\n contents = obj.get()['Body'].read()\n return contents": 1547, "def render_template(self, source, **kwargs_context):\n r\"\"\"Render a template string using sandboxed environment.\n\n :param source: A string containing the page source.\n :param \\*\\*kwargs_context: The context associated with the page.\n :returns: The rendered template.\n \"\"\"\n return self.jinja_env.from_string(source).render(kwargs_context)": 1548, "def emit_db_sequence_updates(engine):\n \"\"\"Set database sequence objects to match the source db\n\n Relevant only when generated from SQLAlchemy connection.\n Needed to avoid subsequent unique key violations after DB build.\"\"\"\n\n if engine and engine.name == 'postgresql':\n # not implemented for other RDBMS; necessity unknown\n conn = engine.connect()\n qry = \"\"\"SELECT 'SELECT last_value FROM ' || n.nspname ||\n '.' || c.relname || ';' AS qry,\n n.nspname || '.' || c.relname AS qual_name\n FROM pg_namespace n\n JOIN pg_class c ON (n.oid = c.relnamespace)\n WHERE c.relkind = 'S'\"\"\"\n for (qry, qual_name) in list(conn.execute(qry)):\n (lastval, ) = conn.execute(qry).first()\n nextval = int(lastval) + 1\n yield \"ALTER SEQUENCE %s RESTART WITH %s;\" % (qual_name, nextval)": 1549, "def method_double_for(self, method_name):\n \"\"\"Returns the method double for the provided method name, creating one if necessary.\n\n :param str method_name: The name of the method to retrieve a method double for.\n :return: The mapped ``MethodDouble``.\n :rtype: MethodDouble\n \"\"\"\n\n if method_name not in self._method_doubles:\n self._method_doubles[method_name] = MethodDouble(method_name, self._target)\n\n return self._method_doubles[method_name]": 1550, "def rgba_bytes_tuple(self, x):\n \"\"\"Provides the color corresponding to value `x` in the\n form of a tuple (R,G,B,A) with int values between 0 and 255.\n \"\"\"\n return tuple(int(u*255.9999) for u in self.rgba_floats_tuple(x))": 1551, "def fft_bandpassfilter(data, fs, lowcut, highcut):\n \"\"\"\n http://www.swharden.com/blog/2009-01-21-signal-filtering-with-python/#comment-16801\n \"\"\"\n fft = np.fft.fft(data)\n # n = len(data)\n # timestep = 1.0 / fs\n # freq = np.fft.fftfreq(n, d=timestep)\n bp = fft.copy()\n\n # Zero out fft coefficients\n # bp[10:-10] = 0\n\n # Normalise\n # bp *= real(fft.dot(fft))/real(bp.dot(bp))\n\n bp *= fft.dot(fft) / bp.dot(bp)\n\n # must multipy by 2 to get the correct amplitude\n ibp = 12 * np.fft.ifft(bp)\n return ibp": 1552, "def print_env_info(key, out=sys.stderr):\n \"\"\"If given environment key is defined, print it out.\"\"\"\n value = os.getenv(key)\n if value is not None:\n print(key, \"=\", repr(value), file=out)": 1553, "def is_cached(file_name):\n\t\"\"\"\n\tCheck if a given file is available in the cache or not\n\t\"\"\"\n\n\tgml_file_path = join(join(expanduser('~'), OCTOGRID_DIRECTORY), file_name)\n\n\treturn isfile(gml_file_path)": 1554, "def set_cache_max(self, cache_name, maxsize, **kwargs):\n \"\"\"\n Sets the maxsize attribute of the named cache\n \"\"\"\n cache = self._get_cache(cache_name)\n cache.set_maxsize(maxsize, **kwargs)": 1555, "def _on_release(self, event):\n \"\"\"Stop dragging.\"\"\"\n if self._drag_cols or self._drag_rows:\n self._visual_drag.place_forget()\n self._dragged_col = None\n self._dragged_row = None": 1556, "def update_cache(self, data):\n \"\"\"Update a cached value.\"\"\"\n UTILS.update(self._cache, data)\n self._save_cache()": 1557, "def angle(x, y):\n \"\"\"Return the angle between vectors a and b in degrees.\"\"\"\n return arccos(dot(x, y)/(norm(x)*norm(y)))*180./pi": 1558, "def add_object(self, object):\n \"\"\"Add object to db session. Only for session-centric object-database mappers.\"\"\"\n if object.id is None:\n object.get_id()\n self.db.engine.save(object)": 1559, "def _cal_dist2center(X, center):\n \"\"\" Calculate the SSE to the cluster center\n \"\"\"\n dmemb2cen = scipy.spatial.distance.cdist(X, center.reshape(1,X.shape[1]), metric='seuclidean')\n return(np.sum(dmemb2cen))": 1560, "def save_hdf5(X, y, path):\n \"\"\"Save data as a HDF5 file.\n\n Args:\n X (numpy or scipy sparse matrix): Data matrix\n y (numpy array): Target vector.\n path (str): Path to the HDF5 file to save data.\n \"\"\"\n\n with h5py.File(path, 'w') as f:\n is_sparse = 1 if sparse.issparse(X) else 0\n f['issparse'] = is_sparse\n f['target'] = y\n\n if is_sparse:\n if not sparse.isspmatrix_csr(X):\n X = X.tocsr()\n\n f['shape'] = np.array(X.shape)\n f['data'] = X.data\n f['indices'] = X.indices\n f['indptr'] = X.indptr\n else:\n f['data'] = X": 1561, "def get_gzipped_contents(input_file):\n \"\"\"\n Returns a gzipped version of a previously opened file's buffer.\n \"\"\"\n zbuf = StringIO()\n zfile = GzipFile(mode=\"wb\", compresslevel=6, fileobj=zbuf)\n zfile.write(input_file.read())\n zfile.close()\n return ContentFile(zbuf.getvalue())": 1562, "def vec_angle(a, b):\n \"\"\"\n Calculate angle between two vectors\n \"\"\"\n cosang = np.dot(a, b)\n sinang = fast_norm(np.cross(a, b))\n return np.arctan2(sinang, cosang)": 1563, "def decamelise(text):\n \"\"\"Convert CamelCase to lower_and_underscore.\"\"\"\n s = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', text)\n return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s).lower()": 1564, "def elapsed_time_from(start_time):\n \"\"\"calculate time delta from latched time and current time\"\"\"\n time_then = make_time(start_time)\n time_now = datetime.utcnow().replace(microsecond=0)\n if time_then is None:\n return\n delta_t = time_now - time_then\n return delta_t": 1565, "def _to_lower_alpha_only(s):\n \"\"\"Return a lowercased string with non alphabetic chars removed.\n\n White spaces are not to be removed.\"\"\"\n s = re.sub(r'\\n', ' ', s.lower())\n return re.sub(r'[^a-z\\s]', '', s)": 1566, "def color_func(func_name):\n \"\"\"\n Call color function base on name\n \"\"\"\n if str(func_name).isdigit():\n return term_color(int(func_name))\n return globals()[func_name]": 1567, "def token_list_to_text(tokenlist):\n \"\"\"\n Concatenate all the text parts again.\n \"\"\"\n ZeroWidthEscape = Token.ZeroWidthEscape\n return ''.join(item[1] for item in tokenlist if item[0] != ZeroWidthEscape)": 1568, "def help(self, level=0):\n \"\"\"return the usage string for available options \"\"\"\n self.cmdline_parser.formatter.output_level = level\n with _patch_optparse():\n return self.cmdline_parser.format_help()": 1569, "def get_request(self, request):\n \"\"\"Sets token-based auth headers.\"\"\"\n request.transport_user = self.username\n request.transport_password = self.api_key\n return request": 1570, "def min_or_none(val1, val2):\n \"\"\"Returns min(val1, val2) returning None only if both values are None\"\"\"\n return min(val1, val2, key=lambda x: sys.maxint if x is None else x)": 1571, "def _run_cmd_get_output(cmd):\n \"\"\"Runs a shell command, returns console output.\n\n Mimics python3's subprocess.getoutput\n \"\"\"\n process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)\n out, err = process.communicate()\n return out or err": 1572, "def cartesian_product(arrays, flat=True, copy=False):\n \"\"\"\n Efficient cartesian product of a list of 1D arrays returning the\n expanded array views for each dimensions. By default arrays are\n flattened, which may be controlled with the flat flag. The array\n views can be turned into regular arrays with the copy flag.\n \"\"\"\n arrays = np.broadcast_arrays(*np.ix_(*arrays))\n if flat:\n return tuple(arr.flatten() if copy else arr.flat for arr in arrays)\n return tuple(arr.copy() if copy else arr for arr in arrays)": 1573, "def is_bool_matrix(l):\n r\"\"\"Checks if l is a 2D numpy array of bools\n\n \"\"\"\n if isinstance(l, np.ndarray):\n if l.ndim == 2 and (l.dtype == bool):\n return True\n return False": 1574, "def match(string, patterns):\n \"\"\"Given a string return true if it matches the supplied list of\n patterns.\n\n Parameters\n ----------\n string : str\n The string to be matched.\n patterns : None or [pattern, ...]\n The series of regular expressions to attempt to match.\n \"\"\"\n if patterns is None:\n return True\n else:\n return any(re.match(pattern, string)\n for pattern in patterns)": 1575, "def tokenize_list(self, text):\n \"\"\"\n Split a text into separate words.\n \"\"\"\n return [self.get_record_token(record) for record in self.analyze(text)]": 1576, "def strip_accents(text):\n \"\"\"\n Strip agents from a string.\n \"\"\"\n\n normalized_str = unicodedata.normalize('NFD', text)\n\n return ''.join([\n c for c in normalized_str if unicodedata.category(c) != 'Mn'])": 1577, "def compose(*funcs):\n \"\"\"compose a list of functions\"\"\"\n return lambda x: reduce(lambda v, f: f(v), reversed(funcs), x)": 1578, "def OnCellBackgroundColor(self, event):\n \"\"\"Cell background color event handler\"\"\"\n\n with undo.group(_(\"Background color\")):\n self.grid.actions.set_attr(\"bgcolor\", event.color)\n\n self.grid.ForceRefresh()\n\n self.grid.update_attribute_toolbar()\n\n event.Skip()": 1579, "def build_docs(directory):\n \"\"\"Builds sphinx docs from a given directory.\"\"\"\n os.chdir(directory)\n process = subprocess.Popen([\"make\", \"html\"], cwd=directory)\n process.communicate()": 1580, "def convert_tstamp(response):\n\t\"\"\"\n\tConvert a Stripe API timestamp response (unix epoch) to a native datetime.\n\n\t:rtype: datetime\n\t\"\"\"\n\tif response is None:\n\t\t# Allow passing None to convert_tstamp()\n\t\treturn response\n\n\t# Overrides the set timezone to UTC - I think...\n\ttz = timezone.utc if settings.USE_TZ else None\n\n\treturn datetime.datetime.fromtimestamp(response, tz)": 1581, "def checkbox_uncheck(self, force_check=False):\n \"\"\"\n Wrapper to uncheck a checkbox\n \"\"\"\n if self.get_attribute('checked'):\n self.click(force_click=force_check)": 1582, "def dict_to_numpy_array(d):\n \"\"\"\n Convert a dict of 1d array to a numpy recarray\n \"\"\"\n return fromarrays(d.values(), np.dtype([(str(k), v.dtype) for k, v in d.items()]))": 1583, "def adapt_array(arr):\n \"\"\"\n http://stackoverflow.com/a/31312102/190597 (SoulNibbler)\n \"\"\"\n out = io.BytesIO()\n np.save(out, arr)\n out.seek(0)\n return sqlite3.Binary(out.read())": 1584, "def __set_token_expired(self, value):\n \"\"\"Internal helper for oauth code\"\"\"\n self._token_expired = datetime.datetime.now() + datetime.timedelta(seconds=value)\n return": 1585, "def check_attribute_exists(instance):\n \"\"\" Additional check for the dimension model, to ensure that attributes\n given as the key and label attribute on the dimension exist. \"\"\"\n attributes = instance.get('attributes', {}).keys()\n if instance.get('key_attribute') not in attributes:\n return False\n label_attr = instance.get('label_attribute')\n if label_attr and label_attr not in attributes:\n return False\n return True": 1586, "def dir_path(dir):\n \"\"\"with dir_path(path) to change into a directory.\"\"\"\n old_dir = os.getcwd()\n os.chdir(dir)\n yield\n os.chdir(old_dir)": 1587, "def bisect_index(a, x):\n \"\"\" Find the leftmost index of an element in a list using binary search.\n\n Parameters\n ----------\n a: list\n A sorted list.\n x: arbitrary\n The element.\n\n Returns\n -------\n int\n The index.\n\n \"\"\"\n i = bisect.bisect_left(a, x)\n if i != len(a) and a[i] == x:\n return i\n raise ValueError": 1588, "def save_form(self, request, form, change):\n \"\"\"\n Super class ordering is important here - user must get saved first.\n \"\"\"\n OwnableAdmin.save_form(self, request, form, change)\n return DisplayableAdmin.save_form(self, request, form, change)": 1589, "def __next__(self):\n \"\"\"\n\n :return: a pair (1-based line number in the input, row)\n \"\"\"\n # Retrieve the row, thereby incrementing the line number:\n row = super(UnicodeReaderWithLineNumber, self).__next__()\n return self.lineno + 1, row": 1590, "def gaussian_variogram_model(m, d):\n \"\"\"Gaussian model, m is [psill, range, nugget]\"\"\"\n psill = float(m[0])\n range_ = float(m[1])\n nugget = float(m[2])\n return psill * (1. - np.exp(-d**2./(range_*4./7.)**2.)) + nugget": 1591, "def title(msg):\n \"\"\"Sets the title of the console window.\"\"\"\n if sys.platform.startswith(\"win\"):\n ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg))": 1592, "def pprint(self, seconds):\n \"\"\"\n Pretty Prints seconds as Hours:Minutes:Seconds.MilliSeconds\n\n :param seconds: The time in seconds.\n \"\"\"\n return (\"%d:%02d:%02d.%03d\", reduce(lambda ll, b: divmod(ll[0], b) + ll[1:], [(seconds * 1000,), 1000, 60, 60]))": 1593, "def normalize(data):\n \"\"\"\n Function to normalize data to have mean 0 and unity standard deviation\n (also called z-transform)\n \n \n Parameters\n ----------\n data : numpy.ndarray\n \n \n Returns\n -------\n numpy.ndarray\n z-transform of input array\n \n \"\"\"\n data = data.astype(float)\n data -= data.mean()\n \n return data / data.std()": 1594, "def print_tree(self, indent=2):\n \"\"\" print_tree: prints out structure of tree\n Args: indent (int): What level of indentation at which to start printing\n Returns: None\n \"\"\"\n config.LOGGER.info(\"{indent}{data}\".format(indent=\" \" * indent, data=str(self)))\n for child in self.children:\n child.print_tree(indent + 1)": 1595, "def is_readable(fp, size=1):\n \"\"\"\n Check if the file-like object is readable.\n\n :param fp: file-like object\n :param size: byte size\n :return: bool\n \"\"\"\n read_size = len(fp.read(size))\n fp.seek(-read_size, 1)\n return read_size == size": 1596, "def strip_head(sequence, values):\n \"\"\"Strips elements of `values` from the beginning of `sequence`.\"\"\"\n values = set(values)\n return list(itertools.dropwhile(lambda x: x in values, sequence))": 1597, "def check_create_folder(filename):\n \"\"\"Check if the folder exisits. If not, create the folder\"\"\"\n os.makedirs(os.path.dirname(filename), exist_ok=True)": 1598, "def to_dict(self):\n \"\"\"Converts the table to a dict.\"\"\"\n return {\"name\": self.table_name, \"kind\": self.table_kind, \"data\": [r.to_dict() for r in self]}": 1599, "def _crop_list_to_size(l, size):\n \"\"\"Make a list a certain size\"\"\"\n for x in range(size - len(l)):\n l.append(False)\n for x in range(len(l) - size):\n l.pop()\n return l": 1600, "def isin_alone(elems, line):\n \"\"\"Check if an element from a list is the only element of a string.\n\n :type elems: list\n :type line: str\n\n \"\"\"\n found = False\n for e in elems:\n if line.strip().lower() == e.lower():\n found = True\n break\n return found": 1601, "def unit_key_from_name(name):\n \"\"\"Return a legal python name for the given name for use as a unit key.\"\"\"\n result = name\n\n for old, new in six.iteritems(UNIT_KEY_REPLACEMENTS):\n result = result.replace(old, new)\n\n # Collapse redundant underscores and convert to uppercase.\n result = re.sub(r'_+', '_', result.upper())\n\n return result": 1602, "def string_to_int( s ):\n \"\"\"Convert a string of bytes into an integer, as per X9.62.\"\"\"\n result = 0\n for c in s:\n if not isinstance(c, int): c = ord( c )\n result = 256 * result + c\n return result": 1603, "def valid_uuid(value):\n \"\"\" Check if value is a valid UUID. \"\"\"\n\n try:\n uuid.UUID(value, version=4)\n return True\n except (TypeError, ValueError, AttributeError):\n return False": 1604, "def to_dataframe(products):\n \"\"\"Return the products from a query response as a Pandas DataFrame\n with the values in their appropriate Python types.\n \"\"\"\n try:\n import pandas as pd\n except ImportError:\n raise ImportError(\"to_dataframe requires the optional dependency Pandas.\")\n\n return pd.DataFrame.from_dict(products, orient='index')": 1605, "def _get_ipv4_from_binary(self, bin_addr):\n \"\"\"Converts binary address to Ipv4 format.\"\"\"\n\n return socket.inet_ntop(socket.AF_INET, struct.pack(\"!L\", bin_addr))": 1606, "def is_symlink(self):\n \"\"\"\n Whether this path is a symbolic link.\n \"\"\"\n try:\n return S_ISLNK(self.lstat().st_mode)\n except OSError as e:\n if e.errno != ENOENT:\n raise\n # Path doesn't exist\n return False": 1607, "def is_valid_folder(parser, arg):\n \"\"\"Check if arg is a valid file that already exists on the file system.\"\"\"\n arg = os.path.abspath(arg)\n if not os.path.isdir(arg):\n parser.error(\"The folder %s does not exist!\" % arg)\n else:\n return arg": 1608, "def abort(self):\n \"\"\" ensure the master exit from Barrier \"\"\"\n self.mutex.release()\n self.turnstile.release()\n self.mutex.release()\n self.turnstile2.release()": 1609, "def Gaussian(x, mu, sig):\n \"\"\"\n Gaussian pdf.\n :param x: free variable.\n :param mu: mean of the distribution.\n :param sig: standard deviation of the distribution.\n :return: sympy.Expr for a Gaussian pdf.\n \"\"\"\n return sympy.exp(-(x - mu)**2/(2*sig**2))/sympy.sqrt(2*sympy.pi*sig**2)": 1610, "def angle_v2_rad(vec_a, vec_b):\n \"\"\"Returns angle between vec_a and vec_b in range [0, PI]. This does not\n distinguish if a is left of or right of b.\n \"\"\"\n # cos(x) = A * B / |A| * |B|\n return math.acos(vec_a.dot(vec_b) / (vec_a.length() * vec_b.length()))": 1611, "def _rectangular(n):\n \"\"\"Checks to see if a 2D list is a valid 2D matrix\"\"\"\n for i in n:\n if len(i) != len(n[0]):\n return False\n return True": 1612, "def is_iterable_of_int(l):\n r\"\"\" Checks if l is iterable and contains only integral types \"\"\"\n if not is_iterable(l):\n return False\n\n return all(is_int(value) for value in l)": 1613, "def is_valid_image_extension(file_path):\n \"\"\"is_valid_image_extension.\"\"\"\n valid_extensions = ['.jpeg', '.jpg', '.gif', '.png']\n _, extension = os.path.splitext(file_path)\n return extension.lower() in valid_extensions": 1614, "def rollback(self):\n\t\t\"\"\"\n\t\tRollback MySQL Transaction to database.\n\t\tMySQLDB: If the database and tables support transactions, this rolls \n\t\tback (cancels) the current transaction; otherwise a \n\t\tNotSupportedError is raised.\n\t\t\n\t\t@author: Nick Verbeck\n\t\t@since: 5/12/2008\n\t\t\"\"\"\n\t\ttry:\n\t\t\tif self.connection is not None:\n\t\t\t\tself.connection.rollback()\n\t\t\t\tself._updateCheckTime()\n\t\t\t\tself.release()\n\t\texcept Exception, e:\n\t\t\tpass": 1615, "def gevent_monkey_patch_report(self):\n \"\"\"\n Report effective gevent monkey patching on the logs.\n \"\"\"\n try:\n import gevent.socket\n import socket\n\n if gevent.socket.socket is socket.socket:\n self.log(\"gevent monkey patching is active\")\n return True\n else:\n self.notify_user(\"gevent monkey patching failed.\")\n except ImportError:\n self.notify_user(\"gevent is not installed, monkey patching failed.\")\n return False": 1616, "def inside_softimage():\n \"\"\"Returns a boolean indicating if the code is executed inside softimage.\"\"\"\n try:\n import maya\n return False\n except ImportError:\n pass\n try:\n from win32com.client import Dispatch as disp\n disp('XSI.Application')\n return True\n except:\n return False": 1617, "def is_int_vector(l):\n r\"\"\"Checks if l is a numpy array of integers\n\n \"\"\"\n if isinstance(l, np.ndarray):\n if l.ndim == 1 and (l.dtype.kind == 'i' or l.dtype.kind == 'u'):\n return True\n return False": 1618, "def test_kwargs_are_optional(self):\n \"\"\"kwarg values always have defaults\"\"\"\n with patch(\"sys.exit\") as mock_exit:\n cli = MicroCLITestCase.T(\"script_name f3\".split()).run()\n # kwargs are optional\n mock_exit.assert_called_with(4)": 1619, "def is_valid_row(cls, row):\n \"\"\"Indicates whether or not the given row contains valid data.\"\"\"\n for k in row.keys():\n if row[k] is None:\n return False\n return True": 1620, "def unixtime_to_datetime(ut):\n \"\"\"Convert a unixtime timestamp to a datetime object.\n The function converts a timestamp in Unix format to a\n datetime object. UTC timezone will also be set.\n :param ut: Unix timestamp to convert\n :returns: a datetime object\n :raises InvalidDateError: when the given timestamp cannot be\n converted into a valid date\n \"\"\"\n\n dt = datetime.datetime.utcfromtimestamp(ut)\n dt = dt.replace(tzinfo=tz.tzutc())\n return dt": 1621, "def is_managed():\n \"\"\"\n Check if a Django project is being managed with ``manage.py`` or\n ``django-admin`` scripts\n\n :return: Check result\n :rtype: bool\n \"\"\"\n for item in sys.argv:\n if re.search(r'manage.py|django-admin|django', item) is not None:\n return True\n return False": 1622, "def __init__(self,operand,operator,**args):\n \"\"\"\n Accepts a NumberGenerator operand, an operator, and\n optional arguments to be provided to the operator when calling\n it on the operand.\n \"\"\"\n # Note that it's currently not possible to set\n # parameters in the superclass when creating an instance,\n # because **args is used by this class itself.\n super(UnaryOperator,self).__init__()\n\n self.operand=operand\n self.operator=operator\n self.args=args": 1623, "def _has_fileno(stream):\n \"\"\"Returns whether the stream object seems to have a working fileno()\n\n Tells whether _redirect_stderr is likely to work.\n\n Parameters\n ----------\n stream : IO stream object\n\n Returns\n -------\n has_fileno : bool\n True if stream.fileno() exists and doesn't raise OSError or\n UnsupportedOperation\n \"\"\"\n try:\n stream.fileno()\n except (AttributeError, OSError, IOError, io.UnsupportedOperation):\n return False\n return True": 1624, "def to_capitalized_camel_case(snake_case_string):\n \"\"\"\n Convert a string from snake case to camel case with the first letter capitalized. For example, \"some_var\"\n would become \"SomeVar\".\n\n :param snake_case_string: Snake-cased string to convert to camel case.\n :returns: Camel-cased version of snake_case_string.\n \"\"\"\n parts = snake_case_string.split('_')\n return ''.join([i.title() for i in parts])": 1625, "def has_multiline_items(maybe_list: Optional[Sequence[str]]):\n \"\"\"Check whether one of the items in the list has multiple lines.\"\"\"\n return maybe_list and any(is_multiline(item) for item in maybe_list)": 1626, "def read(*args):\n \"\"\"Reads complete file contents.\"\"\"\n return io.open(os.path.join(HERE, *args), encoding=\"utf-8\").read()": 1627, "def table_exists(self, table):\n \"\"\"Returns whether the given table exists.\n\n :param table:\n :type table: BQTable\n \"\"\"\n if not self.dataset_exists(table.dataset):\n return False\n\n try:\n self.client.tables().get(projectId=table.project_id,\n datasetId=table.dataset_id,\n tableId=table.table_id).execute()\n except http.HttpError as ex:\n if ex.resp.status == 404:\n return False\n raise\n\n return True": 1628, "def run_func(entry):\n \"\"\"Runs the function associated with the given MenuEntry.\"\"\"\n if entry.func:\n if entry.args and entry.krgs:\n return entry.func(*entry.args, **entry.krgs)\n if entry.args:\n return entry.func(*entry.args)\n if entry.krgs:\n return entry.func(**entry.krgs)\n return entry.func()": 1629, "def peekiter(iterable):\n \"\"\"Return first row and also iterable with same items as original\"\"\"\n it = iter(iterable)\n one = next(it)\n\n def gen():\n \"\"\"Generator that returns first and proxy other items from source\"\"\"\n yield one\n while True:\n yield next(it)\n return (one, gen())": 1630, "def str_ripper(self, text):\n \"\"\"Got this code from here:\n http://stackoverflow.com/questions/6116978/python-replace-multiple-strings\n\n This method takes a set of strings, A, and removes all whole\n elements of set A from string B.\n\n Input: text string to strip based on instance attribute self.censor\n Output: a stripped (censored) text string\n \"\"\"\n return self.pattern.sub(lambda m: self.rep[re.escape(m.group(0))], text)": 1631, "def is_local_url(target):\n \"\"\"Determine if URL is safe to redirect to.\"\"\"\n ref_url = urlparse(request.host_url)\n test_url = urlparse(urljoin(request.host_url, target))\n return test_url.scheme in ('http', 'https') and \\\n ref_url.netloc == test_url.netloc": 1632, "def getSystemVariable(self, remote, name):\n \"\"\"Get single system variable from CCU / Homegear\"\"\"\n if self._server is not None:\n return self._server.getSystemVariable(remote, name)": 1633, "def _is_proper_sequence(seq):\n \"\"\"Returns is seq is sequence and not string.\"\"\"\n return (isinstance(seq, collections.abc.Sequence) and\n not isinstance(seq, str))": 1634, "def get_data_table(filename):\n \"\"\"Returns a DataTable instance built from either the filename, or STDIN if filename is None.\"\"\"\n with get_file_object(filename, \"r\") as rf:\n return DataTable(list(csv.reader(rf)))": 1635, "def is_image(filename):\n \"\"\"Determine if given filename is an image.\"\"\"\n # note: isfile() also accepts symlinks\n return os.path.isfile(filename) and filename.lower().endswith(ImageExts)": 1636, "def last_modified_date(filename):\n \"\"\"Last modified timestamp as a UTC datetime\"\"\"\n mtime = os.path.getmtime(filename)\n dt = datetime.datetime.utcfromtimestamp(mtime)\n return dt.replace(tzinfo=pytz.utc)": 1637, "def _check_methods(self, methods):\n \"\"\" @type methods: tuple \"\"\"\n for method in methods:\n if method not in self.ALLOWED_METHODS:\n raise Exception('Invalid \\'%s\\' method' % method)": 1638, "def timestamp_to_datetime(cls, time_stamp, localized=True):\n \"\"\" Converts a UTC timestamp to a datetime.datetime.\"\"\"\n ret = datetime.datetime.utcfromtimestamp(time_stamp)\n if localized:\n ret = localize(ret, pytz.utc)\n return ret": 1639, "def is_iterable_but_not_string(obj):\n \"\"\"\n Determine whether or not obj is iterable but not a string (eg, a list, set, tuple etc).\n \"\"\"\n return hasattr(obj, '__iter__') and not isinstance(obj, str) and not isinstance(obj, bytes)": 1640, "def validate(datum, schema, field=None, raise_errors=True):\n \"\"\"\n Determine if a python datum is an instance of a schema.\n\n Parameters\n ----------\n datum: Any\n Data being validated\n schema: dict\n Schema\n field: str, optional\n Record field being validated\n raise_errors: bool, optional\n If true, errors are raised for invalid data. If false, a simple\n True (valid) or False (invalid) result is returned\n\n\n Example::\n\n from fastavro.validation import validate\n schema = {...}\n record = {...}\n validate(record, schema)\n \"\"\"\n record_type = extract_record_type(schema)\n result = None\n\n validator = VALIDATORS.get(record_type)\n if validator:\n result = validator(datum, schema=schema,\n parent_ns=field,\n raise_errors=raise_errors)\n elif record_type in SCHEMA_DEFS:\n result = validate(datum,\n schema=SCHEMA_DEFS[record_type],\n field=field,\n raise_errors=raise_errors)\n else:\n raise UnknownType(record_type)\n\n if raise_errors and result is False:\n raise ValidationError(ValidationErrorData(datum, schema, field))\n\n return result": 1641, "def memory_used(self):\n \"\"\"To know the allocated memory at function termination.\n\n ..versionadded:: 4.1\n\n This property might return None if the function is still running.\n\n This function should help to show memory leaks or ram greedy code.\n \"\"\"\n if self._end_memory:\n memory_used = self._end_memory - self._start_memory\n return memory_used\n else:\n return None": 1642, "def __validate_email(self, email):\n \"\"\"Checks if a string looks like an email address\"\"\"\n\n e = re.match(self.EMAIL_ADDRESS_REGEX, email, re.UNICODE)\n if e:\n return email\n else:\n error = \"Invalid email address: \" + str(email)\n msg = self.GRIMOIRELAB_INVALID_FORMAT % {'error': error}\n raise InvalidFormatError(cause=msg)": 1643, "def is_readable_dir(path):\n \"\"\"Returns whether a path names an existing directory we can list and read files from.\"\"\"\n return os.path.isdir(path) and os.access(path, os.R_OK) and os.access(path, os.X_OK)": 1644, "def email_type(arg):\n\t\"\"\"An argparse type representing an email address.\"\"\"\n\tif not is_valid_email_address(arg):\n\t\traise argparse.ArgumentTypeError(\"{0} is not a valid email address\".format(repr(arg)))\n\treturn arg": 1645, "def SchemaValidate(self, xsd):\n \"\"\"Use W3C XSD schema to validate the document as it is\n processed. Activation is only possible before the first\n Read(). If @xsd is None, then XML Schema validation is\n deactivated. \"\"\"\n ret = libxml2mod.xmlTextReaderSchemaValidate(self._o, xsd)\n return ret": 1646, "def arg_bool(name, default=False):\n \"\"\" Fetch a query argument, as a boolean. \"\"\"\n v = request.args.get(name, '')\n if not len(v):\n return default\n return v in BOOL_TRUISH": 1647, "def check_auth(username, pwd):\n \"\"\"This function is called to check if a username /\n password combination is valid.\n \"\"\"\n cfg = get_current_config()\n return username == cfg[\"dashboard_httpauth\"].split(\n \":\")[0] and pwd == cfg[\"dashboard_httpauth\"].split(\":\")[1]": 1648, "def is_rpm_package_installed(pkg):\n \"\"\" checks if a particular rpm package is installed \"\"\"\n\n with settings(hide('warnings', 'running', 'stdout', 'stderr'),\n warn_only=True, capture=True):\n\n result = sudo(\"rpm -q %s\" % pkg)\n if result.return_code == 0:\n return True\n elif result.return_code == 1:\n return False\n else: # print error to user\n print(result)\n raise SystemExit()": 1649, "def is_valid_variable_name(string_to_check):\n \"\"\"\n Returns whether the provided name is a valid variable name in Python\n\n :param string_to_check: the string to be checked\n :return: True or False\n \"\"\"\n\n try:\n\n parse('{} = None'.format(string_to_check))\n return True\n\n except (SyntaxError, ValueError, TypeError):\n\n return False": 1650, "def _clean_str(self, s):\n \"\"\" Returns a lowercase string with punctuation and bad chars removed\n :param s: string to clean\n \"\"\"\n return s.translate(str.maketrans('', '', punctuation)).replace('\\u200b', \" \").strip().lower()": 1651, "def is_empty_object(n, last):\n \"\"\"n may be the inside of block or object\"\"\"\n if n.strip():\n return False\n # seems to be but can be empty code\n last = last.strip()\n markers = {\n ')',\n ';',\n }\n if not last or last[-1] in markers:\n return False\n return True": 1652, "def _validate_key(self, key):\n \"\"\"Returns a boolean indicating if the attribute name is valid or not\"\"\"\n return not any([key.startswith(i) for i in self.EXCEPTIONS])": 1653, "def check(self, var):\n \"\"\"Check whether the provided value is a valid enum constant.\"\"\"\n if not isinstance(var, _str_type): return False\n return _enum_mangle(var) in self._consts": 1654, "def set_value(self, value):\n \"\"\"Set value of the checkbox.\n\n Parameters\n ----------\n value : bool\n value for the checkbox\n\n \"\"\"\n if value:\n self.setChecked(Qt.Checked)\n else:\n self.setChecked(Qt.Unchecked)": 1655, "def install_handle_input(self):\n \"\"\"Install the hook.\"\"\"\n self.pointer = self.get_fptr()\n\n self.hooked = ctypes.windll.user32.SetWindowsHookExA(\n 13,\n self.pointer,\n ctypes.windll.kernel32.GetModuleHandleW(None),\n 0\n )\n if not self.hooked:\n return False\n return True": 1656, "def __eq__(self, other):\n \"\"\"Determine if two objects are equal.\"\"\"\n return isinstance(other, self.__class__) \\\n and self._freeze() == other._freeze()": 1657, "def chmod(f):\n \"\"\" change mod to writeable \"\"\"\n try:\n os.chmod(f, S_IWRITE) # windows (cover all)\n except Exception as e:\n pass\n try:\n os.chmod(f, 0o777) # *nix\n except Exception as e:\n pass": 1658, "def get_ctype(rtype, cfunc, *args):\n \"\"\" Call a C function that takes a pointer as its last argument and\n return the C object that it contains after the function has finished.\n\n :param rtype: C data type is filled by the function\n :param cfunc: C function to call\n :param args: Arguments to call function with\n :return: A pointer to the specified data type\n \"\"\"\n val_p = backend.ffi.new(rtype)\n args = args + (val_p,)\n cfunc(*args)\n return val_p[0]": 1659, "def clean_url(url):\n \"\"\"\n Remove params, query and fragment parts from URL so that `os.path.basename`\n and `os.path.splitext` can work correctly.\n\n @param url: URL to clean.\n @type url: str\n\n @return: Cleaned URL.\n @rtype: str\n \"\"\"\n parsed = urlparse(url.strip())\n reconstructed = ParseResult(\n parsed.scheme, parsed.netloc, parsed.path,\n params='', query='', fragment='')\n return reconstructed.geturl()": 1660, "def wrap(string, length, indent):\n \"\"\" Wrap a string at a line length \"\"\"\n newline = \"\\n\" + \" \" * indent\n return newline.join((string[i : i + length] for i in range(0, len(string), length)))": 1661, "def close_all():\n \"\"\"Close all open/active plotters\"\"\"\n for key, p in _ALL_PLOTTERS.items():\n p.close()\n _ALL_PLOTTERS.clear()\n return True": 1662, "def write_float(self, number):\n \"\"\" Writes a float to the underlying output file as a 4-byte value. \"\"\"\n buf = pack(self.byte_order + \"f\", number)\n self.write(buf)": 1663, "def _delete_whitespace(self):\n \"\"\"Delete all whitespace from the end of the line.\"\"\"\n while isinstance(self._lines[-1], (self._Space, self._LineBreak,\n self._Indent)):\n del self._lines[-1]": 1664, "def angle_between_vectors(x, y):\n \"\"\" Compute the angle between vector x and y \"\"\"\n dp = dot_product(x, y)\n if dp == 0:\n return 0\n xm = magnitude(x)\n ym = magnitude(y)\n return math.acos(dp / (xm*ym)) * (180. / math.pi)": 1665, "def socket_close(self):\n \"\"\"Close our socket.\"\"\"\n if self.sock != NC.INVALID_SOCKET:\n self.sock.close()\n self.sock = NC.INVALID_SOCKET": 1666, "def _close_websocket(self):\n \"\"\"Closes the websocket connection.\"\"\"\n close_method = getattr(self._websocket, \"close\", None)\n if callable(close_method):\n asyncio.ensure_future(close_method(), loop=self._event_loop)\n self._websocket = None\n self._dispatch_event(event=\"close\")": 1667, "def pickle_data(data, picklefile):\n \"\"\"Helper function to pickle `data` in `picklefile`.\"\"\"\n with open(picklefile, 'wb') as f:\n pickle.dump(data, f, protocol=2)": 1668, "def fit_select_best(X, y):\n \"\"\"\n Selects the best fit of the estimators already implemented by choosing the\n model with the smallest mean square error metric for the trained values.\n \"\"\"\n models = [fit(X,y) for fit in [fit_linear, fit_quadratic]]\n errors = map(lambda model: mse(y, model.predict(X)), models)\n\n return min(zip(models, errors), key=itemgetter(1))[0]": 1669, "def softmax(attrs, inputs, proto_obj):\n \"\"\"Softmax function.\"\"\"\n if 'axis' not in attrs:\n attrs = translation_utils._add_extra_attributes(attrs, {'axis': 1})\n return 'softmax', attrs, inputs": 1670, "def disable_wx(self):\n \"\"\"Disable event loop integration with wxPython.\n\n This merely sets PyOS_InputHook to NULL.\n \"\"\"\n if self._apps.has_key(GUI_WX):\n self._apps[GUI_WX]._in_event_loop = False\n self.clear_inputhook()": 1671, "def underline(self, msg):\n \"\"\"Underline the input\"\"\"\n return click.style(msg, underline=True) if self.colorize else msg": 1672, "def on_close(self, evt):\n \"\"\"\n Pop-up menu and wx.EVT_CLOSE closing event\n \"\"\"\n self.stop() # DoseWatcher\n if evt.EventObject is not self: # Avoid deadlocks\n self.Close() # wx.Frame\n evt.Skip()": 1673, "def series_table_row_offset(self, series):\n \"\"\"\n Return the number of rows preceding the data table for *series* in\n the Excel worksheet.\n \"\"\"\n title_and_spacer_rows = series.index * 2\n data_point_rows = series.data_point_offset\n return title_and_spacer_rows + data_point_rows": 1674, "def getChildElementsByTagName(self, tagName):\n \"\"\" Return child elements of type tagName if found, else [] \"\"\"\n result = []\n for child in self.childNodes:\n if isinstance(child, Element):\n if child.tagName == tagName:\n result.append(child)\n return result": 1675, "def mcc(y_true, y_pred, round=True):\n \"\"\"Matthews correlation coefficient\n \"\"\"\n y_true, y_pred = _mask_value_nan(y_true, y_pred)\n if round:\n y_true = np.round(y_true)\n y_pred = np.round(y_pred)\n return skm.matthews_corrcoef(y_true, y_pred)": 1676, "def from_file(cls, file_path, validate=True):\n \"\"\" Creates a Python object from a XML file\n\n :param file_path: Path to the XML file\n :param validate: XML should be validated against the embedded XSD definition\n :type validate: Boolean\n :returns: the Python object\n \"\"\"\n return xmlmap.load_xmlobject_from_file(file_path, xmlclass=cls, validate=validate)": 1677, "def kernelDriverActive(self, interface):\n \"\"\"\n Tell whether a kernel driver is active on given interface number.\n \"\"\"\n result = libusb1.libusb_kernel_driver_active(self.__handle, interface)\n if result == 0:\n return False\n elif result == 1:\n return True\n raiseUSBError(result)": 1678, "def schemaValidateFile(self, filename, options):\n \"\"\"Do a schemas validation of the given resource, it will use\n the SAX streamable validation internally. \"\"\"\n ret = libxml2mod.xmlSchemaValidateFile(self._o, filename, options)\n return ret": 1679, "def clear_globals_reload_modules(self):\n \"\"\"Clears globals and reloads modules\"\"\"\n\n self.code_array.clear_globals()\n self.code_array.reload_modules()\n\n # Clear result cache\n self.code_array.result_cache.clear()": 1680, "def prox_zero(X, step):\n \"\"\"Proximal operator to project onto zero\n \"\"\"\n return np.zeros(X.shape, dtype=X.dtype)": 1681, "def count_rows(self, table_name):\n \"\"\"Return the number of entries in a table by counting them.\"\"\"\n self.table_must_exist(table_name)\n query = \"SELECT COUNT (*) FROM `%s`\" % table_name.lower()\n self.own_cursor.execute(query)\n return int(self.own_cursor.fetchone()[0])": 1682, "def POINTER(obj):\n \"\"\"\n Create ctypes pointer to object.\n\n Notes\n -----\n This function converts None to a real NULL pointer because of bug\n in how ctypes handles None on 64-bit platforms.\n\n \"\"\"\n\n p = ctypes.POINTER(obj)\n if not isinstance(p.from_param, classmethod):\n def from_param(cls, x):\n if x is None:\n return cls()\n else:\n return x\n p.from_param = classmethod(from_param)\n\n return p": 1683, "def cleanup_lib(self):\n \"\"\" unload the previously loaded shared library \"\"\"\n if not self.using_openmp:\n #this if statement is necessary because shared libraries that use\n #OpenMP will core dump when unloaded, this is a well-known issue with OpenMP\n logging.debug('unloading shared library')\n _ctypes.dlclose(self.lib._handle)": 1684, "def negate(self):\n \"\"\"Reverse the range\"\"\"\n self.from_value, self.to_value = self.to_value, self.from_value\n self.include_lower, self.include_upper = self.include_upper, self.include_lower": 1685, "def get_resource_attribute(self, attr):\n \"\"\"Gets the resource attribute if available\n\n :param attr: Name of the attribute\n :return: Value of the attribute, if set in the resource. None otherwise\n \"\"\"\n if attr not in self.resource_attributes:\n raise KeyError(\"%s is not in resource attributes\" % attr)\n\n return self.resource_attributes[attr]": 1686, "def run(self):\n \"\"\"Run the event loop.\"\"\"\n self.signal_init()\n self.listen_init()\n self.logger.info('starting')\n self.loop.start()": 1687, "def _ram_buffer(self):\n \"\"\"Setup the RAM buffer from the C++ code.\"\"\"\n # get the address of the RAM\n address = _LIB.Memory(self._env)\n # create a buffer from the contents of the address location\n buffer_ = ctypes.cast(address, ctypes.POINTER(RAM_VECTOR)).contents\n # create a NumPy array from the buffer\n return np.frombuffer(buffer_, dtype='uint8')": 1688, "def _swap_curly(string):\n \"\"\"Swap single and double curly brackets\"\"\"\n return (\n string.replace('{{ ', '{{').replace('{{', '\\x00').replace('{', '{{')\n .replace('\\x00', '{').replace(' }}', '}}').replace('}}', '\\x00')\n .replace('}', '}}').replace('\\x00', '}')\n )": 1689, "def _int64_feature(value):\n \"\"\"Wrapper for inserting int64 features into Example proto.\"\"\"\n if not isinstance(value, list):\n value = [value]\n return tf.train.Feature(int64_list=tf.train.Int64List(value=value))": 1690, "def now_time(str=False):\n \"\"\"Get the current time.\"\"\"\n if str:\n return datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n return datetime.datetime.now()": 1691, "def home(self):\n \"\"\"Set cursor to initial position and reset any shifting.\"\"\"\n self.command(c.LCD_RETURNHOME)\n self._cursor_pos = (0, 0)\n c.msleep(2)": 1692, "def _getTypename(self, defn):\n \"\"\" Returns the SQL typename required to store the given FieldDefinition \"\"\"\n return 'REAL' if defn.type.float or 'TIME' in defn.type.name or defn.dntoeu else 'INTEGER'": 1693, "def INIT_LIST_EXPR(self, cursor):\n \"\"\"Returns a list of literal values.\"\"\"\n values = [self.parse_cursor(child)\n for child in list(cursor.get_children())]\n return values": 1694, "def cio_close(cio):\n \"\"\"Wraps openjpeg library function cio_close.\n \"\"\"\n OPENJPEG.opj_cio_close.argtypes = [ctypes.POINTER(CioType)]\n OPENJPEG.opj_cio_close(cio)": 1695, "def remove_trailing_string(content, trailing):\n \"\"\"\n Strip trailing component `trailing` from `content` if it exists.\n Used when generating names from view classes.\n \"\"\"\n if content.endswith(trailing) and content != trailing:\n return content[:-len(trailing)]\n return content": 1696, "def format_vars(args):\n \"\"\"Format the given vars in the form: 'flag=value'\"\"\"\n variables = []\n for key, value in args.items():\n if value:\n variables += ['{0}={1}'.format(key, value)]\n return variables": 1697, "def kill_dashboard(self, check_alive=True):\n \"\"\"Kill the dashboard.\n\n Args:\n check_alive (bool): Raise an exception if the process was already\n dead.\n \"\"\"\n self._kill_process_type(\n ray_constants.PROCESS_TYPE_DASHBOARD, check_alive=check_alive)": 1698, "def cat_acc(y_true, y_pred):\n \"\"\"Categorical accuracy\n \"\"\"\n return np.mean(y_true.argmax(axis=1) == y_pred.argmax(axis=1))": 1699, "def string_to_date(value):\n \"\"\"\n Return a Python date that corresponds to the specified string\n representation.\n\n @param value: string representation of a date.\n\n @return: an instance ``datetime.datetime`` represented by the string.\n \"\"\"\n if isinstance(value, datetime.date):\n return value\n\n return dateutil.parser.parse(value).date()": 1700, "def softplus(attrs, inputs, proto_obj):\n \"\"\"Applies the sofplus activation function element-wise to the input.\"\"\"\n new_attrs = translation_utils._add_extra_attributes(attrs, {'act_type' : 'softrelu'})\n return 'Activation', new_attrs, inputs": 1701, "def isoformat(dt):\n \"\"\"Return an ISO-8601 formatted string from the provided datetime object\"\"\"\n if not isinstance(dt, datetime.datetime):\n raise TypeError(\"Must provide datetime.datetime object to isoformat\")\n\n if dt.tzinfo is None:\n raise ValueError(\"naive datetime objects are not allowed beyond the library boundaries\")\n\n return dt.isoformat().replace(\"+00:00\", \"Z\")": 1702, "def print_with_header(header, message, color, indent=0):\n \"\"\"\n Use one of the functions below for printing, not this one.\n \"\"\"\n print()\n padding = ' ' * indent\n print(padding + color + BOLD + header + ENDC + color + message + ENDC)": 1703, "def from_timestamp(microsecond_timestamp):\n \"\"\"Convert a microsecond timestamp to a UTC datetime instance.\"\"\"\n # Create datetime without losing precision from floating point (yes, this\n # is actually needed):\n return datetime.datetime.fromtimestamp(\n microsecond_timestamp // 1000000, datetime.timezone.utc\n ).replace(microsecond=(microsecond_timestamp % 1000000))": 1704, "def calculate_top_margin(self):\n\t\t\"\"\"\n\t\tCalculate the margin in pixels above the plot area, setting\n\t\tborder_top.\n\t\t\"\"\"\n\t\tself.border_top = 5\n\t\tif self.show_graph_title:\n\t\t\tself.border_top += self.title_font_size\n\t\tself.border_top += 5\n\t\tif self.show_graph_subtitle:\n\t\t\tself.border_top += self.subtitle_font_size": 1705, "def timestamp_from_datetime(dt):\n \"\"\"\n Compute timestamp from a datetime object that could be timezone aware\n or unaware.\n \"\"\"\n try:\n utc_dt = dt.astimezone(pytz.utc)\n except ValueError:\n utc_dt = dt.replace(tzinfo=pytz.utc)\n return timegm(utc_dt.timetuple())": 1706, "def _DateToEpoch(date):\n \"\"\"Converts python datetime to epoch microseconds.\"\"\"\n tz_zero = datetime.datetime.utcfromtimestamp(0)\n diff_sec = int((date - tz_zero).total_seconds())\n return diff_sec * 1000000": 1707, "def created_today(self):\n \"\"\"Return True if created today.\"\"\"\n if self.datetime.date() == datetime.today().date():\n return True\n return False": 1708, "def monthly(date=datetime.date.today()):\n \"\"\"\n Take a date object and return the first day of the month.\n \"\"\"\n return datetime.date(date.year, date.month, 1)": 1709, "def update_dict(obj, dict, attributes):\n \"\"\"Update dict with fields from obj.attributes.\n\n :param obj: the object updated into dict\n :param dict: the result dictionary\n :param attributes: a list of attributes belonging to obj\n \"\"\"\n for attribute in attributes:\n if hasattr(obj, attribute) and getattr(obj, attribute) is not None:\n dict[attribute] = getattr(obj, attribute)": 1710, "def _default(self, obj):\n \"\"\" return a serialized version of obj or raise a TypeError\n\n :param obj:\n :return: Serialized version of obj\n \"\"\"\n return obj.__dict__ if isinstance(obj, JsonObj) else json.JSONDecoder().decode(obj)": 1711, "def getpackagepath():\n \"\"\"\n *Get the root path for this python package - used in unit testing code*\n \"\"\"\n moduleDirectory = os.path.dirname(__file__)\n packagePath = os.path.dirname(__file__) + \"/../\"\n\n return packagePath": 1712, "def print_args(output=sys.stdout):\n \"\"\"Decorate a function so that print arguments before calling it.\n\n Args:\n output: writable to print args. (Default: sys.stdout)\n \"\"\"\n def decorator(func):\n \"\"\"The decorator function.\n \"\"\"\n @wraps(func)\n def _(*args, **kwargs):\n \"\"\"The decorated function.\n \"\"\"\n output.write(\n \"Args: {0}, KwArgs: {1}\\n\".format(str(args), str(kwargs)))\n return func(*args, **kwargs)\n return _\n return decorator": 1713, "def generator_to_list(fn):\n \"\"\"This decorator is for flat_list function.\n It converts returned generator to list.\n \"\"\"\n def wrapper(*args, **kw):\n return list(fn(*args, **kw))\n return wrapper": 1714, "def strip_figures(figure):\n\t\"\"\"\n\tStrips a figure into multiple figures with a trace on each of them\n\n\tParameters:\n\t-----------\n\t\tfigure : Figure\n\t\t\tPlotly Figure\n\t\"\"\"\n\tfig=[]\n\tfor trace in figure['data']:\n\t\tfig.append(dict(data=[trace],layout=figure['layout']))\n\treturn fig": 1715, "def Square(x, a, b, c):\n \"\"\"Second order polynomial\n\n Inputs:\n -------\n ``x``: independent variable\n ``a``: coefficient of the second-order term\n ``b``: coefficient of the first-order term\n ``c``: additive constant\n\n Formula:\n --------\n ``a*x^2 + b*x + c``\n \"\"\"\n return a * x ** 2 + b * x + c": 1716, "def parameter_vector(self):\n \"\"\"An array of all parameters (including frozen parameters)\"\"\"\n return np.array([getattr(self, k) for k in self.parameter_names])": 1717, "def position(self, x, y, text):\n \"\"\"\n ANSI Escape sequences\n http://ascii-table.com/ansi-escape-sequences.php\n \"\"\"\n sys.stdout.write(\"\\x1b7\\x1b[%d;%df%s\\x1b8\" % (x, y, text))\n sys.stdout.flush()": 1718, "def transform(self, df):\n \"\"\"\n Transforms a DataFrame in place. Computes all outputs of the DataFrame.\n\n Args:\n df (pandas.DataFrame): DataFrame to transform.\n \"\"\"\n for name, function in self.outputs:\n df[name] = function(df)": 1719, "def delete(self, name):\n \"\"\"Delete object on remote\"\"\"\n obj = self._get_object(name)\n if obj:\n return self.driver.delete_object(obj)": 1720, "def desc(self):\n \"\"\"Get a short description of the device.\"\"\"\n return '{0} (ID: {1}) - {2} - {3}'.format(\n self.name, self.device_id, self.type, self.status)": 1721, "def filter(self, obj, *args, **kwargs):\n \"\"\"\n Filter the given object through the filter chain.\n\n :param obj: The object to filter\n :param args: Additional arguments to pass to each filter function.\n :param kwargs: Additional keyword arguments to pass to each filter\n function.\n :return: The filtered object or :data:`None`\n\n See the documentation of :class:`Filter` on how filtering operates.\n\n Returns the object returned by the last function in the filter chain or\n :data:`None` if any function returned :data:`None`.\n \"\"\"\n for _, _, func in self._filter_order:\n obj = func(obj, *args, **kwargs)\n if obj is None:\n return None\n return obj": 1722, "def fft(t, y, pow2=False, window=None, rescale=False):\n \"\"\"\n FFT of y, assuming complex or real-valued inputs. This goes through the \n numpy fourier transform process, assembling and returning (frequencies, \n complex fft) given time and signal data y.\n\n Parameters\n ----------\n t,y\n Time (t) and signal (y) arrays with which to perform the fft. Note the t\n array is assumed to be evenly spaced.\n \n pow2 = False\n Set this to true if you only want to keep the first 2^n data\n points (speeds up the FFT substantially)\n\n window = None\n Can be set to any of the windowing functions in numpy that require only\n the number of points as the argument, e.g. window='hanning'. \n \n rescale = False\n If True, the FFT will be rescaled by the square root of the ratio of \n variances before and after windowing, such that the sum of component \n amplitudes squared is equal to the actual variance.\n \"\"\"\n # make sure they're numpy arrays, and make copies to avoid the referencing error\n y = _n.array(y)\n t = _n.array(t)\n\n # if we're doing the power of 2, do it\n if pow2:\n keep = 2**int(_n.log2(len(y)))\n\n # now resize the data\n y.resize(keep)\n t.resize(keep)\n\n # Window the data\n if not window in [None, False, 0]:\n try:\n # Get the windowing array\n w = eval(\"_n.\"+window, dict(_n=_n))(len(y))\n \n # Store the original variance\n v0 = _n.average(abs(y)**2)\n \n # window the time domain data \n y = y * w\n \n # Rescale by the variance ratio\n if rescale: y = y * _n.sqrt(v0 / _n.average(abs(y)**2))\n \n except:\n print(\"ERROR: Bad window!\")\n return\n\n # do the actual fft, and normalize\n Y = _n.fft.fftshift( _n.fft.fft(y) / len(t) )\n f = _n.fft.fftshift( _n.fft.fftfreq(len(t), t[1]-t[0]) )\n \n return f, Y": 1723, "def click_estimate_slope():\n \"\"\"\n Takes two clicks and returns the slope.\n\n Right-click aborts.\n \"\"\"\n\n c1 = _pylab.ginput()\n if len(c1)==0:\n return None\n\n c2 = _pylab.ginput()\n if len(c2)==0:\n return None\n\n return (c1[0][1]-c2[0][1])/(c1[0][0]-c2[0][0])": 1724, "def _update_index_on_df(df, index_names):\n \"\"\"Helper function to restore index information after collection. Doesn't\n use self so we can serialize this.\"\"\"\n if index_names:\n df = df.set_index(index_names)\n # Remove names from unnamed indexes\n index_names = _denormalize_index_names(index_names)\n df.index.names = index_names\n return df": 1725, "def is_function(self):\n \"\"\"return True if callback is a vanilla plain jane function\"\"\"\n if self.is_instance() or self.is_class(): return False\n return isinstance(self.callback, (Callable, classmethod))": 1726, "def build_and_start(query, directory):\n \"\"\"This function will create and then start a new Async task with the\n default callbacks argument defined in the decorator.\"\"\"\n\n Async(target=grep, args=[query, directory]).start()": 1727, "def _string_width(self, s):\n \"\"\"Get width of a string in the current font\"\"\"\n s = str(s)\n w = 0\n for char in s:\n char = ord(char)\n w += self.character_widths[char]\n return w * self.font_size / 1000.0": 1728, "def is_subdir(a, b):\n \"\"\"\n Return true if a is a subdirectory of b\n \"\"\"\n a, b = map(os.path.abspath, [a, b])\n\n return os.path.commonpath([a, b]) == b": 1729, "def seaborn_bar_(self, label=None, style=None, opts=None):\n \"\"\"\n Get a Seaborn bar chart\n \"\"\"\n try:\n fig = sns.barplot(self.x, self.y, palette=\"BuGn_d\")\n return fig\n except Exception as e:\n self.err(e, self.seaborn_bar_,\n \"Can not get Seaborn bar chart object\")": 1730, "def getFileDialogTitle(msg, title):\n \"\"\"\n Create nicely-formatted string based on arguments msg and title\n :param msg: the msg to be displayed\n :param title: the window title\n :return: None\n \"\"\"\n if msg and title:\n return \"%s - %s\" % (title, msg)\n if msg and not title:\n return str(msg)\n if title and not msg:\n return str(title)\n return None": 1731, "def img_encode(arr, **kwargs):\n \"\"\"Encode ndarray to base64 string image data\n \n Parameters\n ----------\n arr: ndarray (rows, cols, depth)\n kwargs: passed directly to matplotlib.image.imsave\n \"\"\"\n sio = BytesIO()\n imsave(sio, arr, **kwargs)\n sio.seek(0)\n img_format = kwargs['format'] if kwargs.get('format') else 'png'\n img_str = base64.b64encode(sio.getvalue()).decode()\n\n return 'data:image/{};base64,{}'.format(img_format, img_str)": 1732, "def _check_conversion(key, valid_dict):\n \"\"\"Check for existence of key in dict, return value or raise error\"\"\"\n if key not in valid_dict and key not in valid_dict.values():\n # Only show users the nice string values\n keys = [v for v in valid_dict.keys() if isinstance(v, string_types)]\n raise ValueError('value must be one of %s, not %s' % (keys, key))\n return valid_dict[key] if key in valid_dict else key": 1733, "def get_single_item(d):\n \"\"\"Get an item from a dict which contains just one item.\"\"\"\n assert len(d) == 1, 'Single-item dict must have just one item, not %d.' % len(d)\n return next(six.iteritems(d))": 1734, "def bounding_box_from(points, i, i1, thr):\n \"\"\"Creates bounding box for a line segment\n\n Args:\n points (:obj:`list` of :obj:`Point`)\n i (int): Line segment start, index in points array\n i1 (int): Line segment end, index in points array\n Returns:\n (float, float, float, float): with bounding box min x, min y, max x and max y\n \"\"\"\n pi = points[i]\n pi1 = points[i1]\n\n min_lat = min(pi.lat, pi1.lat)\n min_lon = min(pi.lon, pi1.lon)\n max_lat = max(pi.lat, pi1.lat)\n max_lon = max(pi.lon, pi1.lon)\n\n return min_lat-thr, min_lon-thr, max_lat+thr, max_lon+thr": 1735, "def swap(self):\n \"\"\"Return the box (for horizontal graphs)\"\"\"\n self.xmin, self.ymin = self.ymin, self.xmin\n self.xmax, self.ymax = self.ymax, self.xmax": 1736, "def tob(data, enc='utf8'):\n \"\"\" Convert anything to bytes \"\"\"\n return data.encode(enc) if isinstance(data, six.text_type) else bytes(data)": 1737, "def CleanseComments(line):\n \"\"\"Removes //-comments and single-line C-style /* */ comments.\n\n Args:\n line: A line of C++ source.\n\n Returns:\n The line with single-line comments removed.\n \"\"\"\n commentpos = line.find('//')\n if commentpos != -1 and not IsCppString(line[:commentpos]):\n line = line[:commentpos].rstrip()\n # get rid of /* ... */\n return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)": 1738, "def set_history_file(self, path):\n \"\"\"Set path to history file. \"\" produces no file.\"\"\"\n if path:\n self.history = prompt_toolkit.history.FileHistory(fixpath(path))\n else:\n self.history = prompt_toolkit.history.InMemoryHistory()": 1739, "def Distance(lat1, lon1, lat2, lon2):\n \"\"\"Get distance between pairs of lat-lon points\"\"\"\n\n az12, az21, dist = wgs84_geod.inv(lon1, lat1, lon2, lat2)\n return az21, dist": 1740, "def getMaxAffiliationInstanceID():\n \"\"\"\n\n Returns\n -------\n maximum value of the Primary key from the table \"django-tethne_affiliation_instance\"\n This is used to calculate the next id for primary key.\n\n if the table is empty, 0 is returned\n\n \"\"\"\n dbconnectionhanlder = DBConnection()\n dbconnectionhanlder.cursor.execute(\"SELECT max(id) from `django-tethne_affiliation_instance`\")\n rows = dbconnectionhanlder.cursor.fetchall()\n dbconnectionhanlder.conn.close()\n if rows[0][0] is None:\n return 0\n else:\n return rows[0][0]": 1741, "def var(series):\n \"\"\"\n Returns the variance of values in a series.\n\n Args:\n series (pandas.Series): column to summarize.\n \"\"\"\n if np.issubdtype(series.dtype, np.number):\n return series.var()\n else:\n return np.nan": 1742, "def handle_m2m_user(self, sender, instance, **kwargs):\n \"\"\" Handle many to many relationships for user field \"\"\"\n self.handle_save(instance.user.__class__, instance.user)": 1743, "def maxId(self):\n \"\"\"int: current max id of objects\"\"\"\n if len(self.model.db) == 0:\n return 0\n\n return max(map(lambda obj: obj[\"id\"], self.model.db))": 1744, "def lsem (inlist):\n \"\"\"\nReturns the estimated standard error of the mean (sx-bar) of the\nvalues in the passed list. sem = stdev / sqrt(n)\n\nUsage: lsem(inlist)\n\"\"\"\n sd = stdev(inlist)\n n = len(inlist)\n return sd/math.sqrt(n)": 1745, "def import_js(path, lib_name, globals):\n \"\"\"Imports from javascript source file.\n globals is your globals()\"\"\"\n with codecs.open(path_as_local(path), \"r\", \"utf-8\") as f:\n js = f.read()\n e = EvalJs()\n e.execute(js)\n var = e.context['var']\n globals[lib_name] = var.to_python()": 1746, "def parse_code(url):\n \"\"\"\n Parse the code parameter from the a URL\n\n :param str url: URL to parse\n :return: code query parameter\n :rtype: str\n \"\"\"\n result = urlparse(url)\n query = parse_qs(result.query)\n return query['code']": 1747, "def __call__(self, args):\n \"\"\"Execute the user function.\"\"\"\n window, ij = args\n return self.user_func(srcs, window, ij, global_args), window": 1748, "def release(self):\n \"\"\"\n Releases this resource back to the pool it came from.\n \"\"\"\n if self.errored:\n self.pool.delete_resource(self)\n else:\n self.pool.release(self)": 1749, "def _rm_name_match(s1, s2):\n \"\"\"\n determine whether two sequence names from a repeatmasker alignment match.\n\n :return: True if they are the same string, or if one forms a substring of the\n other, else False\n \"\"\"\n m_len = min(len(s1), len(s2))\n return s1[:m_len] == s2[:m_len]": 1750, "def pull_stream(image):\n \"\"\"\n Return generator of pull status objects\n \"\"\"\n return (json.loads(s) for s in _get_docker().pull(image, stream=True))": 1751, "def _composed_doc(fs):\n \"\"\"\n Generate a docstring for the composition of fs.\n \"\"\"\n if not fs:\n # Argument name for the docstring.\n return 'n'\n\n return '{f}({g})'.format(f=fs[0].__name__, g=_composed_doc(fs[1:]))": 1752, "def date_to_datetime(x):\n \"\"\"Convert a date into a datetime\"\"\"\n if not isinstance(x, datetime) and isinstance(x, date):\n return datetime.combine(x, time())\n return x": 1753, "def unpickle_file(picklefile, **kwargs):\n \"\"\"Helper function to unpickle data from `picklefile`.\"\"\"\n with open(picklefile, 'rb') as f:\n return pickle.load(f, **kwargs)": 1754, "def unpatch(obj, name):\n \"\"\"\n Undo the effects of patch(func, obj, name)\n \"\"\"\n setattr(obj, name, getattr(obj, name).original)": 1755, "def draw(graph, fname):\n \"\"\"Draw a graph and save it into a file\"\"\"\n ag = networkx.nx_agraph.to_agraph(graph)\n ag.draw(fname, prog='dot')": 1756, "def items(iterable):\n \"\"\"\n Iterates over the items of a sequence. If the sequence supports the\n dictionary protocol (iteritems/items) then we use that. Otherwise\n we use the enumerate built-in function.\n \"\"\"\n if hasattr(iterable, 'iteritems'):\n return (p for p in iterable.iteritems())\n elif hasattr(iterable, 'items'):\n return (p for p in iterable.items())\n else:\n return (p for p in enumerate(iterable))": 1757, "def to_json(obj):\n \"\"\"Return a json string representing the python object obj.\"\"\"\n i = StringIO.StringIO()\n w = Writer(i, encoding='UTF-8')\n w.write_value(obj)\n return i.getvalue()": 1758, "def _from_dict(cls, _dict):\n \"\"\"Initialize a KeyValuePair object from a json dictionary.\"\"\"\n args = {}\n if 'key' in _dict:\n args['key'] = Key._from_dict(_dict.get('key'))\n if 'value' in _dict:\n args['value'] = Value._from_dict(_dict.get('value'))\n return cls(**args)": 1759, "def _cdf(self, xloc, dist, base, cache):\n \"\"\"Cumulative distribution function.\"\"\"\n return evaluation.evaluate_forward(dist, base**xloc, cache=cache)": 1760, "def parallel(processes, threads):\n \"\"\"\n execute jobs in processes using N threads\n \"\"\"\n pool = multithread(threads)\n pool.map(run_process, processes)\n pool.close()\n pool.join()": 1761, "def _kw(keywords):\n \"\"\"Turn list of keywords into dictionary.\"\"\"\n r = {}\n for k, v in keywords:\n r[k] = v\n return r": 1762, "def to_snake_case(text):\n \"\"\"Convert to snake case.\n\n :param str text:\n :rtype: str\n :return:\n \"\"\"\n s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', text)\n return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()": 1763, "def add_index_alias(es, index_name, alias_name):\n \"\"\"Add index alias to index_name\"\"\"\n\n es.indices.put_alias(index=index_name, name=terms_alias)": 1764, "def index(obj, index=INDEX_NAME, doc_type=DOC_TYPE):\n \"\"\"\n Index the given document.\n\n https://elasticsearch-py.readthedocs.io/en/master/api.html#elasticsearch.Elasticsearch.index\n https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html\n \"\"\"\n doc = to_dict(obj)\n\n if doc is None:\n return\n\n id = doc.pop('id')\n\n return es_conn.index(index, doc_type, doc, id=id)": 1765, "def iterparse(source, tag, clear=False, events=None):\n \"\"\"\n iterparse variant that supports 'tag' parameter (like lxml),\n yields elements and clears nodes after parsing.\n \"\"\"\n for event, elem in ElementTree.iterparse(source, events=events):\n if elem.tag == tag:\n yield elem\n if clear:\n elem.clear()": 1766, "def is_rfc2822(instance: str):\n \"\"\"Validates RFC2822 format\"\"\"\n if not isinstance(instance, str):\n return True\n return email.utils.parsedate(instance) is not None": 1767, "def b(s):\n\t\"\"\" Encodes Unicode strings to byte strings, if necessary. \"\"\"\n\n\treturn s if isinstance(s, bytes) else s.encode(locale.getpreferredencoding())": 1768, "def _check_color_dim(val):\n \"\"\"Ensure val is Nx(n_col), usually Nx3\"\"\"\n val = np.atleast_2d(val)\n if val.shape[1] not in (3, 4):\n raise RuntimeError('Value must have second dimension of size 3 or 4')\n return val, val.shape[1]": 1769, "def aug_sysargv(cmdstr):\n \"\"\" DEBUG FUNC modify argv to look like you ran a command \"\"\"\n import shlex\n argv = shlex.split(cmdstr)\n sys.argv.extend(argv)": 1770, "def getpass(self, prompt, default=None):\n \"\"\"Provide a password prompt.\"\"\"\n return click.prompt(prompt, hide_input=True, default=default)": 1771, "def unpack_out(self, name):\n return self.parse(\"\"\"\n $enum = $enum_class($value.value)\n \"\"\", enum_class=self._import_type(), value=name)[\"enum\"]": 1772, "def _set_widget_background_color(widget, color):\n \"\"\"\n Changes the base color of a widget (background).\n :param widget: widget to modify\n :param color: the color to apply\n \"\"\"\n pal = widget.palette()\n pal.setColor(pal.Base, color)\n widget.setPalette(pal)": 1773, "def get_mi_vec(slab):\n \"\"\"\n Convenience function which returns the unit vector aligned\n with the miller index.\n \"\"\"\n mvec = np.cross(slab.lattice.matrix[0], slab.lattice.matrix[1])\n return mvec / np.linalg.norm(mvec)": 1774, "def c2f(r, i, ctype_name):\n \"\"\"\n Convert strings to complex number instance with specified numpy type.\n \"\"\"\n\n ftype = c2f_dict[ctype_name]\n return np.typeDict[ctype_name](ftype(r) + 1j * ftype(i))": 1775, "def contained_in(filename, directory):\n \"\"\"Test if a file is located within the given directory.\"\"\"\n filename = os.path.normcase(os.path.abspath(filename))\n directory = os.path.normcase(os.path.abspath(directory))\n return os.path.commonprefix([filename, directory]) == directory": 1776, "def is_collection(obj):\n \"\"\"Tests if an object is a collection.\"\"\"\n\n col = getattr(obj, '__getitem__', False)\n val = False if (not col) else True\n\n if isinstance(obj, basestring):\n val = False\n\n return val": 1777, "def log_exception(exc_info=None, stream=None):\n \"\"\"Log the 'exc_info' tuple in the server log.\"\"\"\n exc_info = exc_info or sys.exc_info()\n stream = stream or sys.stderr\n try:\n from traceback import print_exception\n print_exception(exc_info[0], exc_info[1], exc_info[2], None, stream)\n stream.flush()\n finally:\n exc_info = None": 1778, "def __init__(self, filename, formatting_info=False, handle_ambiguous_date=None):\n \"\"\"Initialize the ExcelWorkbook instance.\"\"\"\n super().__init__(filename)\n self.workbook = xlrd.open_workbook(self.filename, formatting_info=formatting_info)\n self.handle_ambiguous_date = handle_ambiguous_date": 1779, "def handle_exception(error):\n \"\"\"Simple method for handling exceptions raised by `PyBankID`.\n\n :param flask_pybankid.FlaskPyBankIDError error: The exception to handle.\n :return: The exception represented as a dictionary.\n :rtype: dict\n\n \"\"\"\n response = jsonify(error.to_dict())\n response.status_code = error.status_code\n return response": 1780, "def timedcall(executable_function, *args):\n \"\"\"!\n @brief Executes specified method or function with measuring of execution time.\n \n @param[in] executable_function (pointer): Pointer to function or method.\n @param[in] args (*): Arguments of called function or method.\n \n @return (tuple) Execution time and result of execution of function or method (execution_time, result_execution).\n \n \"\"\"\n \n time_start = time.clock();\n result = executable_function(*args);\n time_end = time.clock();\n \n return (time_end - time_start, result);": 1781, "def is_list_of_list(item):\n \"\"\"\n check whether the item is list (tuple)\n and consist of list (tuple) elements\n \"\"\"\n if (\n type(item) in (list, tuple)\n and len(item)\n and isinstance(item[0], (list, tuple))\n ):\n return True\n return False": 1782, "def is_nullable_list(val, vtype):\n \"\"\"Return True if list contains either values of type `vtype` or None.\"\"\"\n return (isinstance(val, list) and\n any(isinstance(v, vtype) for v in val) and\n all((isinstance(v, vtype) or v is None) for v in val))": 1783, "def _expand(self, str, local_vars={}):\n \"\"\"Expand $vars in a string.\"\"\"\n return ninja_syntax.expand(str, self.vars, local_vars)": 1784, "def task_property_present_predicate(service, task, prop):\n \"\"\" True if the json_element passed is present for the task specified.\n \"\"\"\n try:\n response = get_service_task(service, task)\n except Exception as e:\n pass\n\n return (response is not None) and (prop in response)": 1785, "def _merge_args_with_kwargs(args_dict, kwargs_dict):\n \"\"\"Merge args with kwargs.\"\"\"\n ret = args_dict.copy()\n ret.update(kwargs_dict)\n return ret": 1786, "def unique_everseen(seq):\n \"\"\"Solution found here : http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order\"\"\"\n seen = set()\n seen_add = seen.add\n return [x for x in seq if not (x in seen or seen_add(x))]": 1787, "def test_for_image(self, cat, img):\n \"\"\"Tests if image img in category cat exists\"\"\"\n return self.test_for_category(cat) and img in self.items[cat]": 1788, "def is_string(obj):\n \"\"\"Is this a string.\n\n :param object obj:\n :rtype: bool\n \"\"\"\n if PYTHON3:\n str_type = (bytes, str)\n else:\n str_type = (bytes, str, unicode)\n return isinstance(obj, str_type)": 1789, "def parse_float_literal(ast, _variables=None):\n \"\"\"Parse a float value node in the AST.\"\"\"\n if isinstance(ast, (FloatValueNode, IntValueNode)):\n return float(ast.value)\n return INVALID": 1790, "def is_int(string):\n \"\"\"\n Checks if a string is an integer. If the string value is an integer\n return True, otherwise return False. \n \n Args:\n string: a string to test.\n\n Returns: \n boolean\n \"\"\"\n try:\n a = float(string)\n b = int(a)\n except ValueError:\n return False\n else:\n return a == b": 1791, "def stft(func=None, **kwparams):\n \"\"\"\n Short Time Fourier Transform for real data keeping the full FFT block.\n\n Same to the default STFT strategy, but with new defaults. This is the same\n to:\n\n .. code-block:: python\n\n stft.base(transform=numpy.fft.fft,\n inverse_transform=lambda *args: numpy.fft.ifft(*args).real)\n\n See ``stft.base`` docs for more.\n \"\"\"\n from numpy.fft import fft, ifft\n ifft_r = lambda *args: ifft(*args).real\n return stft.base(transform=fft, inverse_transform=ifft_r)(func, **kwparams)": 1792, "def getvariable(name):\n \"\"\"Get the value of a local variable somewhere in the call stack.\"\"\"\n import inspect\n fr = inspect.currentframe()\n try:\n while fr:\n fr = fr.f_back\n vars = fr.f_locals\n if name in vars:\n return vars[name]\n except:\n pass\n return None": 1793, "def get_time(filename):\n\t\"\"\"\n\tGet the modified time for a file as a datetime instance\n\t\"\"\"\n\tts = os.stat(filename).st_mtime\n\treturn datetime.datetime.utcfromtimestamp(ts)": 1794, "def check_empty_dict(GET_dict):\n \"\"\"\n Returns True if the GET querstring contains on values, but it can contain\n empty keys.\n This is better than doing not bool(request.GET) as an empty key will return\n True\n \"\"\"\n empty = True\n for k, v in GET_dict.items():\n # Don't disable on p(age) or 'all' GET param\n if v and k != 'p' and k != 'all':\n empty = False\n return empty": 1795, "def open_file(file, mode):\n\t\"\"\"Open a file.\n\n\t:arg file: file-like or path-like object.\n\t:arg str mode: ``mode`` argument for :func:`open`.\n\t\"\"\"\n\tif hasattr(file, \"read\"):\n\t\treturn file\n\tif hasattr(file, \"open\"):\n\t\treturn file.open(mode)\n\treturn open(file, mode)": 1796, "def rewindbody(self):\n \"\"\"Rewind the file to the start of the body (if seekable).\"\"\"\n if not self.seekable:\n raise IOError, \"unseekable file\"\n self.fp.seek(self.startofbody)": 1797, "def _check_2d_shape(X):\n \"\"\"Check shape of array or sparse matrix.\n\n Assure that X is always 2D: Unlike numpy we always deal with 2D arrays.\n \"\"\"\n if X.dtype.names is None and len(X.shape) != 2:\n raise ValueError('X needs to be 2-dimensional, not '\n '{}-dimensional.'.format(len(X.shape)))": 1798, "def read(filename):\n \"\"\"Read and return `filename` in root dir of project and return string\"\"\"\n return codecs.open(os.path.join(__DIR__, filename), 'r').read()": 1799, "def instance_contains(container, item):\n \"\"\"Search into instance attributes, properties and return values of no-args methods.\"\"\"\n return item in (member for _, member in inspect.getmembers(container))": 1800, "def fill_nulls(self, col: str):\n \"\"\"\n Fill all null values with NaN values in a column.\n Null values are ``None`` or en empty string\n\n :param col: column name\n :type col: str\n\n :example: ``ds.fill_nulls(\"mycol\")``\n \"\"\"\n n = [None, \"\"]\n try:\n self.df[col] = self.df[col].replace(n, nan)\n except Exception as e:\n self.err(e)": 1801, "def skewness(data):\n \"\"\"\n Returns the skewness of ``data``.\n \"\"\"\n\n if len(data) == 0:\n return None\n\n num = moment(data, 3)\n denom = moment(data, 2) ** 1.5\n\n return num / denom if denom != 0 else 0.": 1802, "def inpaint(self):\n \"\"\" Replace masked-out elements in an array using an iterative image inpainting algorithm. \"\"\"\n\n import inpaint\n filled = inpaint.replace_nans(np.ma.filled(self.raster_data, np.NAN).astype(np.float32), 3, 0.01, 2)\n self.raster_data = np.ma.masked_invalid(filled)": 1803, "def available_gpus():\n \"\"\"List of GPU device names detected by TensorFlow.\"\"\"\n local_device_protos = device_lib.list_local_devices()\n return [x.name for x in local_device_protos if x.device_type == 'GPU']": 1804, "def cleanLines(source, lineSep=os.linesep):\n \"\"\"\n :param source: some iterable source (list, file, etc)\n :param lineSep: string of separators (chars) that must be removed\n :return: list of non empty lines with removed separators\n \"\"\"\n stripped = (line.strip(lineSep) for line in source)\n return (line for line in stripped if len(line) != 0)": 1805, "def allclose(a, b):\n \"\"\"\n Test that a and b are close and match in shape.\n\n Parameters\n ----------\n a : ndarray\n First array to check\n\n b : ndarray\n First array to check\n \"\"\"\n from numpy import allclose\n return (a.shape == b.shape) and allclose(a, b)": 1806, "def camel_to_snake_case(name):\n \"\"\"Takes a camelCased string and converts to snake_case.\"\"\"\n pattern = r'[A-Z][a-z]+|[A-Z]+(?![a-z])'\n return '_'.join(map(str.lower, re.findall(pattern, name)))": 1807, "def clear():\n \"\"\"Clears the console.\"\"\"\n if sys.platform.startswith(\"win\"):\n call(\"cls\", shell=True)\n else:\n call(\"clear\", shell=True)": 1808, "def logout(cache):\n \"\"\"\n Logs out the current session by removing it from the cache. This is\n expected to only occur when a session has\n \"\"\"\n cache.set(flask.session['auth0_key'], None)\n flask.session.clear()\n return True": 1809, "def retrieve_asset(filename):\n \"\"\" Retrieves a non-image asset associated with an entry \"\"\"\n\n record = model.Image.get(asset_name=filename)\n if not record:\n raise http_error.NotFound(\"File not found\")\n if not record.is_asset:\n raise http_error.Forbidden()\n\n return flask.send_file(record.file_path, conditional=True)": 1810, "def _closeResources(self):\n \"\"\" Closes the root Dataset.\n \"\"\"\n logger.info(\"Closing: {}\".format(self._fileName))\n self._h5Group.close()\n self._h5Group = None": 1811, "def view_500(request, url=None):\n \"\"\"\n it returns a 500 http response\n \"\"\"\n res = render_to_response(\"500.html\", context_instance=RequestContext(request))\n res.status_code = 500\n return res": 1812, "def staticdir():\n \"\"\"Return the location of the static data directory.\"\"\"\n root = os.path.abspath(os.path.dirname(__file__))\n return os.path.join(root, \"static\")": 1813, "def trim(self):\n \"\"\"Clear not used counters\"\"\"\n for key, value in list(iteritems(self.counters)):\n if value.empty():\n del self.counters[key]": 1814, "def filter(self, f, operator=\"and\"):\n \"\"\"\n Add a filter to the query\n\n Takes a Filter object, or a filterable DSL object.\n \"\"\"\n if self._filtered:\n self._filter_dsl.filter(f)\n else:\n self._build_filtered_query(f, operator)\n return self": 1815, "def flatten(nested):\n \"\"\" Return a flatten version of the nested argument \"\"\"\n flat_return = list()\n\n def __inner_flat(nested,flat):\n for i in nested:\n __inner_flat(i, flat) if isinstance(i, list) else flat.append(i)\n return flat\n\n __inner_flat(nested,flat_return)\n\n return flat_return": 1816, "def merge_pdfs(pdf_filepaths, out_filepath):\n \"\"\" Merge all the PDF files in `pdf_filepaths` in a new PDF file `out_filepath`.\n\n Parameters\n ----------\n pdf_filepaths: list of str\n Paths to PDF files.\n\n out_filepath: str\n Path to the result PDF file.\n\n Returns\n -------\n path: str\n The output file path.\n \"\"\"\n merger = PdfFileMerger()\n for pdf in pdf_filepaths:\n merger.append(PdfFileReader(open(pdf, 'rb')))\n\n merger.write(out_filepath)\n\n return out_filepath": 1817, "def merge_dict(data, *args):\n \"\"\"Merge any number of dictionaries\n \"\"\"\n results = {}\n for current in (data,) + args:\n results.update(current)\n return results": 1818, "def flatten(nested, containers=(list, tuple)):\n \"\"\" Flatten a nested list by yielding its scalar items.\n \"\"\"\n for item in nested:\n if hasattr(item, \"next\") or isinstance(item, containers):\n for subitem in flatten(item):\n yield subitem\n else:\n yield item": 1819, "def flatten_array(grid):\n \"\"\"\n Takes a multi-dimensional array and returns a 1 dimensional array with the\n same contents.\n \"\"\"\n grid = [grid[i][j] for i in range(len(grid)) for j in range(len(grid[i]))]\n while type(grid[0]) is list:\n grid = flatten_array(grid)\n return grid": 1820, "def version_jar(self):\n\t\t\"\"\"\n\t\tSpecial case of version() when the executable is a JAR file.\n\t\t\"\"\"\n\t\tcmd = config.get_command('java')\n\t\tcmd.append('-jar')\n\t\tcmd += self.cmd\n\t\tself.version(cmd=cmd, path=self.cmd[0])": 1821, "def flatten(lis):\n \"\"\"Given a list, possibly nested to any level, return it flattened.\"\"\"\n new_lis = []\n for item in lis:\n if isinstance(item, collections.Sequence) and not isinstance(item, basestring):\n new_lis.extend(flatten(item))\n else:\n new_lis.append(item)\n return new_lis": 1822, "def parse_comments_for_file(filename):\n \"\"\"\n Return a list of all parsed comments in a file. Mostly for testing &\n interactive use.\n \"\"\"\n return [parse_comment(strip_stars(comment), next_line)\n for comment, next_line in get_doc_comments(read_file(filename))]": 1823, "def count_string_diff(a,b):\n \"\"\"Return the number of characters in two strings that don't exactly match\"\"\"\n shortest = min(len(a), len(b))\n return sum(a[i] != b[i] for i in range(shortest))": 1824, "def are_equal_xml(a_xml, b_xml):\n \"\"\"Normalize and compare XML documents for equality. The document may or may not be\n a DataONE type.\n\n Args:\n a_xml: str\n b_xml: str\n XML documents to compare for equality.\n\n Returns:\n bool: ``True`` if the XML documents are semantically equivalent.\n\n \"\"\"\n a_dom = xml.dom.minidom.parseString(a_xml)\n b_dom = xml.dom.minidom.parseString(b_xml)\n return are_equal_elements(a_dom.documentElement, b_dom.documentElement)": 1825, "def generate(env):\n \"\"\"Add Builders and construction variables for SGI MIPS C++ to an Environment.\"\"\"\n\n cplusplus.generate(env)\n\n env['CXX'] = 'CC'\n env['CXXFLAGS'] = SCons.Util.CLVar('-LANG:std')\n env['SHCXX'] = '$CXX'\n env['SHOBJSUFFIX'] = '.o'\n env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1": 1826, "def multis_2_mono(table):\n \"\"\"\n Converts each multiline string in a table to single line.\n\n Parameters\n ----------\n table : list of list of str\n A list of rows containing strings\n\n Returns\n -------\n table : list of lists of str\n \"\"\"\n for row in range(len(table)):\n for column in range(len(table[row])):\n table[row][column] = table[row][column].replace('\\n', ' ')\n\n return table": 1827, "def _manhattan_distance(vec_a, vec_b):\n \"\"\"Return manhattan distance between two lists of numbers.\"\"\"\n if len(vec_a) != len(vec_b):\n raise ValueError('len(vec_a) must equal len(vec_b)')\n return sum(map(lambda a, b: abs(a - b), vec_a, vec_b))": 1828, "def num_leaves(tree):\n \"\"\"Determine the number of leaves in a tree\"\"\"\n if tree.is_leaf:\n return 1\n else:\n return num_leaves(tree.left_child) + num_leaves(tree.right_child)": 1829, "def xeval(source, optimize=True):\n \"\"\"Compiles to native Python bytecode and runs program, returning the\n topmost value on the stack.\n\n Args:\n optimize: Whether to optimize the code after parsing it.\n\n Returns:\n None: If the stack is empty\n obj: If the stack contains a single value\n [obj, obj, ...]: If the stack contains many values\n \"\"\"\n native = xcompile(source, optimize=optimize)\n return native()": 1830, "def str2int(num, radix=10, alphabet=BASE85):\n \"\"\"helper function for quick base conversions from strings to integers\"\"\"\n return NumConv(radix, alphabet).str2int(num)": 1831, "def get_substring_idxs(substr, string):\n \"\"\"\n Return a list of indexes of substr. If substr not found, list is\n empty.\n\n Arguments:\n substr (str): Substring to match.\n string (str): String to match in.\n\n Returns:\n list of int: Start indices of substr.\n \"\"\"\n return [match.start() for match in re.finditer(substr, string)]": 1832, "def _concatenate_virtual_arrays(arrs, cols=None, scaling=None):\n \"\"\"Return a virtual concatenate of several NumPy arrays.\"\"\"\n return None if not len(arrs) else ConcatenatedArrays(arrs, cols,\n scaling=scaling)": 1833, "def short_description(func):\n \"\"\"\n Given an object with a docstring, return the first line of the docstring\n \"\"\"\n\n doc = inspect.getdoc(func)\n if doc is not None:\n doc = inspect.cleandoc(doc)\n lines = doc.splitlines()\n return lines[0]\n\n return \"\"": 1834, "def get_previous(self):\n \"\"\"Get the billing cycle prior to this one. May return None\"\"\"\n return BillingCycle.objects.filter(date_range__lt=self.date_range).order_by('date_range').last()": 1835, "def set_global(node: Node, key: str, value: Any):\n \"\"\"Adds passed value to node's globals\"\"\"\n node.node_globals[key] = value": 1836, "def to_list(var):\n \"\"\"Checks if given value is a list, tries to convert, if it is not.\"\"\"\n if var is None:\n return []\n if isinstance(var, str):\n var = var.split('\\n')\n elif not isinstance(var, list):\n try:\n var = list(var)\n except TypeError:\n raise ValueError(\"{} cannot be converted to the list.\".format(var))\n return var": 1837, "def unpunctuate(s, *, char_blacklist=string.punctuation):\n \"\"\" Remove punctuation from string s. \"\"\"\n # remove punctuation\n s = \"\".join(c for c in s if c not in char_blacklist)\n # remove consecutive spaces\n return \" \".join(filter(None, s.split(\" \")))": 1838, "def create_conda_env(sandbox_dir, env_name, dependencies, options=()):\n \"\"\"\n Create a conda environment inside the current sandbox for the given list of dependencies and options.\n\n Parameters\n ----------\n sandbox_dir : str\n env_name : str\n dependencies : list\n List of conda specs\n options\n List of additional options to pass to conda. Things like [\"-c\", \"conda-forge\"]\n\n Returns\n -------\n (env_dir, env_name)\n \"\"\"\n\n env_dir = os.path.join(sandbox_dir, env_name)\n cmdline = [\"conda\", \"create\", \"--yes\", \"--copy\", \"--quiet\", \"-p\", env_dir] + list(options) + dependencies\n\n log.info(\"Creating conda environment: \")\n log.info(\" command line: %s\", cmdline)\n subprocess.check_call(cmdline, stderr=subprocess.PIPE, stdout=subprocess.PIPE)\n log.debug(\"Environment created\")\n\n return env_dir, env_name": 1839, "def get_decimal_quantum(precision):\n \"\"\"Return minimal quantum of a number, as defined by precision.\"\"\"\n assert isinstance(precision, (int, decimal.Decimal))\n return decimal.Decimal(10) ** (-precision)": 1840, "def get_url(self, cmd, **args):\n \"\"\"Expand the request URL for a request.\"\"\"\n return self.http.base_url + self._mkurl(cmd, *args)": 1841, "def detach_all(self):\n \"\"\"\n Detach from all tracked classes and objects.\n Restore the original constructors and cleanse the tracking lists.\n \"\"\"\n self.detach_all_classes()\n self.objects.clear()\n self.index.clear()\n self._keepalive[:] = []": 1842, "def list2dict(lst):\n \"\"\"Takes a list of (key,value) pairs and turns it into a dict.\"\"\"\n\n dic = {}\n for k,v in lst: dic[k] = v\n return dic": 1843, "def daterange(start_date, end_date):\n \"\"\"\n Yield one date per day from starting date to ending date.\n\n Args:\n start_date (date): starting date.\n end_date (date): ending date.\n\n Yields:\n date: a date for each day within the range.\n \"\"\"\n for n in range(int((end_date - start_date).days)):\n yield start_date + timedelta(n)": 1844, "def energy_string_to_float( string ):\n \"\"\"\n Convert a string of a calculation energy, e.g. '-1.2345 eV' to a float.\n\n Args:\n string (str): The string to convert.\n \n Return\n (float) \n \"\"\"\n energy_re = re.compile( \"(-?\\d+\\.\\d+)\" )\n return float( energy_re.match( string ).group(0) )": 1845, "def render(template=None, ostr=None, **kwargs):\n \"\"\"Generate report from a campaign\n\n :param template: Jinja template to use, ``DEFAULT_TEMPLATE`` is used\n if not specified\n :param ostr: output file or filename. Default is standard output\n \"\"\"\n jinja_environment.filters['texscape'] = tex_escape\n template = template or DEFAULT_TEMPLATE\n ostr = ostr or sys.stdout\n jinja_template = jinja_environment.get_template(template)\n jinja_template.stream(**kwargs).dump(ostr)": 1846, "def abs_img(img):\n \"\"\" Return an image with the binarised version of the data of `img`.\"\"\"\n bool_img = np.abs(read_img(img).get_data())\n return bool_img.astype(int)": 1847, "def get_remote_content(filepath):\n \"\"\" A handy wrapper to get a remote file content \"\"\"\n with hide('running'):\n temp = BytesIO()\n get(filepath, temp)\n content = temp.getvalue().decode('utf-8')\n return content.strip()": 1848, "def object_as_dict(obj):\n \"\"\"Turn an SQLAlchemy model into a dict of field names and values.\n\n Based on https://stackoverflow.com/a/37350445/1579058\n \"\"\"\n return {c.key: getattr(obj, c.key)\n for c in inspect(obj).mapper.column_attrs}": 1849, "def twitter_timeline(screen_name, since_id=None):\n \"\"\" Return relevant twitter timeline \"\"\"\n consumer_key = twitter_credential('consumer_key')\n consumer_secret = twitter_credential('consumer_secret')\n access_token = twitter_credential('access_token')\n access_token_secret = twitter_credential('access_secret')\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n api = tweepy.API(auth)\n return get_all_tweets(screen_name, api, since_id)": 1850, "def size(self):\n \"\"\"\n Recursively find size of a tree. Slow.\n \"\"\"\n\n if self is NULL:\n return 0\n return 1 + self.left.size() + self.right.size()": 1851, "def data_directory():\n \"\"\"Return the absolute path to the directory containing the package data.\"\"\"\n package_directory = os.path.abspath(os.path.dirname(__file__))\n return os.path.join(package_directory, \"data\")": 1852, "def get_Callable_args_res(clb):\n \"\"\"Python version independent function to obtain the parameters\n of a typing.Callable object. Returns as tuple: args, result.\n Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1.\n \"\"\"\n try:\n return clb.__args__, clb.__result__\n except AttributeError:\n # Python 3.6\n return clb.__args__[:-1], clb.__args__[-1]": 1853, "def count_rows_with_nans(X):\n \"\"\"Count the number of rows in 2D arrays that contain any nan values.\"\"\"\n if X.ndim == 2:\n return np.where(np.isnan(X).sum(axis=1) != 0, 1, 0).sum()": 1854, "def min_depth(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n if root is None:\n return 0\n if root.left is not None or root.right is not None:\n return max(self.minDepth(root.left), self.minDepth(root.right))+1\n return min(self.minDepth(root.left), self.minDepth(root.right)) + 1": 1855, "def get_language(self):\n \"\"\"\n Get the language parameter from the current request.\n \"\"\"\n return get_language_parameter(self.request, self.query_language_key, default=self.get_default_language(object=object))": 1856, "def entropy(string):\n \"\"\"Compute entropy on the string\"\"\"\n p, lns = Counter(string), float(len(string))\n return -sum(count/lns * math.log(count/lns, 2) for count in p.values())": 1857, "def _get_str_columns(sf):\n \"\"\"\n Returns a list of names of columns that are string type.\n \"\"\"\n return [name for name in sf.column_names() if sf[name].dtype == str]": 1858, "def _count_leading_whitespace(text):\n \"\"\"Returns the number of characters at the beginning of text that are whitespace.\"\"\"\n idx = 0\n for idx, char in enumerate(text):\n if not char.isspace():\n return idx\n return idx + 1": 1859, "def str2int(string_with_int):\n \"\"\" Collect digits from a string \"\"\"\n return int(\"\".join([char for char in string_with_int if char in string.digits]) or 0)": 1860, "def get_image_dimension(self, url):\n \"\"\"\n Return a tuple that contains (width, height)\n Pass in a url to an image and find out its size without loading the whole file\n If the image wxh could not be found, the tuple will contain `None` values\n \"\"\"\n w_h = (None, None)\n try:\n if url.startswith('//'):\n url = 'http:' + url\n data = requests.get(url).content\n im = Image.open(BytesIO(data))\n\n w_h = im.size\n except Exception:\n logger.warning(\"Error getting image size {}\".format(url), exc_info=True)\n\n return w_h": 1861, "def ident():\n \"\"\"\n This routine returns the 3x3 identity matrix.\n\n http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ident_c.html\n\n :return: The 3x3 identity matrix.\n :rtype: 3x3-Element Array of floats\n \"\"\"\n matrix = stypes.emptyDoubleMatrix()\n libspice.ident_c(matrix)\n return stypes.cMatrixToNumpy(matrix)": 1862, "def dir_modtime(dpath):\n \"\"\"\n Returns the latest modification time of all files/subdirectories in a\n directory\n \"\"\"\n return max(os.path.getmtime(d) for d, _, _ in os.walk(dpath))": 1863, "def head_and_tail_print(self, n=5):\n \"\"\"Display the first and last n elements of a DataFrame.\"\"\"\n from IPython import display\n display.display(display.HTML(self._head_and_tail_table(n)))": 1864, "def polyline(*points):\n \"\"\"Converts a list of points to a Path composed of lines connecting those \n points (i.e. a linear spline or polyline). See also `polygon()`.\"\"\"\n return Path(*[Line(points[i], points[i+1])\n for i in range(len(points) - 1)])": 1865, "def fft_freqs(n_fft, fs):\n \"\"\"Return frequencies for DFT\n\n Parameters\n ----------\n n_fft : int\n Number of points in the FFT.\n fs : float\n The sampling rate.\n \"\"\"\n return np.arange(0, (n_fft // 2 + 1)) / float(n_fft) * float(fs)": 1866, "def get_func_name(func):\n \"\"\"Return a name which includes the module name and function name.\"\"\"\n func_name = getattr(func, '__name__', func.__class__.__name__)\n module_name = func.__module__\n\n if module_name is not None:\n module_name = func.__module__\n return '{}.{}'.format(module_name, func_name)\n\n return func_name": 1867, "def symbol_pos_int(*args, **kwargs):\n \"\"\"Create a sympy.Symbol with positive and integer assumptions.\"\"\"\n kwargs.update({'positive': True,\n 'integer': True})\n return sympy.Symbol(*args, **kwargs)": 1868, "def get_git_branch(git_path='git'):\n \"\"\"Returns the name of the current git branch\n \"\"\"\n branch_match = call((git_path, 'rev-parse', '--symbolic-full-name', 'HEAD'))\n if branch_match == \"HEAD\":\n return None\n else:\n return os.path.basename(branch_match)": 1869, "def _to_array(value):\n \"\"\"As a convenience, turn Python lists and tuples into NumPy arrays.\"\"\"\n if isinstance(value, (tuple, list)):\n return array(value)\n elif isinstance(value, (float, int)):\n return np.float64(value)\n else:\n return value": 1870, "def url_to_image(url):\n \"\"\"\n Fetch an image from url and convert it into a Pillow Image object\n \"\"\"\n r = requests.get(url)\n image = StringIO(r.content)\n return image": 1871, "def home():\n \"\"\"Temporary helper function to link to the API routes\"\"\"\n return dict(links=dict(api='{}{}'.format(request.url, PREFIX[1:]))), \\\n HTTPStatus.OK": 1872, "def get(key, default=None):\n \"\"\" return the key from the request\n \"\"\"\n data = get_form() or get_query_string()\n return data.get(key, default)": 1873, "def difference(ydata1, ydata2):\n \"\"\"\n\n Returns the number you should add to ydata1 to make it line up with ydata2\n\n \"\"\"\n\n y1 = _n.array(ydata1)\n y2 = _n.array(ydata2)\n\n return(sum(y2-y1)/len(ydata1))": 1874, "def to_simple_rdd(sc, features, labels):\n \"\"\"Convert numpy arrays of features and labels into\n an RDD of pairs.\n\n :param sc: Spark context\n :param features: numpy array with features\n :param labels: numpy array with labels\n :return: Spark RDD with feature-label pairs\n \"\"\"\n pairs = [(x, y) for x, y in zip(features, labels)]\n return sc.parallelize(pairs)": 1875, "def get_available_gpus():\n \"\"\"\n Returns a list of string names of all available GPUs\n \"\"\"\n local_device_protos = device_lib.list_local_devices()\n return [x.name for x in local_device_protos if x.device_type == 'GPU']": 1876, "def create_task(coro, loop):\n # pragma: no cover\n \"\"\"Compatibility wrapper for the loop.create_task() call introduced in\n 3.4.2.\"\"\"\n if hasattr(loop, 'create_task'):\n return loop.create_task(coro)\n return asyncio.Task(coro, loop=loop)": 1877, "def conv_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs):\n \"\"\"A block of standard 2d convolutions.\"\"\"\n return conv_block_internal(conv, inputs, filters,\n dilation_rates_and_kernel_sizes, **kwargs)": 1878, "def extract_module_locals(depth=0):\n \"\"\"Returns (module, locals) of the funciton `depth` frames away from the caller\"\"\"\n f = sys._getframe(depth + 1)\n global_ns = f.f_globals\n module = sys.modules[global_ns['__name__']]\n return (module, f.f_locals)": 1879, "def debug(sequence):\n \"\"\"\n adds information to the sequence for better debugging, currently only\n an index property on each point in the sequence.\n \"\"\"\n points = []\n for i, p in enumerate(sequence):\n copy = Point(p)\n copy['index'] = i\n points.append(copy)\n return sequence.__class__(points)": 1880, "def get_file_md5sum(path):\n \"\"\"Calculate the MD5 hash for a file.\"\"\"\n with open(path, 'rb') as fh:\n h = str(hashlib.md5(fh.read()).hexdigest())\n return h": 1881, "def voronoi(data, line_color=None, line_width=2, f_tooltip=None, cmap=None, max_area=1e4, alpha=220):\n \"\"\"\n Draw the voronoi tesselation of the points\n\n :param data: data access object\n :param line_color: line color\n :param line_width: line width\n :param f_tooltip: function to generate a tooltip on mouseover\n :param cmap: color map\n :param max_area: scaling constant to determine the color of the voronoi areas\n :param alpha: color alpha\n \"\"\"\n from geoplotlib.layers import VoronoiLayer\n _global_config.layers.append(VoronoiLayer(data, line_color, line_width, f_tooltip, cmap, max_area, alpha))": 1882, "def _elapsed_time(begin_time, end_time):\n \"\"\"Assuming format YYYY-MM-DD hh:mm:ss\n\n Returns the elapsed time in seconds\n \"\"\"\n\n bt = _str2datetime(begin_time)\n et = _str2datetime(end_time)\n\n return float((et - bt).seconds)": 1883, "def get_var(self, name):\n \"\"\" Returns the variable set with the given name.\n \"\"\"\n for var in self.vars:\n if var.name == name:\n return var\n else:\n raise ValueError": 1884, "def c_array(ctype, values):\n \"\"\"Convert a python string to c array.\"\"\"\n if isinstance(values, np.ndarray) and values.dtype.itemsize == ctypes.sizeof(ctype):\n return (ctype * len(values)).from_buffer_copy(values)\n return (ctype * len(values))(*values)": 1885, "def node__name__(self):\n \"\"\"Return the name of this node or its class name.\"\"\"\n\n return self.node.__name__ \\\n if self.node.__name__ is not None else self.node.__class__.__name__": 1886, "def pointer(self):\n \"\"\"Get a ctypes void pointer to the memory mapped region.\n\n :type: ctypes.c_void_p\n \"\"\"\n return ctypes.cast(ctypes.pointer(ctypes.c_uint8.from_buffer(self.mapping, 0)), ctypes.c_void_p)": 1887, "def load_object_by_name(object_name):\n \"\"\"Load an object from a module by name\"\"\"\n mod_name, attr = object_name.rsplit('.', 1)\n mod = import_module(mod_name)\n return getattr(mod, attr)": 1888, "def __get__(self, obj, objtype):\n \"\"\" Support instance methods \"\"\"\n import functools\n return functools.partial(self.__call__, obj)": 1889, "def matrix_to_gl(matrix):\n \"\"\"\n Convert a numpy row- major homogenous transformation matrix\n to a flat column- major GLfloat transformation.\n\n Parameters\n -------------\n matrix : (4,4) float\n Row- major homogenous transform\n\n Returns\n -------------\n glmatrix : (16,) gl.GLfloat\n Transform in pyglet format\n \"\"\"\n matrix = np.asanyarray(matrix, dtype=np.float64)\n if matrix.shape != (4, 4):\n raise ValueError('matrix must be (4,4)!')\n\n # switch to column major and flatten to (16,)\n column = matrix.T.flatten()\n # convert to GLfloat\n glmatrix = (gl.GLfloat * 16)(*column)\n\n return glmatrix": 1890, "def check_output(args):\n \"\"\"Runs command and returns the output as string.\"\"\"\n log.debug('run: %s', args)\n out = subprocess.check_output(args=args).decode('utf-8')\n log.debug('out: %r', out)\n return out": 1891, "def format_timestamp(timestamp):\n \"\"\"\n Format the UTC timestamp for Elasticsearch\n eg. 2014-07-09T08:37:18.000Z\n\n @see https://docs.python.org/2/library/time.html#time.strftime\n\n :type timestamp int\n :rtype: str\n \"\"\"\n tz_info = tz.tzutc()\n return datetime.fromtimestamp(timestamp, tz=tz_info).strftime(\"%Y-%m-%dT%H:%M:%S.000Z\")": 1892, "def get_page_text(self, page):\n \"\"\"\n Downloads and returns the full text of a particular page\n in the document.\n \"\"\"\n url = self.get_page_text_url(page)\n return self._get_url(url)": 1893, "def convert_2_utc(self, datetime_, timezone):\n \"\"\"convert to datetime to UTC offset.\"\"\"\n\n datetime_ = self.tz_mapper[timezone].localize(datetime_)\n return datetime_.astimezone(pytz.UTC)": 1894, "def get_parent_folder_name(file_path):\n \"\"\"Finds parent folder of file\n\n :param file_path: path\n :return: Name of folder container\n \"\"\"\n return os.path.split(os.path.split(os.path.abspath(file_path))[0])[-1]": 1895, "def family_directory(fonts):\n \"\"\"Get the path of font project directory.\"\"\"\n if fonts:\n dirname = os.path.dirname(fonts[0])\n if dirname == '':\n dirname = '.'\n return dirname": 1896, "def decode_bytes(string):\n \"\"\" Decodes a given base64 string into bytes.\n\n :param str string: The string to decode\n :return: The decoded bytes\n :rtype: bytes\n \"\"\"\n\n if is_string_type(type(string)):\n string = bytes(string, \"utf-8\")\n return base64.decodebytes(string)": 1897, "def intToBin(i):\n \"\"\" Integer to two bytes \"\"\"\n # devide in two parts (bytes)\n i1 = i % 256\n i2 = int(i / 256)\n # make string (little endian)\n return chr(i1) + chr(i2)": 1898, "def p(self):\n \"\"\"\n Helper property containing the percentage this slider is \"filled\".\n \n This property is read-only.\n \"\"\"\n return (self.n-self.nmin)/max((self.nmax-self.nmin),1)": 1899, "def extra_funcs(*funcs):\n \"\"\"Decorator which adds extra functions to be downloaded to the pyboard.\"\"\"\n def extra_funcs_decorator(real_func):\n def wrapper(*args, **kwargs):\n return real_func(*args, **kwargs)\n wrapper.extra_funcs = list(funcs)\n wrapper.source = inspect.getsource(real_func)\n wrapper.name = real_func.__name__\n return wrapper\n return extra_funcs_decorator": 1900, "def basic_word_sim(word1, word2):\n \"\"\"\n Simple measure of similarity: Number of letters in common / max length\n \"\"\"\n return sum([1 for c in word1 if c in word2]) / max(len(word1), len(word2))": 1901, "def remove(parent, idx):\n \"\"\"Remove a value from a dict.\"\"\"\n if isinstance(parent, dict):\n del parent[idx]\n elif isinstance(parent, list):\n del parent[int(idx)]\n else:\n raise JSONPathError(\"Invalid path for operation\")": 1902, "def unique(list):\n \"\"\" Returns a copy of the list without duplicates.\n \"\"\"\n unique = []; [unique.append(x) for x in list if x not in unique]\n return unique": 1903, "def readwav(filename):\n \"\"\"Read a WAV file and returns the data and sample rate\n\n ::\n\n from spectrum.io import readwav\n readwav()\n\n \"\"\"\n from scipy.io.wavfile import read as readwav\n samplerate, signal = readwav(filename)\n return signal, samplerate": 1904, "def option2tuple(opt):\n \"\"\"Return a tuple of option, taking possible presence of level into account\"\"\"\n\n if isinstance(opt[0], int):\n tup = opt[1], opt[2:]\n else:\n tup = opt[0], opt[1:]\n\n return tup": 1905, "def clean_out_dir(directory):\n \"\"\"\n Delete all the files and subdirectories in a directory.\n \"\"\"\n if not isinstance(directory, path):\n directory = path(directory)\n for file_path in directory.files():\n file_path.remove()\n for dir_path in directory.dirs():\n dir_path.rmtree()": 1906, "def get_width():\n \"\"\"Get terminal width\"\"\"\n # Get terminal size\n ws = struct.pack(\"HHHH\", 0, 0, 0, 0)\n ws = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, ws)\n lines, columns, x, y = struct.unpack(\"HHHH\", ws)\n width = min(columns * 39 // 40, columns - 2)\n return width": 1907, "def _normalize_abmn(abmn):\n \"\"\"return a normalized version of abmn\n \"\"\"\n abmn_2d = np.atleast_2d(abmn)\n abmn_normalized = np.hstack((\n np.sort(abmn_2d[:, 0:2], axis=1),\n np.sort(abmn_2d[:, 2:4], axis=1),\n ))\n return abmn_normalized": 1908, "def size(dtype):\n \"\"\"Returns the number of bytes to represent this `dtype`.\"\"\"\n dtype = tf.as_dtype(dtype)\n if hasattr(dtype, 'size'):\n return dtype.size\n return np.dtype(dtype).itemsize": 1909, "def index(self, value):\n\t\t\"\"\"\n\t\tReturn the smallest index of the row(s) with this column\n\t\tequal to value.\n\t\t\"\"\"\n\t\tfor i in xrange(len(self.parentNode)):\n\t\t\tif getattr(self.parentNode[i], self.Name) == value:\n\t\t\t\treturn i\n\t\traise ValueError(value)": 1910, "def refresh(self, document):\n\t\t\"\"\" Load a new copy of a document from the database. does not\n\t\t\treplace the old one \"\"\"\n\t\ttry:\n\t\t\told_cache_size = self.cache_size\n\t\t\tself.cache_size = 0\n\t\t\tobj = self.query(type(document)).filter_by(mongo_id=document.mongo_id).one()\n\t\tfinally:\n\t\t\tself.cache_size = old_cache_size\n\t\tself.cache_write(obj)\n\t\treturn obj": 1911, "def __getitem__(self, index):\n \"\"\"Get the item at the given index.\n\n Index is a tuple of (row, col)\n \"\"\"\n row, col = index\n return self.rows[row][col]": 1912, "def update_screen(self):\n \"\"\"Refresh the screen. You don't need to override this except to update only small portins of the screen.\"\"\"\n self.clock.tick(self.FPS)\n pygame.display.update()": 1913, "def calc_volume(self, sample: np.ndarray):\n \"\"\"Find the RMS of the audio\"\"\"\n return sqrt(np.mean(np.square(sample)))": 1914, "def _get_local_ip(self):\n \"\"\"Try to determine the local IP address of the machine.\"\"\"\n try:\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n # Use Google Public DNS server to determine own IP\n sock.connect(('8.8.8.8', 80))\n\n return sock.getsockname()[0]\n except socket.error:\n try:\n return socket.gethostbyname(socket.gethostname())\n except socket.gaierror:\n return '127.0.0.1'\n finally:\n sock.close()": 1915, "def getScriptLocation():\n\t\"\"\"Helper function to get the location of a Python file.\"\"\"\n\tlocation = os.path.abspath(\"./\")\n\tif __file__.rfind(\"/\") != -1:\n\t\tlocation = __file__[:__file__.rfind(\"/\")]\n\treturn location": 1916, "def class_name(obj):\n \"\"\"\n Get the name of an object, including the module name if available.\n \"\"\"\n\n name = obj.__name__\n module = getattr(obj, '__module__')\n\n if module:\n name = f'{module}.{name}'\n return name": 1917, "def initialize_api(flask_app):\n \"\"\"Initialize an API.\"\"\"\n if not flask_restplus:\n return\n\n api = flask_restplus.Api(version=\"1.0\", title=\"My Example API\")\n api.add_resource(HelloWorld, \"/hello\")\n\n blueprint = flask.Blueprint(\"api\", __name__, url_prefix=\"/api\")\n api.init_app(blueprint)\n flask_app.register_blueprint(blueprint)": 1918, "def register_extension_class(ext, base, *args, **kwargs):\n \"\"\"Instantiate the given extension class and register as a public attribute of the given base.\n\n README: The expected protocol here is to instantiate the given extension and pass the base\n object as the first positional argument, then unpack args and kwargs as additional arguments to\n the extension's constructor.\n \"\"\"\n ext_instance = ext.plugin(base, *args, **kwargs)\n setattr(base, ext.name.lstrip('_'), ext_instance)": 1919, "def get_top(self, *args, **kwargs):\n \"\"\"Return a get_content generator for top submissions.\n\n Corresponds to the submissions provided by\n ``https://www.reddit.com/top/`` for the session.\n\n The additional parameters are passed directly into\n :meth:`.get_content`. Note: the `url` parameter cannot be altered.\n\n \"\"\"\n return self.get_content(self.config['top'], *args, **kwargs)": 1920, "def size(self):\n \"\"\"The size of this parameter, equivalent to self.value.size\"\"\"\n return np.multiply.reduce(self.shape, dtype=np.int32)": 1921, "def length(self):\n \"\"\"Array of vector lengths\"\"\"\n return np.sqrt(np.sum(self**2, axis=1)).view(np.ndarray)": 1922, "async def join(self, ctx, *, channel: discord.VoiceChannel):\n \"\"\"Joins a voice channel\"\"\"\n\n if ctx.voice_client is not None:\n return await ctx.voice_client.move_to(channel)\n\n await channel.connect()": 1923, "def OnMove(self, event):\n \"\"\"Main window move event\"\"\"\n\n # Store window position in config\n position = self.main_window.GetScreenPositionTuple()\n\n config[\"window_position\"] = repr(position)": 1924, "def _handle_chat_name(self, data):\n \"\"\"Handle user name changes\"\"\"\n\n self.room.user.nick = data\n self.conn.enqueue_data(\"user\", self.room.user)": 1925, "def auth_request(self, url, headers, body):\n \"\"\"Perform auth request for token.\"\"\"\n\n return self.req.post(url, headers, body=body)": 1926, "def get_plain_image_as_widget(self):\n \"\"\"Used for generating thumbnails. Does not include overlaid\n graphics.\n \"\"\"\n arr = self.getwin_array(order=self.rgb_order)\n image = self._get_qimage(arr, self.qimg_fmt)\n return image": 1927, "def _get_loggers():\n \"\"\"Return list of Logger classes.\"\"\"\n from .. import loader\n modules = loader.get_package_modules('logger')\n return list(loader.get_plugins(modules, [_Logger]))": 1928, "def copy(self):\n \"\"\"\n Creates a copy of model\n \"\"\"\n return self.__class__(field_type=self.get_field_type(), data=self.export_data())": 1929, "def ffmpeg_works():\n \"\"\"Tries to encode images with ffmpeg to check if it works.\"\"\"\n images = np.zeros((2, 32, 32, 3), dtype=np.uint8)\n try:\n _encode_gif(images, 2)\n return True\n except (IOError, OSError):\n return False": 1930, "def managepy(cmd, extra=None):\n \"\"\"Run manage.py using this component's specific Django settings\"\"\"\n\n extra = extra.split() if extra else []\n run_django_cli(['invoke', cmd] + extra)": 1931, "def branches(self):\n \"\"\"All branches in a list\"\"\"\n result = self.git(self.default + ['branch', '-a', '--no-color'])\n return [l.strip(' *\\n') for l in result.split('\\n') if l.strip(' *\\n')]": 1932, "def get_qualified_name(_object):\n \"\"\"Return the Fully Qualified Name from an instance or class.\"\"\"\n module = _object.__module__\n if hasattr(_object, '__name__'):\n _class = _object.__name__\n\n else:\n _class = _object.__class__.__name__\n\n return module + '.' + _class": 1933, "def __init__(self, form_post_data=None, *args, **kwargs):\n \"\"\"\n Overriding init so we can set the post vars like a normal form and generate\n the form the same way Django does.\n \"\"\"\n kwargs.update({'form_post_data': form_post_data})\n super(MongoModelForm, self).__init__(*args, **kwargs)": 1934, "def object_to_json(obj, indent=2):\n \"\"\"\n transform object to json\n \"\"\"\n instance_json = json.dumps(obj, indent=indent, ensure_ascii=False, cls=DjangoJSONEncoder)\n return instance_json": 1935, "def full_like(array, value, dtype=None):\n \"\"\" Create a shared memory array with the same shape and type as a given array, filled with `value`.\n \"\"\"\n shared = empty_like(array, dtype)\n shared[:] = value\n return shared": 1936, "def __del__(self):\n \"\"\"Frees all resources.\n \"\"\"\n if hasattr(self, '_Api'):\n self._Api.close()\n\n self._Logger.info('object destroyed')": 1937, "def fill_document(doc):\n \"\"\"Add a section, a subsection and some text to the document.\n\n :param doc: the document\n :type doc: :class:`pylatex.document.Document` instance\n \"\"\"\n with doc.create(Section('A section')):\n doc.append('Some regular text and some ')\n doc.append(italic('italic text. '))\n\n with doc.create(Subsection('A subsection')):\n doc.append('Also some crazy characters: $&#{}')": 1938, "def hex_to_hsv(color):\n \"\"\"\n Converts from hex to hsv\n\n Parameters:\n -----------\n color : string\n Color representation on color\n\n Example:\n hex_to_hsv('#ff9933')\n \"\"\"\n color = normalize(color)\n color = color[1:]\n # color=tuple(ord(c)/255.0 for c in color.decode('hex'))\n color = (int(color[0:2], base=16) / 255.0, int(color[2:4],\n base=16) / 255.0, int(color[4:6], base=16) / 255.0)\n return colorsys.rgb_to_hsv(*color)": 1939, "def polite_string(a_string):\n \"\"\"Returns a \"proper\" string that should work in both Py3/Py2\"\"\"\n if is_py3() and hasattr(a_string, 'decode'):\n try:\n return a_string.decode('utf-8')\n except UnicodeDecodeError:\n return a_string\n\n return a_string": 1940, "def isfunc(x):\n \"\"\"\n Returns `True` if the given value is a function or method object.\n\n Arguments:\n x (mixed): value to check.\n\n Returns:\n bool\n \"\"\"\n return any([\n inspect.isfunction(x) and not asyncio.iscoroutinefunction(x),\n inspect.ismethod(x) and not asyncio.iscoroutinefunction(x)\n ])": 1941, "def _get_pretty_string(obj):\n \"\"\"Return a prettier version of obj\n\n Parameters\n ----------\n obj : object\n Object to pretty print\n\n Returns\n -------\n s : str\n Pretty print object repr\n \"\"\"\n sio = StringIO()\n pprint.pprint(obj, stream=sio)\n return sio.getvalue()": 1942, "def action(self):\n \"\"\"\n This class overrides this method\n \"\"\"\n self.return_value = self.function(*self.args, **self.kwargs)": 1943, "def _open_url(url):\n \"\"\"Open a HTTP connection to the URL and return a file-like object.\"\"\"\n response = requests.get(url, stream=True)\n if response.status_code != 200:\n raise IOError(\"Unable to download {}, HTTP {}\".format(url, response.status_code))\n return response": 1944, "def set_parent_path(self, value):\n \"\"\"\n Set the parent path and the path from the new parent path.\n\n :param value: The path to the object's parent\n \"\"\"\n\n self._parent_path = value\n self.path = value + r'/' + self.name\n self._update_childrens_parent_path()": 1945, "def normalize_time(timestamp):\n \"\"\"Normalize time in arbitrary timezone to UTC naive object.\"\"\"\n offset = timestamp.utcoffset()\n if offset is None:\n return timestamp\n return timestamp.replace(tzinfo=None) - offset": 1946, "def _get_all_constants():\n \"\"\"\n Get list of all uppercase, non-private globals (doesn't start with ``_``).\n\n Returns:\n list: Uppercase names defined in `globals()` (variables from this \\\n module).\n \"\"\"\n return [\n key for key in globals().keys()\n if all([\n not key.startswith(\"_\"), # publicly accesible\n key.upper() == key, # uppercase\n type(globals()[key]) in _ALLOWED # and with type from _ALLOWED\n ])\n ]": 1947, "def inverse_transform(self, X):\n \"\"\"Undo the scaling of X according to feature_range.\n\n Note that if truncate is true, any truncated points will not\n be restored exactly.\n\n Parameters\n ----------\n X : array-like with shape [n_samples, n_features]\n Input data that will be transformed.\n \"\"\"\n X = check_array(X, copy=self.copy)\n X -= self.min_\n X /= self.scale_\n return X": 1948, "def closeEvent(self, e):\n \"\"\"Qt slot when the window is closed.\"\"\"\n self.emit('close_widget')\n super(DockWidget, self).closeEvent(e)": 1949, "def wipe(self):\n \"\"\" Wipe the store\n \"\"\"\n keys = list(self.keys()).copy()\n for key in keys:\n self.delete(key)": 1950, "def disassemble_file(filename, outstream=None):\n \"\"\"\n disassemble Python byte-code file (.pyc)\n\n If given a Python source file (\".py\") file, we'll\n try to find the corresponding compiled object.\n \"\"\"\n filename = check_object_path(filename)\n (version, timestamp, magic_int, co, is_pypy,\n source_size) = load_module(filename)\n if type(co) == list:\n for con in co:\n disco(version, con, outstream)\n else:\n disco(version, co, outstream, is_pypy=is_pypy)\n co = None": 1951, "def geodetic_to_ecef(latitude, longitude, altitude):\n \"\"\"Convert WGS84 geodetic coordinates into ECEF\n \n Parameters\n ----------\n latitude : float or array_like\n Geodetic latitude (degrees)\n longitude : float or array_like\n Geodetic longitude (degrees)\n altitude : float or array_like\n Geodetic Height (km) above WGS84 reference ellipsoid.\n \n Returns\n -------\n x, y, z\n numpy arrays of x, y, z locations in km\n \n \"\"\"\n\n\n ellip = np.sqrt(1. - earth_b ** 2 / earth_a ** 2)\n r_n = earth_a / np.sqrt(1. - ellip ** 2 * np.sin(np.deg2rad(latitude)) ** 2)\n\n # colatitude = 90. - latitude\n x = (r_n + altitude) * np.cos(np.deg2rad(latitude)) * np.cos(np.deg2rad(longitude))\n y = (r_n + altitude) * np.cos(np.deg2rad(latitude)) * np.sin(np.deg2rad(longitude))\n z = (r_n * (1. - ellip ** 2) + altitude) * np.sin(np.deg2rad(latitude))\n\n return x, y, z": 1952, "def scan(client, query=None, scroll='5m', raise_on_error=True,\n preserve_order=False, size=1000, **kwargs):\n \"\"\"\n Simple abstraction on top of the\n :meth:`~elasticsearch.Elasticsearch.scroll` api - a simple iterator that\n yields all hits as returned by underlining scroll requests.\n By default scan does not return results in any pre-determined order. To\n have a standard order in the returned documents (either by score or\n explicit sort definition) when scrolling, use ``preserve_order=True``. This\n may be an expensive operation and will negate the performance benefits of\n using ``scan``.\n :arg client: instance of :class:`~elasticsearch.Elasticsearch` to use\n :arg query: body for the :meth:`~elasticsearch.Elasticsearch.search` api\n :arg scroll: Specify how long a consistent view of the index should be\n maintained for scrolled search\n :arg raise_on_error: raises an exception (``ScanError``) if an error is\n encountered (some shards fail to execute). By default we raise.\n :arg preserve_order: don't set the ``search_type`` to ``scan`` - this will\n cause the scroll to paginate with preserving the order. Note that this\n can be an extremely expensive operation and can easily lead to\n unpredictable results, use with caution.\n :arg size: size (per shard) of the batch send at each iteration.\n Any additional keyword arguments will be passed to the initial\n :meth:`~elasticsearch.Elasticsearch.search` call::\n scan(es,\n query={\"query\": {\"match\": {\"title\": \"python\"}}},\n index=\"orders-*\",\n doc_type=\"books\"\n )\n \"\"\"\n if not preserve_order:\n kwargs['search_type'] = 'scan'\n # initial search\n resp = client.search(body=query, scroll=scroll, size=size, **kwargs)\n\n scroll_id = resp.get('_scroll_id')\n if scroll_id is None:\n return\n\n first_run = True\n while True:\n # if we didn't set search_type to scan initial search contains data\n if preserve_order and first_run:\n first_run = False\n else:\n resp = client.scroll(scroll_id, scroll=scroll)\n\n for hit in resp['hits']['hits']:\n yield hit\n\n # check if we have any errrors\n if resp[\"_shards\"][\"failed\"]:\n logger.warning(\n 'Scroll request has failed on %d shards out of %d.',\n resp['_shards']['failed'], resp['_shards']['total']\n )\n if raise_on_error:\n raise ScanError(\n 'Scroll request has failed on %d shards out of %d.' %\n (resp['_shards']['failed'], resp['_shards']['total'])\n )\n\n scroll_id = resp.get('_scroll_id')\n # end of scroll\n if scroll_id is None or not resp['hits']['hits']:\n break": 1953, "def is_valid_regex(regex):\n \"\"\"Function for checking a valid regex.\"\"\"\n if len(regex) == 0:\n return False\n try:\n re.compile(regex)\n return True\n except sre_constants.error:\n return False": 1954, "def check_length(value, length):\n \"\"\"\n Checks length of value\n\n @param value: value to check\n @type value: C{str}\n\n @param length: length checking for\n @type length: C{int}\n\n @return: None when check successful\n\n @raise ValueError: check failed\n \"\"\"\n _length = len(value)\n if _length != length:\n raise ValueError(\"length must be %d, not %d\" % \\\n (length, _length))": 1955, "def line_line_collide(line1, line2):\n \"\"\"Determine if two line segments meet.\n\n This is a helper for :func:`convex_hull_collide` in the\n special case that the two convex hulls are actually\n just line segments. (Even in this case, this is only\n problematic if both segments are on a single line.)\n\n Args:\n line1 (numpy.ndarray): ``2 x 2`` array of start and end nodes.\n line2 (numpy.ndarray): ``2 x 2`` array of start and end nodes.\n\n Returns:\n bool: Indicating if the line segments collide.\n \"\"\"\n s, t, success = segment_intersection(\n line1[:, 0], line1[:, 1], line2[:, 0], line2[:, 1]\n )\n if success:\n return _helpers.in_interval(s, 0.0, 1.0) and _helpers.in_interval(\n t, 0.0, 1.0\n )\n\n else:\n disjoint, _ = parallel_lines_parameters(\n line1[:, 0], line1[:, 1], line2[:, 0], line2[:, 1]\n )\n return not disjoint": 1956, "def hard_equals(a, b):\n \"\"\"Implements the '===' operator.\"\"\"\n if type(a) != type(b):\n return False\n return a == b": 1957, "def _escape(self, s):\n \"\"\"Escape bad characters for regular expressions.\n\n Similar to `re.escape` but allows '%' to pass through.\n\n \"\"\"\n for ch, r_ch in self.ESCAPE_SETS:\n s = s.replace(ch, r_ch)\n return s": 1958, "def copy(string, **kwargs):\n \"\"\"Copy given string into system clipboard.\"\"\"\n window = Tk()\n window.withdraw()\n window.clipboard_clear()\n window.clipboard_append(string)\n window.destroy()\n return": 1959, "def __call__(self, xy):\n \"\"\"Project x and y\"\"\"\n x, y = xy\n return (self.x(x), self.y(y))": 1960, "def fast_exit(code):\n \"\"\"Exit without garbage collection, this speeds up exit by about 10ms for\n things like bash completion.\n \"\"\"\n sys.stdout.flush()\n sys.stderr.flush()\n os._exit(code)": 1961, "def __init__(self, ba=None):\n \"\"\"Constructor.\"\"\"\n self.bytearray = ba or (bytearray(b'\\0') * self.SIZEOF)": 1962, "def safe_rmtree(directory):\n \"\"\"Delete a directory if it's present. If it's not present, no-op.\"\"\"\n if os.path.exists(directory):\n shutil.rmtree(directory, True)": 1963, "def double_exponential_moving_average(data, period):\n \"\"\"\n Double Exponential Moving Average.\n\n Formula:\n DEMA = 2*EMA - EMA(EMA)\n \"\"\"\n catch_errors.check_for_period_error(data, period)\n\n dema = (2 * ema(data, period)) - ema(ema(data, period), period)\n return dema": 1964, "def is_file_url(url):\n \"\"\"Returns true if the given url is a file url\"\"\"\n from .misc import to_text\n\n if not url:\n return False\n if not isinstance(url, six.string_types):\n try:\n url = getattr(url, \"url\")\n except AttributeError:\n raise ValueError(\"Cannot parse url from unknown type: {0!r}\".format(url))\n url = to_text(url, encoding=\"utf-8\")\n return urllib_parse.urlparse(url.lower()).scheme == \"file\"": 1965, "def save_image(pdf_path, img_path, page_num):\n \"\"\"\n\n Creates images for a page of the input pdf document and saves it\n at img_path.\n\n :param pdf_path: path to pdf to create images for.\n :param img_path: path where to save the images.\n :param page_num: page number to create image from in the pdf file.\n :return:\n \"\"\"\n pdf_img = Image(filename=\"{}[{}]\".format(pdf_path, page_num))\n with pdf_img.convert(\"png\") as converted:\n # Set white background.\n converted.background_color = Color(\"white\")\n converted.alpha_channel = \"remove\"\n converted.save(filename=img_path)": 1966, "def version_triple(tag):\n \"\"\"\n returns: a triple of integers from a version tag\n \"\"\"\n groups = re.match(r'v?(\\d+)\\.(\\d+)\\.(\\d+)', tag).groups()\n return tuple(int(n) for n in groups)": 1967, "def __next__(self, reward, ask_id, lbl):\n \"\"\"For Python3 compatibility of generator.\"\"\"\n return self.next(reward, ask_id, lbl)": 1968, "def contains_extractor(document):\n \"\"\"A basic document feature extractor that returns a dict of words that the\n document contains.\"\"\"\n tokens = _get_document_tokens(document)\n features = dict((u'contains({0})'.format(w), True) for w in tokens)\n return features": 1969, "def clean_tmpdir(path):\n \"\"\"Invoked atexit, this removes our tmpdir\"\"\"\n if os.path.exists(path) and \\\n os.path.isdir(path):\n rmtree(path)": 1970, "def _heappop_max(heap):\n \"\"\"Maxheap version of a heappop.\"\"\"\n lastelt = heap.pop() # raises appropriate IndexError if heap is empty\n if heap:\n returnitem = heap[0]\n heap[0] = lastelt\n _siftup_max(heap, 0)\n return returnitem\n return lastelt": 1971, "def get_method_names(obj):\n \"\"\"\n Gets names of all methods implemented in specified object.\n\n :param obj: an object to introspect.\n\n :return: a list with method names.\n \"\"\"\n method_names = []\n \n for method_name in dir(obj):\n\n method = getattr(obj, method_name)\n\n if MethodReflector._is_method(method, method_name):\n method_names.append(method_name)\n\n return method_names": 1972, "def iterate(obj):\n\t\"\"\"Loop over an iterable and track progress, including first and last state.\n\t\n\tOn each iteration yield an Iteration named tuple with the first and last flags, current element index, total\n\titerable length (if possible to acquire), and value, in that order.\n\t\n\t\tfor iteration in iterate(something):\n\t\t\titeration.value # Do something.\n\t\n\tYou can unpack these safely:\n\t\n\t\tfor first, last, index, total, value in iterate(something):\n\t\t\tpass\n\t\n\tIf you want to unpack the values you are iterating across, you can by wrapping the nested unpacking in parenthesis:\n\t\n\t\tfor first, last, index, total, (foo, bar, baz) in iterate(something):\n\t\t\tpass\n\t\n\tEven if the length of the iterable can't be reliably determined this function will still capture the \"last\" state\n\tof the final loop iteration. (Basically: this works with generators.)\n\t\n\tThis process is about 10x slower than simple enumeration on CPython 3.4, so only use it where you actually need to\n\ttrack state. Use `enumerate()` elsewhere.\n\t\"\"\"\n\t\n\tglobal next, Iteration\n\tnext = next\n\tIteration = Iteration\n\t\n\ttotal = len(obj) if isinstance(obj, Sized) else None\n\titerator = iter(obj)\n\tfirst = True\n\tlast = False\n\ti = 0\n\t\n\ttry:\n\t\tvalue = next(iterator)\n\texcept StopIteration:\n\t\treturn\n\t\n\twhile True:\n\t\ttry:\n\t\t\tnext_value = next(iterator)\n\t\texcept StopIteration:\n\t\t\tlast = True\n\t\t\n\t\tyield Iteration(first, last, i, total, value)\n\t\tif last: return\n\t\t\n\t\tvalue = next_value\n\t\ti += 1\n\t\tfirst = False": 1973, "def _select_features(example, feature_list=None):\n \"\"\"Select a subset of features from the example dict.\"\"\"\n feature_list = feature_list or [\"inputs\", \"targets\"]\n return {f: example[f] for f in feature_list}": 1974, "def wget(url):\n \"\"\"\n Download the page into a string\n \"\"\"\n import urllib.parse\n request = urllib.request.urlopen(url)\n filestring = request.read()\n return filestring": 1975, "def _read_text(self, filename):\n \"\"\"\n Helper that reads the UTF-8 content of the specified file, or\n None if the file doesn't exist. This returns a unicode string.\n \"\"\"\n with io.open(filename, 'rt', encoding='utf-8') as f:\n return f.read()": 1976, "def pods(self):\n \"\"\" A list of kubernetes pods corresponding to current workers\n\n See Also\n --------\n KubeCluster.logs\n \"\"\"\n return self.core_api.list_namespaced_pod(\n self.namespace,\n label_selector=format_labels(self.pod_template.metadata.labels)\n ).items": 1977, "def _hide_tick_lines_and_labels(axis):\n \"\"\"\n Set visible property of ticklines and ticklabels of an axis to False\n \"\"\"\n for item in axis.get_ticklines() + axis.get_ticklabels():\n item.set_visible(False)": 1978, "def median_high(data):\n \"\"\"Return the high median of data.\n\n When the number of data points is odd, the middle value is returned.\n When it is even, the larger of the two middle values is returned.\n\n \"\"\"\n data = sorted(data)\n n = len(data)\n if n == 0:\n raise StatisticsError(\"no median for empty data\")\n return data[n // 2]": 1979, "def search_overlap(self, point_list):\n \"\"\"\n Returns all intervals that overlap the point_list.\n \"\"\"\n result = set()\n for j in point_list:\n self.search_point(j, result)\n return result": 1980, "def findMax(arr):\n \"\"\"\n in comparison to argrelmax() more simple and reliable peak finder\n \"\"\"\n out = np.zeros(shape=arr.shape, dtype=bool)\n _calcMax(arr, out)\n return out": 1981, "def pout(msg, log=None):\n \"\"\"Print 'msg' to stdout, and option 'log' at info level.\"\"\"\n _print(msg, sys.stdout, log_func=log.info if log else None)": 1982, "def argmax(l,f=None):\n \"\"\"http://stackoverflow.com/questions/5098580/implementing-argmax-in-python\"\"\"\n if f:\n l = [f(i) for i in l]\n return max(enumerate(l), key=lambda x:x[1])[0]": 1983, "def list_i2str(ilist):\n \"\"\"\n Convert an integer list into a string list.\n \"\"\"\n slist = []\n for el in ilist:\n slist.append(str(el))\n return slist": 1984, "def binSearch(arr, val):\n \"\"\" \n Function for running binary search on a sorted list.\n\n :param arr: (list) a sorted list of integers to search\n :param val: (int) a integer to search for in the sorted array\n :returns: (int) the index of the element if it is found and -1 otherwise.\n \"\"\"\n i = bisect_left(arr, val)\n if i != len(arr) and arr[i] == val:\n return i\n return -1": 1985, "def find(self, name):\n \"\"\"Return the index of the toc entry with name NAME.\n\n Return -1 for failure.\"\"\"\n for i, nm in enumerate(self.data):\n if nm[-1] == name:\n return i\n return -1": 1986, "def multiply(self, number):\n \"\"\"Return a Vector as the product of the vector and a real number.\"\"\"\n return self.from_list([x * number for x in self.to_list()])": 1987, "def _normalize(mat: np.ndarray):\n \"\"\"rescales a numpy array, so that min is 0 and max is 255\"\"\"\n return ((mat - mat.min()) * (255 / mat.max())).astype(np.uint8)": 1988, "def read_stdin():\n \"\"\" Read text from stdin, and print a helpful message for ttys. \"\"\"\n if sys.stdin.isatty() and sys.stdout.isatty():\n print('\\nReading from stdin until end of file (Ctrl + D)...')\n\n return sys.stdin.read()": 1989, "def read_key(suppress=False):\n \"\"\"\n Blocks until a keyboard event happens, then returns that event's name or,\n if missing, its scan code.\n \"\"\"\n event = read_event(suppress)\n return event.name or event.scan_code": 1990, "def fit_transform(self, raw_documents, y=None):\n \"\"\"Learn vocabulary and idf, return term-document matrix.\n This is equivalent to fit followed by transform, but more efficiently\n implemented.\n Parameters\n ----------\n raw_documents : iterable\n an iterable which yields either str, unicode or file objects\n Returns\n -------\n X : sparse matrix, [n_samples, n_features]\n Tf-idf-weighted document-term matrix.\n \"\"\"\n documents = super(TfidfVectorizer, self).fit_transform(\n raw_documents=raw_documents, y=y)\n count = CountVectorizer(encoding=self.encoding,\n decode_error=self.decode_error,\n strip_accents=self.strip_accents,\n lowercase=self.lowercase,\n preprocessor=self.preprocessor,\n tokenizer=self.tokenizer,\n stop_words=self.stop_words,\n token_pattern=self.token_pattern,\n ngram_range=self.ngram_range,\n analyzer=self.analyzer,\n max_df=self.max_df,\n min_df=self.min_df,\n max_features=self.max_features,\n vocabulary=self.vocabulary_,\n binary=self.binary,\n dtype=self.dtype)\n count.fit_transform(raw_documents=raw_documents, y=y)\n self.period_ = count.period_\n self.df_ = count.df_\n self.n = count.n\n return documents": 1991, "def report_stdout(host, stdout):\n \"\"\"Take a stdout and print it's lines to output if lines are present.\n\n :param host: the host where the process is running\n :type host: str\n :param stdout: the std out of that process\n :type stdout: paramiko.channel.Channel\n \"\"\"\n lines = stdout.readlines()\n if lines:\n print(\"STDOUT from {host}:\".format(host=host))\n for line in lines:\n print(line.rstrip(), file=sys.stdout)": 1992, "def rotateImage(image, angle):\n \"\"\"\n rotates a 2d array to a multiple of 90 deg.\n 0 = default\n 1 = 90 deg. cw\n 2 = 180 deg.\n 3 = 90 deg. ccw\n \"\"\"\n image = [list(row) for row in image]\n\n for n in range(angle % 4):\n image = list(zip(*image[::-1]))\n\n return image": 1993, "def generate_seed(seed):\n \"\"\"Generate seed for random number generator\"\"\"\n if seed is None:\n random.seed()\n seed = random.randint(0, sys.maxsize)\n random.seed(a=seed)\n\n return seed": 1994, "def __clear_buffers(self):\n \"\"\"Clears the input and output buffers\"\"\"\n try:\n self._port.reset_input_buffer()\n self._port.reset_output_buffer()\n except AttributeError:\n #pySerial 2.7\n self._port.flushInput()\n self._port.flushOutput()": 1995, "def _change_height(self, ax, new_value):\n \"\"\"Make bars in horizontal bar chart thinner\"\"\"\n for patch in ax.patches:\n current_height = patch.get_height()\n diff = current_height - new_value\n\n # we change the bar height\n patch.set_height(new_value)\n\n # we recenter the bar\n patch.set_y(patch.get_y() + diff * .5)": 1996, "async def terminate(self):\n \"\"\"Terminate a running script.\"\"\"\n self.proc.terminate()\n\n await asyncio.wait_for(self.proc.wait(), self.kill_delay)\n if self.proc.returncode is None:\n self.proc.kill()\n await self.proc.wait()\n\n await super().terminate()": 1997, "def reportMemory(k, options, field=None, isBytes=False):\n \"\"\" Given k kilobytes, report back the correct format as string.\n \"\"\"\n if options.pretty:\n return prettyMemory(int(k), field=field, isBytes=isBytes)\n else:\n if isBytes:\n k /= 1024.\n if field is not None:\n return \"%*dK\" % (field - 1, k) # -1 for the \"K\"\n else:\n return \"%dK\" % int(k)": 1998, "def OnUpdateFigurePanel(self, event):\n \"\"\"Redraw event handler for the figure panel\"\"\"\n\n if self.updating:\n return\n\n self.updating = True\n self.figure_panel.update(self.get_figure(self.code))\n self.updating = False": 1999, "def format_line(data, linestyle):\n \"\"\"Formats a list of elements using the given line style\"\"\"\n return linestyle.begin + linestyle.sep.join(data) + linestyle.end": 2000, "def to_percentage(number, rounding=2):\n \"\"\"Creates a percentage string representation from the given `number`. The\n number is multiplied by 100 before adding a '%' character.\n\n Raises `ValueError` if `number` cannot be converted to a number.\n \"\"\"\n number = float(number) * 100\n number_as_int = int(number)\n rounded = round(number, rounding)\n\n return '{}%'.format(number_as_int if number_as_int == rounded else rounded)": 2001, "def irfftn(a, s, axes=None):\n \"\"\"\n Compute the inverse of the multi-dimensional discrete Fourier transform\n for real input. This function is a wrapper for\n :func:`pyfftw.interfaces.numpy_fft.irfftn`, with an interface similar to\n that of :func:`numpy.fft.irfftn`.\n\n Parameters\n ----------\n a : array_like\n Input array\n s : sequence of ints\n Shape of the output along each transformed axis (input is cropped or\n zero-padded to match). This parameter is not optional because, unlike\n :func:`ifftn`, the output shape cannot be uniquely determined from\n the input shape.\n axes : sequence of ints, optional (default None)\n Axes over which to compute the inverse DFT.\n\n Returns\n -------\n af : ndarray\n Inverse DFT of input array\n \"\"\"\n\n return pyfftw.interfaces.numpy_fft.irfftn(\n a, s=s, axes=axes, overwrite_input=False,\n planner_effort='FFTW_MEASURE', threads=pyfftw_threads)": 2002, "def closest(xarr, val):\n \"\"\" Return the index of the closest in xarr to value val \"\"\"\n idx_closest = np.argmin(np.abs(np.array(xarr) - val))\n return idx_closest": 2003, "def _most_common(iterable):\n \"\"\"Returns the most common element in `iterable`.\"\"\"\n data = Counter(iterable)\n return max(data, key=data.__getitem__)": 2004, "def to_snake_case(s):\n \"\"\"Converts camel-case identifiers to snake-case.\"\"\"\n return re.sub('([^_A-Z])([A-Z])', lambda m: m.group(1) + '_' + m.group(2).lower(), s)": 2005, "def dereference_url(url):\n \"\"\"\n Makes a HEAD request to find the final destination of a URL after\n following any redirects\n \"\"\"\n res = open_url(url, method='HEAD')\n res.close()\n return res.url": 2006, "def speedtest(func, *args, **kwargs):\n \"\"\" Test the speed of a function. \"\"\"\n n = 100\n start = time.time()\n for i in range(n): func(*args,**kwargs)\n end = time.time()\n return (end-start)/n": 2007, "def money(min=0, max=10):\n \"\"\"Return a str of decimal with two digits after a decimal mark.\"\"\"\n value = random.choice(range(min * 100, max * 100))\n return \"%1.2f\" % (float(value) / 100)": 2008, "def clean_float(v):\n \"\"\"Remove commas from a float\"\"\"\n\n if v is None or not str(v).strip():\n return None\n\n return float(str(v).replace(',', ''))": 2009, "def random_letters(n):\n \"\"\"\n Generate a random string from a-zA-Z\n :param n: length of the string\n :return: the random string\n \"\"\"\n return ''.join(random.SystemRandom().choice(string.ascii_letters) for _ in range(n))": 2010, "def _file_and_exists(val, input_files):\n \"\"\"Check if an input is a file and exists.\n\n Checks both locally (staged) and from input files (re-passed but never localized).\n \"\"\"\n return ((os.path.exists(val) and os.path.isfile(val)) or\n val in input_files)": 2011, "def read_uint(data, start, length):\n \"\"\"Extract a uint from a position in a sequence.\"\"\"\n return int.from_bytes(data[start:start+length], byteorder='big')": 2012, "def example_write_file_to_disk_if_changed():\n \"\"\" Try to remove all comments from a file, and save it if changes were made. \"\"\"\n my_file = FileAsObj('/tmp/example_file.txt')\n my_file.rm(my_file.egrep('^#'))\n if my_file.changed:\n my_file.save()": 2013, "def chkstr(s, v):\n \"\"\"\n Small routine for checking whether a string is empty\n even a string\n\n :param s: the string in question\n :param v: variable name\n \"\"\"\n if type(s) != str:\n raise TypeError(\"{var} must be str\".format(var=v))\n if not s:\n raise ValueError(\"{var} cannot be empty\".format(var=v))": 2014, "def get_url_file_name(url):\n \"\"\"Get the file name from an url\n \n Parameters\n ----------\n url : str\n\n Returns\n -------\n str\n The file name \n \"\"\"\n\n assert isinstance(url, (str, _oldstr))\n return urlparse.urlparse(url).path.split('/')[-1]": 2015, "def extent(self):\n \"\"\"Helper for matplotlib imshow\"\"\"\n return (\n self.intervals[1].pix1 - 0.5,\n self.intervals[1].pix2 - 0.5,\n self.intervals[0].pix1 - 0.5,\n self.intervals[0].pix2 - 0.5,\n )": 2016, "def _get_background_color(self):\n \"\"\"Returns background color rgb tuple of right line\"\"\"\n\n color = self.cell_attributes[self.key][\"bgcolor\"]\n return tuple(c / 255.0 for c in color_pack2rgb(color))": 2017, "def resize(self, size):\n \"\"\"Return a new Image instance with the given size.\"\"\"\n return Image(self.pil_image.resize(size, PIL.Image.ANTIALIAS))": 2018, "def min_max_normalize(img):\n \"\"\"Centre and normalize a given array.\n\n Parameters:\n ----------\n img: np.ndarray\n\n \"\"\"\n\n min_img = img.min()\n max_img = img.max()\n\n return (img - min_img) / (max_img - min_img)": 2019, "def get_date(date):\n \"\"\"\n Get the date from a value that could be a date object or a string.\n\n :param date: The date object or string.\n\n :returns: The date object.\n \"\"\"\n if type(date) is str:\n return datetime.strptime(date, '%Y-%m-%d').date()\n else:\n return date": 2020, "def get_shape(img):\n \"\"\"Return the shape of img.\n\n Paramerers\n -----------\n img:\n\n Returns\n -------\n shape: tuple\n \"\"\"\n if hasattr(img, 'shape'):\n shape = img.shape\n else:\n shape = img.get_data().shape\n return shape": 2021, "def setup_path():\n \"\"\"Sets up the python include paths to include src\"\"\"\n import os.path; import sys\n\n if sys.argv[0]:\n top_dir = os.path.dirname(os.path.abspath(sys.argv[0]))\n sys.path = [os.path.join(top_dir, \"src\")] + sys.path\n pass\n return": 2022, "def write_padding(fp, size, divisor=2):\n \"\"\"\n Writes padding bytes given the currently written size.\n\n :param fp: file-like object\n :param divisor: divisor of the byte alignment\n :return: written byte size\n \"\"\"\n remainder = size % divisor\n if remainder:\n return write_bytes(fp, struct.pack('%dx' % (divisor - remainder)))\n return 0": 2023, "def incr(self, key, incr_by=1):\n \"\"\"Increment the key by the given amount.\"\"\"\n return self.database.hincrby(self.key, key, incr_by)": 2024, "def fit_linear(X, y):\n \"\"\"\n Uses OLS to fit the regression.\n \"\"\"\n model = linear_model.LinearRegression()\n model.fit(X, y)\n return model": 2025, "def idx(df, index):\n \"\"\"Universal indexing for numpy and pandas objects.\"\"\"\n if isinstance(df, (pd.DataFrame, pd.Series)):\n return df.iloc[index]\n else:\n return df[index, :]": 2026, "def col_frequencies(col, weights=None, gap_chars='-.'):\n \"\"\"Frequencies of each residue type (totaling 1.0) in a single column.\"\"\"\n counts = col_counts(col, weights, gap_chars)\n # Reduce to frequencies\n scale = 1.0 / sum(counts.values())\n return dict((aa, cnt * scale) for aa, cnt in counts.iteritems())": 2027, "def ServerLoggingStartupInit():\n \"\"\"Initialize the server logging configuration.\"\"\"\n global LOGGER\n if local_log:\n logging.debug(\"Using local LogInit from %s\", local_log)\n local_log.LogInit()\n logging.debug(\"Using local AppLogInit from %s\", local_log)\n LOGGER = local_log.AppLogInit()\n else:\n LogInit()\n LOGGER = AppLogInit()": 2028, "def intty(cls):\n \"\"\" Check if we are in a tty. \"\"\"\n # XXX: temporary hack until we can detect if we are in a pipe or not\n return True\n\n if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty():\n return True\n\n return False": 2029, "def wrap_key(self, key):\n \"\"\"Translate the key into the central cell\n\n This method is only applicable in case of a periodic system.\n \"\"\"\n return tuple(np.round(\n self.integer_cell.shortest_vector(key)\n ).astype(int))": 2030, "def index(self, elem):\n \"\"\"Find the index of elem in the reversed iterator.\"\"\"\n return _coconut.len(self._iter) - self._iter.index(elem) - 1": 2031, "def get_inputs_from_cm(index, cm):\n \"\"\"Return indices of inputs to the node with the given index.\"\"\"\n return tuple(i for i in range(cm.shape[0]) if cm[i][index])": 2032, "def main(filename):\n \"\"\"\n Creates a PDF by embedding the first page from the given image and\n writes some text to it.\n\n @param[in] filename\n The source filename of the image to embed.\n \"\"\"\n\n # Prepare font.\n font_family = 'arial'\n font = Font(font_family, bold=True)\n if not font:\n raise RuntimeError('No font found for %r' % font_family)\n\n # Initialize PDF document on a stream.\n with Document('output.pdf') as document:\n\n # Initialize a new page and begin its context.\n with document.Page() as ctx:\n\n # Open the image to embed.\n with Image(filename) as embed:\n\n # Set the media box for the page to the same as the\n # image to embed.\n ctx.box = embed.box\n\n # Embed the image.\n ctx.embed(embed)\n\n # Write some text.\n ctx.add(Text('Hello World', font, size=14, x=100, y=60))": 2033, "def _index_ordering(redshift_list):\n \"\"\"\n\n :param redshift_list: list of redshifts\n :return: indexes in acending order to be evaluated (from z=0 to z=z_source)\n \"\"\"\n redshift_list = np.array(redshift_list)\n sort_index = np.argsort(redshift_list)\n return sort_index": 2034, "def __mul__(self, other):\n \"\"\"Handle the `*` operator.\"\"\"\n return self._handle_type(other)(self.value * other.value)": 2035, "def bin_to_int(string):\n \"\"\"Convert a one element byte string to signed int for python 2 support.\"\"\"\n if isinstance(string, str):\n return struct.unpack(\"b\", string)[0]\n else:\n return struct.unpack(\"b\", bytes([string]))[0]": 2036, "def end_index(self):\n \"\"\"\n Returns the 1-based index of the last object on this page,\n relative to total objects found (hits).\n \"\"\"\n return ((self.number - 1) * self.paginator.per_page +\n len(self.object_list))": 2037, "def prevmonday(num):\n \"\"\"\n Return unix SECOND timestamp of \"num\" mondays ago\n \"\"\"\n today = get_today()\n lastmonday = today - timedelta(days=today.weekday(), weeks=num)\n return lastmonday": 2038, "def get_line_ending(line):\n \"\"\"Return line ending.\"\"\"\n non_whitespace_index = len(line.rstrip()) - len(line)\n if not non_whitespace_index:\n return ''\n else:\n return line[non_whitespace_index:]": 2039, "def subkey(dct, keys):\n \"\"\"Get an entry from a dict of dicts by the list of keys to 'follow'\n \"\"\"\n key = keys[0]\n if len(keys) == 1:\n return dct[key]\n return subkey(dct[key], keys[1:])": 2040, "def all_collections(db):\n\t\"\"\"\n\tYield all non-sytem collections in db.\n\t\"\"\"\n\tinclude_pattern = r'(?!system\\.)'\n\treturn (\n\t\tdb[name]\n\t\tfor name in db.list_collection_names()\n\t\tif re.match(include_pattern, name)\n\t)": 2041, "def lin_interp(x, rangeX, rangeY):\n \"\"\"\n Interpolate linearly variable x in rangeX onto rangeY.\n \"\"\"\n s = (x - rangeX[0]) / mag(rangeX[1] - rangeX[0])\n y = rangeY[0] * (1 - s) + rangeY[1] * s\n return y": 2042, "def intersect_3d(p1, p2):\n \"\"\"Find the closes point for a given set of lines in 3D.\n\n Parameters\n ----------\n p1 : (M, N) array_like\n Starting points\n p2 : (M, N) array_like\n End points.\n\n Returns\n -------\n x : (N,) ndarray\n Least-squares solution - the closest point of the intersections.\n\n Raises\n ------\n numpy.linalg.LinAlgError\n If computation does not converge.\n\n \"\"\"\n v = p2 - p1\n normed_v = unit_vector(v)\n nx = normed_v[:, 0]\n ny = normed_v[:, 1]\n nz = normed_v[:, 2]\n xx = np.sum(nx**2 - 1)\n yy = np.sum(ny**2 - 1)\n zz = np.sum(nz**2 - 1)\n xy = np.sum(nx * ny)\n xz = np.sum(nx * nz)\n yz = np.sum(ny * nz)\n M = np.array([(xx, xy, xz), (xy, yy, yz), (xz, yz, zz)])\n x = np.sum(\n p1[:, 0] * (nx**2 - 1) + p1[:, 1] * (nx * ny) + p1[:, 2] * (nx * nz)\n )\n y = np.sum(\n p1[:, 0] * (nx * ny) + p1[:, 1] * (ny * ny - 1) + p1[:, 2] * (ny * nz)\n )\n z = np.sum(\n p1[:, 0] * (nx * nz) + p1[:, 1] * (ny * nz) + p1[:, 2] * (nz**2 - 1)\n )\n return np.linalg.lstsq(M, np.array((x, y, z)), rcond=None)[0]": 2043, "def gday_of_year(self):\n \"\"\"Return the number of days since January 1 of the given year.\"\"\"\n return (self.date - dt.date(self.date.year, 1, 1)).days": 2044, "def is_date_type(cls):\n \"\"\"Return True if the class is a date type.\"\"\"\n if not isinstance(cls, type):\n return False\n return issubclass(cls, date) and not issubclass(cls, datetime)": 2045, "def root_parent(self, category=None):\n \"\"\" Returns the topmost parent of the current category. \"\"\"\n return next(filter(lambda c: c.is_root, self.hierarchy()))": 2046, "def stop_at(iterable, idx):\n \"\"\"Stops iterating before yielding the specified idx.\"\"\"\n for i, item in enumerate(iterable):\n if i == idx: return\n yield item": 2047, "def previous_quarter(d):\n \"\"\"\n Retrieve the previous quarter for dt\n \"\"\"\n from django_toolkit.datetime_util import quarter as datetime_quarter\n return quarter( (datetime_quarter(datetime(d.year, d.month, d.day))[0] + timedelta(days=-1)).date() )": 2048, "def links(cls, page):\n \"\"\"return all links on a page, including potentially rel= links.\"\"\"\n for match in cls.HREF_RE.finditer(page):\n yield cls.href_match_to_url(match)": 2049, "def get_size(path):\n \"\"\" Returns the size in bytes if `path` is a file,\n or the size of all files in `path` if it's a directory.\n Analogous to `du -s`.\n \"\"\"\n if os.path.isfile(path):\n return os.path.getsize(path)\n return sum(get_size(os.path.join(path, f)) for f in os.listdir(path))": 2050, "def _unordered_iterator(self):\n \"\"\"\n Return the value of each QuerySet, but also add the '#' property to each\n return item.\n \"\"\"\n for i, qs in zip(self._queryset_idxs, self._querysets):\n for item in qs:\n setattr(item, '#', i)\n yield item": 2051, "def _fill(self):\n \"\"\"Advance the iterator without returning the old head.\"\"\"\n try:\n self._head = self._iterable.next()\n except StopIteration:\n self._head = None": 2052, "def memsize(self):\n \"\"\" Total array cell + indexes size\n \"\"\"\n return self.size + 1 + TYPE.size(gl.BOUND_TYPE) * len(self.bounds)": 2053, "def load(raw_bytes):\n \"\"\"\n given a bytes object, should return a base python data\n structure that represents the object.\n \"\"\"\n try:\n if not isinstance(raw_bytes, string_type):\n raw_bytes = raw_bytes.decode()\n return json.loads(raw_bytes)\n except ValueError as e:\n raise SerializationException(str(e))": 2054, "def _extract_node_text(node):\n \"\"\"Extract text from a given lxml node.\"\"\"\n\n texts = map(\n six.text_type.strip, map(six.text_type, map(unescape, node.xpath(\".//text()\")))\n )\n return \" \".join(text for text in texts if text)": 2055, "def compose_all(tups):\n \"\"\"Compose all given tuples together.\"\"\"\n from . import ast # I weep for humanity\n return functools.reduce(lambda x, y: x.compose(y), map(ast.make_tuple, tups), ast.make_tuple({}))": 2056, "def json(body, charset='utf-8', **kwargs):\n \"\"\"Takes JSON formatted data, converting it into native Python objects\"\"\"\n return json_converter.loads(text(body, charset=charset))": 2057, "def get_abi3_suffix():\n \"\"\"Return the file extension for an abi3-compliant Extension()\"\"\"\n for suffix, _, _ in (s for s in imp.get_suffixes() if s[2] == imp.C_EXTENSION):\n if '.abi3' in suffix: # Unix\n return suffix\n elif suffix == '.pyd': # Windows\n return suffix": 2058, "def json_dumps(self, obj):\n \"\"\"Serializer for consistency\"\"\"\n return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))": 2059, "def _cumprod(l):\n \"\"\"Cumulative product of a list.\n\n Args:\n l: a list of integers\n Returns:\n a list with one more element (starting with 1)\n \"\"\"\n ret = [1]\n for item in l:\n ret.append(ret[-1] * item)\n return ret": 2060, "def typename(obj):\n \"\"\"Returns the type of obj as a string. More descriptive and specific than\n type(obj), and safe for any object, unlike __class__.\"\"\"\n if hasattr(obj, '__class__'):\n return getattr(obj, '__class__').__name__\n else:\n return type(obj).__name__": 2061, "def json_decode(data):\n \"\"\"\n Decodes the given JSON as primitives\n \"\"\"\n if isinstance(data, six.binary_type):\n data = data.decode('utf-8')\n\n return json.loads(data)": 2062, "def prettify(elem):\n \"\"\"Return a pretty-printed XML string for the Element.\n \"\"\"\n rough_string = ET.tostring(elem, 'utf-8')\n reparsed = minidom.parseString(rough_string)\n return reparsed.toprettyxml(indent=\"\\t\")": 2063, "def classify_clusters(points, n=10):\n \"\"\"\n Return an array of K-Means cluster classes for an array of `shapely.geometry.Point` objects.\n \"\"\"\n arr = [[p.x, p.y] for p in points.values]\n clf = KMeans(n_clusters=n)\n clf.fit(arr)\n classes = clf.predict(arr)\n return classes": 2064, "def _sourced_dict(self, source=None, **kwargs):\n \"\"\"Like ``dict(**kwargs)``, but where the ``source`` key is special.\n \"\"\"\n if source:\n kwargs['source'] = source\n elif self.source:\n kwargs['source'] = self.source\n return kwargs": 2065, "def get_element_attribute_or_empty(element, attribute_name):\n \"\"\"\n\n Args:\n element (element): The xib's element.\n attribute_name (str): The desired attribute's name.\n\n Returns:\n The attribute's value, or an empty str if none exists.\n\n \"\"\"\n return element.attributes[attribute_name].value if element.hasAttribute(attribute_name) else \"\"": 2066, "def make_lambda(call):\n \"\"\"Wrap an AST Call node to lambda expression node.\n call: ast.Call node\n \"\"\"\n empty_args = ast.arguments(args=[], vararg=None, kwarg=None, defaults=[])\n return ast.Lambda(args=empty_args, body=call)": 2067, "def is_changed():\n \"\"\" Checks if current project has any noncommited changes. \"\"\"\n executed, changed_lines = execute_git('status --porcelain', output=False)\n merge_not_finished = mod_path.exists('.git/MERGE_HEAD')\n return changed_lines.strip() or merge_not_finished": 2068, "def apply_kwargs(func, **kwargs):\n \"\"\"Call *func* with kwargs, but only those kwargs that it accepts.\n \"\"\"\n new_kwargs = {}\n params = signature(func).parameters\n for param_name in params.keys():\n if param_name in kwargs:\n new_kwargs[param_name] = kwargs[param_name]\n return func(**new_kwargs)": 2069, "def run_tests(self):\n\t\t\"\"\"\n\t\tInvoke pytest, replacing argv. Return result code.\n\t\t\"\"\"\n\t\twith _save_argv(_sys.argv[:1] + self.addopts):\n\t\t\tresult_code = __import__('pytest').main()\n\t\t\tif result_code:\n\t\t\t\traise SystemExit(result_code)": 2070, "def print_matrix(X, decimals=1):\n \"\"\"Pretty printing for numpy matrix X\"\"\"\n for row in np.round(X, decimals=decimals):\n print(row)": 2071, "def get_table_width(table):\n \"\"\"\n Gets the width of the table that would be printed.\n :rtype: ``int``\n \"\"\"\n columns = transpose_table(prepare_rows(table))\n widths = [max(len(cell) for cell in column) for column in columns]\n return len('+' + '|'.join('-' * (w + 2) for w in widths) + '+')": 2072, "def open01(x, limit=1.e-6):\n \"\"\"Constrain numbers to (0,1) interval\"\"\"\n try:\n return np.array([min(max(y, limit), 1. - limit) for y in x])\n except TypeError:\n return min(max(x, limit), 1. - limit)": 2073, "def _check_graphviz_available(output_format):\n \"\"\"check if we need graphviz for different output format\"\"\"\n try:\n subprocess.call([\"dot\", \"-V\"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n except OSError:\n print(\n \"The output format '%s' is currently not available.\\n\"\n \"Please install 'Graphviz' to have other output formats \"\n \"than 'dot' or 'vcg'.\" % output_format\n )\n sys.exit(32)": 2074, "def index(m, val):\n \"\"\"\n Return the indices of all the ``val`` in ``m``\n \"\"\"\n mm = np.array(m)\n idx_tuple = np.where(mm == val)\n idx = idx_tuple[0].tolist()\n\n return idx": 2075, "def _unique_rows_numpy(a):\n \"\"\"return unique rows\"\"\"\n a = np.ascontiguousarray(a)\n unique_a = np.unique(a.view([('', a.dtype)] * a.shape[1]))\n return unique_a.view(a.dtype).reshape((unique_a.shape[0], a.shape[1]))": 2076, "def executable_exists(executable):\n \"\"\"Test if an executable is available on the system.\"\"\"\n for directory in os.getenv(\"PATH\").split(\":\"):\n if os.path.exists(os.path.join(directory, executable)):\n return True\n return False": 2077, "def values(self):\n \"\"\"return a list of all state values\"\"\"\n values = []\n for __, data in self.items():\n values.append(data)\n return values": 2078, "def btc_make_p2sh_address( script_hex ):\n \"\"\"\n Make a P2SH address from a hex script\n \"\"\"\n h = hashing.bin_hash160(binascii.unhexlify(script_hex))\n addr = bin_hash160_to_address(h, version_byte=multisig_version_byte)\n return addr": 2079, "def get_dimension_array(array):\n \"\"\"\n Get dimension of an array getting the number of rows and the max num of\n columns.\n \"\"\"\n if all(isinstance(el, list) for el in array):\n result = [len(array), len(max([x for x in array], key=len,))]\n\n # elif array and isinstance(array, list):\n else:\n result = [len(array), 1]\n\n return result": 2080, "def get_dt_list(fn_list):\n \"\"\"Get list of datetime objects, extracted from a filename\n \"\"\"\n dt_list = np.array([fn_getdatetime(fn) for fn in fn_list])\n return dt_list": 2081, "def poke_array(self, store, name, elemtype, elements, container, visited, _stack):\n \"\"\"abstract method\"\"\"\n raise NotImplementedError": 2082, "def is_valid(email):\n \"\"\"Email address validation method.\n\n :param email: Email address to be saved.\n :type email: basestring\n :returns: True if email address is correct, False otherwise.\n :rtype: bool\n \"\"\"\n if isinstance(email, basestring) and EMAIL_RE.match(email):\n return True\n return False": 2083, "def loadmat(filename):\n \"\"\"This function should be called instead of direct spio.loadmat\n as it cures the problem of not properly recovering python dictionaries\n from mat files. It calls the function check keys to cure all entries\n which are still mat-objects\n \"\"\"\n data = sploadmat(filename, struct_as_record=False, squeeze_me=True)\n return _check_keys(data)": 2084, "def _float_almost_equal(float1, float2, places=7):\n \"\"\"Return True if two numbers are equal up to the\n specified number of \"places\" after the decimal point.\n \"\"\"\n\n if round(abs(float2 - float1), places) == 0:\n return True\n\n return False": 2085, "def getFunction(self):\n \"\"\"Called by remote workers. Useful to populate main module globals()\n for interactive shells. Retrieves the serialized function.\"\"\"\n return functionFactory(\n self.code,\n self.name,\n self.defaults,\n self.globals,\n self.imports,\n )": 2086, "def is_text(obj, name=None):\n \"\"\"\n returns True if object is text-like\n \"\"\"\n try: # python2\n ans = isinstance(obj, basestring)\n except NameError: # python3\n ans = isinstance(obj, str)\n if name:\n print(\"is_text: (%s) %s = %s\" % (ans, name, obj.__class__),\n file=sys.stderr)\n return ans": 2087, "def _get_or_create_stack(name):\n \"\"\"Returns a thread local stack uniquified by the given name.\"\"\"\n stack = getattr(_LOCAL_STACKS, name, None)\n if stack is None:\n stack = []\n setattr(_LOCAL_STACKS, name, stack)\n return stack": 2088, "def unlock(self):\n \"\"\"Closes the session to the database.\"\"\"\n if not hasattr(self, 'session'):\n raise RuntimeError('Error detected! The session that you want to close does not exist any more!')\n logger.debug(\"Closed database session of '%s'\" % self._database)\n self.session.close()\n del self.session": 2089, "def find_frequencies(data, freq=44100, bits=16):\n \"\"\"Convert audio data into a frequency-amplitude table using fast fourier\n transformation.\n\n Return a list of tuples (frequency, amplitude).\n\n Data should only contain one channel of audio.\n \"\"\"\n # Fast fourier transform\n n = len(data)\n p = _fft(data)\n uniquePts = numpy.ceil((n + 1) / 2.0)\n\n # Scale by the length (n) and square the value to get the amplitude\n p = [(abs(x) / float(n)) ** 2 * 2 for x in p[0:uniquePts]]\n p[0] = p[0] / 2\n if n % 2 == 0:\n p[-1] = p[-1] / 2\n\n # Generate the frequencies and zip with the amplitudes\n s = freq / float(n)\n freqArray = numpy.arange(0, uniquePts * s, s)\n return zip(freqArray, p)": 2090, "def log_no_newline(self, msg):\n \"\"\" print the message to the predefined log file without newline \"\"\"\n self.print2file(self.logfile, False, False, msg)": 2091, "def close_log(log, verbose=True):\n \"\"\"Close log\n\n This method closes and active logging.Logger instance.\n\n Parameters\n ----------\n log : logging.Logger\n Logging instance\n\n \"\"\"\n\n if verbose:\n print('Closing log file:', log.name)\n\n # Send closing message.\n log.info('The log file has been closed.')\n\n # Remove all handlers from log.\n [log.removeHandler(handler) for handler in log.handlers]": 2092, "def get_geoip(ip):\n \"\"\"Lookup country for IP address.\"\"\"\n reader = geolite2.reader()\n ip_data = reader.get(ip) or {}\n return ip_data.get('country', {}).get('iso_code')": 2093, "def setLoggerAll(self, mthd):\n \"\"\" Sends all messages to ``logger.[mthd]()`` for handling \"\"\"\n for key in self._logger_methods:\n self._logger_methods[key] = mthd": 2094, "def time_range(from_=None, to=None): # todo datetime conversion\n \"\"\"\n :param str from_:\n :param str to:\n\n :return: dict\n \"\"\"\n args = locals()\n return {\n k.replace('_', ''): v for k, v in args.items()\n }": 2095, "def path_to_list(pathstr):\n \"\"\"Conver a path string to a list of path elements.\"\"\"\n return [elem for elem in pathstr.split(os.path.pathsep) if elem]": 2096, "def write(self, text):\n \"\"\"Write text. An additional attribute terminator with a value of\n None is added to the logging record to indicate that StreamHandler\n should not add a newline.\"\"\"\n self.logger.log(self.loglevel, text, extra={'terminator': None})": 2097, "def camelcase_to_slash(name):\n \"\"\" Converts CamelCase to camel/case\n\n code ripped from http://stackoverflow.com/questions/1175208/does-the-python-standard-library-have-function-to-convert-camelcase-to-camel-cas\n \"\"\"\n\n s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1/\\2', name)\n return re.sub('([a-z0-9])([A-Z])', r'\\1/\\2', s1).lower()": 2098, "def main(argv=None):\n \"\"\"Run a Tensorflow model on the Iris dataset.\"\"\"\n args = parse_arguments(sys.argv if argv is None else argv)\n\n tf.logging.set_verbosity(tf.logging.INFO)\n learn_runner.run(\n experiment_fn=get_experiment_fn(args),\n output_dir=args.job_dir)": 2099, "def add_suffix(fullname, suffix):\n \"\"\" Add suffix to a full file name\"\"\"\n name, ext = os.path.splitext(fullname)\n return name + '_' + suffix + ext": 2100, "def from_file(filename, mime=False):\n \"\"\" Opens file, attempts to identify content based\n off magic number and will return the file extension.\n If mime is True it will return the mime type instead.\n\n :param filename: path to file\n :param mime: Return mime, not extension\n :return: guessed extension or mime\n \"\"\"\n\n head, foot = _file_details(filename)\n return _magic(head, foot, mime, ext_from_filename(filename))": 2101, "def process_instance(self, instance):\n self.log.debug(\"e = mc^2\")\n self.log.info(\"About to fail..\")\n self.log.warning(\"Failing.. soooon..\")\n self.log.critical(\"Ok, you're done.\")\n assert False, \"\"\"ValidateFailureMock was destined to fail..\n\nHere's some extended information about what went wrong.\n\nIt has quite the long string associated with it, including\na few newlines and a list.\n\n- Item 1\n- Item 2\n\n\"\"\"": 2102, "def markdown_media_css():\n \"\"\" Add css requirements to HTML.\n\n :returns: Editor template context.\n\n \"\"\"\n return dict(\n CSS_SET=posixpath.join(\n settings.MARKDOWN_SET_PATH, settings.MARKDOWN_SET_NAME, 'style.css'\n ),\n CSS_SKIN=posixpath.join(\n 'django_markdown', 'skins', settings.MARKDOWN_EDITOR_SKIN,\n 'style.css'\n )\n )": 2103, "def cross_list(*sequences):\n \"\"\"\n From: http://book.opensourceproject.org.cn/lamp/python/pythoncook2/opensource/0596007973/pythoncook2-chp-19-sect-9.html\n \"\"\"\n result = [[ ]]\n for seq in sequences:\n result = [sublist+[item] for sublist in result for item in seq]\n return result": 2104, "def get_filename_safe_string(string):\n \"\"\"\n Converts a string to a string that is safe for a filename\n Args:\n string (str): A string to make safe for a filename\n\n Returns:\n str: A string safe for a filename\n \"\"\"\n invalid_filename_chars = ['\\\\', '/', ':', '\"', '*', '?', '|', '\\n',\n '\\r']\n if string is None:\n string = \"None\"\n for char in invalid_filename_chars:\n string = string.replace(char, \"\")\n string = string.rstrip(\".\")\n\n return string": 2105, "def aggregate(d, y_size, x_size):\n \"\"\"Average every 4 elements (2x2) in a 2D array\"\"\"\n if d.ndim != 2:\n # we can't guarantee what blocks we are getting and how\n # it should be reshaped to do the averaging.\n raise ValueError(\"Can't aggregrate (reduce) data arrays with \"\n \"more than 2 dimensions.\")\n if not (x_size.is_integer() and y_size.is_integer()):\n raise ValueError(\"Aggregation factors are not integers\")\n for agg_size, chunks in zip([y_size, x_size], d.chunks):\n for chunk_size in chunks:\n if chunk_size % agg_size != 0:\n raise ValueError(\"Aggregation requires arrays with \"\n \"shapes and chunks divisible by the \"\n \"factor\")\n\n new_chunks = (tuple(int(x / y_size) for x in d.chunks[0]),\n tuple(int(x / x_size) for x in d.chunks[1]))\n return da.core.map_blocks(_mean, d, y_size, x_size, dtype=d.dtype, chunks=new_chunks)": 2106, "def Softsign(a):\n \"\"\"\n Softsign op.\n \"\"\"\n return np.divide(a, np.add(np.abs(a), 1)),": 2107, "def variance(arr):\n \"\"\"variance of the values, must have 2 or more entries.\n\n :param arr: list of numbers\n :type arr: number[] a number array\n :return: variance\n :rtype: float\n\n \"\"\"\n avg = average(arr)\n return sum([(float(x)-avg)**2 for x in arr])/float(len(arr)-1)": 2108, "def plot(self):\n \"\"\"Plot the empirical histogram versus best-fit distribution's PDF.\"\"\"\n plt.plot(self.bin_edges, self.hist, self.bin_edges, self.best_pdf)": 2109, "def _histplot_op(ax, data, **kwargs):\n \"\"\"Add a histogram for the data to the axes.\"\"\"\n bins = get_bins(data)\n ax.hist(data, bins=bins, align=\"left\", density=True, **kwargs)\n return ax": 2110, "def axes_off(ax):\n \"\"\"Get rid of all axis ticks, lines, etc.\n \"\"\"\n ax.set_frame_on(False)\n ax.axes.get_yaxis().set_visible(False)\n ax.axes.get_xaxis().set_visible(False)": 2111, "def to_camel_case(snake_case_name):\n \"\"\"\n Converts snake_cased_names to CamelCaseNames.\n\n :param snake_case_name: The name you'd like to convert from.\n :type snake_case_name: string\n\n :returns: A converted string\n :rtype: string\n \"\"\"\n bits = snake_case_name.split('_')\n return ''.join([bit.capitalize() for bit in bits])": 2112, "def rgb2gray(img):\n \"\"\"Converts an RGB image to grayscale using matlab's algorithm.\"\"\"\n T = np.linalg.inv(np.array([\n [1.0, 0.956, 0.621],\n [1.0, -0.272, -0.647],\n [1.0, -1.106, 1.703],\n ]))\n r_c, g_c, b_c = T[0]\n r, g, b = np.rollaxis(as_float_image(img), axis=-1)\n return r_c * r + g_c * g + b_c * b": 2113, "def jac(x,a):\n \"\"\" Jacobian matrix given Christophe's suggestion of f \"\"\"\n return (x-a) / np.sqrt(((x-a)**2).sum(1))[:,np.newaxis]": 2114, "def SegmentMax(a, ids):\n \"\"\"\n Segmented max op.\n \"\"\"\n func = lambda idxs: np.amax(a[idxs], axis=0)\n return seg_map(func, a, ids),": 2115, "def change_cell(self, x, y, ch, fg, bg):\n \"\"\"Change cell in position (x;y).\n \"\"\"\n self.console.draw_char(x, y, ch, fg, bg)": 2116, "def memory_usage(method):\n \"\"\"Log memory usage before and after a method.\"\"\"\n def wrapper(*args, **kwargs):\n logging.info('Memory before method %s is %s.',\n method.__name__, runtime.memory_usage().current())\n result = method(*args, **kwargs)\n logging.info('Memory after method %s is %s',\n method.__name__, runtime.memory_usage().current())\n return result\n return wrapper": 2117, "def _rendered_size(text, point_size, font_file):\n \"\"\"\n Return a (width, height) pair representing the size of *text* in English\n Metric Units (EMU) when rendered at *point_size* in the font defined in\n *font_file*.\n \"\"\"\n emu_per_inch = 914400\n px_per_inch = 72.0\n\n font = _Fonts.font(font_file, point_size)\n px_width, px_height = font.getsize(text)\n\n emu_width = int(px_width / px_per_inch * emu_per_inch)\n emu_height = int(px_height / px_per_inch * emu_per_inch)\n\n return emu_width, emu_height": 2118, "def submit_form_id(step, id):\n \"\"\"\n Submit the form having given id.\n \"\"\"\n form = world.browser.find_element_by_xpath(str('id(\"{id}\")'.format(id=id)))\n form.submit()": 2119, "def _tofloat(obj):\n \"\"\"Convert to float if object is a float string.\"\"\"\n if \"inf\" in obj.lower().strip():\n return obj\n try:\n return int(obj)\n except ValueError:\n try:\n return float(obj)\n except ValueError:\n return obj": 2120, "def get_subject(self, msg):\n \"\"\"Extracts the subject line from an EmailMessage object.\"\"\"\n\n text, encoding = decode_header(msg['subject'])[-1]\n\n try:\n text = text.decode(encoding)\n\n # If it's already decoded, ignore error\n except AttributeError:\n pass\n\n return text": 2121, "def update(packages, env=None, user=None):\n \"\"\"\n Update conda packages in a conda env\n\n Attributes\n ----------\n packages: list of packages comma delimited\n \"\"\"\n packages = ' '.join(packages.split(','))\n cmd = _create_conda_cmd('update', args=[packages, '--yes', '-q'], env=env, user=user)\n return _execcmd(cmd, user=user)": 2122, "def _check_fpos(self, fp_, fpos, offset, block):\n \"\"\"Check file position matches blocksize\"\"\"\n if (fp_.tell() + offset != fpos):\n warnings.warn(\"Actual \"+block+\" header size does not match expected\")\n return": 2123, "def assert_any_call(self, *args, **kwargs):\n \"\"\"assert the mock has been called with the specified arguments.\n\n The assert passes if the mock has *ever* been called, unlike\n `assert_called_with` and `assert_called_once_with` that only pass if\n the call is the most recent one.\"\"\"\n kall = call(*args, **kwargs)\n if kall not in self.call_args_list:\n expected_string = self._format_mock_call_signature(args, kwargs)\n raise AssertionError(\n '%s call not found' % expected_string\n )": 2124, "def update(self, *args, **kwargs):\n \"\"\" A handy update() method which returns self :)\n\n :rtype: DictProxy\n \"\"\"\n super(DictProxy, self).update(*args, **kwargs)\n return self": 2125, "def all_strings(arr):\n \"\"\"\n Ensures that the argument is a list that either is empty or contains only strings\n :param arr: list\n :return:\n \"\"\"\n if not isinstance([], list):\n raise TypeError(\"non-list value found where list is expected\")\n return all(isinstance(x, str) for x in arr)": 2126, "def install():\n \"\"\"\n Installs ScoutApm SQL Instrumentation by monkeypatching the `cursor`\n method of BaseDatabaseWrapper, to return a wrapper that instruments any\n calls going through it.\n \"\"\"\n\n @monkeypatch_method(BaseDatabaseWrapper)\n def cursor(original, self, *args, **kwargs):\n result = original(*args, **kwargs)\n return _DetailedTracingCursorWrapper(result, self)\n\n logger.debug(\"Monkey patched SQL\")": 2127, "def is_integer(obj):\n \"\"\"Is this an integer.\n\n :param object obj:\n :return:\n \"\"\"\n if PYTHON3:\n return isinstance(obj, int)\n return isinstance(obj, (int, long))": 2128, "def move_up(lines=1, file=sys.stdout):\n \"\"\" Move the cursor up a number of lines.\n\n Esc[ValueA:\n Moves the cursor up by the specified number of lines without changing\n columns. If the cursor is already on the top line, ANSI.SYS ignores\n this sequence.\n \"\"\"\n move.up(lines).write(file=file)": 2129, "def gmove(pattern, destination):\n \"\"\"Move all file found by glob.glob(pattern) to destination directory.\n\n Args:\n pattern (str): Glob pattern\n destination (str): Path to the destination directory.\n\n Returns:\n bool: True if the operation is successful, False otherwise.\n \"\"\"\n for item in glob.glob(pattern):\n if not move(item, destination):\n return False\n return True": 2130, "def is_sparse_vector(x):\n \"\"\" x is a 2D sparse matrix with it's first shape equal to 1.\n \"\"\"\n return sp.issparse(x) and len(x.shape) == 2 and x.shape[0] == 1": 2131, "def movingaverage(arr, window):\n \"\"\"\n Calculates the moving average (\"rolling mean\") of an array\n of a certain window size.\n \"\"\"\n m = np.ones(int(window)) / int(window)\n return scipy.ndimage.convolve1d(arr, m, axis=0, mode='reflect')": 2132, "def split_multiline(value):\n \"\"\"Split a multiline string into a list, excluding blank lines.\"\"\"\n return [element for element in (line.strip() for line in value.split('\\n'))\n if element]": 2133, "def has_field(mc, field_name):\n \"\"\"\n detect if a model has a given field has\n\n :param field_name:\n :param mc:\n :return:\n \"\"\"\n try:\n mc._meta.get_field(field_name)\n except FieldDoesNotExist:\n return False\n return True": 2134, "def many_until1(these, term):\n \"\"\"Like many_until but must consume at least one of these.\n \"\"\"\n first = [these()]\n these_results, term_result = many_until(these, term)\n return (first + these_results, term_result)": 2135, "def allsame(list_, strict=True):\n \"\"\"\n checks to see if list is equal everywhere\n\n Args:\n list_ (list):\n\n Returns:\n True if all items in the list are equal\n \"\"\"\n if len(list_) == 0:\n return True\n first_item = list_[0]\n return list_all_eq_to(list_, first_item, strict)": 2136, "def ncores_reserved(self):\n \"\"\"\n Returns the number of cores reserved in this moment.\n A core is reserved if it's still not running but\n we have submitted the task to the queue manager.\n \"\"\"\n return sum(task.manager.num_cores for task in self if task.status == task.S_SUB)": 2137, "def stop(self):\n \"\"\"stop server\"\"\"\n try:\n self.shutdown()\n except (PyMongoError, ServersError) as exc:\n logger.info(\"Killing %s with signal, shutdown command failed: %r\",\n self.name, exc)\n return process.kill_mprocess(self.proc)": 2138, "def build_list_type_validator(item_validator):\n \"\"\"Return a function which validates that the value is a list of items\n which are validated using item_validator.\n \"\"\"\n def validate_list_of_type(value):\n return [item_validator(item) for item in validate_list(value)]\n return validate_list_of_type": 2139, "def allZero(buffer):\n \"\"\"\n Tries to determine if a buffer is empty.\n \n @type buffer: str\n @param buffer: Buffer to test if it is empty.\n \n @rtype: bool\n @return: C{True} if the given buffer is empty, i.e. full of zeros,\n C{False} if it doesn't.\n \"\"\"\n allZero = True\n for byte in buffer:\n if byte != \"\\x00\":\n allZero = False\n break\n return allZero": 2140, "def isstring(value):\n \"\"\"Report whether the given value is a byte or unicode string.\"\"\"\n classes = (str, bytes) if pyutils.PY3 else basestring # noqa: F821\n return isinstance(value, classes)": 2141, "async def scalar(self, query, as_tuple=False):\n \"\"\"Get single value from ``select()`` query, i.e. for aggregation.\n\n :return: result is the same as after sync ``query.scalar()`` call\n \"\"\"\n query = self._swap_database(query)\n return (await scalar(query, as_tuple=as_tuple))": 2142, "def raw_connection_from(engine_or_conn):\n \"\"\"Extract a raw_connection and determine if it should be automatically closed.\n\n Only connections opened by this package will be closed automatically.\n \"\"\"\n if hasattr(engine_or_conn, 'cursor'):\n return engine_or_conn, False\n if hasattr(engine_or_conn, 'connection'):\n return engine_or_conn.connection, False\n return engine_or_conn.raw_connection(), True": 2143, "def executemany(self, sql, *params):\n \"\"\"Prepare a database query or command and then execute it against\n all parameter sequences found in the sequence seq_of_params.\n\n :param sql: the SQL statement to execute with optional ? parameters\n :param params: sequence parameters for the markers in the SQL.\n \"\"\"\n fut = self._run_operation(self._impl.executemany, sql, *params)\n return fut": 2144, "def information(filename):\n \"\"\"Returns the file exif\"\"\"\n check_if_this_file_exist(filename)\n filename = os.path.abspath(filename)\n result = get_json(filename)\n result = result[0]\n return result": 2145, "def _Enum(docstring, *names):\n \"\"\"Utility to generate enum classes used by annotations.\n\n Args:\n docstring: Docstring for the generated enum class.\n *names: Enum names.\n\n Returns:\n A class that contains enum names as attributes.\n \"\"\"\n enums = dict(zip(names, range(len(names))))\n reverse = dict((value, key) for key, value in enums.iteritems())\n enums['reverse_mapping'] = reverse\n enums['__doc__'] = docstring\n return type('Enum', (object,), enums)": 2146, "def is_exe(fpath):\n \"\"\"\n Path references an executable file.\n \"\"\"\n return os.path.isfile(fpath) and os.access(fpath, os.X_OK)": 2147, "def logout(self):\n \"\"\"\n Logout from the remote server.\n \"\"\"\n self.client.write('exit\\r\\n')\n self.client.read_all()\n self.client.close()": 2148, "def get_adjacent_matrix(self):\n \"\"\"Get adjacency matrix.\n\n Returns:\n :param adj: adjacency matrix\n :type adj: np.ndarray\n \"\"\"\n edges = self.edges\n num_edges = len(edges) + 1\n adj = np.zeros([num_edges, num_edges])\n\n for k in range(num_edges - 1):\n adj[edges[k].L, edges[k].R] = 1\n adj[edges[k].R, edges[k].L] = 1\n\n return adj": 2149, "def get_shared_memory_bytes():\n \"\"\"Get the size of the shared memory file system.\n\n Returns:\n The size of the shared memory file system in bytes.\n \"\"\"\n # Make sure this is only called on Linux.\n assert sys.platform == \"linux\" or sys.platform == \"linux2\"\n\n shm_fd = os.open(\"/dev/shm\", os.O_RDONLY)\n try:\n shm_fs_stats = os.fstatvfs(shm_fd)\n # The value shm_fs_stats.f_bsize is the block size and the\n # value shm_fs_stats.f_bavail is the number of available\n # blocks.\n shm_avail = shm_fs_stats.f_bsize * shm_fs_stats.f_bavail\n finally:\n os.close(shm_fd)\n\n return shm_avail": 2150, "def from_json_str(cls, json_str):\n \"\"\"Convert json string representation into class instance.\n\n Args:\n json_str: json representation as string.\n\n Returns:\n New instance of the class with data loaded from json string.\n \"\"\"\n return cls.from_json(json.loads(json_str, cls=JsonDecoder))": 2151, "def is_timestamp(obj):\n \"\"\"\n Yaml either have automatically converted it to a datetime object\n or it is a string that will be validated later.\n \"\"\"\n return isinstance(obj, datetime.datetime) or is_string(obj) or is_int(obj) or is_float(obj)": 2152, "def ner_chunk(args):\n \"\"\"Chunk named entities.\"\"\"\n chunker = NEChunker(lang=args.lang)\n tag(chunker, args)": 2153, "def cell_ends_with_code(lines):\n \"\"\"Is the last line of the cell a line with code?\"\"\"\n if not lines:\n return False\n if not lines[-1].strip():\n return False\n if lines[-1].startswith('#'):\n return False\n return True": 2154, "def get_prep_value(self, value):\n \"\"\"Convert JSON object to a string\"\"\"\n if self.null and value is None:\n return None\n return json.dumps(value, **self.dump_kwargs)": 2155, "def reset(self):\n \"\"\"Reset analyzer state\n \"\"\"\n self.prevframe = None\n self.wasmoving = False\n self.t0 = 0\n self.ismoving = False": 2156, "def _get_non_empty_list(cls, iter):\n \"\"\"Return a list of the input, excluding all ``None`` values.\"\"\"\n res = []\n for value in iter:\n if hasattr(value, 'items'):\n value = cls._get_non_empty_dict(value) or None\n if value is not None:\n res.append(value)\n return res": 2157, "def __exit__(self, *args):\n \"\"\"\n Cleanup any necessary opened files\n \"\"\"\n\n if self._output_file_handle:\n self._output_file_handle.close()\n self._output_file_handle = None": 2158, "def normalize(X):\n \"\"\" equivalent to scipy.preprocessing.normalize on sparse matrices\n , but lets avoid another depedency just for a small utility function \"\"\"\n X = coo_matrix(X)\n X.data = X.data / sqrt(bincount(X.row, X.data ** 2))[X.row]\n return X": 2159, "def get_selected_values(self, selection):\n \"\"\"Return a list of values for the given selection.\"\"\"\n return [v for b, v in self._choices if b & selection]": 2160, "def equal(obj1, obj2):\n \"\"\"Calculate equality between two (Comparable) objects.\"\"\"\n Comparable.log(obj1, obj2, '==')\n equality = obj1.equality(obj2)\n Comparable.log(obj1, obj2, '==', result=equality)\n return equality": 2161, "def getMedian(numericValues):\n \"\"\"\n Gets the median of a list of values\n Returns a float/int\n \"\"\"\n theValues = sorted(numericValues)\n\n if len(theValues) % 2 == 1:\n return theValues[(len(theValues) + 1) / 2 - 1]\n else:\n lower = theValues[len(theValues) / 2 - 1]\n upper = theValues[len(theValues) / 2]\n\n return (float(lower + upper)) / 2": 2162, "def check_exists(filename, oappend=False):\n \"\"\"\n Avoid overwriting some files accidentally.\n \"\"\"\n if op.exists(filename):\n if oappend:\n return oappend\n logging.error(\"`{0}` found, overwrite (Y/N)?\".format(filename))\n overwrite = (raw_input() == 'Y')\n else:\n overwrite = True\n\n return overwrite": 2163, "def _pooling_output_shape(input_shape, pool_size=(2, 2),\n strides=None, padding='VALID'):\n \"\"\"Helper: compute the output shape for the pooling layer.\"\"\"\n dims = (1,) + pool_size + (1,) # NHWC\n spatial_strides = strides or (1,) * len(pool_size)\n strides = (1,) + spatial_strides + (1,)\n pads = padtype_to_pads(input_shape, dims, strides, padding)\n operand_padded = onp.add(input_shape, onp.add(*zip(*pads)))\n t = onp.floor_divide(onp.subtract(operand_padded, dims), strides) + 1\n return tuple(t)": 2164, "def other_ind(self):\n \"\"\"last row or column of square A\"\"\"\n return np.full(self.n_min, self.size - 1, dtype=np.int)": 2165, "def encode(strs):\n \"\"\"Encodes a list of strings to a single string.\n :type strs: List[str]\n :rtype: str\n \"\"\"\n res = ''\n for string in strs.split():\n res += str(len(string)) + \":\" + string\n return res": 2166, "def Max(a, axis, keep_dims):\n \"\"\"\n Max reduction op.\n \"\"\"\n return np.amax(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),\n keepdims=keep_dims),": 2167, "def __connect():\n \"\"\"\n Connect to a redis instance.\n \"\"\"\n global redis_instance\n if use_tcp_socket:\n redis_instance = redis.StrictRedis(host=hostname, port=port)\n else:\n redis_instance = redis.StrictRedis(unix_socket_path=unix_socket)": 2168, "def from_array(cls, arr):\n \"\"\"Convert a structured NumPy array into a Table.\"\"\"\n return cls().with_columns([(f, arr[f]) for f in arr.dtype.names])": 2169, "def from_dict(cls, d):\n \"\"\"Create an instance from a dictionary.\"\"\"\n return cls(**{k: v for k, v in d.items() if k in cls.ENTRIES})": 2170, "def objectcount(data, key):\n \"\"\"return the count of objects of key\"\"\"\n objkey = key.upper()\n return len(data.dt[objkey])": 2171, "def iterexpand(arry, extra):\n \"\"\"\n Expand dimensions by iteratively append empty axes.\n\n Parameters\n ----------\n arry : ndarray\n The original array\n\n extra : int\n The number of empty axes to append\n \"\"\"\n for d in range(arry.ndim, arry.ndim+extra):\n arry = expand_dims(arry, axis=d)\n return arry": 2172, "def aws_to_unix_id(aws_key_id):\n \"\"\"Converts a AWS Key ID into a UID\"\"\"\n uid_bytes = hashlib.sha256(aws_key_id.encode()).digest()[-2:]\n if USING_PYTHON2:\n return 2000 + int(from_bytes(uid_bytes) // 2)\n else:\n return 2000 + (int.from_bytes(uid_bytes, byteorder=sys.byteorder) // 2)": 2173, "def flattened_nested_key_indices(nested_dict):\n \"\"\"\n Combine the outer and inner keys of nested dictionaries into a single\n ordering.\n \"\"\"\n outer_keys, inner_keys = collect_nested_keys(nested_dict)\n combined_keys = list(sorted(set(outer_keys + inner_keys)))\n return {k: i for (i, k) in enumerate(combined_keys)}": 2174, "def run(self, *args, **kwargs):\n \"\"\" Connect and run bot in event loop. \"\"\"\n self.eventloop.run_until_complete(self.connect(*args, **kwargs))\n try:\n self.eventloop.run_forever()\n finally:\n self.eventloop.stop()": 2175, "def ensure_dir_exists(directory):\n \"\"\"Se asegura de que un directorio exista.\"\"\"\n if directory and not os.path.exists(directory):\n os.makedirs(directory)": 2176, "def ReadTif(tifFile):\n \"\"\"Reads a tif file to a 2D NumPy array\"\"\"\n img = Image.open(tifFile)\n img = np.array(img)\n return img": 2177, "def append_scope(self):\n \"\"\"Create a new scope in the current frame.\"\"\"\n self.stack.current.append(Scope(self.stack.current.current))": 2178, "def _isnan(self):\n \"\"\"\n Return if each value is NaN.\n \"\"\"\n if self._can_hold_na:\n return isna(self)\n else:\n # shouldn't reach to this condition by checking hasnans beforehand\n values = np.empty(len(self), dtype=np.bool_)\n values.fill(False)\n return values": 2179, "def send_dir(self, local_path, remote_path, user='root'):\n \"\"\"Upload a directory on the remote host.\n \"\"\"\n self.enable_user(user)\n return self.ssh_pool.send_dir(user, local_path, remote_path)": 2180, "def symlink(source, destination):\n \"\"\"Create a symbolic link\"\"\"\n log(\"Symlinking {} as {}\".format(source, destination))\n cmd = [\n 'ln',\n '-sf',\n source,\n destination,\n ]\n subprocess.check_call(cmd)": 2181, "def set_header(self, key, value):\n \"\"\" Sets a HTTP header for future requests. \"\"\"\n self.conn.issue_command(\"Header\", _normalize_header(key), value)": 2182, "def rank(self):\n \"\"\"how high in sorted list each key is. inverse permutation of sorter, such that sorted[rank]==keys\"\"\"\n r = np.empty(self.size, np.int)\n r[self.sorter] = np.arange(self.size)\n return r": 2183, "def batchify(data, batch_size):\n \"\"\"Reshape data into (num_example, batch_size)\"\"\"\n nbatch = data.shape[0] // batch_size\n data = data[:nbatch * batch_size]\n data = data.reshape((batch_size, nbatch)).T\n return data": 2184, "def _clip(sid, prefix):\n \"\"\"Clips a prefix from the beginning of a string if it exists.\"\"\"\n return sid[len(prefix):] if sid.startswith(prefix) else sid": 2185, "def safe_setattr(obj, name, value):\n \"\"\"Attempt to setattr but catch AttributeErrors.\"\"\"\n try:\n setattr(obj, name, value)\n return True\n except AttributeError:\n return False": 2186, "def remover(file_path):\n \"\"\"Delete a file or directory path only if it exists.\"\"\"\n if os.path.isfile(file_path):\n os.remove(file_path)\n return True\n elif os.path.isdir(file_path):\n shutil.rmtree(file_path)\n return True\n else:\n return False": 2187, "def safe_delete(filename):\n \"\"\"Delete a file safely. If it's not present, no-op.\"\"\"\n try:\n os.unlink(filename)\n except OSError as e:\n if e.errno != errno.ENOENT:\n raise": 2188, "def cli(env, identifier):\n \"\"\"Delete an image.\"\"\"\n\n image_mgr = SoftLayer.ImageManager(env.client)\n image_id = helpers.resolve_id(image_mgr.resolve_ids, identifier, 'image')\n\n image_mgr.delete_image(image_id)": 2189, "def set_rate(rate):\n \"\"\"Defines the ideal rate at which computation is to be performed\n\n :arg rate: the frequency in Hertz \n :type rate: int or float\n\n :raises: TypeError: if argument 'rate' is not int or float\n \"\"\"\n if not (isinstance(rate, int) or isinstance(rate, float)):\n raise TypeError(\"argument to set_rate is expected to be int or float\")\n global loop_duration\n loop_duration = 1.0/rate": 2190, "def _platform_pylib_exts(): # nocover\n \"\"\"\n Returns .so, .pyd, or .dylib depending on linux, win or mac.\n On python3 return the previous with and without abi (e.g.\n .cpython-35m-x86_64-linux-gnu) flags. On python2 returns with\n and without multiarch.\n \"\"\"\n import sysconfig\n valid_exts = []\n if six.PY2:\n # see also 'SHLIB_EXT'\n base_ext = '.' + sysconfig.get_config_var('SO').split('.')[-1]\n else:\n # return with and without API flags\n # handle PEP 3149 -- ABI version tagged .so files\n base_ext = '.' + sysconfig.get_config_var('EXT_SUFFIX').split('.')[-1]\n for tag in _extension_module_tags():\n valid_exts.append('.' + tag + base_ext)\n valid_exts.append(base_ext)\n return tuple(valid_exts)": 2191, "def apply_argument_parser(argumentsParser, options=None):\n \"\"\" Apply the argument parser. \"\"\"\n if options is not None:\n args = argumentsParser.parse_args(options)\n else:\n args = argumentsParser.parse_args()\n return args": 2192, "def _visual_width(line):\n \"\"\"Get the the number of columns required to display a string\"\"\"\n\n return len(re.sub(colorama.ansitowin32.AnsiToWin32.ANSI_CSI_RE, \"\", line))": 2193, "def column_exists(cr, table, column):\n \"\"\" Check whether a certain column exists \"\"\"\n cr.execute(\n 'SELECT count(attname) FROM pg_attribute '\n 'WHERE attrelid = '\n '( SELECT oid FROM pg_class WHERE relname = %s ) '\n 'AND attname = %s',\n (table, column))\n return cr.fetchone()[0] == 1": 2194, "def query_sum(queryset, field):\n \"\"\"\n Let the DBMS perform a sum on a queryset\n \"\"\"\n return queryset.aggregate(s=models.functions.Coalesce(models.Sum(field), 0))['s']": 2195, "def adapter(data, headers, **kwargs):\n \"\"\"Wrap vertical table in a function for TabularOutputFormatter.\"\"\"\n keys = ('sep_title', 'sep_character', 'sep_length')\n return vertical_table(data, headers, **filter_dict_by_key(kwargs, keys))": 2196, "def user_parse(data):\n \"\"\"Parse information from the provider.\"\"\"\n _user = data.get('response', {}).get('user', {})\n yield 'id', _user.get('name')\n yield 'username', _user.get('name')\n yield 'link', _user.get('blogs', [{}])[0].get('url')": 2197, "def clip_image(image, clip_min, clip_max):\n \"\"\" Clip an image, or an image batch, with upper and lower threshold. \"\"\"\n return np.minimum(np.maximum(clip_min, image), clip_max)": 2198, "def clean_time(time_string):\n \"\"\"Return a datetime from the Amazon-provided datetime string\"\"\"\n # Get a timezone-aware datetime object from the string\n time = dateutil.parser.parse(time_string)\n if not settings.USE_TZ:\n # If timezone support is not active, convert the time to UTC and\n # remove the timezone field\n time = time.astimezone(timezone.utc).replace(tzinfo=None)\n return time": 2199, "def string_to_float_list(string_var):\n \"\"\"Pull comma separated string values out of a text file and converts them to float list\"\"\"\n try:\n return [float(s) for s in string_var.strip('[').strip(']').split(', ')]\n except:\n return [float(s) for s in string_var.strip('[').strip(']').split(',')]": 2200, "def parse_query_string(query):\n \"\"\"\n parse_query_string:\n very simplistic. won't do the right thing with list values\n \"\"\"\n result = {}\n qparts = query.split('&')\n for item in qparts:\n key, value = item.split('=')\n key = key.strip()\n value = value.strip()\n result[key] = unquote_plus(value)\n return result": 2201, "def get_dict_for_attrs(obj, attrs):\n \"\"\"\n Returns dictionary for each attribute from given ``obj``.\n \"\"\"\n data = {}\n for attr in attrs:\n data[attr] = getattr(obj, attr)\n return data": 2202, "def tree(string, token=[WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA]):\n \"\"\" Transforms the output of parse() into a Text object.\n The token parameter lists the order of tags in each token in the input string.\n \"\"\"\n return Text(string, token)": 2203, "def dropna(self, subset=None):\n \"\"\"Remove missing values according to Baloo's convention.\n\n Parameters\n ----------\n subset : list of str, optional\n Which columns to check for missing values in.\n\n Returns\n -------\n DataFrame\n DataFrame with no null values in columns.\n\n \"\"\"\n subset = check_and_obtain_subset_columns(subset, self)\n not_nas = [v.notna() for v in self[subset]._iter()]\n and_filter = reduce(lambda x, y: x & y, not_nas)\n\n return self[and_filter]": 2204, "def clean_dict_keys(d):\n \"\"\"Convert all keys of the dict 'd' to (ascii-)strings.\n\n :Raises: UnicodeEncodeError\n \"\"\"\n new_d = {}\n for (k, v) in d.iteritems():\n new_d[str(k)] = v\n return new_d": 2205, "def test3():\n \"\"\"Test the multiprocess\n \"\"\"\n import time\n \n p = MVisionProcess()\n p.start()\n time.sleep(5)\n p.stop()": 2206, "def reprkwargs(kwargs, sep=', ', fmt=\"{0!s}={1!r}\"):\n \"\"\"Display kwargs.\"\"\"\n return sep.join(fmt.format(k, v) for k, v in kwargs.iteritems())": 2207, "def remove_punctuation(text, exceptions=[]):\n \"\"\"\n Return a string with punctuation removed.\n\n Parameters:\n text (str): The text to remove punctuation from.\n exceptions (list): List of symbols to keep in the given text.\n\n Return:\n str: The input text without the punctuation.\n \"\"\"\n\n all_but = [\n r'\\w',\n r'\\s'\n ]\n\n all_but.extend(exceptions)\n\n pattern = '[^{}]'.format(''.join(all_but))\n\n return re.sub(pattern, '', text)": 2208, "def is_file(path):\n \"\"\"Determine if a Path or string is a file on the file system.\"\"\"\n try:\n return path.expanduser().absolute().is_file()\n except AttributeError:\n return os.path.isfile(os.path.abspath(os.path.expanduser(str(path))))": 2209, "def exit_and_fail(self, msg=None, out=None):\n \"\"\"Exits the runtime with a nonzero exit code, indicating failure.\n\n :param msg: A string message to print to stderr or another custom file desciptor before exiting.\n (Optional)\n :param out: The file descriptor to emit `msg` to. (Optional)\n \"\"\"\n self.exit(result=PANTS_FAILED_EXIT_CODE, msg=msg, out=out)": 2210, "def palettebar(height, length, colormap):\n \"\"\"Return the channels of a palettebar.\n \"\"\"\n cbar = np.tile(np.arange(length) * 1.0 / (length - 1), (height, 1))\n cbar = (cbar * (colormap.values.max() + 1 - colormap.values.min())\n + colormap.values.min())\n\n return colormap.palettize(cbar)": 2211, "def do_exit(self, arg):\n \"\"\"Exit the shell session.\"\"\"\n\n if self.current:\n self.current.close()\n self.resource_manager.close()\n del self.resource_manager\n return True": 2212, "def user_return(self, frame, return_value):\n \"\"\"This function is called when a return trap is set here.\"\"\"\n pdb.Pdb.user_return(self, frame, return_value)": 2213, "def unzip_file_to_dir(path_to_zip, output_directory):\n \"\"\"\n Extract a ZIP archive to a directory\n \"\"\"\n z = ZipFile(path_to_zip, 'r')\n z.extractall(output_directory)\n z.close()": 2214, "def _basic_field_data(field, obj):\n \"\"\"Returns ``obj.field`` data as a dict\"\"\"\n value = field.value_from_object(obj)\n return {Field.TYPE: FieldType.VAL, Field.VALUE: value}": 2215, "def translate_v3(vec, amount):\n \"\"\"Return a new Vec3 that is translated version of vec.\"\"\"\n\n return Vec3(vec.x+amount, vec.y+amount, vec.z+amount)": 2216, "def _parallel_compare_helper(class_obj, pairs, x, x_link=None):\n \"\"\"Internal function to overcome pickling problem in python2.\"\"\"\n return class_obj._compute(pairs, x, x_link)": 2217, "def datetime_created(self):\n \"\"\"Returns file group's create aware *datetime* in UTC format.\"\"\"\n if self.info().get('datetime_created'):\n return dateutil.parser.parse(self.info()['datetime_created'])": 2218, "def context(self):\n \"\"\" Convenient access to shared context \"\"\"\n if self._context is not None:\n return self._context\n else:\n logger.warning(\"Using shared context without a lock\")\n return self._executor._shared_context": 2219, "def counter(items):\n \"\"\"\n Simplest required implementation of collections.Counter. Required as 2.6\n does not have Counter in collections.\n \"\"\"\n results = {}\n for item in items:\n results[item] = results.get(item, 0) + 1\n return results": 2220, "def filter_bolts(table, header):\n \"\"\" filter to keep bolts \"\"\"\n bolts_info = []\n for row in table:\n if row[0] == 'bolt':\n bolts_info.append(row)\n return bolts_info, header": 2221, "def pylint_raw(options):\n \"\"\"\n Use check_output to run pylint.\n Because pylint changes the exit code based on the code score,\n we have to wrap it in a try/except block.\n\n :param options:\n :return:\n \"\"\"\n command = ['pylint']\n command.extend(options)\n\n proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n outs, __ = proc.communicate()\n\n return outs.decode()": 2222, "def print_param_values(self_):\n \"\"\"Print the values of all this object's Parameters.\"\"\"\n self = self_.self\n for name,val in self.param.get_param_values():\n print('%s.%s = %s' % (self.name,name,val))": 2223, "def info(txt):\n \"\"\"Print, emphasized 'neutral', the given 'txt' message\"\"\"\n\n print(\"%s# %s%s%s\" % (PR_EMPH_CC, get_time_stamp(), txt, PR_NC))\n sys.stdout.flush()": 2224, "def pprint(obj, verbose=False, max_width=79, newline='\\n'):\n \"\"\"\n Like `pretty` but print to stdout.\n \"\"\"\n printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline)\n printer.pretty(obj)\n printer.flush()\n sys.stdout.write(newline)\n sys.stdout.flush()": 2225, "def pytest_runtest_logreport(self, report):\n \"\"\"Store all test reports for evaluation on finish\"\"\"\n rep = report\n res = self.config.hook.pytest_report_teststatus(report=rep)\n cat, letter, word = res\n self.stats.setdefault(cat, []).append(rep)": 2226, "def prettyprint(d):\n \"\"\"Print dicttree in Json-like format. keys are sorted\n \"\"\"\n print(json.dumps(d, sort_keys=True, \n indent=4, separators=(\",\" , \": \")))": 2227, "def printdict(adict):\n \"\"\"printdict\"\"\"\n dlist = list(adict.keys())\n dlist.sort()\n for i in range(0, len(dlist)):\n print(dlist[i], adict[dlist[i]])": 2228, "def show_progress(self):\n \"\"\"If we are in a progress scope, and no log messages have been\n shown, write out another '.'\"\"\"\n if self.in_progress_hanging:\n sys.stdout.write('.')\n sys.stdout.flush()": 2229, "def pprint(o, stream=None, indent=1, width=80, depth=None):\n \"\"\"Pretty-print a Python o to a stream [default is sys.stdout].\"\"\"\n printer = PrettyPrinter(\n stream=stream, indent=indent, width=width, depth=depth)\n printer.pprint(o)": 2230, "def get(cls):\n \"\"\"Subsystems used outside of any task.\"\"\"\n return {\n SourceRootConfig,\n Reporting,\n Reproducer,\n RunTracker,\n Changed,\n BinaryUtil.Factory,\n Subprocess.Factory\n }": 2231, "def ss(*args, **kwargs):\n \"\"\"\n exactly like s, but doesn't return variable names or file positions (useful for logging)\n\n since -- 10-15-2015\n return -- str\n \"\"\"\n if not args:\n raise ValueError(\"you didn't pass any arguments to print out\")\n\n with Reflect.context(args, **kwargs) as r:\n instance = V_CLASS(r, stream, **kwargs)\n return instance.value().strip()": 2232, "def _shape(self, df):\n \"\"\"\n Calculate table chape considering index levels.\n \"\"\"\n\n row, col = df.shape\n return row + df.columns.nlevels, col + df.index.nlevels": 2233, "def ansi(color, text):\n \"\"\"Wrap text in an ansi escape sequence\"\"\"\n code = COLOR_CODES[color]\n return '\\033[1;{0}m{1}{2}'.format(code, text, RESET_TERM)": 2234, "def get_encoding(binary):\n \"\"\"Return the encoding type.\"\"\"\n\n try:\n from chardet import detect\n except ImportError:\n LOGGER.error(\"Please install the 'chardet' module\")\n sys.exit(1)\n\n encoding = detect(binary).get('encoding')\n\n return 'iso-8859-1' if encoding == 'CP949' else encoding": 2235, "def _get_os_environ_dict(keys):\n \"\"\"Return a dictionary of key/values from os.environ.\"\"\"\n return {k: os.environ.get(k, _UNDEFINED) for k in keys}": 2236, "def to_json(data):\n \"\"\"Return data as a JSON string.\"\"\"\n return json.dumps(data, default=lambda x: x.__dict__, sort_keys=True, indent=4)": 2237, "def getfield(f):\n \"\"\"convert values from cgi.Field objects to plain values.\"\"\"\n if isinstance(f, list):\n return [getfield(x) for x in f]\n else:\n return f.value": 2238, "def time_string(seconds):\n \"\"\"Returns time in seconds as a string formatted HHHH:MM:SS.\"\"\"\n s = int(round(seconds)) # round to nearest second\n h, s = divmod(s, 3600) # get hours and remainder\n m, s = divmod(s, 60) # split remainder into minutes and seconds\n return \"%2i:%02i:%02i\" % (h, m, s)": 2239, "def fields(self):\n \"\"\"Returns the list of field names of the model.\"\"\"\n return (self.attributes.values() + self.lists.values()\n + self.references.values())": 2240, "def translate_index_to_position(self, index):\n \"\"\"\n Given an index for the text, return the corresponding (row, col) tuple.\n (0-based. Returns (0, 0) for index=0.)\n \"\"\"\n # Find start of this line.\n row, row_index = self._find_line_start_index(index)\n col = index - row_index\n\n return row, col": 2241, "def _set_property(self, val, *args):\n \"\"\"Private method that sets the value currently of the property\"\"\"\n val = UserClassAdapter._set_property(self, val, *args)\n if val:\n Adapter._set_property(self, val, *args)\n return val": 2242, "def metadata(self):\n \"\"\"google.protobuf.Message: the current operation metadata.\"\"\"\n if not self._operation.HasField(\"metadata\"):\n return None\n\n return protobuf_helpers.from_any_pb(\n self._metadata_type, self._operation.metadata\n )": 2243, "def stop(pid):\n \"\"\"Shut down a specific process.\n\n Args:\n pid: the pid of the process to shutdown.\n \"\"\"\n if psutil.pid_exists(pid):\n try:\n p = psutil.Process(pid)\n p.kill()\n except Exception:\n pass": 2244, "def get_all_items(obj):\n \"\"\"\n dict.items() but with a separate row for each value in a MultiValueDict\n \"\"\"\n if hasattr(obj, 'getlist'):\n items = []\n for key in obj:\n for value in obj.getlist(key):\n items.append((key, value))\n return items\n else:\n return obj.items()": 2245, "def get_translucent_cmap(r, g, b):\n\n class TranslucentCmap(BaseColormap):\n glsl_map = \"\"\"\n vec4 translucent_fire(float t) {{\n return vec4({0}, {1}, {2}, t);\n }}\n \"\"\".format(r, g, b)\n\n return TranslucentCmap()": 2246, "def execute(self, sql, params=None):\n \"\"\"Just a pointer to engine.execute\n \"\"\"\n # wrap in a transaction to ensure things are committed\n # https://github.com/smnorris/pgdata/issues/3\n with self.engine.begin() as conn:\n result = conn.execute(sql, params)\n return result": 2247, "def each_img(dir_path):\n \"\"\"\n Iterates through each image in the given directory. (not recursive)\n :param dir_path: Directory path where images files are present\n :return: Iterator to iterate through image files\n \"\"\"\n for fname in os.listdir(dir_path):\n if fname.endswith('.jpg') or fname.endswith('.png') or fname.endswith('.bmp'):\n yield fname": 2248, "async def delete(self):\n \"\"\"\n Delete task (in any state) permanently.\n\n Returns `True` is task is deleted.\n \"\"\"\n the_tuple = await self.queue.delete(self.tube, self.task_id)\n\n self.update_from_tuple(the_tuple)\n\n return bool(self.state == DONE)": 2249, "def rndstr(size=16):\n \"\"\"\n Returns a string of random ascii characters or digits\n\n :param size: The length of the string\n :return: string\n \"\"\"\n _basech = string.ascii_letters + string.digits\n return \"\".join([rnd.choice(_basech) for _ in range(size)])": 2250, "def column(self):\n \"\"\"\n Returns a zero-based column number of the beginning of this range.\n \"\"\"\n line, column = self.source_buffer.decompose_position(self.begin_pos)\n return column": 2251, "def get_object_attrs(obj):\n \"\"\"\n Get the attributes of an object using dir.\n\n This filters protected attributes\n \"\"\"\n attrs = [k for k in dir(obj) if not k.startswith('__')]\n if not attrs:\n attrs = dir(obj)\n return attrs": 2252, "def zrank(self, name, value):\n \"\"\"\n Returns the rank of the element.\n\n :param name: str the name of the redis key\n :param value: the element in the sorted set\n \"\"\"\n with self.pipe as pipe:\n value = self.valueparse.encode(value)\n return pipe.zrank(self.redis_key(name), value)": 2253, "def view_extreme_groups(token, dstore):\n \"\"\"\n Show the source groups contributing the most to the highest IML\n \"\"\"\n data = dstore['disagg_by_grp'].value\n data.sort(order='extreme_poe')\n return rst_table(data[::-1])": 2254, "def read(fname):\n \"\"\"Quick way to read a file content.\"\"\"\n content = None\n with open(os.path.join(here, fname)) as f:\n content = f.read()\n return content": 2255, "def OnRootView(self, event):\n \"\"\"Reset view to the root of the tree\"\"\"\n self.adapter, tree, rows = self.RootNode()\n self.squareMap.SetModel(tree, self.adapter)\n self.RecordHistory()\n self.ConfigureViewTypeChoices()": 2256, "def read_folder(directory):\n \"\"\"read text files in directory and returns them as array\n\n Args:\n directory: where the text files are\n\n Returns:\n Array of text\n \"\"\"\n res = []\n for filename in os.listdir(directory):\n with io.open(os.path.join(directory, filename), encoding=\"utf-8\") as f:\n content = f.read()\n res.append(content)\n return res": 2257, "def find_lt(a, x):\n \"\"\"Find rightmost value less than x\"\"\"\n i = bisect.bisect_left(a, x)\n if i:\n return a[i-1]\n raise ValueError": 2258, "def yticks(self):\n \"\"\"Compute the yticks labels of this grid, used for plotting the y-axis ticks when visualizing a regular\"\"\"\n return np.linspace(np.min(self[:, 0]), np.max(self[:, 0]), 4)": 2259, "def return_type(type_name, formatter=None):\n \"\"\"Specify that this function returns a typed value.\n\n Args:\n type_name (str): A type name known to the global typedargs type system\n formatter (str): An optional name of a formatting function specified\n for the type given in type_name.\n \"\"\"\n\n def _returns(func):\n annotated(func)\n func.metadata.typed_returnvalue(type_name, formatter)\n return func\n\n return _returns": 2260, "def extract_words(lines):\n \"\"\"\n Extract from the given iterable of lines the list of words.\n\n :param lines: an iterable of lines;\n :return: a generator of words of lines.\n \"\"\"\n for line in lines:\n for word in re.findall(r\"\\w+\", line):\n yield word": 2261, "def r_num(obj):\n \"\"\"Read list of numbers.\"\"\"\n if isinstance(obj, (list, tuple)):\n it = iter\n else:\n it = LinesIterator\n dataset = Dataset([Dataset.FLOAT])\n return dataset.load(it(obj))": 2262, "def process_module(self, module):\n \"\"\"inspect the source file to find encoding problem\"\"\"\n if module.file_encoding:\n encoding = module.file_encoding\n else:\n encoding = \"ascii\"\n\n with module.stream() as stream:\n for lineno, line in enumerate(stream):\n self._check_encoding(lineno + 1, line, encoding)": 2263, "def map_keys_deep(f, dct):\n \"\"\"\n Implementation of map that recurses. This tests the same keys at every level of dict and in lists\n :param f: 2-ary function expecting a key and value and returns a modified key\n :param dct: Dict for deep processing\n :return: Modified dct with matching props mapped\n \"\"\"\n return _map_deep(lambda k, v: [f(k, v), v], dct)": 2264, "def redirect_std():\n \"\"\"\n Connect stdin/stdout to controlling terminal even if the scripts input and output\n were redirected. This is useful in utilities based on termenu.\n \"\"\"\n stdin = sys.stdin\n stdout = sys.stdout\n if not sys.stdin.isatty():\n sys.stdin = open_raw(\"/dev/tty\", \"r\", 0)\n if not sys.stdout.isatty():\n sys.stdout = open_raw(\"/dev/tty\", \"w\", 0)\n\n return stdin, stdout": 2265, "def _help():\n \"\"\" Display both SQLAlchemy and Python help statements \"\"\"\n\n statement = '%s%s' % (shelp, phelp % ', '.join(cntx_.keys()))\n print statement.strip()": 2266, "def __setitem__(self, field, value):\n \"\"\" :see::meth:RedisMap.__setitem__ \"\"\"\n return self._client.hset(self.key_prefix, field, self._dumps(value))": 2267, "def mark(self, n=1):\n \"\"\"Mark the occurrence of a given number of events.\"\"\"\n self.tick_if_necessary()\n self.count += n\n self.m1_rate.update(n)\n self.m5_rate.update(n)\n self.m15_rate.update(n)": 2268, "def _post(self, url, params, uploads=None):\n \"\"\" Wrapper method for POST calls. \"\"\"\n self._call(self.POST, url, params, uploads)": 2269, "def prep_regex(patterns):\n \"\"\"Compile regex patterns.\"\"\"\n\n flags = 0 if Config.options.case_sensitive else re.I\n\n return [re.compile(pattern, flags) for pattern in patterns]": 2270, "def match_paren(self, tokens, item):\n \"\"\"Matches a paren.\"\"\"\n match, = tokens\n return self.match(match, item)": 2271, "def remove_legend(ax=None):\n \"\"\"Remove legend for axes or gca.\n\n See http://osdir.com/ml/python.matplotlib.general/2005-07/msg00285.html\n \"\"\"\n from pylab import gca, draw\n if ax is None:\n ax = gca()\n ax.legend_ = None\n draw()": 2272, "def unmatched(match):\n \"\"\"Return unmatched part of re.Match object.\"\"\"\n start, end = match.span(0)\n return match.string[:start]+match.string[end:]": 2273, "def seq():\n \"\"\"\n Counts up sequentially from a number based on the current time\n\n :rtype int:\n \"\"\"\n current_frame = inspect.currentframe().f_back\n trace_string = \"\"\n while current_frame.f_back:\n trace_string = trace_string + current_frame.f_back.f_code.co_name\n current_frame = current_frame.f_back\n return counter.get_from_trace(trace_string)": 2274, "def is_valid_email(email):\n \"\"\"\n Check if email is valid\n \"\"\"\n pattern = re.compile(r'[\\w\\.-]+@[\\w\\.-]+[.]\\w+')\n return bool(pattern.match(email))": 2275, "def _Members(self, group):\n \"\"\"Unify members of a group and accounts with the group as primary gid.\"\"\"\n group.members = set(group.members).union(self.gids.get(group.gid, []))\n return group": 2276, "def kill(self):\n \"\"\"Kill the browser.\n\n This is useful when the browser is stuck.\n \"\"\"\n if self.process:\n self.process.kill()\n self.process.wait()": 2277, "def f(x, a, c):\n \"\"\" Objective function (sum of squared residuals) \"\"\"\n v = g(x, a, c)\n return v.dot(v)": 2278, "def clean():\n \"\"\"clean - remove build artifacts.\"\"\"\n run('rm -rf build/')\n run('rm -rf dist/')\n run('rm -rf puzzle.egg-info')\n run('find . -name __pycache__ -delete')\n run('find . -name *.pyc -delete')\n run('find . -name *.pyo -delete')\n run('find . -name *~ -delete')\n\n log.info('cleaned up')": 2279, "def check_version():\n \"\"\"Sanity check version information for corrupt virtualenv symlinks\n \"\"\"\n if sys.version_info[0:3] == PYTHON_VERSION_INFO[0:3]:\n return\n\n sys.exit(\n ansi.error() + ' your virtual env points to the wrong python version. '\n 'This is likely because you used a python installer that clobbered '\n 'the system installation, which breaks virtualenv creation. '\n 'To fix, check this symlink, and delete the installation of python '\n 'that it is brokenly pointing to, then delete the virtual env itself '\n 'and rerun lore install: ' + os.linesep + os.linesep + BIN_PYTHON +\n os.linesep\n )": 2280, "def _remove_none_values(dictionary):\n \"\"\" Remove dictionary keys whose value is None \"\"\"\n return list(map(dictionary.pop,\n [i for i in dictionary if dictionary[i] is None]))": 2281, "def join(self, room):\n \"\"\"Lets a user join a room on a specific Namespace.\"\"\"\n self.socket.rooms.add(self._get_room_name(room))": 2282, "def _remove_duplicate_files(xs):\n \"\"\"Remove files specified multiple times in a list.\n \"\"\"\n seen = set([])\n out = []\n for x in xs:\n if x[\"path\"] not in seen:\n out.append(x)\n seen.add(x[\"path\"])\n return out": 2283, "def on_error(e): # pragma: no cover\n \"\"\"Error handler\n\n RuntimeError or ValueError exceptions raised by commands will be handled\n by this function.\n \"\"\"\n exname = {'RuntimeError': 'Runtime error', 'Value Error': 'Value error'}\n sys.stderr.write('{}: {}\\n'.format(exname[e.__class__.__name__], str(e)))\n sys.stderr.write('See file slam_error.log for additional details.\\n')\n sys.exit(1)": 2284, "def __copy__(self):\n \"\"\"A magic method to implement shallow copy behavior.\"\"\"\n return self.__class__.load(self.dump(), context=self.context)": 2285, "def PopTask(self):\n \"\"\"Retrieves and removes the first task from the heap.\n\n Returns:\n Task: the task or None if the heap is empty.\n \"\"\"\n try:\n _, task = heapq.heappop(self._heap)\n\n except IndexError:\n return None\n self._task_identifiers.remove(task.identifier)\n return task": 2286, "def _curve(x1, y1, x2, y2, hunit = HUNIT, vunit = VUNIT):\n \"\"\"\n Return a PyX curved path from (x1, y1) to (x2, y2),\n such that the slope at either end is zero.\n \"\"\"\n ax1, ax2, axm = x1 * hunit, x2 * hunit, (x1 + x2) * hunit / 2\n ay1, ay2 = y1 * vunit, y2 * vunit\n return pyx.path.curve(ax1, ay1, axm, ay1, axm, ay2, ax2, ay2)": 2287, "def once(func):\n \"\"\"Runs a thing once and once only.\"\"\"\n lock = threading.Lock()\n\n def new_func(*args, **kwargs):\n if new_func.called:\n return\n with lock:\n if new_func.called:\n return\n rv = func(*args, **kwargs)\n new_func.called = True\n return rv\n\n new_func = update_wrapper(new_func, func)\n new_func.called = False\n return new_func": 2288, "def union_overlapping(intervals):\n \"\"\"Union any overlapping intervals in the given set.\"\"\"\n disjoint_intervals = []\n\n for interval in intervals:\n if disjoint_intervals and disjoint_intervals[-1].overlaps(interval):\n disjoint_intervals[-1] = disjoint_intervals[-1].union(interval)\n else:\n disjoint_intervals.append(interval)\n\n return disjoint_intervals": 2289, "def _generate_phrases(self, sentences):\n \"\"\"Method to generate contender phrases given the sentences of the text\n document.\n\n :param sentences: List of strings where each string represents a\n sentence which forms the text.\n :return: Set of string tuples where each tuple is a collection\n of words forming a contender phrase.\n \"\"\"\n phrase_list = set()\n # Create contender phrases from sentences.\n for sentence in sentences:\n word_list = [word.lower() for word in wordpunct_tokenize(sentence)]\n phrase_list.update(self._get_phrase_list_from_words(word_list))\n return phrase_list": 2290, "def unapostrophe(text):\n \"\"\"Strip apostrophe and 's' from the end of a string.\"\"\"\n text = re.sub(r'[%s]s?$' % ''.join(APOSTROPHES), '', text)\n return text": 2291, "def _do_remove_prefix(name):\n \"\"\"Strip the possible prefix 'Table: ' from a table name.\"\"\"\n res = name\n if isinstance(res, str):\n if (res.find('Table: ') == 0):\n res = res.replace('Table: ', '', 1)\n return res": 2292, "def do_restart(self, line):\n \"\"\"Request that the Outstation perform a cold restart. Command syntax is: restart\"\"\"\n self.application.master.Restart(opendnp3.RestartType.COLD, restart_callback)": 2293, "def distinct(l):\n \"\"\"\n Return a list where the duplicates have been removed.\n\n Args:\n l (list): the list to filter.\n\n Returns:\n list: the same list without duplicates.\n \"\"\"\n seen = set()\n seen_add = seen.add\n return (_ for _ in l if not (_ in seen or seen_add(_)))": 2294, "def fixpath(path):\n \"\"\"Uniformly format a path.\"\"\"\n return os.path.normpath(os.path.realpath(os.path.expanduser(path)))": 2295, "def drop_trailing_zeros_decimal(num):\n \"\"\" Drops the trailinz zeros from decimal value.\n Returns a string\n \"\"\"\n out = str(num)\n return out.rstrip('0').rstrip('.') if '.' in out else out": 2296, "def rstjinja(app, docname, source):\n \"\"\"\n Render our pages as a jinja template for fancy templating goodness.\n \"\"\"\n # Make sure we're outputting HTML\n if app.builder.format != 'html':\n return\n src = source[0]\n rendered = app.builder.templates.render_string(\n src, app.config.html_context\n )\n source[0] = rendered": 2297, "def conf(self):\n \"\"\"Generate the Sphinx `conf.py` configuration file\n\n Returns:\n (str): the contents of the `conf.py` file.\n \"\"\"\n return self.env.get_template('conf.py.j2').render(\n metadata=self.metadata,\n package=self.package)": 2298, "def render_to_json(templates, context, request):\n \"\"\"\n Generate a JSON HttpResponse with rendered template HTML.\n \"\"\"\n html = render_to_string(\n templates,\n context=context,\n request=request\n )\n _json = json.dumps({\n \"html\": html\n })\n return HttpResponse(_json)": 2299, "def specialRound(number, rounding):\n \"\"\"A method used to round a number in the way that UsefulUtils rounds.\"\"\"\n temp = 0\n if rounding == 0:\n temp = number\n else:\n temp = round(number, rounding)\n if temp % 1 == 0:\n return int(temp)\n else:\n return float(temp)": 2300, "def requests_request(method, url, **kwargs):\n \"\"\"Requests-mock requests.request wrapper.\"\"\"\n session = local_sessions.session\n response = session.request(method=method, url=url, **kwargs)\n session.close()\n return response": 2301, "def unique(self, name):\n \"\"\"Make a variable name unique by appending a number if needed.\"\"\"\n # Make sure the name is valid\n name = self.valid(name)\n # Make sure it's not too long\n name = self.trim(name)\n # Now make sure it's unique\n unique_name = name\n i = 2\n while unique_name in self.names:\n unique_name = name + str(i)\n i += 1\n self.names.add(unique_name)\n return unique_name": 2302, "def check_type_and_size_of_param_list(param_list, expected_length):\n \"\"\"\n Ensure that param_list is a list with the expected length. Raises a helpful\n ValueError if this is not the case.\n \"\"\"\n try:\n assert isinstance(param_list, list)\n assert len(param_list) == expected_length\n except AssertionError:\n msg = \"param_list must be a list containing {} elements.\"\n raise ValueError(msg.format(expected_length))\n\n return None": 2303, "def _request_limit_reached(exception):\n \"\"\" Checks if exception was raised because of too many executed requests. (This is a temporal solution and\n will be changed in later package versions.)\n\n :param exception: Exception raised during download\n :type exception: Exception\n :return: True if exception is caused because too many requests were executed at once and False otherwise\n :rtype: bool\n \"\"\"\n return isinstance(exception, requests.HTTPError) and \\\n exception.response.status_code == requests.status_codes.codes.TOO_MANY_REQUESTS": 2304, "def is_float_array(val):\n \"\"\"\n Checks whether a variable is a numpy float array.\n\n Parameters\n ----------\n val\n The variable to check.\n\n Returns\n -------\n bool\n True if the variable is a numpy float array. Otherwise False.\n\n \"\"\"\n return is_np_array(val) and issubclass(val.dtype.type, np.floating)": 2305, "def _log_disconnect(self):\n \"\"\" Decrement connection count \"\"\"\n if self.logged:\n self.server.stats.connectionClosed()\n self.logged = False": 2306, "def download_sdk(url):\n \"\"\"Downloads the SDK and returns a file-like object for the zip content.\"\"\"\n r = requests.get(url)\n r.raise_for_status()\n return StringIO(r.content)": 2307, "def disable_insecure_request_warning():\n \"\"\"Suppress warning about untrusted SSL certificate.\"\"\"\n import requests\n from requests.packages.urllib3.exceptions import InsecureRequestWarning\n requests.packages.urllib3.disable_warnings(InsecureRequestWarning)": 2308, "def price_rounding(price, decimals=2):\n \"\"\"Takes a decimal price and rounds to a number of decimal places\"\"\"\n try:\n exponent = D('.' + decimals * '0')\n except InvalidOperation:\n # Currencies with no decimal places, ex. JPY, HUF\n exponent = D()\n return price.quantize(exponent, rounding=ROUND_UP)": 2309, "def process_response(self, response):\n \"\"\"\n Load a JSON response.\n\n :param Response response: The HTTP response.\n :return dict: The JSON-loaded content.\n \"\"\"\n if response.status_code != 200:\n raise TwilioException('Unable to fetch page', response)\n\n return json.loads(response.text)": 2310, "def _pad(self, text):\n \"\"\"Pad the text.\"\"\"\n top_bottom = (\"\\n\" * self._padding) + \" \"\n right_left = \" \" * self._padding * self.PAD_WIDTH\n return top_bottom + right_left + text + right_left + top_bottom": 2311, "def __get__(self, obj, objtype):\n if not self.is_method:\n self.is_method = True\n \"\"\"Support instance methods.\"\"\"\n return functools.partial(self.__call__, obj)": 2312, "def execute_only_once():\n \"\"\"\n Each called in the code to this function is guaranteed to return True the\n first time and False afterwards.\n\n Returns:\n bool: whether this is the first time this function gets called from this line of code.\n\n Example:\n .. code-block:: python\n\n if execute_only_once():\n # do something only once\n \"\"\"\n f = inspect.currentframe().f_back\n ident = (f.f_code.co_filename, f.f_lineno)\n if ident in _EXECUTE_HISTORY:\n return False\n _EXECUTE_HISTORY.add(ident)\n return True": 2313, "def where_is(strings, pattern, n=1, lookup_func=re.match):\n \"\"\"Return index of the nth match found of pattern in strings\n\n Parameters\n ----------\n strings: list of str\n List of strings\n\n pattern: str\n Pattern to be matched\n\n nth: int\n Number of times the match must happen to return the item index.\n\n lookup_func: callable\n Function to match each item in strings to the pattern, e.g., re.match or re.search.\n\n Returns\n -------\n index: int\n Index of the nth item that matches the pattern.\n If there are no n matches will return -1\n \"\"\"\n count = 0\n for idx, item in enumerate(strings):\n if lookup_func(pattern, item):\n count += 1\n if count == n:\n return idx\n return -1": 2314, "def sem(inlist):\n \"\"\"\nReturns the estimated standard error of the mean (sx-bar) of the\nvalues in the passed list. sem = stdev / sqrt(n)\n\nUsage: lsem(inlist)\n\"\"\"\n sd = stdev(inlist)\n n = len(inlist)\n return sd / math.sqrt(n)": 2315, "def unwind(self):\n \"\"\" Get a list of all ancestors in descending order of level, including a new instance of self\n \"\"\"\n return [ QuadKey(self.key[:l+1]) for l in reversed(range(len(self.key))) ]": 2316, "def polyline(self, arr):\n \"\"\"Draw a set of lines\"\"\"\n for i in range(0, len(arr) - 1):\n self.line(arr[i][0], arr[i][1], arr[i + 1][0], arr[i + 1][1])": 2317, "def print(*a):\n \"\"\" print just one that returns what you give it instead of None \"\"\"\n try:\n _print(*a)\n return a[0] if len(a) == 1 else a\n except:\n _print(*a)": 2318, "def clear(self):\n \"\"\"\n Clear screen and go to 0,0\n \"\"\"\n # Erase current output first.\n self.erase()\n\n # Send \"Erase Screen\" command and go to (0, 0).\n output = self.output\n\n output.erase_screen()\n output.cursor_goto(0, 0)\n output.flush()\n\n self.request_absolute_cursor_position()": 2319, "def _days_in_month(date):\n \"\"\"The number of days in the month of the given date\"\"\"\n if date.month == 12:\n reference = type(date)(date.year + 1, 1, 1)\n else:\n reference = type(date)(date.year, date.month + 1, 1)\n return (reference - timedelta(days=1)).day": 2320, "def roc_auc(y_true, y_score):\n \"\"\"\n Returns are under the ROC curve\n \"\"\"\n notnull = ~np.isnan(y_true)\n fpr, tpr, thresholds = sklearn.metrics.roc_curve(y_true[notnull], y_score[notnull])\n return sklearn.metrics.auc(fpr, tpr)": 2321, "def format_exception(e):\n \"\"\"Returns a string containing the type and text of the exception.\n\n \"\"\"\n from .utils.printing import fill\n return '\\n'.join(fill(line) for line in traceback.format_exception_only(type(e), e))": 2322, "def parse_response(self, resp):\n \"\"\"\n Parse the xmlrpc response.\n \"\"\"\n p, u = self.getparser()\n p.feed(resp.content)\n p.close()\n return u.close()": 2323, "def setup_detect_python2():\n \"\"\"\n Call this before using the refactoring tools to create them on demand\n if needed.\n \"\"\"\n if None in [RTs._rt_py2_detect, RTs._rtp_py2_detect]:\n RTs._rt_py2_detect = RefactoringTool(py2_detect_fixers)\n RTs._rtp_py2_detect = RefactoringTool(py2_detect_fixers,\n {'print_function': True})": 2324, "def copy_image_on_background(image, color=WHITE):\n \"\"\"\n Create a new image by copying the image on a *color* background.\n\n Args:\n image (PIL.Image.Image): Image to copy\n color (tuple): Background color usually WHITE or BLACK\n\n Returns:\n PIL.Image.Image\n\n \"\"\"\n background = Image.new(\"RGB\", image.size, color)\n background.paste(image, mask=image.split()[3])\n return background": 2325, "def select_fields_as_sql(self):\n \"\"\"\n Returns the selected fields or expressions as a SQL string.\n \"\"\"\n return comma_join(list(self._fields) + ['%s AS %s' % (v, k) for k, v in self._calculated_fields.items()])": 2326, "def kill_mprocess(process):\n \"\"\"kill process\n Args:\n process - Popen object for process\n \"\"\"\n if process and proc_alive(process):\n process.terminate()\n process.communicate()\n return not proc_alive(process)": 2327, "def get_randomized_guid_sample(self, item_count):\n \"\"\" Fetch a subset of randomzied GUIDs from the whitelist \"\"\"\n dataset = self.get_whitelist()\n random.shuffle(dataset)\n return dataset[:item_count]": 2328, "def write_image(filename, image):\n \"\"\" Write image data to PNG, JPG file\n\n :param filename: name of PNG or JPG file to write data to\n :type filename: str\n :param image: image data to write to file\n :type image: numpy array\n \"\"\"\n data_format = get_data_format(filename)\n if data_format is MimeType.JPG:\n LOGGER.warning('Warning: jpeg is a lossy format therefore saved data will be modified.')\n return Image.fromarray(image).save(filename)": 2329, "def plot_and_save(self, **kwargs):\n \"\"\"Used when the plot method defined does not create a figure nor calls save_plot\n Then the plot method has to use self.fig\"\"\"\n self.fig = pyplot.figure()\n self.plot()\n self.axes = pyplot.gca()\n self.save_plot(self.fig, self.axes, **kwargs)\n pyplot.close(self.fig)": 2330, "def iterate_chunks(file, chunk_size):\n \"\"\"\n Iterate chunks of size chunk_size from a file-like object\n \"\"\"\n chunk = file.read(chunk_size)\n while chunk:\n yield chunk\n chunk = file.read(chunk_size)": 2331, "def validate_string_list(lst):\n \"\"\"Validate that the input is a list of strings.\n\n Raises ValueError if not.\"\"\"\n if not isinstance(lst, list):\n raise ValueError('input %r must be a list' % lst)\n for x in lst:\n if not isinstance(x, basestring):\n raise ValueError('element %r in list must be a string' % x)": 2332, "def clean_df(df, fill_nan=True, drop_empty_columns=True):\n \"\"\"Clean a pandas dataframe by:\n 1. Filling empty values with Nan\n 2. Dropping columns with all empty values\n\n Args:\n df: Pandas DataFrame\n fill_nan (bool): If any empty values (strings, None, etc) should be replaced with NaN\n drop_empty_columns (bool): If columns whose values are all empty should be dropped\n\n Returns:\n DataFrame: cleaned DataFrame\n\n \"\"\"\n if fill_nan:\n df = df.fillna(value=np.nan)\n if drop_empty_columns:\n df = df.dropna(axis=1, how='all')\n return df.sort_index()": 2333, "def extract(self):\n \"\"\"\n Creates a copy of this tabarray in the form of a numpy ndarray.\n\n Useful if you want to do math on array elements, e.g. if you have a \n subset of the columns that are all numerical, you can construct a \n numerical matrix and do matrix operations.\n\n \"\"\"\n return np.vstack([self[r] for r in self.dtype.names]).T.squeeze()": 2334, "def delete_entry(self, key):\n \"\"\"Delete an object from the redis table\"\"\"\n pipe = self.client.pipeline()\n pipe.srem(self.keys_container, key)\n pipe.delete(key)\n pipe.execute()": 2335, "def match_files(files, pattern: Pattern):\n \"\"\"Yields file name if matches a regular expression pattern.\"\"\"\n\n for name in files:\n if re.match(pattern, name):\n yield name": 2336, "def _selectItem(self, index):\n \"\"\"Select item in the list\n \"\"\"\n self._selectedIndex = index\n self.setCurrentIndex(self.model().createIndex(index, 0))": 2337, "def percentile_index(a, q):\n \"\"\"\n Returns the index of the value at the Qth percentile in array a.\n \"\"\"\n return np.where(\n a==np.percentile(a, q, interpolation='nearest')\n )[0][0]": 2338, "def sanitize_word(s):\n \"\"\"Remove non-alphanumerical characters from metric word.\n And trim excessive underscores.\n \"\"\"\n s = re.sub('[^\\w-]+', '_', s)\n s = re.sub('__+', '_', s)\n return s.strip('_')": 2339, "def _attach_files(filepaths, email_):\n \"\"\"Take a list of filepaths and attach the files to a MIMEMultipart.\n\n Args:\n filepaths (list(str)): A list of filepaths.\n email_ (email.MIMEMultipart): A MIMEMultipart email_.\n \"\"\"\n for filepath in filepaths:\n base = os.path.basename(filepath)\n with open(filepath, \"rb\") as file:\n part = MIMEApplication(file.read(), Name=base)\n part[\"Content-Disposition\"] = 'attachment; filename=\"%s\"' % base\n email_.attach(part)": 2340, "def send(r, stream=False):\n \"\"\"Just sends the request using its send method and returns its response. \"\"\"\n r.send(stream=stream)\n return r.response": 2341, "def handle_data(self, data):\n \"\"\"\n Djeffify data between tags\n \"\"\"\n if data.strip():\n data = djeffify_string(data)\n self.djhtml += data": 2342, "def splitext_no_dot(filename):\n \"\"\"\n Wrap os.path.splitext to return the name and the extension\n without the '.' (e.g., csv instead of .csv)\n \"\"\"\n name, ext = os.path.splitext(filename)\n ext = ext.lower()\n return name, ext.strip('.')": 2343, "def boolean(flag):\n \"\"\"\n Convert string in boolean\n \"\"\"\n s = flag.lower()\n if s in ('1', 'yes', 'true'):\n return True\n elif s in ('0', 'no', 'false'):\n return False\n raise ValueError('Unknown flag %r' % s)": 2344, "def autoscan():\n \"\"\"autoscan will check all of the serial ports to see if they have\n a matching VID:PID for a MicroPython board.\n \"\"\"\n for port in serial.tools.list_ports.comports():\n if is_micropython_usb_device(port):\n connect_serial(port[0])": 2345, "def _session_set(self, key, value):\n \"\"\"\n Saves a value to session.\n \"\"\"\n\n self.session[self._session_key(key)] = value": 2346, "def internal_reset(self):\n \"\"\"\n internal state reset.\n used e.g. in unittests\n \"\"\"\n log.critical(\"PIA internal_reset()\")\n self.empty_key_toggle = True\n self.current_input_char = None\n self.input_repead = 0": 2347, "def get_member(thing_obj, member_string):\n \"\"\"Get a member from an object by (string) name\"\"\"\n mems = {x[0]: x[1] for x in inspect.getmembers(thing_obj)}\n if member_string in mems:\n return mems[member_string]": 2348, "def _replace_service_arg(self, name, index, args):\n \"\"\" Replace index in list with service \"\"\"\n args[index] = self.get_instantiated_service(name)": 2349, "def _dotify(cls, data):\n \"\"\"Add dots.\"\"\"\n return ''.join(char if char in cls.PRINTABLE_DATA else '.' for char in data)": 2350, "def is_set(self, key):\n \"\"\"Return True if variable is a set\"\"\"\n data = self.model.get_data()\n return isinstance(data[key], set)": 2351, "def dropna(self):\n \"\"\"Returns MultiIndex without any rows containing null values according to Baloo's convention.\n\n Returns\n -------\n MultiIndex\n MultiIndex with no null values.\n\n \"\"\"\n not_nas = [v.notna() for v in self.values]\n and_filter = reduce(lambda x, y: x & y, not_nas)\n\n return self[and_filter]": 2352, "def reset_default_logger():\n \"\"\"\n Resets the internal default logger to the initial configuration\n \"\"\"\n global logger\n global _loglevel\n global _logfile\n global _formatter\n _loglevel = logging.DEBUG\n _logfile = None\n _formatter = None\n logger = setup_logger(name=LOGZERO_DEFAULT_LOGGER, logfile=_logfile, level=_loglevel, formatter=_formatter)": 2353, "def save_pdf(path):\n \"\"\"\n Saves a pdf of the current matplotlib figure.\n\n :param path: str, filepath to save to\n \"\"\"\n\n pp = PdfPages(path)\n pp.savefig(pyplot.gcf())\n pp.close()": 2354, "def generate_id():\n \"\"\"Generate new UUID\"\"\"\n # TODO: Use six.string_type to Py3 compat\n try:\n return unicode(uuid1()).replace(u\"-\", u\"\")\n except NameError:\n return str(uuid1()).replace(u\"-\", u\"\")": 2355, "def is_valid_varname(varname):\n \"\"\" Checks syntax and validity of a variable name \"\"\"\n if not isinstance(varname, six.string_types):\n return False\n match_obj = re.match(varname_regex, varname)\n valid_syntax = match_obj is not None\n valid_name = not keyword.iskeyword(varname)\n isvalid = valid_syntax and valid_name\n return isvalid": 2356, "def setAutoRangeOn(self, axisNumber):\n \"\"\" Sets the auto-range of the axis on.\n\n :param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes).\n \"\"\"\n setXYAxesAutoRangeOn(self, self.xAxisRangeCti, self.yAxisRangeCti, axisNumber)": 2357, "def unique_element(ll):\n \"\"\" returns unique elements from a list preserving the original order \"\"\"\n seen = {}\n result = []\n for item in ll:\n if item in seen:\n continue\n seen[item] = 1\n result.append(item)\n return result": 2358, "def wait_on_rate_limit(self, value):\n \"\"\"Enable or disable automatic rate-limit handling.\"\"\"\n check_type(value, bool, may_be_none=False)\n self._wait_on_rate_limit = value": 2359, "def _send_file(self, filename):\n \"\"\"\n Sends a file via FTP.\n \"\"\"\n # pylint: disable=E1101\n ftp = ftplib.FTP(host=self.host)\n ftp.login(user=self.user, passwd=self.password)\n ftp.set_pasv(True)\n ftp.storbinary(\"STOR %s\" % os.path.basename(filename),\n file(filename, 'rb'))": 2360, "def send_photo(self, photo: str, caption: str=None, reply: Message=None, on_success: callable=None,\n reply_markup: botapi.ReplyMarkup=None):\n \"\"\"\n Send photo to this peer.\n :param photo: File path to photo to send.\n :param caption: Caption for photo\n :param reply: Message object or message_id to reply to.\n :param on_success: Callback to call when call is complete.\n\n :type reply: int or Message\n \"\"\"\n self.twx.send_photo(peer=self, photo=photo, caption=caption, reply=reply, reply_markup=reply_markup,\n on_success=on_success)": 2361, "def sys_pipes_forever(encoding=_default_encoding):\n \"\"\"Redirect all C output to sys.stdout/err\n \n This is not a context manager; it turns on C-forwarding permanently.\n \"\"\"\n global _mighty_wurlitzer\n if _mighty_wurlitzer is None:\n _mighty_wurlitzer = sys_pipes(encoding)\n _mighty_wurlitzer.__enter__()": 2362, "def _check_for_errors(etree: ET.ElementTree):\n \"\"\"Check AniDB response XML tree for errors.\"\"\"\n if etree.getroot().tag == 'error':\n raise APIError(etree.getroot().text)": 2363, "def previous_friday(dt):\n \"\"\"\n If holiday falls on Saturday or Sunday, use previous Friday instead.\n \"\"\"\n if dt.weekday() == 5:\n return dt - timedelta(1)\n elif dt.weekday() == 6:\n return dt - timedelta(2)\n return dt": 2364, "def save_model(self, request, obj, form, change):\n \"\"\"\n Set currently authenticated user as the author of the gallery.\n \"\"\"\n obj.author = request.user\n obj.save()": 2365, "def set_position(self, x, y, width, height):\n \"\"\"Set window top-left corner position and size\"\"\"\n SetWindowPos(self._hwnd, None, x, y, width, height, ctypes.c_uint(0))": 2366, "def set_constraint_bound(self, name, value):\n \"\"\"Set the upper bound of a constraint.\"\"\"\n index = self._get_constraint_index(name)\n self.upper_bounds[index] = value\n self._reset_solution()": 2367, "def set_axis_options(self, row, column, text):\n \"\"\"Set additionnal options as plain text.\"\"\"\n\n subplot = self.get_subplot_at(row, column)\n subplot.set_axis_options(text)": 2368, "def set_default(self, key, value):\n \"\"\"Set the default value for this key.\n Default only used when no value is provided by the user via\n arg, config or env.\n \"\"\"\n k = self._real_key(key.lower())\n self._defaults[k] = value": 2369, "def stringc(text, color):\n \"\"\"\n Return a string with terminal colors.\n \"\"\"\n if has_colors:\n text = str(text)\n\n return \"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\"\n else:\n return text": 2370, "def chunks(iterable, chunk):\n \"\"\"Yield successive n-sized chunks from an iterable.\"\"\"\n for i in range(0, len(iterable), chunk):\n yield iterable[i:i + chunk]": 2371, "def _print_memory(self, memory):\n \"\"\"Print memory.\n \"\"\"\n for addr, value in memory.items():\n print(\" 0x%08x : 0x%08x (%d)\" % (addr, value, value))": 2372, "def sort_by_name(self):\n \"\"\"Sort list elements by name.\"\"\"\n super(JSSObjectList, self).sort(key=lambda k: k.name)": 2373, "def cached_query(qs, timeout=None):\n \"\"\" Auto cached queryset and generate results.\n \"\"\"\n cache_key = generate_cache_key(qs)\n return get_cached(cache_key, list, args=(qs,), timeout=None)": 2374, "def csort(objs, key):\n \"\"\"Order-preserving sorting function.\"\"\"\n idxs = dict((obj, i) for (i, obj) in enumerate(objs))\n return sorted(objs, key=lambda obj: (key(obj), idxs[obj]))": 2375, "def validate_type(self, type_):\n \"\"\"Take an str/unicode `type_` and raise a ValueError if it's not \n a valid type for the object.\n \n A valid type for a field is a value from the types_set attribute of \n that field's class. \n \n \"\"\"\n if type_ is not None and type_ not in self.types_set:\n raise ValueError('Invalid type for %s:%s' % (self.__class__, type_))": 2376, "def mpl_outside_legend(ax, **kwargs):\n \"\"\" Places a legend box outside a matplotlib Axes instance. \"\"\"\n box = ax.get_position()\n ax.set_position([box.x0, box.y0, box.width * 0.75, box.height])\n # Put a legend to the right of the current axis\n ax.legend(loc='upper left', bbox_to_anchor=(1, 1), **kwargs)": 2377, "def smooth_array(array, amount=1):\n \"\"\"\n\n Returns the nearest-neighbor (+/- amount) smoothed array.\n This does not modify the array or slice off the funny end points.\n\n \"\"\"\n if amount==0: return array\n\n # we have to store the old values in a temp array to keep the\n # smoothing from affecting the smoothing\n new_array = _n.array(array)\n\n for n in range(len(array)):\n new_array[n] = smooth(array, n, amount)\n\n return new_array": 2378, "def pick_unused_port(self):\n \"\"\" Pick an unused port. There is a slight chance that this wont work. \"\"\"\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.bind(('127.0.0.1', 0))\n _, port = s.getsockname()\n s.close()\n return port": 2379, "def run(context, port):\n \"\"\" Run the Webserver/SocketIO and app\n \"\"\"\n global ctx\n ctx = context\n app.run(port=port)": 2380, "def enter_room(self, sid, room, namespace=None):\n \"\"\"Enter a room.\n\n The only difference with the :func:`socketio.Server.enter_room` method\n is that when the ``namespace`` argument is not given the namespace\n associated with the class is used.\n \"\"\"\n return self.server.enter_room(sid, room,\n namespace=namespace or self.namespace)": 2381, "def end(self):\n \"\"\"End of the Glances server session.\"\"\"\n if not self.args.disable_autodiscover:\n self.autodiscover_client.close()\n self.server.end()": 2382, "def delistify(x):\n \"\"\" A basic slug version of a given parameter list. \"\"\"\n if isinstance(x, list):\n x = [e.replace(\"'\", \"\") for e in x]\n return '-'.join(sorted(x))\n return x": 2383, "def access_to_sympy(self, var_name, access):\n \"\"\"\n Transform a (multidimensional) variable access to a flattend sympy expression.\n\n Also works with flat array accesses.\n \"\"\"\n base_sizes = self.variables[var_name][1]\n\n expr = sympy.Number(0)\n\n for dimension, a in enumerate(access):\n base_size = reduce(operator.mul, base_sizes[dimension+1:], sympy.Integer(1))\n\n expr += base_size*a\n\n return expr": 2384, "def get_py_source(file):\n \"\"\"\n Retrieves and returns the source code for any Python\n files requested by the UI via the host agent\n\n @param file [String] The fully qualified path to a file\n \"\"\"\n try:\n response = None\n pysource = \"\"\n\n if regexp_py.search(file) is None:\n response = {\"error\": \"Only Python source files are allowed. (*.py)\"}\n else:\n with open(file, 'r') as pyfile:\n pysource = pyfile.read()\n\n response = {\"data\": pysource}\n\n except Exception as e:\n response = {\"error\": str(e)}\n finally:\n return response": 2385, "def _root_mean_square_error(y, y_pred, w):\n \"\"\"Calculate the root mean square error.\"\"\"\n return np.sqrt(np.average(((y_pred - y) ** 2), weights=w))": 2386, "def toArray(self):\n \"\"\"\n Returns a copy of this SparseVector as a 1-dimensional NumPy array.\n \"\"\"\n arr = np.zeros((self.size,), dtype=np.float64)\n arr[self.indices] = self.values\n return arr": 2387, "def step_next_line(self):\n \"\"\"Sets cursor as beginning of next line.\"\"\"\n self._eol.append(self.position)\n self._lineno += 1\n self._col_offset = 0": 2388, "def read_sphinx_environment(pth):\n \"\"\"Read the sphinx environment.pickle file at path `pth`.\"\"\"\n\n with open(pth, 'rb') as fo:\n env = pickle.load(fo)\n return env": 2389, "def _is_image_sequenced(image):\n \"\"\"Determine if the image is a sequenced image.\"\"\"\n try:\n image.seek(1)\n image.seek(0)\n result = True\n except EOFError:\n result = False\n\n return result": 2390, "def consecutive(data, stepsize=1):\n \"\"\"Converts array into chunks with consecutive elements of given step size.\n http://stackoverflow.com/questions/7352684/how-to-find-the-groups-of-consecutive-elements-from-an-array-in-numpy\n \"\"\"\n return np.split(data, np.where(np.diff(data) != stepsize)[0] + 1)": 2391, "def __contains__ (self, key):\n \"\"\"Check lowercase key item.\"\"\"\n assert isinstance(key, basestring)\n return dict.__contains__(self, key.lower())": 2392, "def reindent(s, numspaces):\n \"\"\" reinidents a string (s) by the given number of spaces (numspaces) \"\"\"\n leading_space = numspaces * ' '\n lines = [leading_space + line.strip()for line in s.splitlines()]\n return '\\n'.join(lines)": 2393, "def wrap_count(method):\n \"\"\"\n Returns number of wraps around given method.\n \"\"\"\n number = 0\n while hasattr(method, '__aspects_orig'):\n number += 1\n method = method.__aspects_orig\n return number": 2394, "def insert_many(self, items):\n \"\"\"\n Insert many items at once into a temporary table.\n\n \"\"\"\n return SessionContext.session.execute(\n self.insert(values=[\n to_dict(item, self.c)\n for item in items\n ]),\n ).rowcount": 2395, "def get_count(self, query):\n \"\"\"\n Returns a number of query results. This is faster than .count() on the query\n \"\"\"\n count_q = query.statement.with_only_columns(\n [func.count()]).order_by(None)\n count = query.session.execute(count_q).scalar()\n return count": 2396, "def downgrade(directory, sql, tag, x_arg, revision):\n \"\"\"Revert to a previous version\"\"\"\n _downgrade(directory, revision, sql, tag, x_arg)": 2397, "def sqliteRowsToDicts(sqliteRows):\n \"\"\"\n Unpacks sqlite rows as returned by fetchall\n into an array of simple dicts.\n\n :param sqliteRows: array of rows returned from fetchall DB call\n :return: array of dicts, keyed by the column names.\n \"\"\"\n return map(lambda r: dict(zip(r.keys(), r)), sqliteRows)": 2398, "def get_type_len(self):\n \"\"\"Retrieve the type and length for a data record.\"\"\"\n # Check types and set type/len\n self.get_sql()\n return self.type, self.len, self.len_decimal": 2399, "def exists(self, filepath):\n \"\"\"Determines if the specified file/folder exists, even if it\n is on a remote server.\"\"\"\n if self.is_ssh(filepath):\n self._check_ftp()\n remotepath = self._get_remote(filepath)\n try:\n self.ftp.stat(remotepath)\n except IOError as e:\n if e.errno == errno.ENOENT:\n return False\n else:\n return True\n else:\n return os.path.exists(filepath)": 2400, "def ensure_tuple(obj):\n \"\"\"Try and make the given argument into a tuple.\"\"\"\n if obj is None:\n return tuple()\n if isinstance(obj, Iterable) and not isinstance(obj, six.string_types):\n return tuple(obj)\n return obj,": 2401, "def calculate_bounding_box(data):\n \"\"\"\n Returns a 2 x m array indicating the min and max along each\n dimension.\n \"\"\"\n mins = data.min(0)\n maxes = data.max(0)\n return mins, maxes": 2402, "def _create_complete_graph(node_ids):\n \"\"\"Create a complete graph from the list of node ids.\n\n Args:\n node_ids: a list of node ids\n\n Returns:\n An undirected graph (as a networkx.Graph)\n \"\"\"\n g = nx.Graph()\n g.add_nodes_from(node_ids)\n for (i, j) in combinations(node_ids, 2):\n g.add_edge(i, j)\n return g": 2403, "def glr_path_static():\n \"\"\"Returns path to packaged static files\"\"\"\n return os.path.abspath(os.path.join(os.path.dirname(__file__), '_static'))": 2404, "def image_format(value):\n \"\"\"\n Confirms that the uploaded image is of supported format.\n\n Args:\n value (File): The file with an `image` property containing the image\n\n Raises:\n django.forms.ValidationError\n\n \"\"\"\n\n if value.image.format.upper() not in constants.ALLOWED_IMAGE_FORMATS:\n raise ValidationError(MESSAGE_INVALID_IMAGE_FORMAT)": 2405, "def standard_deviation(numbers):\n \"\"\"Return standard deviation.\"\"\"\n numbers = list(numbers)\n if not numbers:\n return 0\n mean = sum(numbers) / len(numbers)\n return (sum((n - mean) ** 2 for n in numbers) /\n len(numbers)) ** .5": 2406, "def fetch_header(self):\n \"\"\"Make a header request to the endpoint.\"\"\"\n query = self.query().add_query_parameter(req='header')\n return self._parse_messages(self.get_query(query).content)[0]": 2407, "def dt2str(dt, flagSeconds=True):\n \"\"\"Converts datetime object to str if not yet an str.\"\"\"\n if isinstance(dt, str):\n return dt\n return dt.strftime(_FMTS if flagSeconds else _FMT)": 2408, "def add_device_callback(self, callback):\n \"\"\"Register a callback to be invoked when a new device appears.\"\"\"\n _LOGGER.debug('Added new callback %s ', callback)\n self._cb_new_device.append(callback)": 2409, "def any_contains_any(strings, candidates):\n \"\"\"Whether any of the strings contains any of the candidates.\"\"\"\n for string in strings:\n for c in candidates:\n if c in string:\n return True": 2410, "def load(cls, fname):\n \"\"\"\n Loads the flow from a JSON file.\n\n :param fname: the file to load\n :type fname: str\n :return: the flow\n :rtype: Flow\n \"\"\"\n with open(fname) as f:\n content = f.readlines()\n return Flow.from_json(''.join(content))": 2411, "def _write_config(config, cfg_file):\n \"\"\"\n Write a config object to the settings.cfg file.\n\n :param config: A ConfigParser object to write to the settings.cfg file.\n \"\"\"\n directory = os.path.dirname(cfg_file)\n if not os.path.exists(directory):\n os.makedirs(directory)\n with open(cfg_file, \"w+\") as output_file:\n config.write(output_file)": 2412, "def dump_stmt_strings(stmts, fname):\n \"\"\"Save printed statements in a file.\n\n Parameters\n ----------\n stmts_in : list[indra.statements.Statement]\n A list of statements to save in a text file.\n fname : Optional[str]\n The name of a text file to save the printed statements into.\n \"\"\"\n with open(fname, 'wb') as fh:\n for st in stmts:\n fh.write(('%s\\n' % st).encode('utf-8'))": 2413, "def validate_stringlist(s):\n \"\"\"Validate a list of strings\n\n Parameters\n ----------\n val: iterable of strings\n\n Returns\n -------\n list\n list of str\n\n Raises\n ------\n ValueError\"\"\"\n if isinstance(s, six.string_types):\n return [six.text_type(v.strip()) for v in s.split(',') if v.strip()]\n else:\n try:\n return list(map(validate_str, s))\n except TypeError as e:\n raise ValueError(e.message)": 2414, "def write_line(self, line, count=1):\n \"\"\"writes the line and count newlines after the line\"\"\"\n self.write(line)\n self.write_newlines(count)": 2415, "def make_strslice(lineno, s, lower, upper):\n \"\"\" Wrapper: returns String Slice node\n \"\"\"\n return symbols.STRSLICE.make_node(lineno, s, lower, upper)": 2416, "def filedata(self):\n \"\"\"Property providing access to the :class:`.FileDataAPI`\"\"\"\n if self._filedata_api is None:\n self._filedata_api = self.get_filedata_api()\n return self._filedata_api": 2417, "def _str_to_list(s):\n \"\"\"Converts a comma separated string to a list\"\"\"\n _list = s.split(\",\")\n return list(map(lambda i: i.lstrip(), _list))": 2418, "def backward_char(self, e): # (C-b)\n u\"\"\"Move back a character. \"\"\"\n self.l_buffer.backward_char(self.argument_reset)\n self.finalize()": 2419, "def top(n, width=WIDTH, style=STYLE):\n \"\"\"Prints the top row of a table\"\"\"\n return hrule(n, width, linestyle=STYLES[style].top)": 2420, "def _repr_strip(mystring):\n \"\"\"\n Returns the string without any initial or final quotes.\n \"\"\"\n r = repr(mystring)\n if r.startswith(\"'\") and r.endswith(\"'\"):\n return r[1:-1]\n else:\n return r": 2421, "def text_remove_empty_lines(text):\n \"\"\"\n Whitespace normalization:\n\n - Strip empty lines\n - Strip trailing whitespace\n \"\"\"\n lines = [ line.rstrip() for line in text.splitlines() if line.strip() ]\n return \"\\n\".join(lines)": 2422, "def strip_spaces(value, sep=None, join=True):\n \"\"\"Cleans trailing whitespaces and replaces also multiple whitespaces with a single space.\"\"\"\n value = value.strip()\n value = [v.strip() for v in value.split(sep)]\n join_sep = sep or ' '\n return join_sep.join(value) if join else value": 2423, "def chmod(scope, filename, mode):\n \"\"\"\n Changes the permissions of the given file (or list of files)\n to the given mode. You probably want to use an octal representation\n for the integer, e.g. \"chmod(myfile, 0644)\".\n\n :type filename: string\n :param filename: A filename.\n :type mode: int\n :param mode: The access permissions.\n \"\"\"\n for file in filename:\n os.chmod(file, mode[0])\n return True": 2424, "def set_title(self, title, **kwargs):\n \"\"\"Sets the title on the underlying matplotlib AxesSubplot.\"\"\"\n ax = self.get_axes()\n ax.set_title(title, **kwargs)": 2425, "def show_yticklabels(self, row, column):\n \"\"\"Show the y-axis tick labels for a subplot.\n\n :param row,column: specify the subplot.\n\n \"\"\"\n subplot = self.get_subplot_at(row, column)\n subplot.show_yticklabels()": 2426, "def _replace_file(path, content):\n \"\"\"Writes a file if it doesn't already exist with the same content.\n\n This is useful because cargo uses timestamps to decide whether to compile things.\"\"\"\n if os.path.exists(path):\n with open(path, 'r') as f:\n if content == f.read():\n print(\"Not overwriting {} because it is unchanged\".format(path), file=sys.stderr)\n return\n\n with open(path, 'w') as f:\n f.write(content)": 2427, "def correspond(text):\n \"\"\"Communicate with the child process without closing stdin.\"\"\"\n subproc.stdin.write(text)\n subproc.stdin.flush()\n return drain()": 2428, "def numberp(v):\n \"\"\"Return true iff 'v' is a number.\"\"\"\n return (not(isinstance(v, bool)) and\n (isinstance(v, int) or isinstance(v, float)))": 2429, "def replace_variable_node(node, annotation):\n \"\"\"Replace a node annotated by `nni.variable`.\n node: the AST node to replace\n annotation: annotation string\n \"\"\"\n assert type(node) is ast.Assign, 'nni.variable is not annotating assignment expression'\n assert len(node.targets) == 1, 'Annotated assignment has more than one left-hand value'\n name, expr = parse_nni_variable(annotation)\n assert test_variable_equal(node.targets[0], name), 'Annotated variable has wrong name'\n node.value = expr\n return node": 2430, "def _swap_rows(self, i, j):\n \"\"\"Swap i and j rows\n\n As the side effect, determinant flips.\n\n \"\"\"\n\n L = np.eye(3, dtype='intc')\n L[i, i] = 0\n L[j, j] = 0\n L[i, j] = 1\n L[j, i] = 1\n self._L.append(L.copy())\n self._A = np.dot(L, self._A)": 2431, "def transformer(data, label):\n \"\"\" data preparation \"\"\"\n data = mx.image.imresize(data, IMAGE_SIZE, IMAGE_SIZE)\n data = mx.nd.transpose(data, (2, 0, 1))\n data = data.astype(np.float32) / 128.0 - 1\n return data, label": 2432, "def purge_duplicates(list_in):\n \"\"\"Remove duplicates from list while preserving order.\n\n Parameters\n ----------\n list_in: Iterable\n\n Returns\n -------\n list\n List of first occurences in order\n \"\"\"\n _list = []\n for item in list_in:\n if item not in _list:\n _list.append(item)\n return _list": 2433, "def get_point_hash(self, point):\n \"\"\"\n return geohash for given point with self.precision\n :param point: GeoPoint instance\n :return: string\n \"\"\"\n return geohash.encode(point.latitude, point.longitude, self.precision)": 2434, "def __eq__(self, anotherset):\n \"\"\"Tests on itemlist equality\"\"\"\n if not isinstance(anotherset, LR0ItemSet):\n raise TypeError\n if len(self.itemlist) != len(anotherset.itemlist):\n return False\n for element in self.itemlist:\n if element not in anotherset.itemlist:\n return False\n return True": 2435, "def paint(self, tbl):\n \"\"\"\n Paint the table on terminal\n Currently only print out basic string format\n \"\"\"\n if not isinstance(tbl, Table):\n logging.error(\"unable to paint table: invalid object\")\n return False\n\n self.term.stream.write(self.term.clear)\n\n self.term.stream.write(str(tbl))\n return True": 2436, "def check_int(integer):\n \"\"\"\n Check if number is integer or not.\n\n :param integer: Number as str\n :return: Boolean\n \"\"\"\n if not isinstance(integer, str):\n return False\n if integer[0] in ('-', '+'):\n return integer[1:].isdigit()\n return integer.isdigit()": 2437, "def timedelta2millisecond(td):\n \"\"\"Get milliseconds from a timedelta.\"\"\"\n milliseconds = td.days * 24 * 60 * 60 * 1000\n milliseconds += td.seconds * 1000\n milliseconds += td.microseconds / 1000\n return milliseconds": 2438, "def __getitem__(self, name):\n \"\"\"\n A pymongo-like behavior for dynamically obtaining a collection of documents\n \"\"\"\n if name not in self._collections:\n self._collections[name] = Collection(self.db, name)\n return self._collections[name]": 2439, "def _get_example_length(example):\n \"\"\"Returns the maximum length between the example inputs and targets.\"\"\"\n length = tf.maximum(tf.shape(example[0])[0], tf.shape(example[1])[0])\n return length": 2440, "def flatten4d3d(x):\n \"\"\"Flatten a 4d-tensor into a 3d-tensor by joining width and height.\"\"\"\n xshape = shape_list(x)\n result = tf.reshape(x, [xshape[0], xshape[1] * xshape[2], xshape[3]])\n return result": 2441, "def get_indent(text):\n \"\"\"Get indent of text.\n\n https://stackoverflow.com/questions/2268532/grab-a-lines-whitespace-\n indention-with-python\n \"\"\"\n indent = ''\n\n ret = re.match(r'(\\s*)', text)\n if ret:\n indent = ret.group(1)\n\n return indent": 2442, "def is_lazy_iterable(obj):\n \"\"\"\n Returns whether *obj* is iterable lazily, such as generators, range objects, etc.\n \"\"\"\n return isinstance(obj,\n (types.GeneratorType, collections.MappingView, six.moves.range, enumerate))": 2443, "def is_in(self, search_list, pair):\n \"\"\"\n If pair is in search_list, return the index. Otherwise return -1\n \"\"\"\n index = -1\n for nr, i in enumerate(search_list):\n if(np.all(i == pair)):\n return nr\n return index": 2444, "def is_readable(filename):\n \"\"\"Check if file is a regular file and is readable.\"\"\"\n return os.path.isfile(filename) and os.access(filename, os.R_OK)": 2445, "def _genTex2D(self):\n \"\"\"Generate an empty texture in OpenGL\"\"\"\n for face in range(6):\n gl.glTexImage2D(self.target0 + face, 0, self.internal_fmt, self.width, self.height, 0,\n self.pixel_fmt, gl.GL_UNSIGNED_BYTE, 0)": 2446, "def int2str(num, radix=10, alphabet=BASE85):\n \"\"\"helper function for quick base conversions from integers to strings\"\"\"\n return NumConv(radix, alphabet).int2str(num)": 2447, "def start(self):\n \"\"\"Start the receiver.\n \"\"\"\n if not self._is_running:\n self._do_run = True\n self._thread.start()\n return self": 2448, "def is_valid_uid(uid):\n \"\"\"\n :return: True if it is a valid DHIS2 UID, False if not\n \"\"\"\n pattern = r'^[A-Za-z][A-Za-z0-9]{10}$'\n if not isinstance(uid, string_types):\n return False\n return bool(re.compile(pattern).match(uid))": 2449, "def seconds(num):\n \"\"\"\n Pause for this many seconds\n \"\"\"\n now = pytime.time()\n end = now + num\n until(end)": 2450, "def format_time(time):\n \"\"\" Formats the given time into HH:MM:SS \"\"\"\n h, r = divmod(time / 1000, 3600)\n m, s = divmod(r, 60)\n\n return \"%02d:%02d:%02d\" % (h, m, s)": 2451, "def fileModifiedTimestamp(fname):\n \"\"\"return \"YYYY-MM-DD\" when the file was modified.\"\"\"\n modifiedTime=os.path.getmtime(fname)\n stamp=time.strftime('%Y-%m-%d', time.localtime(modifiedTime))\n return stamp": 2452, "def start(self):\n \"\"\"Activate the TypingStream on stdout\"\"\"\n self.streams.append(sys.stdout)\n sys.stdout = self.stream": 2453, "def current_offset(local_tz=None):\n \"\"\"\n Returns current utcoffset for a timezone. Uses\n DEFAULT_LOCAL_TZ by default. That value can be\n changed at runtime using the func below.\n \"\"\"\n if local_tz is None:\n local_tz = DEFAULT_LOCAL_TZ\n dt = local_tz.localize(datetime.now())\n return dt.utcoffset()": 2454, "def __hash__(self):\n \"\"\"Return ``hash(self)``.\"\"\"\n return hash((type(self), self.domain, self.range, self.partition))": 2455, "def set_cursor_position(self, position):\n \"\"\"Set cursor position\"\"\"\n position = self.get_position(position)\n cursor = self.textCursor()\n cursor.setPosition(position)\n self.setTextCursor(cursor)\n self.ensureCursorVisible()": 2456, "def clear_timeline(self):\n \"\"\"\n Clear the contents of the TimeLine Canvas\n\n Does not modify the actual markers dictionary and thus after\n redrawing all markers are visible again.\n \"\"\"\n self._timeline.delete(tk.ALL)\n self._canvas_ticks.delete(tk.ALL)": 2457, "async def iso(self, source):\n \"\"\"Convert to timestamp.\"\"\"\n from datetime import datetime\n unix_timestamp = int(source)\n return datetime.fromtimestamp(unix_timestamp).isoformat()": 2458, "def listfolderpath(p):\n \"\"\"\n generator of list folder in the path.\n folders only\n \"\"\"\n for entry in scandir.scandir(p):\n if entry.is_dir():\n yield entry.path": 2459, "def render_template(env, filename, values=None):\n \"\"\"\n Render a jinja template\n \"\"\"\n if not values:\n values = {}\n tmpl = env.get_template(filename)\n return tmpl.render(values)": 2460, "def listified_tokenizer(source):\n \"\"\"Tokenizes *source* and returns the tokens as a list of lists.\"\"\"\n io_obj = io.StringIO(source)\n return [list(a) for a in tokenize.generate_tokens(io_obj.readline)]": 2461, "def save_notebook(work_notebook, write_file):\n \"\"\"Saves the Jupyter work_notebook to write_file\"\"\"\n with open(write_file, 'w') as out_nb:\n json.dump(work_notebook, out_nb, indent=2)": 2462, "def conv3x3(in_channels, out_channels, stride=1):\n \"\"\"\n 3x3 convolution with padding.\n Original code has had bias turned off, because Batch Norm would remove the bias either way\n \"\"\"\n return nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)": 2463, "def camel_to_(s):\n \"\"\"\n Convert CamelCase to camel_case\n \"\"\"\n s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', s)\n return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()": 2464, "def toJson(protoObject, indent=None):\n \"\"\"\n Serialises a protobuf object as json\n \"\"\"\n # Using the internal method because this way we can reformat the JSON\n js = json_format.MessageToDict(protoObject, False)\n return json.dumps(js, indent=indent)": 2465, "def toListInt(value):\n \"\"\"\n Convert a value to list of ints, if possible.\n \"\"\"\n if TypeConverters._can_convert_to_list(value):\n value = TypeConverters.toList(value)\n if all(map(lambda v: TypeConverters._is_integer(v), value)):\n return [int(v) for v in value]\n raise TypeError(\"Could not convert %s to list of ints\" % value)": 2466, "def cmd_dns_lookup_reverse(ip_address, verbose):\n \"\"\"Perform a reverse lookup of a given IP address.\n\n Example:\n\n \\b\n $ $ habu.dns.lookup.reverse 8.8.8.8\n {\n \"hostname\": \"google-public-dns-a.google.com\"\n }\n \"\"\"\n if verbose:\n logging.basicConfig(level=logging.INFO, format='%(message)s')\n print(\"Looking up %s...\" % ip_address, file=sys.stderr)\n\n answer = lookup_reverse(ip_address)\n\n if answer:\n print(json.dumps(answer, indent=4))\n else:\n print(\"[X] %s is not valid IPv4/IPV6 address\" % ip_address)\n\n return True": 2467, "def stop_process(self):\n \"\"\"\n Stops the child process.\n \"\"\"\n self._process.terminate()\n if not self._process.waitForFinished(100):\n self._process.kill()": 2468, "def stop(self):\n \"\"\"\n Stop this server so that the calling process can exit\n \"\"\"\n # unsetup_fuse()\n self.fuse_process.teardown()\n for uuid in self.processes:\n self.processes[uuid].terminate()": 2469, "def forward(self, step):\n \"\"\"Move the turtle forward.\n\n :param step: Integer. Distance to move forward.\n \"\"\"\n x = self.pos_x + math.cos(math.radians(self.rotation)) * step\n y = self.pos_y + math.sin(math.radians(self.rotation)) * step\n prev_brush_state = self.brush_on\n self.brush_on = True\n self.move(x, y)\n self.brush_on = prev_brush_state": 2470, "def l2_norm(arr):\n \"\"\"\n The l2 norm of an array is is defined as: sqrt(||x||), where ||x|| is the\n dot product of the vector.\n \"\"\"\n arr = np.asarray(arr)\n return np.sqrt(np.dot(arr.ravel().squeeze(), arr.ravel().squeeze()))": 2471, "def default_strlen(strlen=None):\n \"\"\"Sets the default string length for lstring and ilwd:char, if they are\n treated as strings. Default is 50.\n \"\"\"\n if strlen is not None:\n _default_types_status['default_strlen'] = strlen\n # update the typeDicts as needed\n lstring_as_obj(_default_types_status['lstring_as_obj'])\n ilwd_as_int(_default_types_status['ilwd_as_int'])\n return _default_types_status['default_strlen']": 2472, "def onLeftDown(self, event=None):\n \"\"\" left button down: report x,y coords, start zooming mode\"\"\"\n if event is None:\n return\n self.cursor_mode_action('leftdown', event=event)\n self.ForwardEvent(event=event.guiEvent)": 2473, "def omnihash(obj):\n \"\"\" recursively hash unhashable objects \"\"\"\n if isinstance(obj, set):\n return hash(frozenset(omnihash(e) for e in obj))\n elif isinstance(obj, (tuple, list)):\n return hash(tuple(omnihash(e) for e in obj))\n elif isinstance(obj, dict):\n return hash(frozenset((k, omnihash(v)) for k, v in obj.items()))\n else:\n return hash(obj)": 2474, "def cover(session):\n \"\"\"Run the final coverage report.\n This outputs the coverage report aggregating coverage from the unit\n test runs (not system test runs), and then erases coverage data.\n \"\"\"\n session.interpreter = 'python3.6'\n session.install('coverage', 'pytest-cov')\n session.run('coverage', 'report', '--show-missing', '--fail-under=100')\n session.run('coverage', 'erase')": 2475, "def find_one(line, lookup):\n \"\"\"\n regexp search with one value to return.\n\n :param line: Line\n :param lookup: regexp\n :return: Match group or False\n \"\"\"\n match = re.search(lookup, line)\n if match:\n if match.group(1):\n return match.group(1)\n return False": 2476, "def teardown_test(self, context):\n \"\"\"\n Tears down the Django test\n \"\"\"\n context.test.tearDownClass()\n context.test._post_teardown(run=True)\n del context.test": 2477, "def glog(x,l = 2):\n \"\"\"\n Generalised logarithm\n\n :param x: number\n :param p: number added befor logarithm \n\n \"\"\"\n return np.log((x+np.sqrt(x**2+l**2))/2)/np.log(l)": 2478, "def _ioctl (self, func, args):\n \"\"\"Call ioctl() with given parameters.\"\"\"\n import fcntl\n return fcntl.ioctl(self.sockfd.fileno(), func, args)": 2479, "def inheritdoc(method):\n \"\"\"Set __doc__ of *method* to __doc__ of *method* in its parent class.\n\n Since this is used on :class:`.StringMixIn`, the \"parent class\" used is\n ``str``. This function can be used as a decorator.\n \"\"\"\n method.__doc__ = getattr(str, method.__name__).__doc__\n return method": 2480, "def split_elements(value):\n \"\"\"Split a string with comma or space-separated elements into a list.\"\"\"\n l = [v.strip() for v in value.split(',')]\n if len(l) == 1:\n l = value.split()\n return l": 2481, "def _remove_from_index(index, obj):\n \"\"\"Removes object ``obj`` from the ``index``.\"\"\"\n try:\n index.value_map[indexed_value(index, obj)].remove(obj.id)\n except KeyError:\n pass": 2482, "def keys(self, index=None):\n \"\"\"Returns a list of keys in the database\n \"\"\"\n with self._lmdb.begin() as txn:\n return [key.decode() for key, _ in txn.cursor()]": 2483, "def make_bound(lower, upper, lineno):\n \"\"\" Wrapper: Creates an array bound\n \"\"\"\n return symbols.BOUND.make_node(lower, upper, lineno)": 2484, "def load_image(fname):\n \"\"\" read an image from file - PIL doesnt close nicely \"\"\"\n with open(fname, \"rb\") as f:\n i = Image.open(fname)\n #i.load()\n return i": 2485, "def get_dict_to_encoded_url(data):\n \"\"\"\n Converts a dict to an encoded URL.\n Example: given data = {'a': 1, 'b': 2}, it returns 'a=1&b=2'\n \"\"\"\n unicode_data = dict([(k, smart_str(v)) for k, v in data.items()])\n encoded = urllib.urlencode(unicode_data)\n return encoded": 2486, "def load(self, filename='classifier.dump'):\n \"\"\"\n Unpickles the classifier used\n \"\"\"\n ifile = open(filename, 'r+')\n self.classifier = pickle.load(ifile)\n ifile.close()": 2487, "def get_body_size(params, boundary):\n \"\"\"Returns the number of bytes that the multipart/form-data encoding\n of ``params`` will be.\"\"\"\n size = sum(p.get_size(boundary) for p in MultipartParam.from_params(params))\n return size + len(boundary) + 6": 2488, "def load_graph_from_rdf(fname):\n \"\"\" reads an RDF file into a graph \"\"\"\n print(\"reading RDF from \" + fname + \"....\")\n store = Graph()\n store.parse(fname, format=\"n3\")\n print(\"Loaded \" + str(len(store)) + \" tuples\")\n return store": 2489, "def __init__(self, usb):\n \"\"\"Constructs a FastbootCommands instance.\n\n Arguments:\n usb: UsbHandle instance.\n \"\"\"\n self._usb = usb\n self._protocol = self.protocol_handler(usb)": 2490, "def _if(ctx, logical_test, value_if_true=0, value_if_false=False):\n \"\"\"\n Returns one value if the condition evaluates to TRUE, and another value if it evaluates to FALSE\n \"\"\"\n return value_if_true if conversions.to_boolean(logical_test, ctx) else value_if_false": 2491, "def _find(string, sub_string, start_index):\n \"\"\"Return index of sub_string in string.\n\n Raise TokenError if sub_string is not found.\n \"\"\"\n result = string.find(sub_string, start_index)\n if result == -1:\n raise TokenError(\"expected '{0}'\".format(sub_string))\n return result": 2492, "def human_uuid():\n \"\"\"Returns a good UUID for using as a human readable string.\"\"\"\n return base64.b32encode(\n hashlib.sha1(uuid.uuid4().bytes).digest()).lower().strip('=')": 2493, "def safe_int(val, default=None):\n \"\"\"\n Returns int() of val if val is not convertable to int use default\n instead\n\n :param val:\n :param default:\n \"\"\"\n\n try:\n val = int(val)\n except (ValueError, TypeError):\n val = default\n\n return val": 2494, "def normal_log_q(self,z):\n \"\"\"\n The unnormalized log posterior components for mean-field normal family (the quantity we want to approximate)\n RAO-BLACKWELLIZED!\n \"\"\" \n means, scale = self.get_means_and_scales()\n return ss.norm.logpdf(z,loc=means,scale=scale)": 2495, "def process_request(self, request, response):\n \"\"\"Logs the basic endpoint requested\"\"\"\n self.logger.info('Requested: {0} {1} {2}'.format(request.method, request.relative_uri, request.content_type))": 2496, "def v_normalize(v):\n \"\"\"\n Normalizes the given vector.\n \n The vector given may have any number of dimensions.\n \"\"\"\n vmag = v_magnitude(v)\n return [ v[i]/vmag for i in range(len(v)) ]": 2497, "def map(cls, iterable, func, *a, **kw):\n \"\"\"\n Iterable-first replacement of Python's built-in `map()` function.\n \"\"\"\n\n return cls(func(x, *a, **kw) for x in iterable)": 2498, "def OnTogglePlay(self, event):\n \"\"\"Toggles the video status between play and hold\"\"\"\n\n if self.player.get_state() == vlc.State.Playing:\n self.player.pause()\n else:\n self.player.play()\n\n event.Skip()": 2499, "def clean_with_zeros(self,x):\n \"\"\" set nan and inf rows from x to zero\"\"\"\n x[~np.any(np.isnan(x) | np.isinf(x),axis=1)] = 0\n return x": 2500, "def get_process_handle(self):\n \"\"\"\n @rtype: L{ProcessHandle}\n @return: Process handle received from the system.\n Returns C{None} if the handle is not available.\n \"\"\"\n # The handle doesn't need to be closed.\n # See http://msdn.microsoft.com/en-us/library/ms681423(VS.85).aspx\n hProcess = self.raw.u.CreateProcessInfo.hProcess\n if hProcess in (0, win32.NULL, win32.INVALID_HANDLE_VALUE):\n hProcess = None\n else:\n hProcess = ProcessHandle(hProcess, False, win32.PROCESS_ALL_ACCESS)\n return hProcess": 2501, "def _position():\n \"\"\"Returns the current xy coordinates of the mouse cursor as a two-integer\n tuple by calling the GetCursorPos() win32 function.\n\n Returns:\n (x, y) tuple of the current xy coordinates of the mouse cursor.\n \"\"\"\n\n cursor = POINT()\n ctypes.windll.user32.GetCursorPos(ctypes.byref(cursor))\n return (cursor.x, cursor.y)": 2502, "def comment (self, s, **args):\n \"\"\"Write DOT comment.\"\"\"\n self.write(u\"// \")\n self.writeln(s=s, **args)": 2503, "def vectorize(values):\n \"\"\"\n Takes a value or list of values and returns a single result, joined by \",\"\n if necessary.\n \"\"\"\n if isinstance(values, list):\n return ','.join(str(v) for v in values)\n return values": 2504, "def top_1_tpu(inputs):\n \"\"\"find max and argmax over the last dimension.\n\n Works well on TPU\n\n Args:\n inputs: A tensor with shape [..., depth]\n\n Returns:\n values: a Tensor with shape [...]\n indices: a Tensor with shape [...]\n \"\"\"\n inputs_max = tf.reduce_max(inputs, axis=-1, keepdims=True)\n mask = tf.to_int32(tf.equal(inputs_max, inputs))\n index = tf.range(tf.shape(inputs)[-1]) * mask\n return tf.squeeze(inputs_max, -1), tf.reduce_max(index, axis=-1)": 2505, "def close(self):\n \"\"\"Closes this response.\"\"\"\n if self._connection:\n self._connection.close()\n self._response.close()": 2506, "def retry_call(func, cleanup=lambda: None, retries=0, trap=()):\n\t\"\"\"\n\tGiven a callable func, trap the indicated exceptions\n\tfor up to 'retries' times, invoking cleanup on the\n\texception. On the final attempt, allow any exceptions\n\tto propagate.\n\t\"\"\"\n\tattempts = count() if retries == float('inf') else range(retries)\n\tfor attempt in attempts:\n\t\ttry:\n\t\t\treturn func()\n\t\texcept trap:\n\t\t\tcleanup()\n\n\treturn func()": 2507, "def reduce_json(data):\n \"\"\"Reduce a JSON object\"\"\"\n return reduce(lambda x, y: int(x) + int(y), data.values())": 2508, "def convert_value(bind, value):\n \"\"\" Type casting. \"\"\"\n type_name = get_type(bind)\n try:\n return typecast.cast(type_name, value)\n except typecast.ConverterError:\n return value": 2509, "def chop(seq, size):\n \"\"\"Chop a sequence into chunks of the given size.\"\"\"\n chunk = lambda i: seq[i:i+size]\n return map(chunk,xrange(0,len(seq),size))": 2510, "def write_str2file(pathname, astr):\n \"\"\"writes a string to file\"\"\"\n fname = pathname\n fhandle = open(fname, 'wb')\n fhandle.write(astr)\n fhandle.close()": 2511, "def MatrixInverse(a, adj):\n \"\"\"\n Matrix inversion op.\n \"\"\"\n return np.linalg.inv(a if not adj else _adjoint(a)),": 2512, "def _write_color_ansi (fp, text, color):\n \"\"\"Colorize text with given color.\"\"\"\n fp.write(esc_ansicolor(color))\n fp.write(text)\n fp.write(AnsiReset)": 2513, "def _show_traceback(method):\n \"\"\"decorator for showing tracebacks in IPython\"\"\"\n def m(self, *args, **kwargs):\n try:\n return(method(self, *args, **kwargs))\n except Exception as e:\n ip = get_ipython()\n if ip is None:\n self.log.warning(\"Exception in widget method %s: %s\", method, e, exc_info=True)\n else:\n ip.showtraceback()\n return m": 2514, "def _write_pidfile(pidfile):\n \"\"\" Write file with current process ID.\n \"\"\"\n pid = str(os.getpid())\n handle = open(pidfile, 'w')\n try:\n handle.write(\"%s\\n\" % pid)\n finally:\n handle.close()": 2515, "def random_color(_min=MIN_COLOR, _max=MAX_COLOR):\n \"\"\"Returns a random color between min and max.\"\"\"\n return color(random.randint(_min, _max))": 2516, "def SegmentMin(a, ids):\n \"\"\"\n Segmented min op.\n \"\"\"\n func = lambda idxs: np.amin(a[idxs], axis=0)\n return seg_map(func, a, ids),": 2517, "def save_dot(self, fd):\n \"\"\" Saves a representation of the case in the Graphviz DOT language.\n \"\"\"\n from pylon.io import DotWriter\n DotWriter(self).write(fd)": 2518, "def _prepare_proxy(self, conn):\n \"\"\"\n Establish tunnel connection early, because otherwise httplib\n would improperly set Host: header to proxy's IP:port.\n \"\"\"\n conn.set_tunnel(self._proxy_host, self.port, self.proxy_headers)\n conn.connect()": 2519, "def cleanup_nodes(doc):\n \"\"\"\n Remove text nodes containing only whitespace\n \"\"\"\n for node in doc.documentElement.childNodes:\n if node.nodeType == Node.TEXT_NODE and node.nodeValue.isspace():\n doc.documentElement.removeChild(node)\n return doc": 2520, "def _run_asyncio(loop, zmq_context):\n \"\"\"\n Run asyncio (should be called in a thread) and close the loop and the zmq context when the thread ends\n :param loop:\n :param zmq_context:\n :return:\n \"\"\"\n try:\n asyncio.set_event_loop(loop)\n loop.run_forever()\n except:\n pass\n finally:\n loop.close()\n zmq_context.destroy(1000)": 2521, "def _is_iterable(item):\n \"\"\" Checks if an item is iterable (list, tuple, generator), but not string \"\"\"\n return isinstance(item, collections.Iterable) and not isinstance(item, six.string_types)": 2522, "def _parse(self, date_str, format='%Y-%m-%d'):\n \"\"\"\n helper function for parsing FRED date string into datetime\n \"\"\"\n rv = pd.to_datetime(date_str, format=format)\n if hasattr(rv, 'to_pydatetime'):\n rv = rv.to_pydatetime()\n return rv": 2523, "def normalize_text(text, line_len=80, indent=\"\"):\n \"\"\"Wrap the text on the given line length.\"\"\"\n return \"\\n\".join(\n textwrap.wrap(\n text, width=line_len, initial_indent=indent, subsequent_indent=indent\n )\n )": 2524, "def threadid(self):\n \"\"\"\n Current thread ident. If current thread is main thread then it returns ``None``.\n\n :type: int or None\n \"\"\"\n current = self.thread.ident\n main = get_main_thread()\n if main is None:\n return current\n else:\n return current if current != main.ident else None": 2525, "def trans_from_matrix(matrix):\n \"\"\" Convert a vtk matrix to a numpy.ndarray \"\"\"\n t = np.zeros((4, 4))\n for i in range(4):\n for j in range(4):\n t[i, j] = matrix.GetElement(i, j)\n return t": 2526, "def get_file_extension_type(filename):\n \"\"\"\n Return the group associated to the file\n :param filename:\n :return: str\n \"\"\"\n ext = get_file_extension(filename)\n if ext:\n for name, group in EXTENSIONS.items():\n if ext in group:\n return name\n return \"OTHER\"": 2527, "def inspect_cuda():\n \"\"\" Return cuda device information and nvcc/cuda setup \"\"\"\n nvcc_settings = nvcc_compiler_settings()\n sysconfig.get_config_vars()\n nvcc_compiler = ccompiler.new_compiler()\n sysconfig.customize_compiler(nvcc_compiler)\n customize_compiler_for_nvcc(nvcc_compiler, nvcc_settings)\n\n output = inspect_cuda_version_and_devices(nvcc_compiler, nvcc_settings)\n\n return json.loads(output), nvcc_settings": 2528, "def iteritems(data, **kwargs):\n \"\"\"Iterate over dict items.\"\"\"\n return iter(data.items(**kwargs)) if IS_PY3 else data.iteritems(**kwargs)": 2529, "def random_id(size=8, chars=string.ascii_letters + string.digits):\n\t\"\"\"Generates a random string of given size from the given chars.\n\n\t@param size: The size of the random string.\n\t@param chars: Constituent pool of characters to draw random characters from.\n\t@type size: number\n\t@type chars: string\n\t@rtype: string\n\t@return: The string of random characters.\n\t\"\"\"\n\treturn ''.join(random.choice(chars) for _ in range(size))": 2530, "def require_root(fn):\n \"\"\"\n Decorator to make sure, that user is root.\n \"\"\"\n @wraps(fn)\n def xex(*args, **kwargs):\n assert os.geteuid() == 0, \\\n \"You have to be root to run function '%s'.\" % fn.__name__\n return fn(*args, **kwargs)\n\n return xex": 2531, "def normalize(self):\n \"\"\" Normalize data. \"\"\"\n\n if self.preprocessed_data.empty:\n data = self.original_data\n else:\n data = self.preprocessed_data\n\n data = pd.DataFrame(preprocessing.normalize(data), columns=data.columns, index=data.index)\n self.preprocessed_data = data": 2532, "def normalize(df, style = 'mean'):\n \"\"\" Returns a normalized version of a DataFrame or Series\n Parameters:\n df - DataFrame or Series\n The data to normalize\n style - function or string, default 'mean'\n The style to use when computing the norms. Takes 'mean' or 'minmax' to\n do mean or min-max normalization respectively. User-defined functions that take\n a pandas Series as input and return a normalized pandas Series are also accepted\n \"\"\"\n if style == 'mean':\n df_mean,df_std = df.mean(),df.std()\n return (df-df_mean)/df_std\n elif style == 'minmax':\n col_min,col_max = df.min(),df.max()\n return (df-col_min)/(col_max-col_min)\n else:\n return style(df)": 2533, "def get_qapp():\n \"\"\"Return an instance of QApplication. Creates one if neccessary.\n\n :returns: a QApplication instance\n :rtype: QApplication\n :raises: None\n \"\"\"\n global app\n app = QtGui.QApplication.instance()\n if app is None:\n app = QtGui.QApplication([], QtGui.QApplication.GuiClient)\n return app": 2534, "def column_names(self, table):\n \"\"\"An iterable of column names, for a particular table or\n view.\"\"\"\n\n table_info = self.execute(\n u'PRAGMA table_info(%s)' % quote(table))\n return (column['name'] for column in table_info)": 2535, "def get_iter_string_reader(stdin):\n \"\"\" return an iterator that returns a chunk of a string every time it is\n called. notice that even though bufsize_type might be line buffered, we're\n not doing any line buffering here. that's because our StreamBufferer\n handles all buffering. we just need to return a reasonable-sized chunk. \"\"\"\n bufsize = 1024\n iter_str = (stdin[i:i + bufsize] for i in range(0, len(stdin), bufsize))\n return get_iter_chunk_reader(iter_str)": 2536, "def __str__(self):\n \"\"\"Executes self.function to convert LazyString instance to a real\n str.\"\"\"\n if not hasattr(self, '_str'):\n self._str=self.function(*self.args, **self.kwargs)\n return self._str": 2537, "def to_string(s, encoding='utf-8'):\n \"\"\"\n Accept unicode(py2) or bytes(py3)\n\n Returns:\n py2 type: str\n py3 type: str\n \"\"\"\n if six.PY2:\n return s.encode(encoding)\n if isinstance(s, bytes):\n return s.decode(encoding)\n return s": 2538, "def get_tweepy_auth(twitter_api_key,\n twitter_api_secret,\n twitter_access_token,\n twitter_access_token_secret):\n \"\"\"Make a tweepy auth object\"\"\"\n auth = tweepy.OAuthHandler(twitter_api_key, twitter_api_secret)\n auth.set_access_token(twitter_access_token, twitter_access_token_secret)\n return auth": 2539, "def urlencoded(body, charset='ascii', **kwargs):\n \"\"\"Converts query strings into native Python objects\"\"\"\n return parse_query_string(text(body, charset=charset), False)": 2540, "def aloha_to_html(html_source):\n \"\"\"Converts HTML5 from Aloha to a more structured HTML5\"\"\"\n xml = aloha_to_etree(html_source)\n return etree.tostring(xml, pretty_print=True)": 2541, "def exit(self):\n \"\"\"Handle interactive exit.\n\n This method calls the ask_exit callback.\"\"\"\n if self.confirm_exit:\n if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):\n self.ask_exit()\n else:\n self.ask_exit()": 2542, "def __del__(self):\n \"\"\"Cleanup the session if it was created here\"\"\"\n if self._cleanup_session:\n self._session.loop.run_until_complete(self._session.close())": 2543, "def get_just_date(self):\n \"\"\"Parses just date from date-time\n\n :return: Just day, month and year (setting hours to 00:00:00)\n \"\"\"\n return datetime.datetime(\n self.date_time.year,\n self.date_time.month,\n self.date_time.day\n )": 2544, "def __getitem__(self, key):\n \"\"\"Returns a new PRDD of elements from that key.\"\"\"\n return self.from_rdd(self._rdd.map(lambda x: x[key]))": 2545, "def load_file_to_base64_str(f_path):\n \"\"\"Loads the content of a file into a base64 string.\n\n Args:\n f_path: full path to the file including the file name.\n\n Returns:\n A base64 string representing the content of the file in utf-8 encoding.\n \"\"\"\n path = abs_path(f_path)\n with io.open(path, 'rb') as f:\n f_bytes = f.read()\n base64_str = base64.b64encode(f_bytes).decode(\"utf-8\")\n return base64_str": 2546, "def url_to_image(url, flag=cv2.IMREAD_COLOR):\n \"\"\" download the image, convert it to a NumPy array, and then read\n it into OpenCV format \"\"\"\n resp = urlopen(url)\n image = np.asarray(bytearray(resp.read()), dtype=\"uint8\")\n image = cv2.imdecode(image, flag)\n return image": 2547, "def visible_area(self):\n \"\"\"\n Calculated like in the official client.\n Returns (top_left, bottom_right).\n \"\"\"\n # looks like zeach has a nice big screen\n half_viewport = Vec(1920, 1080) / 2 / self.scale\n top_left = self.world.center - half_viewport\n bottom_right = self.world.center + half_viewport\n return top_left, bottom_right": 2548, "def read_numpy(fd, byte_order, dtype, count):\n \"\"\"Read tag data from file and return as numpy array.\"\"\"\n return numpy.fromfile(fd, byte_order+dtype[-1], count)": 2549, "def fit_gaussian(x, y, yerr, p0):\n \"\"\" Fit a Gaussian to the data \"\"\"\n try:\n popt, pcov = curve_fit(gaussian, x, y, sigma=yerr, p0=p0, absolute_sigma=True)\n except RuntimeError:\n return [0],[0]\n return popt, pcov": 2550, "def resize_image_with_crop_or_pad(img, target_height, target_width):\n \"\"\"\n Crops and/or pads an image to a target width and height.\n\n Resizes an image to a target width and height by either cropping the image or padding it with zeros.\n\n NO CENTER CROP. NO CENTER PAD. (Just fill bottom right or crop bottom right)\n\n :param img: Numpy array representing the image.\n :param target_height: Target height.\n :param target_width: Target width.\n :return: The cropped and padded image.\n \"\"\"\n h, w = target_height, target_width\n max_h, max_w, c = img.shape\n\n # crop\n img = crop_center(img, min(max_h, h), min(max_w, w))\n\n # pad\n padded_img = np.zeros(shape=(h, w, c), dtype=img.dtype)\n padded_img[:img.shape[0], :img.shape[1], :img.shape[2]] = img\n\n return padded_img": 2551, "def load_from_file(cls, file_path: str):\n \"\"\" Read and reconstruct the data from a JSON file. \"\"\"\n with open(file_path, \"r\") as f:\n data = json.load(f)\n item = cls.decode(data=data)\n return item": 2552, "def __call__(self, img):\n \"\"\"\n Args:\n img (PIL Image): Image to be padded.\n\n Returns:\n PIL Image: Padded image.\n \"\"\"\n return F.pad(img, self.padding, self.fill, self.padding_mode)": 2553, "def rAsciiLine(ifile):\n \"\"\"Returns the next non-blank line in an ASCII file.\"\"\"\n\n _line = ifile.readline().strip()\n while len(_line) == 0:\n _line = ifile.readline().strip()\n return _line": 2554, "def filter_query(s):\n \"\"\"\n Filters given query with the below regex\n and returns lists of quoted and unquoted strings\n \"\"\"\n matches = re.findall(r'(?:\"([^\"]*)\")|([^\"]*)', s)\n result_quoted = [t[0].strip() for t in matches if t[0]]\n result_unquoted = [t[1].strip() for t in matches if t[1]]\n return result_quoted, result_unquoted": 2555, "def eof(fd):\n \"\"\"Determine if end-of-file is reached for file fd.\"\"\"\n b = fd.read(1)\n end = len(b) == 0\n if not end:\n curpos = fd.tell()\n fd.seek(curpos - 1)\n return end": 2556, "def read_large_int(self, bits, signed=True):\n \"\"\"Reads a n-bits long integer value.\"\"\"\n return int.from_bytes(\n self.read(bits // 8), byteorder='little', signed=signed)": 2557, "def get_starting_chunk(filename, length=1024):\n \"\"\"\n :param filename: File to open and get the first little chunk of.\n :param length: Number of bytes to read, default 1024.\n :returns: Starting chunk of bytes.\n \"\"\"\n # Ensure we open the file in binary mode\n with open(filename, 'rb') as f:\n chunk = f.read(length)\n return chunk": 2558, "def standard_input():\n \"\"\"Generator that yields lines from standard input.\"\"\"\n with click.get_text_stream(\"stdin\") as stdin:\n while stdin.readable():\n line = stdin.readline()\n if line:\n yield line.strip().encode(\"utf-8\")": 2559, "def cor(y_true, y_pred):\n \"\"\"Compute Pearson correlation coefficient.\n \"\"\"\n y_true, y_pred = _mask_nan(y_true, y_pred)\n return np.corrcoef(y_true, y_pred)[0, 1]": 2560, "def log_magnitude_spectrum(frames):\n \"\"\"Compute the log of the magnitude spectrum of frames\"\"\"\n return N.log(N.abs(N.fft.rfft(frames)).clip(1e-5, N.inf))": 2561, "def multi_pop(d, *args):\n \"\"\" pops multiple keys off a dict like object \"\"\"\n retval = {}\n for key in args:\n if key in d:\n retval[key] = d.pop(key)\n return retval": 2562, "def _ReturnConnection(self):\n\t\t\"\"\"\n\t\tReturns a connection back to the pool\n\t\t\n\t\t@author: Nick Verbeck\n\t\t@since: 9/7/2008\n\t\t\"\"\"\n\t\tif self.conn is not None:\n\t\t\tif self.connInfo.commitOnEnd is True or self.commitOnEnd is True:\n\t\t\t\tself.conn.Commit()\n\t\t\t\t\t\n\t\t\tPool().returnConnection(self.conn)\n\t\t\tself.conn = None": 2563, "def from_url(url, db=None, **kwargs):\n \"\"\"\n Returns an active Redis client generated from the given database URL.\n\n Will attempt to extract the database id from the path url fragment, if\n none is provided.\n \"\"\"\n from redis.client import Redis\n return Redis.from_url(url, db, **kwargs)": 2564, "def parse_prefix(identifier):\n \"\"\"\n Parse identifier such as a|c|le|d|li|re|or|AT4G00480.1 and return\n tuple of prefix string (separated at '|') and suffix (AGI identifier)\n \"\"\"\n pf, id = (), identifier\n if \"|\" in identifier:\n pf, id = tuple(identifier.split('|')[:-1]), identifier.split('|')[-1]\n\n return pf, id": 2565, "def ordered_yaml_dump(data, stream=None, Dumper=None, **kwds):\n \"\"\"Dumps the stream from an OrderedDict.\n Taken from\n\n http://stackoverflow.com/questions/5121931/in-python-how-can-you-load-yaml-\n mappings-as-ordereddicts\"\"\"\n Dumper = Dumper or yaml.Dumper\n\n class OrderedDumper(Dumper):\n pass\n\n def _dict_representer(dumper, data):\n return dumper.represent_mapping(\n yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,\n data.items())\n OrderedDumper.add_representer(OrderedDict, _dict_representer)\n return yaml.dump(data, stream, OrderedDumper, **kwds)": 2566, "def to_dict(self):\n \"\"\"Serialize representation of the table for local caching.\"\"\"\n return {'schema': self.schema, 'name': self.name, 'columns': [col.to_dict() for col in self._columns],\n 'foreign_keys': self.foreign_keys.to_dict(), 'ref_keys': self.ref_keys.to_dict()}": 2567, "def replace_print(fileobj=sys.stderr):\n \"\"\"Sys.out replacer, by default with stderr.\n\n Use it like this:\n with replace_print_with(fileobj):\n print \"hello\" # writes to the file\n print \"done\" # prints to stdout\n\n Args:\n fileobj: a file object to replace stdout.\n\n Yields:\n The printer.\n \"\"\"\n printer = _Printer(fileobj)\n\n previous_stdout = sys.stdout\n sys.stdout = printer\n try:\n yield printer\n finally:\n sys.stdout = previous_stdout": 2568, "def _delete_keys(dct, keys):\n \"\"\"Returns a copy of dct without `keys` keys\n \"\"\"\n c = deepcopy(dct)\n assert isinstance(keys, list)\n for k in keys:\n c.pop(k)\n return c": 2569, "def var_dump(*obs):\n\t\"\"\"\n\t shows structured information of a object, list, tuple etc\n\t\"\"\"\n\ti = 0\n\tfor x in obs:\n\t\t\n\t\tstr = var_dump_output(x, 0, ' ', '\\n', True)\n\t\tprint (str.strip())\n\t\t\n\t\t#dump(x, 0, i, '', object)\n\t\ti += 1": 2570, "def camelcase_underscore(name):\n \"\"\" Convert camelcase names to underscore \"\"\"\n s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', name)\n return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()": 2571, "def first(series, order_by=None):\n \"\"\"\n Returns the first value of a series.\n\n Args:\n series (pandas.Series): column to summarize.\n\n Kwargs:\n order_by: a pandas.Series or list of series (can be symbolic) to order\n the input series by before summarization.\n \"\"\"\n\n if order_by is not None:\n series = order_series_by(series, order_by)\n first_s = series.iloc[0]\n return first_s": 2572, "def clean(self, text):\n \"\"\"Remove all unwanted characters from text.\"\"\"\n return ''.join([c for c in text if c in self.alphabet])": 2573, "def __normalize_list(self, msg):\n \"\"\"Split message to list by commas and trim whitespace.\"\"\"\n if isinstance(msg, list):\n msg = \"\".join(msg)\n return list(map(lambda x: x.strip(), msg.split(\",\")))": 2574, "def Print(x, data, message, **kwargs): # pylint: disable=invalid-name\n \"\"\"Call tf.Print.\n\n Args:\n x: a Tensor.\n data: a list of Tensor\n message: a string\n **kwargs: keyword arguments to tf.Print\n Returns:\n a Tensor which is identical in value to x\n \"\"\"\n return PrintOperation(x, data, message, **kwargs).outputs[0]": 2575, "def clean_py_files(path):\n \"\"\"\n Removes all .py files.\n\n :param path: the path\n :return: None\n \"\"\"\n\n for dirname, subdirlist, filelist in os.walk(path):\n\n for f in filelist:\n if f.endswith('py'):\n os.remove(os.path.join(dirname, f))": 2576, "def clean_whitespace(statement):\n \"\"\"\n Remove any consecutive whitespace characters from the statement text.\n \"\"\"\n import re\n\n # Replace linebreaks and tabs with spaces\n statement.text = statement.text.replace('\\n', ' ').replace('\\r', ' ').replace('\\t', ' ')\n\n # Remove any leeding or trailing whitespace\n statement.text = statement.text.strip()\n\n # Remove consecutive spaces\n statement.text = re.sub(' +', ' ', statement.text)\n\n return statement": 2577, "def _to_base_type(self, msg):\n \"\"\"Convert a Message value to a Model instance (entity).\"\"\"\n ent = _message_to_entity(msg, self._modelclass)\n ent.blob_ = self._protocol_impl.encode_message(msg)\n return ent": 2578, "def py3round(number):\n \"\"\"Unified rounding in all python versions.\"\"\"\n if abs(round(number) - number) == 0.5:\n return int(2.0 * round(number / 2.0))\n\n return int(round(number))": 2579, "def strip_xml_namespace(root):\n \"\"\"Strip out namespace data from an ElementTree.\n\n This function is recursive and will traverse all\n subnodes to the root element\n\n @param root: the root element\n\n @return: the same root element, minus namespace\n \"\"\"\n try:\n root.tag = root.tag.split('}')[1]\n except IndexError:\n pass\n\n for element in root.getchildren():\n strip_xml_namespace(element)": 2580, "def clean(s):\n \"\"\"Removes trailing whitespace on each line.\"\"\"\n lines = [l.rstrip() for l in s.split('\\n')]\n return '\\n'.join(lines)": 2581, "def time_func(func, name, *args, **kwargs):\n \"\"\" call a func with args and kwargs, print name of func and how\n long it took. \"\"\"\n tic = time.time()\n out = func(*args, **kwargs)\n toc = time.time()\n print('%s took %0.2f seconds' % (name, toc - tic))\n return out": 2582, "def get_unique_indices(df, axis=1):\n \"\"\"\n\n :param df:\n :param axis:\n :return:\n \"\"\"\n return dict(zip(df.columns.names, dif.columns.levels))": 2583, "def validate_string(option, value):\n \"\"\"Validates that 'value' is an instance of `basestring` for Python 2\n or `str` for Python 3.\n \"\"\"\n if isinstance(value, string_type):\n return value\n raise TypeError(\"Wrong type for %s, value must be \"\n \"an instance of %s\" % (option, string_type.__name__))": 2584, "def __init__(self, master=None, compound=tk.RIGHT, autohidescrollbar=True, **kwargs):\n \"\"\"\n Create a Listbox with a vertical scrollbar.\n\n :param master: master widget\n :type master: widget\n :param compound: side for the Scrollbar to be on (:obj:`tk.LEFT` or :obj:`tk.RIGHT`)\n :type compound: str\n :param autohidescrollbar: whether to use an :class:`~ttkwidgets.AutoHideScrollbar` or a :class:`ttk.Scrollbar`\n :type autohidescrollbar: bool\n :param kwargs: keyword arguments passed on to the :class:`tk.Listbox` initializer\n \"\"\"\n ttk.Frame.__init__(self, master)\n self.columnconfigure(1, weight=1)\n self.rowconfigure(0, weight=1)\n self.listbox = tk.Listbox(self, **kwargs)\n if autohidescrollbar:\n self.scrollbar = AutoHideScrollbar(self, orient=tk.VERTICAL, command=self.listbox.yview)\n else:\n self.scrollbar = ttk.Scrollbar(self, orient=tk.VERTICAL, command=self.listbox.yview)\n self.config_listbox(yscrollcommand=self.scrollbar.set)\n if compound is not tk.LEFT and compound is not tk.RIGHT:\n raise ValueError(\"Invalid compound value passed: {0}\".format(compound))\n self.__compound = compound\n self._grid_widgets()": 2585, "def pop_all(self):\n \"\"\"\n NON-BLOCKING POP ALL IN QUEUE, IF ANY\n \"\"\"\n with self.lock:\n output = list(self.queue)\n self.queue.clear()\n\n return output": 2586, "def join(mapping, bind, values):\n \"\"\" Merge all the strings. Put space between them. \"\"\"\n return [' '.join([six.text_type(v) for v in values if v is not None])]": 2587, "def _replace_docstring_header(paragraph):\n \"\"\"Process NumPy-like function docstrings.\"\"\"\n\n # Replace Markdown headers in docstrings with light headers in bold.\n paragraph = re.sub(_docstring_header_pattern,\n r'*\\1*',\n paragraph,\n )\n\n paragraph = re.sub(_docstring_parameters_pattern,\n r'\\n* `\\1` (\\2)\\n',\n paragraph,\n )\n\n return paragraph": 2588, "def raise_(exception=ABSENT, *args, **kwargs):\n \"\"\"Raise (or re-raises) an exception.\n\n :param exception: Exception object to raise, or an exception class.\n In the latter case, remaining arguments are passed\n to the exception's constructor.\n If omitted, the currently handled exception is re-raised.\n \"\"\"\n if exception is ABSENT:\n raise\n else:\n if inspect.isclass(exception):\n raise exception(*args, **kwargs)\n else:\n if args or kwargs:\n raise TypeError(\"can't pass arguments along with \"\n \"exception object to raise_()\")\n raise exception": 2589, "def from_traceback(cls, tb):\n \"\"\" Construct a Bytecode from the given traceback \"\"\"\n while tb.tb_next:\n tb = tb.tb_next\n return cls(tb.tb_frame.f_code, current_offset=tb.tb_lasti)": 2590, "def camel_to_underscore(string):\n \"\"\"Convert camelcase to lowercase and underscore.\n\n Recipe from http://stackoverflow.com/a/1176023\n\n Args:\n string (str): The string to convert.\n\n Returns:\n str: The converted string.\n \"\"\"\n string = FIRST_CAP_RE.sub(r'\\1_\\2', string)\n return ALL_CAP_RE.sub(r'\\1_\\2', string).lower()": 2591, "def _scale_shape(dshape, scale = (1,1,1)):\n \"\"\"returns the shape after scaling (should be the same as ndimage.zoom\"\"\"\n nshape = np.round(np.array(dshape) * np.array(scale))\n return tuple(nshape.astype(np.int))": 2592, "def get_value(key, obj, default=missing):\n \"\"\"Helper for pulling a keyed value off various types of objects\"\"\"\n if isinstance(key, int):\n return _get_value_for_key(key, obj, default)\n return _get_value_for_keys(key.split('.'), obj, default)": 2593, "def get_package_info(package):\n \"\"\"Gets the PyPI information for a given package.\"\"\"\n url = 'https://pypi.python.org/pypi/{}/json'.format(package)\n r = requests.get(url)\n r.raise_for_status()\n return r.json()": 2594, "def _add(self, codeobj):\n \"\"\"Add a child (variable) to this object.\"\"\"\n assert isinstance(codeobj, CodeVariable)\n self.variables.append(codeobj)": 2595, "def make_key(observer):\n \"\"\"Construct a unique, hashable, immutable key for an observer.\"\"\"\n\n if hasattr(observer, \"__self__\"):\n inst = observer.__self__\n method_name = observer.__name__\n key = (id(inst), method_name)\n else:\n key = id(observer)\n return key": 2596, "def get_attr(self, method_name):\n \"\"\"Get attribute from the target object\"\"\"\n return self.attrs.get(method_name) or self.get_callable_attr(method_name)": 2597, "def _shape(self):\n \"\"\"Return the tensor shape of the matrix operator\"\"\"\n return tuple(reversed(self.output_dims())) + tuple(\n reversed(self.input_dims()))": 2598, "def set_json_item(key, value):\n \"\"\" manipulate json data on the fly\n \"\"\"\n data = get_json()\n data[key] = value\n\n request = get_request()\n request[\"BODY\"] = json.dumps(data)": 2599, "def sub(name, func,**kwarg):\n \"\"\" Add subparser\n\n \"\"\"\n sp = subparsers.add_parser(name, **kwarg)\n sp.set_defaults(func=func)\n sp.arg = sp.add_argument\n return sp": 2600, "def add_text_to_image(fname, txt, opFilename):\n \"\"\" convert an image by adding text \"\"\"\n ft = ImageFont.load(\"T://user//dev//src//python//_AS_LIB//timR24.pil\")\n #wh = ft.getsize(txt)\n print(\"Adding text \", txt, \" to \", fname, \" pixels wide to file \" , opFilename)\n im = Image.open(fname)\n draw = ImageDraw.Draw(im)\n draw.text((0, 0), txt, fill=(0, 0, 0), font=ft)\n del draw \n im.save(opFilename)": 2601, "def similarity_transformation(rot, mat):\n \"\"\" R x M x R^-1 \"\"\"\n return np.dot(rot, np.dot(mat, np.linalg.inv(rot)))": 2602, "def _iter_response(self, url, params=None):\n \"\"\"Return an enumerable that iterates through a multi-page API request\"\"\"\n if params is None:\n params = {}\n params['page_number'] = 1\n\n # Last page lists itself as next page\n while True:\n response = self._request(url, params)\n\n for item in response['result_data']:\n yield item\n\n # Last page lists itself as next page\n if response['service_meta']['next_page_number'] == params['page_number']:\n break\n\n params['page_number'] += 1": 2603, "def round_figures(x, n):\n \"\"\"Returns x rounded to n significant figures.\"\"\"\n return round(x, int(n - math.ceil(math.log10(abs(x)))))": 2604, "def fetch_token(self, **kwargs):\n \"\"\"Exchange a code (and 'state' token) for a bearer token\"\"\"\n return super(AsanaOAuth2Session, self).fetch_token(self.token_url, client_secret=self.client_secret, **kwargs)": 2605, "def _handle_shell(self,cfg_file,*args,**options):\n \"\"\"Command 'supervisord shell' runs the interactive command shell.\"\"\"\n args = (\"--interactive\",) + args\n return supervisorctl.main((\"-c\",cfg_file) + args)": 2606, "def interpolate(table, field, fmt, **kwargs):\n \"\"\"\n Convenience function to interpolate all values in the given `field` using\n the `fmt` string.\n\n The ``where`` keyword argument can be given with a callable or expression\n which is evaluated on each row and which should return True if the\n conversion should be applied on that row, else False.\n\n \"\"\"\n\n conv = lambda v: fmt % v\n return convert(table, field, conv, **kwargs)": 2607, "def to_lisp(o, keywordize_keys: bool = True):\n \"\"\"Recursively convert Python collections into Lisp collections.\"\"\"\n if not isinstance(o, (dict, frozenset, list, set, tuple)):\n return o\n else: # pragma: no cover\n return _to_lisp_backup(o, keywordize_keys=keywordize_keys)": 2608, "def rotateImage(img, angle):\n \"\"\"\n\n querries scipy.ndimage.rotate routine\n :param img: image to be rotated\n :param angle: angle to be rotated (radian)\n :return: rotated image\n \"\"\"\n imgR = scipy.ndimage.rotate(img, angle, reshape=False)\n return imgR": 2609, "def make_table_map(table, headers):\n \"\"\"Create a function to map from rows with the structure of the headers to the structure of the table.\"\"\"\n\n header_parts = {}\n for i, h in enumerate(headers):\n header_parts[h] = 'row[{}]'.format(i)\n\n body_code = 'lambda row: [{}]'.format(','.join(header_parts.get(c.name, 'None') for c in table.columns))\n header_code = 'lambda row: [{}]'.format(\n ','.join(header_parts.get(c.name, \"'{}'\".format(c.name)) for c in table.columns))\n\n return eval(header_code), eval(body_code)": 2610, "def print_statements(self):\n \"\"\"Print all INDRA Statements collected by the processors.\"\"\"\n for i, stmt in enumerate(self.statements):\n print(\"%s: %s\" % (i, stmt))": 2611, "def download_file(bucket_name, path, target, sagemaker_session):\n \"\"\"Download a Single File from S3 into a local path\n\n Args:\n bucket_name (str): S3 bucket name\n path (str): file path within the bucket\n target (str): destination directory for the downloaded file.\n sagemaker_session (:class:`sagemaker.session.Session`): a sagemaker session to interact with S3.\n \"\"\"\n path = path.lstrip('/')\n boto_session = sagemaker_session.boto_session\n\n s3 = boto_session.resource('s3')\n bucket = s3.Bucket(bucket_name)\n bucket.download_file(path, target)": 2612, "def set_subparsers_args(self, *args, **kwargs):\n \"\"\"\n Sets args and kwargs that are passed when creating a subparsers group\n in an argparse.ArgumentParser i.e. when calling\n argparser.ArgumentParser.add_subparsers\n \"\"\"\n self.subparsers_args = args\n self.subparsers_kwargs = kwargs": 2613, "def save_keras_definition(keras_model, path):\n \"\"\"\n Save a Keras model definition to JSON with given path\n \"\"\"\n model_json = keras_model.to_json()\n with open(path, \"w\") as json_file:\n json_file.write(model_json)": 2614, "def add_arguments(parser):\n \"\"\"\n adds arguments for the swap urls command\n \"\"\"\n parser.add_argument('-o', '--old-environment', help='Old environment name', required=True)\n parser.add_argument('-n', '--new-environment', help='New environment name', required=True)": 2615, "def adapt_array(arr):\n \"\"\"\n Adapts a Numpy array into an ARRAY string to put into the database.\n\n Parameters\n ----------\n arr: array\n The Numpy array to be adapted into an ARRAY type that can be inserted into a SQL file.\n\n Returns\n -------\n ARRAY\n The adapted array object\n\n \"\"\"\n out = io.BytesIO()\n np.save(out, arr), out.seek(0)\n return buffer(out.read())": 2616, "def ensure_iterable(inst):\n \"\"\"\n Wraps scalars or string types as a list, or returns the iterable instance.\n \"\"\"\n if isinstance(inst, string_types):\n return [inst]\n elif not isinstance(inst, collections.Iterable):\n return [inst]\n else:\n return inst": 2617, "def write(url, content, **args):\n \"\"\"Put an object into a ftps URL.\"\"\"\n with FTPSResource(url, **args) as resource:\n resource.write(content)": 2618, "def dump_nparray(self, obj, class_name=numpy_ndarray_class_name):\n \"\"\"\n ``numpy.ndarray`` dumper.\n \"\"\"\n return {\"$\" + class_name: self._json_convert(obj.tolist())}": 2619, "def get_seconds_until_next_day(now=None):\n \"\"\"\n Returns the number of seconds until the next day (utc midnight). This is the long-term rate limit used by Strava.\n :param now: A (utc) timestamp\n :type now: arrow.arrow.Arrow\n :return: the number of seconds until next day, as int\n \"\"\"\n if now is None:\n now = arrow.utcnow()\n return (now.ceil('day') - now).seconds": 2620, "def expect_all(a, b):\n \"\"\"\\\n Asserts that two iterables contain the same values.\n \"\"\"\n assert all(_a == _b for _a, _b in zip_longest(a, b))": 2621, "async def repeat(ctx, times: int, content='repeating...'):\n \"\"\"Repeats a message multiple times.\"\"\"\n for i in range(times):\n await ctx.send(content)": 2622, "async def wait_and_quit(loop):\n\t\"\"\"Wait until all task are executed.\"\"\"\n\tfrom pylp.lib.tasks import running\n\tif running:\n\t\tawait asyncio.wait(map(lambda runner: runner.future, running))": 2623, "def generate_split_tsv_lines(fn, header):\n \"\"\"Returns dicts with header-keys and psm statistic values\"\"\"\n for line in generate_tsv_psms_line(fn):\n yield {x: y for (x, y) in zip(header, line.strip().split('\\t'))}": 2624, "def add_form_widget_attr(field, attr_name, attr_value, replace=0):\n \"\"\"\n Adds widget attributes to a bound form field.\n\n This is helpful if you would like to add a certain class to all your forms\n (i.e. `form-control` to all form fields when you are using Bootstrap)::\n\n {% load libs_tags %}\n {% for field in form.fields %}\n {% add_form_widget_attr field 'class' 'form-control' as field_ %}\n {{ field_ }}\n {% endfor %}\n\n The tag will check if the attr already exists and only append your value.\n If you would like to replace existing attrs, set `replace=1`::\n\n {% add_form_widget_attr field 'class' 'form-control' replace=1 as\n field_ %}\n\n\n \"\"\"\n if not replace:\n attr = field.field.widget.attrs.get(attr_name, '')\n attr += force_text(attr_value)\n field.field.widget.attrs[attr_name] = attr\n return field\n else:\n field.field.widget.attrs[attr_name] = attr_value\n return field": 2625, "def add(self, value):\n \"\"\"Add the element *value* to the set.\"\"\"\n if value not in self._set:\n self._set.add(value)\n self._list.add(value)": 2626, "def filter_symlog(y, base=10.0):\n \"\"\"Symmetrical logarithmic scale.\n\n Optional arguments:\n\n *base*:\n The base of the logarithm.\n \"\"\"\n log_base = np.log(base)\n sign = np.sign(y)\n logs = np.log(np.abs(y) / log_base)\n return sign * logs": 2627, "def __init__(self, interval, key):\n \"\"\"Constructor. See class docstring for parameter details.\"\"\"\n self.interval = interval\n self.key = key": 2628, "def setwinsize(self, rows, cols):\n \"\"\"Set the terminal window size of the child tty.\n \"\"\"\n self._winsize = (rows, cols)\n self.pty.set_size(cols, rows)": 2629, "def delete(gandi, resource):\n \"\"\"Delete DNSSEC key.\n \"\"\"\n\n result = gandi.dnssec.delete(resource)\n gandi.echo('Delete successful.')\n\n return result": 2630, "def create_aws_lambda(ctx, bucket, region_name, aws_access_key_id, aws_secret_access_key):\n \"\"\"Creates an AWS Chalice project for deployment to AWS Lambda.\"\"\"\n from canari.commands.create_aws_lambda import create_aws_lambda\n create_aws_lambda(ctx.project, bucket, region_name, aws_access_key_id, aws_secret_access_key)": 2631, "def confusion_matrix(self):\n \"\"\"Confusion matrix plot\n \"\"\"\n return plot.confusion_matrix(self.y_true, self.y_pred,\n self.target_names, ax=_gen_ax())": 2632, "def s2b(s):\n \"\"\"\n String to binary.\n \"\"\"\n ret = []\n for c in s:\n ret.append(bin(ord(c))[2:].zfill(8))\n return \"\".join(ret)": 2633, "def show_approx(self, numfmt='%.3g'):\n \"\"\"Show the probabilities rounded and sorted by key, for the\n sake of portable doctests.\"\"\"\n return ', '.join([('%s: ' + numfmt) % (v, p)\n for (v, p) in sorted(self.prob.items())])": 2634, "def _transform_triple_numpy(x):\n \"\"\"Transform triple index into a 1-D numpy array.\"\"\"\n return np.array([x.head, x.relation, x.tail], dtype=np.int64)": 2635, "def text(el, strip=True):\n \"\"\"\n Return the text of a ``BeautifulSoup`` element\n \"\"\"\n if not el:\n return \"\"\n\n text = el.text\n if strip:\n text = text.strip()\n return text": 2636, "def get_boto_session(\n region,\n aws_access_key_id=None,\n aws_secret_access_key=None,\n aws_session_token=None\n ):\n \"\"\"Get a boto3 session.\"\"\"\n return boto3.session.Session(\n region_name=region,\n aws_secret_access_key=aws_secret_access_key,\n aws_access_key_id=aws_access_key_id,\n aws_session_token=aws_session_token\n )": 2637, "def ibatch(iterable, size):\n \"\"\"Yield a series of batches from iterable, each size elements long.\"\"\"\n source = iter(iterable)\n while True:\n batch = itertools.islice(source, size)\n yield itertools.chain([next(batch)], batch)": 2638, "def disable_cert_validation():\n \"\"\"Context manager to temporarily disable certificate validation in the standard SSL\n library.\n\n Note: This should not be used in production code but is sometimes useful for\n troubleshooting certificate validation issues.\n\n By design, the standard SSL library does not provide a way to disable verification\n of the server side certificate. However, a patch to disable validation is described\n by the library developers. This context manager allows applying the patch for\n specific sections of code.\n\n \"\"\"\n current_context = ssl._create_default_https_context\n ssl._create_default_https_context = ssl._create_unverified_context\n try:\n yield\n finally:\n ssl._create_default_https_context = current_context": 2639, "def get_cache(self, decorated_function, *args, **kwargs):\n\t\t\"\"\" :meth:`WCacheStorage.get_cache` method implementation\n\t\t\"\"\"\n\t\thas_value = self.has(decorated_function, *args, **kwargs)\n\t\tcached_value = None\n\t\tif has_value is True:\n\t\t\tcached_value = self.get_result(decorated_function, *args, **kwargs)\n\t\treturn WCacheStorage.CacheEntry(has_value=has_value, cached_value=cached_value)": 2640, "def unsort_vector(data, indices_of_increasing):\n \"\"\"Upermutate 1-D data that is sorted by indices_of_increasing.\"\"\"\n return numpy.array([data[indices_of_increasing.index(i)] for i in range(len(data))])": 2641, "def swap_priority(self, key1, key2):\n \"\"\"\n Fast way to swap the priority level of two items in the pqdict. Raises\n ``KeyError`` if either key does not exist.\n\n \"\"\"\n heap = self._heap\n position = self._position\n if key1 not in self or key2 not in self:\n raise KeyError\n pos1, pos2 = position[key1], position[key2]\n heap[pos1].key, heap[pos2].key = key2, key1\n position[key1], position[key2] = pos2, pos1": 2642, "def recursively_get_files_from_directory(directory):\n \"\"\"\n Return all filenames under recursively found in a directory\n \"\"\"\n return [\n os.path.join(root, filename)\n for root, directories, filenames in os.walk(directory)\n for filename in filenames\n ]": 2643, "def _set_module_names_for_sphinx(modules: List, new_name: str):\n \"\"\" Trick sphinx into displaying the desired module in these objects' documentation. \"\"\"\n for obj in modules:\n obj.__module__ = new_name": 2644, "def _depr(fn, usage, stacklevel=3):\n \"\"\"Internal convenience function for deprecation warnings\"\"\"\n warn('{0} is deprecated. Use {1} instead'.format(fn, usage),\n stacklevel=stacklevel, category=DeprecationWarning)": 2645, "def _run_once(self):\n \"\"\"Run once, should be called only from loop()\"\"\"\n try:\n self.do_wait()\n self._execute_wakeup_tasks()\n self._trigger_timers()\n except Exception as e:\n Log.error(\"Error occured during _run_once(): \" + str(e))\n Log.error(traceback.format_exc())\n self.should_exit = True": 2646, "def from_pydatetime(cls, pydatetime):\n \"\"\"\n Creates sql datetime2 object from Python datetime object\n ignoring timezone\n @param pydatetime: Python datetime object\n @return: sql datetime2 object\n \"\"\"\n return cls(date=Date.from_pydate(pydatetime.date),\n time=Time.from_pytime(pydatetime.time))": 2647, "def set_scrollregion(self, event=None):\n \"\"\" Set the scroll region on the canvas\"\"\"\n self.canvas.configure(scrollregion=self.canvas.bbox('all'))": 2648, "def is_alive(self):\n \"\"\"\n Will test whether the ACS service is up and alive.\n \"\"\"\n response = self.get_monitoring_heartbeat()\n if response.status_code == 200 and response.content == 'alive':\n return True\n\n return False": 2649, "def _subclassed(base, *classes):\n \"\"\"Check if all classes are subclassed from base.\n \"\"\"\n return all(map(lambda obj: isinstance(obj, base), classes))": 2650, "def _opt_call_from_base_type(self, value):\n \"\"\"Call _from_base_type() if necessary.\n\n If the value is a _BaseValue instance, unwrap it and call all\n _from_base_type() methods. Otherwise, return the value\n unchanged.\n \"\"\"\n if isinstance(value, _BaseValue):\n value = self._call_from_base_type(value.b_val)\n return value": 2651, "def _port_not_in_use():\n \"\"\"Use the port 0 trick to find a port not in use.\"\"\"\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n port = 0\n s.bind(('', port))\n _, port = s.getsockname()\n return port": 2652, "def copy(a):\n \"\"\" Copy an array to the shared memory. \n\n Notes\n -----\n copy is not always necessary because the private memory is always copy-on-write.\n\n Use :code:`a = copy(a)` to immediately dereference the old 'a' on private memory\n \"\"\"\n shared = anonymousmemmap(a.shape, dtype=a.dtype)\n shared[:] = a[:]\n return shared": 2653, "def load(self, name):\n \"\"\"Loads and returns foreign library.\"\"\"\n name = ctypes.util.find_library(name)\n return ctypes.cdll.LoadLibrary(name)": 2654, "def _maybe_to_categorical(array):\n \"\"\"\n Coerce to a categorical if a series is given.\n\n Internal use ONLY.\n \"\"\"\n if isinstance(array, (ABCSeries, ABCCategoricalIndex)):\n return array._values\n elif isinstance(array, np.ndarray):\n return Categorical(array)\n return array": 2655, "def circstd(dts, axis=2):\n \"\"\"Circular standard deviation\"\"\"\n R = np.abs(np.exp(1.0j * dts).mean(axis=axis))\n return np.sqrt(-2.0 * np.log(R))": 2656, "def save_config_value(request, response, key, value):\n \"\"\"Sets value of key `key` to `value` in both session and cookies.\"\"\"\n request.session[key] = value\n response.set_cookie(key, value, expires=one_year_from_now())\n return response": 2657, "def set_label ( self, object, label ):\n \"\"\" Sets the label for a specified object.\n \"\"\"\n label_name = self.label\n if label_name[:1] != '=':\n xsetattr( object, label_name, label )": 2658, "def add_exec_permission_to(target_file):\n \"\"\"Add executable permissions to the file\n\n :param target_file: the target file whose permission to be changed\n \"\"\"\n mode = os.stat(target_file).st_mode\n os.chmod(target_file, mode | stat.S_IXUSR)": 2659, "def _is_subsequence_of(self, sub, sup):\n \"\"\"\n Parameters\n ----------\n sub : str\n sup : str\n\n Returns\n -------\n bool\n \"\"\"\n return bool(re.search(\".*\".join(sub), sup))": 2660, "def AmericanDateToEpoch(self, date_str):\n \"\"\"Take a US format date and return epoch.\"\"\"\n try:\n epoch = time.strptime(date_str, \"%m/%d/%Y\")\n return int(calendar.timegm(epoch)) * 1000000\n except ValueError:\n return 0": 2661, "def _is_valid_api_url(self, url):\n \"\"\"Callback for is_valid_api_url.\"\"\"\n # Check response is a JSON with ok: 1\n data = {}\n try:\n r = requests.get(url, proxies=self.proxy_servers)\n content = to_text_string(r.content, encoding='utf-8')\n data = json.loads(content)\n except Exception as error:\n logger.error(str(error))\n\n return data.get('ok', 0) == 1": 2662, "def cudaMalloc(count, ctype=None):\n \"\"\"\n Allocate device memory.\n\n Allocate memory on the device associated with the current active\n context.\n\n Parameters\n ----------\n count : int\n Number of bytes of memory to allocate\n ctype : _ctypes.SimpleType, optional\n ctypes type to cast returned pointer.\n\n Returns\n -------\n ptr : ctypes pointer\n Pointer to allocated device memory.\n\n \"\"\"\n\n ptr = ctypes.c_void_p()\n status = _libcudart.cudaMalloc(ctypes.byref(ptr), count)\n cudaCheckStatus(status)\n if ctype != None:\n ptr = ctypes.cast(ptr, ctypes.POINTER(ctype))\n return ptr": 2663, "def convert_time_string(date_str):\n \"\"\" Change a date string from the format 2018-08-15T23:55:17 into a datetime object \"\"\"\n dt, _, _ = date_str.partition(\".\")\n dt = datetime.strptime(dt, \"%Y-%m-%dT%H:%M:%S\")\n return dt": 2664, "def Sum(a, axis, keep_dims):\n \"\"\"\n Sum reduction op.\n \"\"\"\n return np.sum(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),\n keepdims=keep_dims),": 2665, "def is_git_repo():\n \"\"\"Check whether the current folder is a Git repo.\"\"\"\n cmd = \"git\", \"rev-parse\", \"--git-dir\"\n try:\n subprocess.run(cmd, stdout=subprocess.DEVNULL, check=True)\n return True\n except subprocess.CalledProcessError:\n return False": 2666, "def is_archlinux():\n \"\"\"return True if the current distribution is running on debian like OS.\"\"\"\n if platform.system().lower() == 'linux':\n if platform.linux_distribution() == ('', '', ''):\n # undefined distribution. Fixed in python 3.\n if os.path.exists('/etc/arch-release'):\n return True\n return False": 2667, "def lazy_reverse_binmap(f, xs):\n \"\"\"\n Same as lazy_binmap, except the parameters are flipped for the binary function\n \"\"\"\n return (f(y, x) for x, y in zip(xs, xs[1:]))": 2668, "def isin(self, column, compare_list):\n \"\"\"\n Returns a boolean list where each elements is whether that element in the column is in the compare_list.\n\n :param column: single column name, does not work for multiple columns\n :param compare_list: list of items to compare to\n :return: list of booleans\n \"\"\"\n return [x in compare_list for x in self._data[self._columns.index(column)]]": 2669, "def jsonify(symbol):\n \"\"\" returns json format for symbol \"\"\"\n try:\n # all symbols have a toJson method, try it\n return json.dumps(symbol.toJson(), indent=' ')\n except AttributeError:\n pass\n return json.dumps(symbol, indent=' ')": 2670, "def table_width(self):\n \"\"\"Return the width of the table including padding and borders.\"\"\"\n outer_widths = max_dimensions(self.table_data, self.padding_left, self.padding_right)[2]\n outer_border = 2 if self.outer_border else 0\n inner_border = 1 if self.inner_column_border else 0\n return table_width(outer_widths, outer_border, inner_border)": 2671, "def save_as_png(self, filename, width=300, height=250, render_time=1):\n \"\"\"Open saved html file in an virtual browser and save a screen shot to PNG format.\"\"\"\n self.driver.set_window_size(width, height)\n self.driver.get('file://{path}/{filename}'.format(\n path=os.getcwd(), filename=filename + \".html\"))\n time.sleep(render_time)\n self.driver.save_screenshot(filename + \".png\")": 2672, "def is_all_field_none(self):\n \"\"\"\n :rtype: bool\n \"\"\"\n\n if self._type_ is not None:\n return False\n\n if self._value is not None:\n return False\n\n if self._name is not None:\n return False\n\n return True": 2673, "def _get_line_no_from_comments(py_line):\n \"\"\"Return the line number parsed from the comment or 0.\"\"\"\n matched = LINECOL_COMMENT_RE.match(py_line)\n if matched:\n return int(matched.group(1))\n else:\n return 0": 2674, "def is_integer_array(val):\n \"\"\"\n Checks whether a variable is a numpy integer array.\n\n Parameters\n ----------\n val\n The variable to check.\n\n Returns\n -------\n bool\n True if the variable is a numpy integer array. Otherwise False.\n\n \"\"\"\n return is_np_array(val) and issubclass(val.dtype.type, np.integer)": 2675, "def can_route(self, endpoint, method=None, **kwargs):\n \"\"\"Make sure we can route to the given endpoint or url.\n\n This checks for `http.get` permission (or other methods) on the ACL of\n route functions, attached via the `ACL` decorator.\n\n :param endpoint: A URL or endpoint to check for permission to access.\n :param method: The HTTP method to check; defaults to `'GET'`.\n :param **kwargs: The context to pass to predicates.\n\n \"\"\"\n\n view = flask.current_app.view_functions.get(endpoint)\n if not view:\n endpoint, args = flask._request_ctx.top.match(endpoint)\n view = flask.current_app.view_functions.get(endpoint)\n if not view:\n return False\n\n return self.can('http.' + (method or 'GET').lower(), view, **kwargs)": 2676, "def best(self):\n \"\"\"\n Returns the element with the highest probability.\n \"\"\"\n b = (-1e999999, None)\n for k, c in iteritems(self.counts):\n b = max(b, (c, k))\n return b[1]": 2677, "def test_value(self, value):\n \"\"\"Test if value is an instance of float.\"\"\"\n if not isinstance(value, float):\n raise ValueError('expected float value: ' + str(type(value)))": 2678, "def _column_resized(self, col, old_width, new_width):\n \"\"\"Update the column width.\"\"\"\n self.dataTable.setColumnWidth(col, new_width)\n self._update_layout()": 2679, "def from_df(data_frame):\n \"\"\"Parses data and builds an instance of this class\n\n :param data_frame: pandas DataFrame\n :return: SqlTable\n \"\"\"\n labels = data_frame.keys().tolist()\n data = data_frame.values.tolist()\n return SqlTable(labels, data, \"{:.3f}\", \"\\n\")": 2680, "def transpose(table):\n \"\"\"\n transpose matrix\n \"\"\"\n t = []\n for i in range(0, len(table[0])):\n t.append([row[i] for row in table])\n return t": 2681, "def truncate(self, table):\n \"\"\"Empty a table by deleting all of its rows.\"\"\"\n if isinstance(table, (list, set, tuple)):\n for t in table:\n self._truncate(t)\n else:\n self._truncate(table)": 2682, "def rsa_eq(key1, key2):\n \"\"\"\n Only works for RSAPublic Keys\n\n :param key1:\n :param key2:\n :return:\n \"\"\"\n pn1 = key1.public_numbers()\n pn2 = key2.public_numbers()\n # Check if two RSA keys are in fact the same\n if pn1 == pn2:\n return True\n else:\n return False": 2683, "def dispatch(self, request, *args, **kwargs):\n \"\"\"Dispatch all HTTP methods to the proxy.\"\"\"\n self.request = DownstreamRequest(request)\n self.args = args\n self.kwargs = kwargs\n\n self._verify_config()\n\n self.middleware = MiddlewareSet(self.proxy_middleware)\n\n return self.proxy()": 2684, "def str_dict(some_dict):\n \"\"\"Convert dict of ascii str/unicode to dict of str, if necessary\"\"\"\n return {str(k): str(v) for k, v in some_dict.items()}": 2685, "def to_list(self):\n \"\"\"Convert this confusion matrix into a 2x2 plain list of values.\"\"\"\n return [[int(self.table.cell_values[0][1]), int(self.table.cell_values[0][2])],\n [int(self.table.cell_values[1][1]), int(self.table.cell_values[1][2])]]": 2686, "def stop_capture(self):\n \"\"\"Stop listening for output from the stenotype machine.\"\"\"\n super(Treal, self).stop_capture()\n if self._machine:\n self._machine.close()\n self._stopped()": 2687, "def _tableExists(self, tableName):\n cursor=_conn.execute(\"\"\"\n SELECT * FROM sqlite_master WHERE name ='{0}' and type='table';\n \"\"\".format(tableName))\n exists = cursor.fetchone() is not None\n cursor.close()\n return exists": 2688, "def search_for_tweets_about(user_id, params):\n \"\"\" Search twitter API \"\"\"\n url = \"https://api.twitter.com/1.1/search/tweets.json\"\n response = make_twitter_request(url, user_id, params)\n return process_tweets(response.json()[\"statuses\"])": 2689, "def chmod_plus_w(path):\n \"\"\"Equivalent of unix `chmod +w path`\"\"\"\n path_mode = os.stat(path).st_mode\n path_mode &= int('777', 8)\n path_mode |= stat.S_IWRITE\n os.chmod(path, path_mode)": 2690, "def multipart_parse_json(api_url, data):\n \"\"\"\n Send a post request and parse the JSON response (potentially containing\n non-ascii characters).\n @param api_url: the url endpoint to post to.\n @param data: a dictionary that will be passed to requests.post\n \"\"\"\n headers = {'Content-Type': 'application/x-www-form-urlencoded'}\n response_text = requests.post(api_url, data=data, headers=headers)\\\n .text.encode('ascii', errors='replace')\n\n return json.loads(response_text.decode())": 2691, "def finished(self):\n \"\"\"\n Must be called to print final progress label.\n \"\"\"\n self.progress_bar.set_state(ProgressBar.STATE_DONE)\n self.progress_bar.show()": 2692, "def shutdown():\n \"\"\"Manually shutdown the async API.\n\n Cancels all related tasks and all the socket transportation.\n \"\"\"\n global handler, transport, protocol\n if handler is not None:\n handler.close()\n transport.close()\n handler = None\n transport = None\n protocol = None": 2693, "def __cmp__(self, other):\n \"\"\"Comparsion not implemented.\"\"\"\n # Stops python 2 from allowing comparsion of arbitrary objects\n raise TypeError('unorderable types: {}, {}'\n ''.format(self.__class__.__name__, type(other)))": 2694, "def parse(self, data, mimetype):\n \"\"\"\n Parses a byte array containing a JSON document and returns a Python object.\n :param data: The byte array containing a JSON document.\n :param MimeType mimetype: The mimetype chose to parse the data.\n :return: A Python object.\n \"\"\"\n encoding = mimetype.params.get('charset') or 'utf-8'\n\n return json.loads(data.decode(encoding))": 2695, "def install_from_zip(url):\n \"\"\"Download and unzip from url.\"\"\"\n fname = 'tmp.zip'\n downlad_file(url, fname)\n unzip_file(fname)\n print(\"Removing {}\".format(fname))\n os.unlink(fname)": 2696, "def get_conn(self):\n \"\"\"\n Opens a connection to the cloudant service and closes it automatically if used as context manager.\n\n .. note::\n In the connection form:\n - 'host' equals the 'Account' (optional)\n - 'login' equals the 'Username (or API Key)' (required)\n - 'password' equals the 'Password' (required)\n\n :return: an authorized cloudant session context manager object.\n :rtype: cloudant\n \"\"\"\n conn = self.get_connection(self.cloudant_conn_id)\n\n self._validate_connection(conn)\n\n cloudant_session = cloudant(user=conn.login, passwd=conn.password, account=conn.host)\n\n return cloudant_session": 2697, "def push(self, el):\n \"\"\" Put a new element in the queue. \"\"\"\n count = next(self.counter)\n heapq.heappush(self._queue, (el, count))": 2698, "def update_target(self, name, current, total):\n \"\"\"Updates progress bar for a specified target.\"\"\"\n self.refresh(self._bar(name, current, total))": 2699, "def get_input(input_func, input_str):\n \"\"\"\n Get input from the user given an input function and an input string\n \"\"\"\n val = input_func(\"Please enter your {0}: \".format(input_str))\n while not val or not len(val.strip()):\n val = input_func(\"You didn't enter a valid {0}, please try again: \".format(input_str))\n return val": 2700, "def print_display_png(o):\n \"\"\"\n A function to display sympy expression using display style LaTeX in PNG.\n \"\"\"\n s = latex(o, mode='plain')\n s = s.strip('$')\n # As matplotlib does not support display style, dvipng backend is\n # used here.\n png = latex_to_png('$$%s$$' % s, backend='dvipng')\n return png": 2701, "def dist(x1, x2, axis=0):\n \"\"\"Return the distance between two points.\n\n Set axis=1 if x1 is a vector and x2 a matrix to get a vector of distances.\n \"\"\"\n return np.linalg.norm(x2 - x1, axis=axis)": 2702, "def get_indentation(func):\n \"\"\"Extracts a function's indentation as a string,\n In contrast to an inspect.indentsize based implementation,\n this function preserves tabs if present.\n \"\"\"\n src_lines = getsourcelines(func)[0]\n for line in src_lines:\n if not (line.startswith('@') or line.startswith('def') or line.lstrip().startswith('#')):\n return line[:len(line) - len(line.lstrip())]\n return pytypes.default_indent": 2703, "def counter_from_str(self, string):\n \"\"\"Build word frequency list from incoming string.\"\"\"\n string_list = [chars for chars in string if chars not in self.punctuation]\n string_joined = ''.join(string_list)\n tokens = self.punkt.word_tokenize(string_joined)\n return Counter(tokens)": 2704, "def _make_index(df, cols=META_IDX):\n \"\"\"Create an index from the columns of a dataframe\"\"\"\n return pd.MultiIndex.from_tuples(\n pd.unique(list(zip(*[df[col] for col in cols]))), names=tuple(cols))": 2705, "def _try_compile(source, name):\n \"\"\"Attempts to compile the given source, first as an expression and\n then as a statement if the first approach fails.\n\n Utility function to accept strings in functions that otherwise\n expect code objects\n \"\"\"\n try:\n c = compile(source, name, 'eval')\n except SyntaxError:\n c = compile(source, name, 'exec')\n return c": 2706, "def _sort_lambda(sortedby='cpu_percent',\n sortedby_secondary='memory_percent'):\n \"\"\"Return a sort lambda function for the sortedbykey\"\"\"\n ret = None\n if sortedby == 'io_counters':\n ret = _sort_io_counters\n elif sortedby == 'cpu_times':\n ret = _sort_cpu_times\n return ret": 2707, "def items(self, limit=0):\n \"\"\"Return iterator for items in each page\"\"\"\n i = ItemIterator(self.iterator)\n i.limit = limit\n return i": 2708, "def __init__(self, root_section='lago', defaults={}):\n \"\"\"__init__\n Args:\n root_section (str): root section in the init\n defaults (dict): Default dictonary to load, can be empty.\n \"\"\"\n\n self.root_section = root_section\n self._defaults = defaults\n self._config = defaultdict(dict)\n self._config.update(self.load())\n self._parser = None": 2709, "def conv2d(x_input, w_matrix):\n \"\"\"conv2d returns a 2d convolution layer with full stride.\"\"\"\n return tf.nn.conv2d(x_input, w_matrix, strides=[1, 1, 1, 1], padding='SAME')": 2710, "def percent_d(data, period):\n \"\"\"\n %D.\n\n Formula:\n %D = SMA(%K, 3)\n \"\"\"\n p_k = percent_k(data, period)\n percent_d = sma(p_k, 3)\n return percent_d": 2711, "def line_segment(X0, X1):\n r\"\"\"\n Calculate the voxel coordinates of a straight line between the two given\n end points\n\n Parameters\n ----------\n X0 and X1 : array_like\n The [x, y] or [x, y, z] coordinates of the start and end points of\n the line.\n\n Returns\n -------\n coords : list of lists\n A list of lists containing the X, Y, and Z coordinates of all voxels\n that should be drawn between the start and end points to create a solid\n line.\n \"\"\"\n X0 = sp.around(X0).astype(int)\n X1 = sp.around(X1).astype(int)\n if len(X0) == 3:\n L = sp.amax(sp.absolute([[X1[0]-X0[0]], [X1[1]-X0[1]], [X1[2]-X0[2]]])) + 1\n x = sp.rint(sp.linspace(X0[0], X1[0], L)).astype(int)\n y = sp.rint(sp.linspace(X0[1], X1[1], L)).astype(int)\n z = sp.rint(sp.linspace(X0[2], X1[2], L)).astype(int)\n return [x, y, z]\n else:\n L = sp.amax(sp.absolute([[X1[0]-X0[0]], [X1[1]-X0[1]]])) + 1\n x = sp.rint(sp.linspace(X0[0], X1[0], L)).astype(int)\n y = sp.rint(sp.linspace(X0[1], X1[1], L)).astype(int)\n return [x, y]": 2712, "def version(self):\n \"\"\"Spotify version information\"\"\"\n url: str = get_url(\"/service/version.json\")\n params = {\"service\": \"remote\"}\n r = self._request(url=url, params=params)\n return r.json()": 2713, "def multiply(traj):\n \"\"\"Sophisticated simulation of multiplication\"\"\"\n z=traj.x*traj.y\n traj.f_add_result('z',z=z, comment='I am the product of two reals!')": 2714, "def getOffset(self, loc):\n \"\"\" Returns the offset between the given point and this point \"\"\"\n return Location(loc.x - self.x, loc.y - self.y)": 2715, "def unit_ball_L2(shape):\n \"\"\"A tensorflow variable tranfomed to be constrained in a L2 unit ball.\n\n EXPERIMENTAL: Do not use for adverserial examples if you need to be confident\n they are strong attacks. We are not yet confident in this code.\n \"\"\"\n x = tf.Variable(tf.zeros(shape))\n return constrain_L2(x)": 2716, "def correlation(df, rowvar=False):\n \"\"\"\n Calculate column-wise Pearson correlations using ``numpy.ma.corrcoef``\n\n Input data is masked to ignore NaNs when calculating correlations. Data is returned as\n a Pandas ``DataFrame`` of column_n x column_n dimensions, with column index copied to\n both axes.\n\n :param df: Pandas DataFrame\n :return: Pandas DataFrame (n_columns x n_columns) of column-wise correlations\n \"\"\"\n\n # Create a correlation matrix for all correlations\n # of the columns (filled with na for all values)\n df = df.copy()\n maskv = np.ma.masked_where(np.isnan(df.values), df.values)\n cdf = np.ma.corrcoef(maskv, rowvar=False)\n cdf = pd.DataFrame(np.array(cdf))\n cdf.columns = df.columns\n cdf.index = df.columns\n cdf = cdf.sort_index(level=0, axis=1)\n cdf = cdf.sort_index(level=0)\n return cdf": 2717, "def assert_visible(self, locator, msg=None):\n \"\"\"\n Hard assert for whether and element is present and visible in the current window/frame\n\n :params locator: the locator of the element to search for\n :params msg: (Optional) msg explaining the difference\n \"\"\"\n e = driver.find_elements_by_locator(locator)\n if len(e) == 0:\n raise AssertionError(\"Element at %s was not found\" % locator)\n assert e.is_displayed()": 2718, "def distance(vec1, vec2):\n \"\"\"Calculate the distance between two Vectors\"\"\"\n if isinstance(vec1, Vector2) \\\n and isinstance(vec2, Vector2):\n dist_vec = vec2 - vec1\n return dist_vec.length()\n else:\n raise TypeError(\"vec1 and vec2 must be Vector2's\")": 2719, "def compute_gradient(self):\n \"\"\"Compute the gradient of the current model using the training set\n \"\"\"\n delta = self.predict(self.X) - self.y\n return delta.dot(self.X) / len(self.X)": 2720, "def _get_indent_length(line):\n \"\"\"Return the length of the indentation on the given token's line.\"\"\"\n result = 0\n for char in line:\n if char == \" \":\n result += 1\n elif char == \"\\t\":\n result += _TAB_LENGTH\n else:\n break\n return result": 2721, "def quit(self):\n \"\"\" Quits the application (called when the last window is closed)\n \"\"\"\n logger.debug(\"ArgosApplication.quit called\")\n assert len(self.mainWindows) == 0, \\\n \"Bug: still {} windows present at application quit!\".format(len(self.mainWindows))\n self.qApplication.quit()": 2722, "def state(self):\n \"\"\"Return internal state, useful for testing.\"\"\"\n return {'c': self.c, 's0': self.s0, 's1': self.s1, 's2': self.s2}": 2723, "def indent(self):\n \"\"\"\n Begins an indented block. Must be used in a 'with' code block.\n All calls to the logger inside of the block will be indented.\n \"\"\"\n blk = IndentBlock(self, self._indent)\n self._indent += 1\n return blk": 2724, "def nlargest(self, n=None):\n\t\t\"\"\"List the n most common elements and their counts.\n\n\t\tList is from the most\n\t\tcommon to the least. If n is None, the list all element counts.\n\n\t\tRun time should be O(m log m) where m is len(self)\n\t\tArgs:\n\t\t\tn (int): The number of elements to return\n\t\t\"\"\"\n\t\tif n is None:\n\t\t\treturn sorted(self.counts(), key=itemgetter(1), reverse=True)\n\t\telse:\n\t\t\treturn heapq.nlargest(n, self.counts(), key=itemgetter(1))": 2725, "def get_cov(config):\n \"\"\"Returns the coverage object of pytest-cov.\"\"\"\n\n # Check with hasplugin to avoid getplugin exception in older pytest.\n if config.pluginmanager.hasplugin('_cov'):\n plugin = config.pluginmanager.getplugin('_cov')\n if plugin.cov_controller:\n return plugin.cov_controller.cov\n return None": 2726, "def setblocking(fd, blocking):\n \"\"\"Set the O_NONBLOCK flag for a file descriptor. Availability: Unix.\"\"\"\n if not fcntl:\n warnings.warn('setblocking() not supported on Windows')\n flags = fcntl.fcntl(fd, fcntl.F_GETFL)\n if blocking:\n flags |= os.O_NONBLOCK\n else:\n flags &= ~os.O_NONBLOCK\n fcntl.fcntl(fd, fcntl.F_SETFL, flags)": 2727, "def process_kill(pid, sig=None):\n \"\"\"Send signal to process.\n \"\"\"\n sig = sig or signal.SIGTERM\n os.kill(pid, sig)": 2728, "def get_readline_tail(self, n=10):\n \"\"\"Get the last n items in readline history.\"\"\"\n end = self.shell.readline.get_current_history_length() + 1\n start = max(end-n, 1)\n ghi = self.shell.readline.get_history_item\n return [ghi(x) for x in range(start, end)]": 2729, "def surface(cls, predstr):\n \"\"\"Instantiate a Pred from its quoted string representation.\"\"\"\n lemma, pos, sense, _ = split_pred_string(predstr)\n return cls(Pred.SURFACE, lemma, pos, sense, predstr)": 2730, "def set_icon(self, bmp):\n \"\"\"Sets main window icon to given wx.Bitmap\"\"\"\n\n _icon = wx.EmptyIcon()\n _icon.CopyFromBitmap(bmp)\n self.SetIcon(_icon)": 2731, "def _update_bordercolor(self, bordercolor):\n \"\"\"Updates background color\"\"\"\n\n border_color = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVEBORDER)\n border_color.SetRGB(bordercolor)\n\n self.linecolor_choice.SetColour(border_color)": 2732, "def connect(*args, **kwargs):\n \"\"\"Create database connection, use TraceCursor as the cursor_factory.\"\"\"\n kwargs['cursor_factory'] = TraceCursor\n conn = pg_connect(*args, **kwargs)\n return conn": 2733, "def get_screen_resolution(self):\n \"\"\"Return the screen resolution of the primary screen.\"\"\"\n widget = QDesktopWidget()\n geometry = widget.availableGeometry(widget.primaryScreen())\n return geometry.width(), geometry.height()": 2734, "def from_tuple(tup):\n \"\"\"Convert a tuple into a range with error handling.\n\n Parameters\n ----------\n tup : tuple (len 2 or 3)\n The tuple to turn into a range.\n\n Returns\n -------\n range : range\n The range from the tuple.\n\n Raises\n ------\n ValueError\n Raised when the tuple length is not 2 or 3.\n \"\"\"\n if len(tup) not in (2, 3):\n raise ValueError(\n 'tuple must contain 2 or 3 elements, not: %d (%r' % (\n len(tup),\n tup,\n ),\n )\n return range(*tup)": 2735, "def submit(self, fn, *args, **kwargs):\n \"\"\"Submit an operation\"\"\"\n corofn = asyncio.coroutine(lambda: fn(*args, **kwargs))\n return run_coroutine_threadsafe(corofn(), self.loop)": 2736, "def sample_correlations(self):\n \"\"\"Returns an `ExpMatrix` containing all pairwise sample correlations.\n\n Returns\n -------\n `ExpMatrix`\n The sample correlation matrix.\n\n \"\"\"\n C = np.corrcoef(self.X.T)\n corr_matrix = ExpMatrix(genes=self.samples, samples=self.samples, X=C)\n return corr_matrix": 2737, "def clone_with_copy(src_path, dest_path):\n \"\"\"Clone a directory try by copying it.\n\n Args:\n src_path: The directory to be copied.\n dest_path: The location to copy the directory to.\n \"\"\"\n log.info('Cloning directory tree %s to %s', src_path, dest_path)\n shutil.copytree(src_path, dest_path)": 2738, "def heappop_max(heap):\n \"\"\"Maxheap version of a heappop.\"\"\"\n lastelt = heap.pop() # raises appropriate IndexError if heap is empty\n if heap:\n returnitem = heap[0]\n heap[0] = lastelt\n _siftup_max(heap, 0)\n return returnitem\n return lastelt": 2739, "def coverage():\n \"\"\"check code coverage quickly with the default Python\"\"\"\n run(\"coverage run --source {PROJECT_NAME} -m py.test\".format(PROJECT_NAME=PROJECT_NAME))\n run(\"coverage report -m\")\n run(\"coverage html\")\n\n webbrowser.open('file://' + os.path.realpath(\"htmlcov/index.html\"), new=2)": 2740, "def new_from_list(cls, items, **kwargs):\n \"\"\"Populates the ListView with a string list.\n\n Args:\n items (list): list of strings to fill the widget with.\n \"\"\"\n obj = cls(**kwargs)\n for item in items:\n obj.append(ListItem(item))\n return obj": 2741, "def csvtolist(inputstr):\n \"\"\" converts a csv string into a list \"\"\"\n reader = csv.reader([inputstr], skipinitialspace=True)\n output = []\n for r in reader:\n output += r\n return output": 2742, "def putkeyword(self, keyword, value, makesubrecord=False):\n \"\"\"Put the value of a column keyword.\n (see :func:`table.putcolkeyword`)\"\"\"\n return self._table.putcolkeyword(self._column, keyword, value, makesubrecord)": 2743, "def format_op_hdr():\n \"\"\"\n Build the header\n \"\"\"\n txt = 'Base Filename'.ljust(36) + ' '\n txt += 'Lines'.rjust(7) + ' '\n txt += 'Words'.rjust(7) + ' '\n txt += 'Unique'.ljust(8) + ''\n return txt": 2744, "def format_arg(value):\n \"\"\"\n :param value:\n Some value in a dataset.\n :type value:\n varies\n :return:\n unicode representation of that value\n :rtype:\n `unicode`\n \"\"\"\n translator = repr if isinstance(value, six.string_types) else six.text_type\n return translator(value)": 2745, "def makedirs(directory):\n \"\"\" Resursively create a named directory. \"\"\"\n parent = os.path.dirname(os.path.abspath(directory))\n if not os.path.exists(parent):\n makedirs(parent)\n os.mkdir(directory)": 2746, "def create_db_schema(cls, cur, schema_name):\n \"\"\"\n Create Postgres schema script and execute it on cursor\n \"\"\"\n create_schema_script = \"CREATE SCHEMA {0} ;\\n\".format(schema_name)\n cur.execute(create_schema_script)": 2747, "def create_rot2d(angle):\n \"\"\"Create 2D rotation matrix\"\"\"\n ca = math.cos(angle)\n sa = math.sin(angle)\n return np.array([[ca, -sa], [sa, ca]])": 2748, "def sp_rand(m,n,a):\n \"\"\"\n Generates an mxn sparse 'd' matrix with round(a*m*n) nonzeros.\n \"\"\"\n if m == 0 or n == 0: return spmatrix([], [], [], (m,n))\n nnz = min(max(0, int(round(a*m*n))), m*n)\n nz = matrix(random.sample(range(m*n), nnz), tc='i')\n return spmatrix(normal(nnz,1), nz%m, matrix([int(ii) for ii in nz/m]), (m,n))": 2749, "def append_table(self, name, **kwargs):\n \"\"\"Create a new table.\"\"\"\n self.stack.append(Table(name, **kwargs))": 2750, "def build_gui(self, container):\n \"\"\"\n This is responsible for building the viewer's UI. It should\n place the UI in `container`. Override this to make a custom\n UI.\n \"\"\"\n vbox = Widgets.VBox()\n vbox.set_border_width(0)\n\n w = Viewers.GingaViewerWidget(viewer=self)\n vbox.add_widget(w, stretch=1)\n\n # need to put this in an hbox with an expanding label or the\n # browser wants to resize the canvas, distorting it\n hbox = Widgets.HBox()\n hbox.add_widget(vbox, stretch=0)\n hbox.add_widget(Widgets.Label(''), stretch=1)\n\n container.set_widget(hbox)": 2751, "def add_object(self, obj):\n \"\"\"Add object to local and app environment storage\n\n :param obj: Instance of a .NET object\n \"\"\"\n if obj.top_level_object:\n if isinstance(obj, DotNetNamespace):\n self.namespaces[obj.name] = obj\n self.objects[obj.id] = obj": 2752, "def get_2D_samples_gauss(n, m, sigma, random_state=None):\n \"\"\" Deprecated see make_2D_samples_gauss \"\"\"\n return make_2D_samples_gauss(n, m, sigma, random_state=None)": 2753, "def str_to_class(class_name):\n \"\"\"\n Returns a class based on class name \n \"\"\"\n mod_str, cls_str = class_name.rsplit('.', 1)\n mod = __import__(mod_str, globals(), locals(), [''])\n cls = getattr(mod, cls_str)\n return cls": 2754, "def next(self):\n \"\"\"Retrieve the next row.\"\"\"\n # I'm pretty sure this is the completely wrong way to go about this, but\n # oh well, this works.\n if not hasattr(self, '_iter'):\n self._iter = self.readrow_as_dict()\n return self._iter.next()": 2755, "def move_datetime_year(dt, direction, num_shifts):\n \"\"\"\n Move datetime 1 year in the chosen direction.\n unit is a no-op, to keep the API the same as the day case\n \"\"\"\n delta = relativedelta(years=+num_shifts)\n return _move_datetime(dt, direction, delta)": 2756, "def getBuffer(x):\n \"\"\"\n Copy @x into a (modifiable) ctypes byte array\n \"\"\"\n b = bytes(x)\n return (c_ubyte * len(b)).from_buffer_copy(bytes(x))": 2757, "def __enter__(self):\n \"\"\" Implements the context manager protocol. Specially useful for asserting exceptions\n \"\"\"\n clone = self.clone()\n self._contexts.append(clone)\n self.reset()\n return self": 2758, "def custodian_archive(packages=None):\n \"\"\"Create a lambda code archive for running custodian.\n\n Lambda archive currently always includes `c7n` and\n `pkg_resources`. Add additional packages in the mode block.\n\n Example policy that includes additional packages\n\n .. code-block:: yaml\n\n policy:\n name: lambda-archive-example\n resource: s3\n mode:\n packages:\n - botocore\n\n packages: List of additional packages to include in the lambda archive.\n\n \"\"\"\n modules = {'c7n', 'pkg_resources'}\n if packages:\n modules = filter(None, modules.union(packages))\n return PythonPackageArchive(*sorted(modules))": 2759, "def group(data, num):\n \"\"\" Split data into chunks of num chars each \"\"\"\n return [data[i:i+num] for i in range(0, len(data), num)]": 2760, "def to_query_parameters(parameters):\n \"\"\"Converts DB-API parameter values into query parameters.\n\n :type parameters: Mapping[str, Any] or Sequence[Any]\n :param parameters: A dictionary or sequence of query parameter values.\n\n :rtype: List[google.cloud.bigquery.query._AbstractQueryParameter]\n :returns: A list of query parameters.\n \"\"\"\n if parameters is None:\n return []\n\n if isinstance(parameters, collections_abc.Mapping):\n return to_query_parameters_dict(parameters)\n\n return to_query_parameters_list(parameters)": 2761, "def replace_month_abbr_with_num(date_str, lang=DEFAULT_DATE_LANG):\n \"\"\"Replace month strings occurrences with month number.\"\"\"\n num, abbr = get_month_from_date_str(date_str, lang)\n return re.sub(abbr, str(num), date_str, flags=re.IGNORECASE)": 2762, "def parse_datetime(dt_str, format):\n \"\"\"Create a timezone-aware datetime object from a datetime string.\"\"\"\n t = time.strptime(dt_str, format)\n return datetime(t[0], t[1], t[2], t[3], t[4], t[5], t[6], pytz.UTC)": 2763, "def _converter(self, value):\n \"\"\"Convert raw input value of the field.\"\"\"\n if not isinstance(value, datetime.date):\n raise TypeError('{0} is not valid date'.format(value))\n return value": 2764, "def set_as_object(self, value):\n \"\"\"\n Sets a new value to map element\n\n :param value: a new element or map value.\n \"\"\"\n self.clear()\n map = MapConverter.to_map(value)\n self.append(map)": 2765, "def datetime_to_timestamp(dt):\n \"\"\"Convert a UTC datetime to a Unix timestamp\"\"\"\n delta = dt - datetime.utcfromtimestamp(0)\n return delta.seconds + delta.days * 24 * 3600": 2766, "def replace_all(text, dic):\n \"\"\"Takes a string and dictionary. replaces all occurrences of i with j\"\"\"\n\n for i, j in dic.iteritems():\n text = text.replace(i, j)\n return text": 2767, "def to_pydatetime(self):\n \"\"\"\n Converts datetimeoffset object into Python's datetime.datetime object\n @return: time zone aware datetime.datetime\n \"\"\"\n dt = datetime.datetime.combine(self._date.to_pydate(), self._time.to_pytime())\n from .tz import FixedOffsetTimezone\n return dt.replace(tzinfo=_utc).astimezone(FixedOffsetTimezone(self._offset))": 2768, "def __enter__(self):\n \"\"\"Enable the download log filter.\"\"\"\n self.logger = logging.getLogger('pip.download')\n self.logger.addFilter(self)": 2769, "def triangle_area(pt1, pt2, pt3):\n r\"\"\"Return the area of a triangle.\n\n Parameters\n ----------\n pt1: (X,Y) ndarray\n Starting vertex of a triangle\n pt2: (X,Y) ndarray\n Second vertex of a triangle\n pt3: (X,Y) ndarray\n Ending vertex of a triangle\n\n Returns\n -------\n area: float\n Area of the given triangle.\n\n \"\"\"\n a = 0.0\n\n a += pt1[0] * pt2[1] - pt2[0] * pt1[1]\n a += pt2[0] * pt3[1] - pt3[0] * pt2[1]\n a += pt3[0] * pt1[1] - pt1[0] * pt3[1]\n\n return abs(a) / 2": 2770, "def parse_command_args():\n \"\"\"Command line parser.\"\"\"\n parser = argparse.ArgumentParser(description='Register PB devices.')\n parser.add_argument('num_pb', type=int,\n help='Number of PBs devices to register.')\n return parser.parse_args()": 2771, "def __len__(self):\n \"\"\" This will equal 124 for the V1 database. \"\"\"\n length = 0\n for typ, siz, _ in self.format:\n length += siz\n return length": 2772, "def decompress(f):\n \"\"\"Decompress a Plan 9 image file. Assumes f is already cued past the\n initial 'compressed\\n' string.\n \"\"\"\n\n r = meta(f.read(60))\n return r, decomprest(f, r[4])": 2773, "def delete_cell(self, key):\n \"\"\"Deletes key cell\"\"\"\n\n try:\n self.code_array.pop(key)\n\n except KeyError:\n pass\n\n self.grid.code_array.result_cache.clear()": 2774, "def pop():\n \"\"\"Remove instance from instance list\"\"\"\n pid = os.getpid()\n thread = threading.current_thread()\n Wdb._instances.pop((pid, thread))": 2775, "def runcoro(async_function):\n \"\"\"\n Runs an asynchronous function without needing to use await - useful for lambda\n\n Args:\n async_function (Coroutine): The asynchronous function to run\n \"\"\"\n\n future = _asyncio.run_coroutine_threadsafe(async_function, client.loop)\n result = future.result()\n return result": 2776, "def remove(self, key):\n \"\"\"remove the value found at key from the queue\"\"\"\n item = self.item_finder.pop(key)\n item[-1] = None\n self.removed_count += 1": 2777, "def lock_file(f, block=False):\n \"\"\"\n If block=False (the default), die hard and fast if another process has\n already grabbed the lock for this file.\n\n If block=True, wait for the lock to be released, then continue.\n \"\"\"\n try:\n flags = fcntl.LOCK_EX\n if not block:\n flags |= fcntl.LOCK_NB\n fcntl.flock(f.fileno(), flags)\n except IOError as e:\n if e.errno in (errno.EACCES, errno.EAGAIN):\n raise SystemExit(\"ERROR: %s is locked by another process.\" %\n f.name)\n raise": 2778, "def determine_interactive(self):\n\t\t\"\"\"Determine whether we're in an interactive shell.\n\t\tSets interactivity off if appropriate.\n\t\tcf http://stackoverflow.com/questions/24861351/how-to-detect-if-python-script-is-being-run-as-a-background-process\n\t\t\"\"\"\n\t\ttry:\n\t\t\tif not sys.stdout.isatty() or os.getpgrp() != os.tcgetpgrp(sys.stdout.fileno()):\n\t\t\t\tself.interactive = 0\n\t\t\t\treturn False\n\t\texcept Exception:\n\t\t\tself.interactive = 0\n\t\t\treturn False\n\t\tif self.interactive == 0:\n\t\t\treturn False\n\t\treturn True": 2779, "def create_bigquery_table(self, database, schema, table_name, callback,\n sql):\n \"\"\"Create a bigquery table. The caller must supply a callback\n that takes one argument, a `google.cloud.bigquery.Table`, and mutates\n it.\n \"\"\"\n conn = self.get_thread_connection()\n client = conn.handle\n\n view_ref = self.table_ref(database, schema, table_name, conn)\n view = google.cloud.bigquery.Table(view_ref)\n callback(view)\n\n with self.exception_handler(sql):\n client.create_table(view)": 2780, "def _guess_extract_method(fname):\n \"\"\"Guess extraction method, given file name (or path).\"\"\"\n for method, extensions in _EXTRACTION_METHOD_TO_EXTS:\n for ext in extensions:\n if fname.endswith(ext):\n return method\n return ExtractMethod.NO_EXTRACT": 2781, "def bootstrap_indexes(data, n_samples=10000):\n \"\"\"\nGiven data points data, where axis 0 is considered to delineate points, return\nan generator for sets of bootstrap indexes. This can be used as a list\nof bootstrap indexes (with list(bootstrap_indexes(data))) as well.\n \"\"\"\n for _ in xrange(n_samples):\n yield randint(data.shape[0], size=(data.shape[0],))": 2782, "def compute_boxplot(self, series):\n \"\"\"\n Compute boxplot for given pandas Series.\n \"\"\"\n from matplotlib.cbook import boxplot_stats\n series = series[series.notnull()]\n if len(series.values) == 0:\n return {}\n elif not is_numeric_dtype(series):\n return self.non_numeric_stats(series)\n stats = boxplot_stats(list(series.values))[0]\n stats['count'] = len(series.values)\n stats['fliers'] = \"|\".join(map(str, stats['fliers']))\n return stats": 2783, "def IsBinary(self, filename):\n\t\t\"\"\"Returns true if the guessed mimetyped isnt't in text group.\"\"\"\n\t\tmimetype = mimetypes.guess_type(filename)[0]\n\t\tif not mimetype:\n\t\t\treturn False # e.g. README, \"real\" binaries usually have an extension\n\t\t# special case for text files which don't start with text/\n\t\tif mimetype in TEXT_MIMETYPES:\n\t\t\treturn False\n\t\treturn not mimetype.startswith(\"text/\")": 2784, "def retrieve_by_id(self, id_):\n \"\"\"Return a JSSObject for the element with ID id_\"\"\"\n items_with_id = [item for item in self if item.id == int(id_)]\n if len(items_with_id) == 1:\n return items_with_id[0].retrieve()": 2785, "def install_rpm_py():\n \"\"\"Install RPM Python binding.\"\"\"\n python_path = sys.executable\n cmd = '{0} install.py'.format(python_path)\n exit_status = os.system(cmd)\n if exit_status != 0:\n raise Exception('Command failed: {0}'.format(cmd))": 2786, "def enable_ssl(self, *args, **kwargs):\n \"\"\"\n Transforms the regular socket.socket to an ssl.SSLSocket for secure\n connections. Any arguments are passed to ssl.wrap_socket:\n http://docs.python.org/dev/library/ssl.html#ssl.wrap_socket\n \"\"\"\n if self.handshake_sent:\n raise SSLError('can only enable SSL before handshake')\n\n self.secure = True\n self.sock = ssl.wrap_socket(self.sock, *args, **kwargs)": 2787, "def convert_timeval(seconds_since_epoch):\n \"\"\"Convert time into C style timeval.\"\"\"\n frac, whole = math.modf(seconds_since_epoch)\n microseconds = math.floor(frac * 1000000)\n seconds = math.floor(whole)\n return seconds, microseconds": 2788, "def growthfromrange(rangegrowth, startdate, enddate):\n \"\"\"\n Annual growth given growth from start date to end date.\n \"\"\"\n _yrs = (pd.Timestamp(enddate) - pd.Timestamp(startdate)).total_seconds() /\\\n dt.timedelta(365.25).total_seconds()\n return yrlygrowth(rangegrowth, _yrs)": 2789, "def recursively_update(d, d2):\n \"\"\"dict.update but which merges child dicts (dict2 takes precedence where there's conflict).\"\"\"\n for k, v in d2.items():\n if k in d:\n if isinstance(v, dict):\n recursively_update(d[k], v)\n continue\n d[k] = v": 2790, "def reject(self):\n \"\"\"\n Rejects the snapshot and closes the widget.\n \"\"\"\n if self.hideWindow():\n self.hideWindow().show()\n \n self.close()\n self.deleteLater()": 2791, "def robust_int(v):\n \"\"\"Parse an int robustly, ignoring commas and other cruft. \"\"\"\n\n if isinstance(v, int):\n return v\n\n if isinstance(v, float):\n return int(v)\n\n v = str(v).replace(',', '')\n\n if not v:\n return None\n\n return int(v)": 2792, "def send(socket, data, num_bytes=20):\n \"\"\"Send data to specified socket.\n\n\n :param socket: open socket instance\n :param data: data to send\n :param num_bytes: number of bytes to read\n\n :return: received data\n \"\"\"\n pickled_data = pickle.dumps(data, -1)\n length = str(len(pickled_data)).zfill(num_bytes)\n socket.sendall(length.encode())\n socket.sendall(pickled_data)": 2793, "def _trim_zeros_complex(str_complexes, na_rep='NaN'):\n \"\"\"\n Separates the real and imaginary parts from the complex number, and\n executes the _trim_zeros_float method on each of those.\n \"\"\"\n def separate_and_trim(str_complex, na_rep):\n num_arr = str_complex.split('+')\n return (_trim_zeros_float([num_arr[0]], na_rep) +\n ['+'] +\n _trim_zeros_float([num_arr[1][:-1]], na_rep) +\n ['j'])\n\n return [''.join(separate_and_trim(x, na_rep)) for x in str_complexes]": 2794, "def display(self):\n \"\"\" Get screen width and height \"\"\"\n w, h = self.session.window_size()\n return Display(w*self.scale, h*self.scale)": 2795, "def _snake_to_camel_case(value):\n \"\"\"Convert snake case string to camel case.\"\"\"\n words = value.split(\"_\")\n return words[0] + \"\".join(map(str.capitalize, words[1:]))": 2796, "def deleted(self, instance):\n \"\"\"\n Convenience method for deleting a model (automatically commits the\n delete to the database and returns with an HTTP 204 status code)\n \"\"\"\n self.session_manager.delete(instance, commit=True)\n return '', HTTPStatus.NO_CONTENT": 2797, "def page_title(step, title):\n \"\"\"\n Check that the page title matches the given one.\n \"\"\"\n\n with AssertContextManager(step):\n assert_equals(world.browser.title, title)": 2798, "def __run(self):\n \"\"\"Hacked run function, which installs the trace.\"\"\"\n sys.settrace(self.globaltrace)\n self.__run_backup()\n self.run = self.__run_backup": 2799, "def main():\n \"\"\"Parse the command line and run :func:`migrate`.\"\"\"\n parser = get_args_parser()\n args = parser.parse_args()\n config = Config.from_parse_args(args)\n migrate(config)": 2800, "def __to_localdatetime(val):\n \"\"\"Convert val into a local datetime for tz Europe/Amsterdam.\"\"\"\n try:\n dt = datetime.strptime(val, __DATE_FORMAT)\n dt = pytz.timezone(__TIMEZONE).localize(dt)\n return dt\n except (ValueError, TypeError):\n return None": 2801, "def merge(database=None, directory=None, verbose=None):\n \"\"\"Merge migrations into one.\"\"\"\n router = get_router(directory, database, verbose)\n router.merge()": 2802, "def _add_params_docstring(params):\n \"\"\" Add params to doc string\n \"\"\"\n p_string = \"\\nAccepts the following paramters: \\n\"\n for param in params:\n p_string += \"name: %s, required: %s, description: %s \\n\" % (param['name'], param['required'], param['description'])\n return p_string": 2803, "def from_string(cls, string):\n \"\"\"\n Simply logs a warning if the desired enum value is not found.\n\n :param string:\n :return:\n \"\"\"\n\n # find enum value\n for attr in dir(cls):\n value = getattr(cls, attr)\n if value == string:\n return value\n\n # if not found, log warning and return the value passed in\n logger.warning(\"{} is not a valid enum value for {}.\".format(string, cls.__name__))\n return string": 2804, "def callJavaFunc(func, *args):\n \"\"\" Call Java Function \"\"\"\n gateway = _get_gateway()\n args = [_py2java(gateway, a) for a in args]\n result = func(*args)\n return _java2py(gateway, result)": 2805, "def to_str(obj):\n \"\"\"Attempts to convert given object to a string object\n \"\"\"\n if not isinstance(obj, str) and PY3 and isinstance(obj, bytes):\n obj = obj.decode('utf-8')\n return obj if isinstance(obj, string_types) else str(obj)": 2806, "def ucamel_method(func):\n \"\"\"\n Decorator to ensure the given snake_case method is also written in\n UpperCamelCase in the given namespace. That was mainly written to\n avoid confusion when using wxPython and its UpperCamelCaseMethods.\n \"\"\"\n frame_locals = inspect.currentframe().f_back.f_locals\n frame_locals[snake2ucamel(func.__name__)] = func\n return func": 2807, "def validate(self):\n \"\"\"Validate the configuration file.\"\"\"\n validator = Draft4Validator(self.SCHEMA)\n if not validator.is_valid(self.config):\n for err in validator.iter_errors(self.config):\n LOGGER.error(str(err.message))\n validator.validate(self.config)": 2808, "def bbox(self):\n \"\"\"\n The minimal `~photutils.aperture.BoundingBox` for the cutout\n region with respect to the original (large) image.\n \"\"\"\n\n return BoundingBox(self.slices[1].start, self.slices[1].stop,\n self.slices[0].start, self.slices[0].stop)": 2809, "def _draw_lines_internal(self, coords, colour, bg):\n \"\"\"Helper to draw lines connecting a set of nodes that are scaled for the Screen.\"\"\"\n for i, (x, y) in enumerate(coords):\n if i == 0:\n self._screen.move(x, y)\n else:\n self._screen.draw(x, y, colour=colour, bg=bg, thin=True)": 2810, "def change_dir(directory):\n \"\"\"\n Wraps a function to run in a given directory.\n\n \"\"\"\n def cd_decorator(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n org_path = os.getcwd()\n os.chdir(directory)\n func(*args, **kwargs)\n os.chdir(org_path)\n return wrapper\n return cd_decorator": 2811, "def TextWidget(*args, **kw):\n \"\"\"Forces a parameter value to be text\"\"\"\n kw['value'] = str(kw['value'])\n kw.pop('options', None)\n return TextInput(*args,**kw)": 2812, "def scale_dtype(arr, dtype):\n \"\"\"Convert an array from 0..1 to dtype, scaling up linearly\n \"\"\"\n max_int = np.iinfo(dtype).max\n return (arr * max_int).astype(dtype)": 2813, "def shape_list(l,shape,dtype):\n \"\"\" Shape a list of lists into the appropriate shape and data type \"\"\"\n return np.array(l, dtype=dtype).reshape(shape)": 2814, "def get_record_by_name(self, index, name):\n \"\"\"\n Searches for a single document in the given index on the 'name' field .\n Performs a case-insensitive search by utilizing Elasticsearch's `match_phrase` query.\n \n Args:\n index: `str`. The name of an Elasticsearch index (i.e. biosamples).\n name: `str`. The value of a document's name key to search for.\n \n Returns:\n `dict` containing the document that was indexed into Elasticsearch.\n \n Raises:\n `MultipleHitsException`: More than 1 hit is returned.\n \"\"\"\n result = self.ES.search(\n index=index,\n body={\n \"query\": {\n \"match_phrase\": {\n \"name\": name,\n }\n }\n }\n )\n hits = result[\"hits\"][\"hits\"]\n if not hits:\n return {}\n elif len(hits) == 1:\n return hits[0][\"_source\"]\n else:\n # Mult. records found with same prefix. See if a single record whose name attr matches\n # the match phrase exactly (in a lower-case comparison). \n for h in hits:\n source = h[\"_source\"]\n record_name = source[\"name\"]\n if record_name.lower().strip() == name.lower().strip():\n return source\n msg = \"match_phrase search found multiple records matching query '{}' for index '{}'.\".format(name, index)\n raise MultipleHitsException(msg)": 2815, "def add_datetime(dataframe, timestamp_key='UNIXTIME'):\n \"\"\"Add an additional DATETIME column with standar datetime format.\n\n This currently manipulates the incoming DataFrame!\n \"\"\"\n\n def convert_data(timestamp):\n return datetime.fromtimestamp(float(timestamp) / 1e3, UTC_TZ)\n\n try:\n log.debug(\"Adding DATETIME column to the data\")\n converted = dataframe[timestamp_key].apply(convert_data)\n dataframe['DATETIME'] = converted\n except KeyError:\n log.warning(\"Could not add DATETIME column\")": 2816, "def keys(self):\n \"\"\"Return ids of all indexed documents.\"\"\"\n result = []\n if self.fresh_index is not None:\n result += self.fresh_index.keys()\n if self.opt_index is not None:\n result += self.opt_index.keys()\n return result": 2817, "def all_documents(index=INDEX_NAME):\n \"\"\"\n Get all documents from the given index.\n\n Returns full Elasticsearch objects so you can get metadata too.\n \"\"\"\n query = {\n 'query': {\n 'match_all': {}\n }\n }\n for result in raw_query(query, index=index):\n yield result": 2818, "def flat(l):\n \"\"\"\nReturns the flattened version of a '2D' list. List-correlate to the a.flat()\nmethod of NumPy arrays.\n\nUsage: flat(l)\n\"\"\"\n newl = []\n for i in range(len(l)):\n for j in range(len(l[i])):\n newl.append(l[i][j])\n return newl": 2819, "def ylabelsize(self, size, index=1):\n \"\"\"Set the size of the label.\n\n Parameters\n ----------\n size : int\n\n Returns\n -------\n Chart\n\n \"\"\"\n self.layout['yaxis' + str(index)]['titlefont']['size'] = size\n return self": 2820, "def _extract_value(self, value):\n \"\"\"If the value is true/false/null replace with Python equivalent.\"\"\"\n return ModelEndpoint._value_map.get(smart_str(value).lower(), value)": 2821, "def __getattribute__(self, attr):\n \"\"\"Retrieve attr from current active etree implementation\"\"\"\n if (attr not in object.__getattribute__(self, '__dict__')\n and attr not in Etree.__dict__):\n return object.__getattribute__(self._etree, attr)\n return object.__getattribute__(self, attr)": 2822, "def decode_unicode_string(string):\n \"\"\"\n Decode string encoded by `unicode_string`\n \"\"\"\n if string.startswith('[BASE64-DATA]') and string.endswith('[/BASE64-DATA]'):\n return base64.b64decode(string[len('[BASE64-DATA]'):-len('[/BASE64-DATA]')])\n return string": 2823, "def add_element_to_doc(doc, tag, value):\n \"\"\"Set text value of an etree.Element of tag, appending a new element with given tag if it doesn't exist.\"\"\"\n element = doc.find(\".//%s\" % tag)\n if element is None:\n element = etree.SubElement(doc, tag)\n element.text = value": 2824, "def make_exception_message(exc):\n \"\"\"\n An exception is passed in and this function\n returns the proper string depending on the result\n so it is readable enough.\n \"\"\"\n if str(exc):\n return '%s: %s\\n' % (exc.__class__.__name__, exc)\n else:\n return '%s\\n' % (exc.__class__.__name__)": 2825, "def prepare_query_params(**kwargs):\n \"\"\"\n Prepares given parameters to be used in querystring.\n \"\"\"\n return [\n (sub_key, sub_value)\n for key, value in kwargs.items()\n for sub_key, sub_value in expand(value, key)\n if sub_value is not None\n ]": 2826, "def expandvars_dict(settings):\n \"\"\"Expands all environment variables in a settings dictionary.\"\"\"\n return dict(\n (key, os.path.expandvars(value))\n for key, value in settings.iteritems()\n )": 2827, "def get_numbers(s):\n \"\"\"Extracts all integers from a string an return them in a list\"\"\"\n\n result = map(int, re.findall(r'[0-9]+', unicode(s)))\n return result + [1] * (2 - len(result))": 2828, "def is_nested_object(obj):\n \"\"\"\n return a boolean if we have a nested object, e.g. a Series with 1 or\n more Series elements\n\n This may not be necessarily be performant.\n\n \"\"\"\n\n if isinstance(obj, ABCSeries) and is_object_dtype(obj):\n\n if any(isinstance(v, ABCSeries) for v in obj.values):\n return True\n\n return False": 2829, "def get_data(self):\n \"\"\"\n Fetch the data field if it does not exist.\n \"\"\"\n try:\n return DocumentDataDict(self.__dict__['data'])\n except KeyError:\n self._lazy_load()\n return DocumentDataDict(self.__dict__['data'])": 2830, "def ffmpeg_version():\n \"\"\"Returns the available ffmpeg version\n\n Returns\n ----------\n version : str\n version number as string\n \"\"\"\n\n cmd = [\n 'ffmpeg',\n '-version'\n ]\n\n output = sp.check_output(cmd)\n aac_codecs = [\n x for x in\n output.splitlines() if \"ffmpeg version \" in str(x)\n ][0]\n hay = aac_codecs.decode('ascii')\n match = re.findall(r'ffmpeg version (\\d+\\.)?(\\d+\\.)?(\\*|\\d+)', hay)\n if match:\n return \"\".join(match[0])\n else:\n return None": 2831, "def is_same_file (filename1, filename2):\n \"\"\"Check if filename1 and filename2 point to the same file object.\n There can be false negatives, ie. the result is False, but it is\n the same file anyway. Reason is that network filesystems can create\n different paths to the same physical file.\n \"\"\"\n if filename1 == filename2:\n return True\n if os.name == 'posix':\n return os.path.samefile(filename1, filename2)\n return is_same_filename(filename1, filename2)": 2832, "def file_read(filename):\n \"\"\"Read a file and close it. Returns the file source.\"\"\"\n fobj = open(filename,'r');\n source = fobj.read();\n fobj.close()\n return source": 2833, "def get_column_definition(self, table, column):\n \"\"\"Retrieve the column definition statement for a column from a table.\"\"\"\n # Parse column definitions for match\n for col in self.get_column_definition_all(table):\n if col.strip('`').startswith(column):\n return col.strip(',')": 2834, "def is_palindrome(string, strict=True):\n \"\"\"\n Checks if the string is a palindrome (https://en.wikipedia.org/wiki/Palindrome).\n\n :param string: String to check.\n :type string: str\n :param strict: True if white spaces matter (default), false otherwise.\n :type strict: bool\n :return: True if the string is a palindrome (like \"otto\", or \"i topi non avevano nipoti\" if strict=False),\n False otherwise\n \"\"\"\n if is_full_string(string):\n if strict:\n return reverse(string) == string\n return is_palindrome(SPACES_RE.sub('', string))\n return False": 2835, "def remove_na_arraylike(arr):\n \"\"\"\n Return array-like containing only true/non-NaN values, possibly empty.\n \"\"\"\n if is_extension_array_dtype(arr):\n return arr[notna(arr)]\n else:\n return arr[notna(lib.values_from_object(arr))]": 2836, "def contains_geometric_info(var):\n \"\"\" Check whether the passed variable is a tuple with two floats or integers \"\"\"\n return isinstance(var, tuple) and len(var) == 2 and all(isinstance(val, (int, float)) for val in var)": 2837, "def init_app(self, app):\n \"\"\"Initialize Flask application.\"\"\"\n app.config.from_pyfile('{0}.cfg'.format(app.name), silent=True)": 2838, "def converged(matrix1, matrix2):\n \"\"\"\n Check for convergence by determining if \n matrix1 and matrix2 are approximately equal.\n \n :param matrix1: The matrix to compare with matrix2\n :param matrix2: The matrix to compare with matrix1\n :returns: True if matrix1 and matrix2 approximately equal\n \"\"\"\n if isspmatrix(matrix1) or isspmatrix(matrix2):\n return sparse_allclose(matrix1, matrix2)\n\n return np.allclose(matrix1, matrix2)": 2839, "def getFlaskResponse(responseString, httpStatus=200):\n \"\"\"\n Returns a Flask response object for the specified data and HTTP status.\n \"\"\"\n return flask.Response(responseString, status=httpStatus, mimetype=MIMETYPE)": 2840, "def fmt_sz(intval):\n \"\"\" Format a byte sized value.\n \"\"\"\n try:\n return fmt.human_size(intval)\n except (ValueError, TypeError):\n return \"N/A\".rjust(len(fmt.human_size(0)))": 2841, "def replace_nones(dict_or_list):\n \"\"\"Update a dict or list in place to replace\n 'none' string values with Python None.\"\"\"\n\n def replace_none_in_value(value):\n if isinstance(value, basestring) and value.lower() == \"none\":\n return None\n return value\n\n items = dict_or_list.iteritems() if isinstance(dict_or_list, dict) else enumerate(dict_or_list)\n\n for accessor, value in items:\n if isinstance(value, (dict, list)):\n replace_nones(value)\n else:\n dict_or_list[accessor] = replace_none_in_value(value)": 2842, "def isdir(self, path):\n \"\"\"Return true if the path refers to an existing directory.\n\n Parameters\n ----------\n path : str\n Path of directory on the remote side to check.\n \"\"\"\n result = True\n try:\n self.sftp_client.lstat(path)\n except FileNotFoundError:\n result = False\n\n return result": 2843, "def cartesian_lists(d):\n \"\"\"\n turns a dict of lists into a list of dicts that represents\n the cartesian product of the initial lists\n\n Example\n -------\n cartesian_lists({'a':[0, 2], 'b':[3, 4, 5]}\n returns\n [ {'a':0, 'b':3}, {'a':0, 'b':4}, ... {'a':2, 'b':5} ]\n\n \"\"\"\n return [{k: v for k, v in zip(d.keys(), args)}\n for args in itertools.product(*d.values())]": 2844, "def iiscgi(application):\n\t\"\"\"A specialized version of the reference WSGI-CGI server to adapt to Microsoft IIS quirks.\n\t\n\tThis is not a production quality interface and will behave badly under load.\n\t\"\"\"\n\ttry:\n\t\tfrom wsgiref.handlers import IISCGIHandler\n\texcept ImportError:\n\t\tprint(\"Python 3.2 or newer is required.\")\n\t\n\tif not __debug__:\n\t\twarnings.warn(\"Interactive debugging and other persistence-based processes will not work.\")\n\t\n\tIISCGIHandler().run(application)": 2845, "def arguments_as_dict(cls, *args, **kwargs):\n \"\"\"\n Generate the arguments dictionary provided to :py:meth:`generate_name` and :py:meth:`calculate_total_steps`.\n\n This makes it possible to fetch arguments by name regardless of\n whether they were passed as positional or keyword arguments. Unnamed\n positional arguments are provided as a tuple under the key ``pos``.\n \"\"\"\n all_args = (None, ) + args\n return inspect.getcallargs(cls.run, *all_args, **kwargs)": 2846, "def update(self, **kwargs):\n \"\"\"Creates or updates a property for the instance for each parameter.\"\"\"\n for key, value in kwargs.items():\n setattr(self, key, value)": 2847, "def hamming(s, t):\n \"\"\"\n Calculate the Hamming distance between two strings. From Wikipedia article: Iterative with two matrix rows.\n\n :param s: string 1\n :type s: str\n :param t: string 2\n :type s: str\n :return: Hamming distance\n :rtype: float\n \"\"\"\n if len(s) != len(t):\n raise ValueError('Hamming distance needs strings of equal length.')\n return sum(s_ != t_ for s_, t_ in zip(s, t))": 2848, "def get_free_mb(folder):\n \"\"\" Return folder/drive free space (in bytes)\n \"\"\"\n if platform.system() == 'Windows':\n free_bytes = ctypes.c_ulonglong(0)\n ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(folder), None, None, ctypes.pointer(free_bytes))\n return free_bytes.value/1024/1024\n else:\n st = os.statvfs(folder)\n return st.f_bavail * st.f_frsize/1024/1024": 2849, "def filtany(entities, **kw):\n \"\"\"Filter a set of entities based on method return. Use keyword arguments.\n \n Example:\n filtmeth(entities, id='123')\n filtmeth(entities, name='bart')\n\n Multiple filters are 'OR'.\n \"\"\"\n ret = set()\n for k,v in kw.items():\n for entity in entities:\n if getattr(entity, k)() == v:\n ret.add(entity)\n return ret": 2850, "def sine_wave(i, frequency=FREQUENCY, framerate=FRAMERATE, amplitude=AMPLITUDE):\n \"\"\"\n Returns value of a sine wave at a given frequency and framerate\n for a given sample i\n \"\"\"\n omega = 2.0 * pi * float(frequency)\n sine = sin(omega * (float(i) / float(framerate)))\n return float(amplitude) * sine": 2851, "def _cdf(self, xloc, dist, cache):\n \"\"\"Cumulative distribution function.\"\"\"\n return evaluation.evaluate_forward(dist, numpy.e**xloc, cache=cache)": 2852, "def manhattan(h1, h2): # # 7 us @array, 31 us @list \\w 100 bins\n r\"\"\"\n Equal to Minowski distance with :math:`p=1`.\n \n See also\n --------\n minowski\n \"\"\"\n h1, h2 = __prepare_histogram(h1, h2)\n return scipy.sum(scipy.absolute(h1 - h2))": 2853, "def data_from_techshop_ws(tws_url):\n \"\"\"Scrapes data from techshop.ws.\"\"\"\n\n r = requests.get(tws_url)\n if r.status_code == 200:\n data = BeautifulSoup(r.text, \"lxml\")\n else:\n data = \"There was an error while accessing data on techshop.ws.\"\n\n return data": 2854, "def deskew(S):\n \"\"\"Converts a skew-symmetric cross-product matrix to its corresponding\n vector. Only works for 3x3 matrices.\n\n Parameters\n ----------\n S : :obj:`numpy.ndarray` of float\n A 3x3 skew-symmetric matrix.\n\n Returns\n -------\n :obj:`numpy.ndarray` of float\n A 3-entry vector that corresponds to the given cross product matrix.\n \"\"\"\n x = np.zeros(3)\n x[0] = S[2,1]\n x[1] = S[0,2]\n x[2] = S[1,0]\n return x": 2855, "def get_distance_matrix(x):\n \"\"\"Get distance matrix given a matrix. Used in testing.\"\"\"\n square = nd.sum(x ** 2.0, axis=1, keepdims=True)\n distance_square = square + square.transpose() - (2.0 * nd.dot(x, x.transpose()))\n return nd.sqrt(distance_square)": 2856, "def _mean_absolute_error(y, y_pred, w):\n \"\"\"Calculate the mean absolute error.\"\"\"\n return np.average(np.abs(y_pred - y), weights=w)": 2857, "def dft(blk, freqs, normalize=True):\n \"\"\"\n Complex non-optimized Discrete Fourier Transform\n\n Finds the DFT for values in a given frequency list, in order, over the data\n block seen as periodic.\n\n Parameters\n ----------\n blk :\n An iterable with well-defined length. Don't use this function with Stream\n objects!\n freqs :\n List of frequencies to find the DFT, in rad/sample. FFT implementations\n like numpy.fft.ftt finds the coefficients for N frequencies equally\n spaced as ``line(N, 0, 2 * pi, finish=False)`` for N frequencies.\n normalize :\n If True (default), the coefficient sums are divided by ``len(blk)``,\n and the coefficient for the DC level (frequency equals to zero) is the\n mean of the block. If False, that coefficient would be the sum of the\n data in the block.\n\n Returns\n -------\n A list of DFT values for each frequency, in the same order that they appear\n in the freqs input.\n\n Note\n ----\n This isn't a FFT implementation, and performs :math:`O(M . N)` float\n pointing operations, with :math:`M` and :math:`N` equals to the length of\n the inputs. This function can find the DFT for any specific frequency, with\n no need for zero padding or finding all frequencies in a linearly spaced\n band grid with N frequency bins at once.\n\n \"\"\"\n dft_data = (sum(xn * cexp(-1j * n * f) for n, xn in enumerate(blk))\n for f in freqs)\n if normalize:\n lblk = len(blk)\n return [v / lblk for v in dft_data]\n return list(dft_data)": 2858, "def softmax(xs):\n \"\"\"Stable implementation of the softmax function.\"\"\"\n ys = xs - np.max(xs)\n exps = np.exp(ys)\n return exps / exps.sum(axis=0)": 2859, "def timestamp_filename(basename, ext=None):\n \"\"\"\n Return a string of the form [basename-TIMESTAMP.ext]\n where TIMESTAMP is of the form YYYYMMDD-HHMMSS-MILSEC\n \"\"\"\n dt = datetime.now().strftime('%Y%m%d-%H%M%S-%f')\n if ext:\n return '%s-%s.%s' % (basename, dt, ext)\n return '%s-%s' % (basename, dt)": 2860, "def random_id(length):\n \"\"\"Generates a random ID of given length\"\"\"\n\n def char():\n \"\"\"Generate single random char\"\"\"\n\n return random.choice(string.ascii_letters + string.digits)\n\n return \"\".join(char() for _ in range(length))": 2861, "def get_incomplete_path(filename):\n \"\"\"Returns a temporary filename based on filename.\"\"\"\n random_suffix = \"\".join(\n random.choice(string.ascii_uppercase + string.digits) for _ in range(6))\n return filename + \".incomplete\" + random_suffix": 2862, "def adjacency(tree):\n \"\"\"\n Construct the adjacency matrix of the tree\n :param tree:\n :return:\n \"\"\"\n dd = ids(tree)\n N = len(dd)\n A = np.zeros((N, N))\n\n def _adj(node):\n if np.isscalar(node):\n return\n elif isinstance(node, tuple) and len(node) == 2:\n A[dd[node], dd[node[0]]] = 1\n A[dd[node[0]], dd[node]] = 1\n _adj(node[0])\n\n A[dd[node], dd[node[1]]] = 1\n A[dd[node[1]], dd[node]] = 1\n _adj(node[1])\n\n _adj(tree)\n return A": 2863, "def generate_random_id(size=6, chars=string.ascii_uppercase + string.digits):\n \"\"\"Generate random id numbers.\"\"\"\n return \"\".join(random.choice(chars) for x in range(size))": 2864, "def nest(thing):\n \"\"\"Use tensorflows nest function if available, otherwise just wrap object in an array\"\"\"\n tfutil = util.get_module('tensorflow.python.util')\n if tfutil:\n return tfutil.nest.flatten(thing)\n else:\n return [thing]": 2865, "def get_ref_dict(self, schema):\n \"\"\"Method to create a dictionary containing a JSON reference to the\n schema in the spec\n \"\"\"\n schema_key = make_schema_key(schema)\n ref_schema = build_reference(\n \"schema\", self.openapi_version.major, self.refs[schema_key]\n )\n if getattr(schema, \"many\", False):\n return {\"type\": \"array\", \"items\": ref_schema}\n return ref_schema": 2866, "def text_response(self, contents, code=200, headers={}):\n \"\"\"shortcut to return simple plain/text messages in the response.\n\n :param contents: a string with the response contents\n :param code: the http status code\n :param headers: a dict with optional headers\n :returns: a :py:class:`flask.Response` with the ``text/plain`` **Content-Type** header.\n \"\"\"\n return Response(contents, status=code, headers={\n 'Content-Type': 'text/plain'\n })": 2867, "def make_name(estimator):\n \"\"\"Helper function that returns the name of estimator or the given string\n if a string is given\n \"\"\"\n if estimator is not None:\n if isinstance(estimator, six.string_types):\n estimator_name = estimator\n else:\n estimator_name = estimator.__class__.__name__\n else:\n estimator_name = None\n return estimator_name": 2868, "def OnContextMenu(self, event):\n \"\"\"Context menu event handler\"\"\"\n\n self.grid.PopupMenu(self.grid.contextmenu)\n\n event.Skip()": 2869, "def list_files(directory):\n \"\"\"Returns all files in a given directory\n \"\"\"\n return [f for f in pathlib.Path(directory).iterdir() if f.is_file() and not f.name.startswith('.')]": 2870, "def filter_query_string(query):\n \"\"\"\n Return a version of the query string with the _e, _k and _s values\n removed.\n \"\"\"\n return '&'.join([q for q in query.split('&')\n if not (q.startswith('_k=') or q.startswith('_e=') or q.startswith('_s'))])": 2871, "def unique_items(seq):\n \"\"\"Return the unique items from iterable *seq* (in order).\"\"\"\n seen = set()\n return [x for x in seq if not (x in seen or seen.add(x))]": 2872, "def adjust(cols, light):\n \"\"\"Create palette.\"\"\"\n raw_colors = [cols[0], *cols, \"#FFFFFF\",\n \"#000000\", *cols, \"#FFFFFF\"]\n\n return colors.generic_adjust(raw_colors, light)": 2873, "def median_date(dt_list):\n \"\"\"Calcuate median datetime from datetime list\n \"\"\"\n #dt_list_sort = sorted(dt_list)\n idx = len(dt_list)/2\n if len(dt_list) % 2 == 0:\n md = mean_date([dt_list[idx-1], dt_list[idx]])\n else:\n md = dt_list[idx]\n return md": 2874, "def RadiusGrid(gridSize):\n \"\"\"\n Return a square grid with values of the distance from the centre \n of the grid to each gridpoint\n \"\"\"\n x,y=np.mgrid[0:gridSize,0:gridSize]\n x = x-(gridSize-1.0)/2.0\n y = y-(gridSize-1.0)/2.0\n return np.abs(x+1j*y)": 2875, "def __absolute__(self, uri):\n \"\"\" Get the absolute uri for a file\n\n :param uri: URI of the resource to be retrieved\n :return: Absolute Path\n \"\"\"\n return op.abspath(op.join(self.__path__, uri))": 2876, "def autocorr_coeff(x, t, tau1, tau2):\n \"\"\"Calculate the autocorrelation coefficient.\"\"\"\n return corr_coeff(x, x, t, tau1, tau2)": 2877, "def paren_change(inputstring, opens=opens, closes=closes):\n \"\"\"Determine the parenthetical change of level (num closes - num opens).\"\"\"\n count = 0\n for c in inputstring:\n if c in opens: # open parens/brackets/braces\n count -= 1\n elif c in closes: # close parens/brackets/braces\n count += 1\n return count": 2878, "def count(data, axis=None):\n \"\"\"Count the number of non-NA in this array along the given axis or axes\n \"\"\"\n return np.sum(np.logical_not(isnull(data)), axis=axis)": 2879, "def string_to_list(string, sep=\",\", filter_empty=False):\n \"\"\"Transforma una string con elementos separados por `sep` en una lista.\"\"\"\n return [value.strip() for value in string.split(sep)\n if (not filter_empty or value)]": 2880, "def sparse_to_matrix(sparse):\n \"\"\"\n Take a sparse (n,3) list of integer indexes of filled cells,\n turn it into a dense (m,o,p) matrix.\n\n Parameters\n -----------\n sparse: (n,3) int, index of filled cells\n\n Returns\n ------------\n dense: (m,o,p) bool, matrix of filled cells\n \"\"\"\n\n sparse = np.asanyarray(sparse, dtype=np.int)\n if not util.is_shape(sparse, (-1, 3)):\n raise ValueError('sparse must be (n,3)!')\n\n shape = sparse.max(axis=0) + 1\n matrix = np.zeros(np.product(shape), dtype=np.bool)\n multiplier = np.array([np.product(shape[1:]), shape[2], 1])\n\n index = (sparse * multiplier).sum(axis=1)\n matrix[index] = True\n\n dense = matrix.reshape(shape)\n return dense": 2881, "def get_size(self):\n \"\"\"see doc in Term class\"\"\"\n self.curses.setupterm()\n return self.curses.tigetnum('cols'), self.curses.tigetnum('lines')": 2882, "def get_mouse_location(self):\n \"\"\"\n Get the current mouse location (coordinates and screen number).\n\n :return: a namedtuple with ``x``, ``y`` and ``screen_num`` fields\n \"\"\"\n x = ctypes.c_int(0)\n y = ctypes.c_int(0)\n screen_num = ctypes.c_int(0)\n _libxdo.xdo_get_mouse_location(\n self._xdo, ctypes.byref(x), ctypes.byref(y),\n ctypes.byref(screen_num))\n return mouse_location(x.value, y.value, screen_num.value)": 2883, "def write_property(fh, key, value):\n \"\"\"\n Write a single property to the file in Java properties format.\n\n :param fh: a writable file-like object\n :param key: the key to write\n :param value: the value to write\n \"\"\"\n if key is COMMENT:\n write_comment(fh, value)\n return\n\n _require_string(key, 'keys')\n _require_string(value, 'values')\n\n fh.write(_escape_key(key))\n fh.write(b'=')\n fh.write(_escape_value(value))\n fh.write(b'\\n')": 2884, "def get_current_branch():\n \"\"\"\n Return the current branch\n \"\"\"\n cmd = [\"git\", \"rev-parse\", \"--abbrev-ref\", \"HEAD\"]\n output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)\n return output.strip().decode(\"utf-8\")": 2885, "def _get_config_or_default(self, key, default, as_type=lambda x: x):\n \"\"\"Return a main config value, or default if it does not exist.\"\"\"\n\n if self.main_config.has_option(self.main_section, key):\n return as_type(self.main_config.get(self.main_section, key))\n return default": 2886, "def disable_stdout_buffering():\n \"\"\"This turns off stdout buffering so that outputs are immediately\n materialized and log messages show up before the program exits\"\"\"\n stdout_orig = sys.stdout\n sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)\n # NOTE(brandyn): This removes the original stdout\n return stdout_orig": 2887, "def remove_ext(fname):\n \"\"\"Removes the extension from a filename\n \"\"\"\n bn = os.path.basename(fname)\n return os.path.splitext(bn)[0]": 2888, "def uint8sc(im):\n \"\"\"Scale the image to uint8\n\n Parameters:\n -----------\n im: 2d array\n The image\n\n Returns:\n --------\n im: 2d array (dtype uint8)\n The scaled image to uint8\n \"\"\"\n im = np.asarray(im)\n immin = im.min()\n immax = im.max()\n imrange = immax - immin\n return cv2.convertScaleAbs(im - immin, alpha=255 / imrange)": 2889, "def qualified_name_import(cls):\n \"\"\"Full name of a class, including the module. Like qualified_class_name, but when you already have a class \"\"\"\n\n parts = qualified_name(cls).split('.')\n\n return \"from {} import {}\".format('.'.join(parts[:-1]), parts[-1])": 2890, "def server(self):\n \"\"\"Returns the size of remote files\n \"\"\"\n try:\n tar = urllib2.urlopen(self.registry)\n meta = tar.info()\n return int(meta.getheaders(\"Content-Length\")[0])\n except (urllib2.URLError, IndexError):\n return \" \"": 2891, "def cric__decision_tree():\n \"\"\" Decision Tree\n \"\"\"\n model = sklearn.tree.DecisionTreeClassifier(random_state=0, max_depth=4)\n\n # we want to explain the raw probability outputs of the trees\n model.predict = lambda X: model.predict_proba(X)[:,1]\n \n return model": 2892, "def get_properties(cls):\n \"\"\"Get all properties of the MessageFlags class.\"\"\"\n property_names = [p for p in dir(cls)\n if isinstance(getattr(cls, p), property)]\n return property_names": 2893, "def cleanup(self):\n \"\"\"Clean up any temporary files.\"\"\"\n for file in glob.glob(self.basename + '*'):\n os.unlink(file)": 2894, "def get_coordinates_by_full_name(self, name):\n \"\"\"Retrieves a person's coordinates by full name\"\"\"\n person = self.get_person_by_full_name(name)\n if not person:\n return '', ''\n return person.latitude, person.longitude": 2895, "def get_model(name):\n \"\"\"\n Convert a model's verbose name to the model class. This allows us to\n use the models verbose name in steps.\n \"\"\"\n\n model = MODELS.get(name.lower(), None)\n\n assert model, \"Could not locate model by name '%s'\" % name\n\n return model": 2896, "def get_month_start_date(self):\n \"\"\"Returns the first day of the current month\"\"\"\n now = timezone.now()\n return timezone.datetime(day=1, month=now.month, year=now.year, tzinfo=now.tzinfo)": 2897, "def get_propety_by_name(pif, name):\n \"\"\"Get a property by name\"\"\"\n warn(\"This method has been deprecated in favor of get_property_by_name\")\n return next((x for x in pif.properties if x.name == name), None)": 2898, "def update(self, params):\n \"\"\"Update the dev_info data from a dictionary.\n\n Only updates if it already exists in the device.\n \"\"\"\n dev_info = self.json_state.get('deviceInfo')\n dev_info.update({k: params[k] for k in params if dev_info.get(k)})": 2899, "def compare_dict(da, db):\n \"\"\"\n Compare differencs from two dicts\n \"\"\"\n sa = set(da.items())\n sb = set(db.items())\n \n diff = sa & sb\n return dict(sa - diff), dict(sb - diff)": 2900, "def _increase_file_handle_limit():\n \"\"\"Raise the open file handles permitted by the Dusty daemon process\n and its child processes. The number we choose here needs to be within\n the OS X default kernel hard limit, which is 10240.\"\"\"\n logging.info('Increasing file handle limit to {}'.format(constants.FILE_HANDLE_LIMIT))\n resource.setrlimit(resource.RLIMIT_NOFILE,\n (constants.FILE_HANDLE_LIMIT, resource.RLIM_INFINITY))": 2901, "def datetime_delta_to_ms(delta):\n \"\"\"\n Given a datetime.timedelta object, return the delta in milliseconds\n \"\"\"\n delta_ms = delta.days * 24 * 60 * 60 * 1000\n delta_ms += delta.seconds * 1000\n delta_ms += delta.microseconds / 1000\n delta_ms = int(delta_ms)\n return delta_ms": 2902, "def dt2ts(dt):\n \"\"\"Converts to float representing number of seconds since 1970-01-01 GMT.\"\"\"\n # Note: no assertion to really keep this fast\n assert isinstance(dt, (datetime.datetime, datetime.date))\n ret = time.mktime(dt.timetuple())\n if isinstance(dt, datetime.datetime):\n ret += 1e-6 * dt.microsecond\n return ret": 2903, "def Print(self):\n \"\"\"Prints the values and freqs/probs in ascending order.\"\"\"\n for val, prob in sorted(self.d.iteritems()):\n print(val, prob)": 2904, "def parse_env_var(s):\n \"\"\"Parse an environment variable string\n\n Returns a key-value tuple\n\n Apply the same logic as `docker run -e`:\n \"If the operator names an environment variable without specifying a value,\n then the current value of the named variable is propagated into the\n container's environment\n \"\"\"\n parts = s.split('=', 1)\n if len(parts) == 2:\n k, v = parts\n return (k, v)\n\n k = parts[0]\n return (k, os.getenv(k, ''))": 2905, "def get_user_id_from_email(self, email):\n \"\"\" Uses the get-all-user-accounts Portals API to retrieve the\n user-id by supplying an email. \"\"\"\n accts = self.get_all_user_accounts()\n\n for acct in accts:\n if acct['email'] == email:\n return acct['id']\n return None": 2906, "def process_bool_arg(arg):\n \"\"\" Determine True/False from argument \"\"\"\n if isinstance(arg, bool):\n return arg\n elif isinstance(arg, basestring):\n if arg.lower() in [\"true\", \"1\"]:\n return True\n elif arg.lower() in [\"false\", \"0\"]:\n return False": 2907, "def graph_from_dot_file(path):\n \"\"\"Load graph as defined by a DOT file.\n \n The file is assumed to be in DOT format. It will\n be loaded, parsed and a Dot class will be returned, \n representing the graph.\n \"\"\"\n \n fd = file(path, 'rb')\n data = fd.read()\n fd.close()\n \n return graph_from_dot_data(data)": 2908, "def getAttributeData(self, name, channel=None):\n \"\"\" Returns a attribut \"\"\"\n return self._getNodeData(name, self._ATTRIBUTENODE, channel)": 2909, "def __getLogger(cls):\n \"\"\" Get the logger for this object.\n\n :returns: (Logger) A Logger object.\n \"\"\"\n if cls.__logger is None:\n cls.__logger = opf_utils.initLogger(cls)\n return cls.__logger": 2910, "def depgraph_to_dotsrc(dep_graph, show_cycles, nodot, reverse):\n \"\"\"Convert the dependency graph (DepGraph class) to dot source code.\n \"\"\"\n if show_cycles:\n dotsrc = cycles2dot(dep_graph, reverse=reverse)\n elif not nodot:\n dotsrc = dep2dot(dep_graph, reverse=reverse)\n else:\n dotsrc = None\n return dotsrc": 2911, "def commit(self, message=None, amend=False, stage=True):\n \"\"\"Commit any changes, optionally staging all changes beforehand.\"\"\"\n return git_commit(self.repo_dir, message=message,\n amend=amend, stage=stage)": 2912, "def wrap(text, width=70, **kwargs):\n \"\"\"Wrap a single paragraph of text, returning a list of wrapped lines.\n\n Reformat the single paragraph in 'text' so it fits in lines of no\n more than 'width' columns, and return a list of wrapped lines. By\n default, tabs in 'text' are expanded with string.expandtabs(), and\n all other whitespace characters (including newline) are converted to\n space. See TextWrapper class for available keyword args to customize\n wrapping behaviour.\n \"\"\"\n w = TextWrapper(width=width, **kwargs)\n return w.wrap(text)": 2913, "def split_every(iterable, n): # TODO: Remove this, or make it return a generator.\n \"\"\"\n A generator of n-length chunks of an input iterable\n \"\"\"\n i = iter(iterable)\n piece = list(islice(i, n))\n while piece:\n yield piece\n piece = list(islice(i, n))": 2914, "def _read_group_h5(filename, groupname):\n \"\"\"Return group content.\n\n Args:\n filename (:class:`pathlib.Path`): path of hdf5 file.\n groupname (str): name of group to read.\n Returns:\n :class:`numpy.array`: content of group.\n \"\"\"\n with h5py.File(filename, 'r') as h5f:\n data = h5f[groupname][()]\n return data": 2915, "def Value(self, name):\n \"\"\"Returns the value coresponding to the given enum name.\"\"\"\n if name in self._enum_type.values_by_name:\n return self._enum_type.values_by_name[name].number\n raise ValueError('Enum %s has no value defined for name %s' % (\n self._enum_type.name, name))": 2916, "def async_comp_check(self, original, loc, tokens):\n \"\"\"Check for Python 3.6 async comprehension.\"\"\"\n return self.check_py(\"36\", \"async comprehension\", original, loc, tokens)": 2917, "def _size_36():\n \"\"\" returns the rows, columns of terminal \"\"\"\n from shutil import get_terminal_size\n dim = get_terminal_size()\n if isinstance(dim, list):\n return dim[0], dim[1]\n return dim.lines, dim.columns": 2918, "def fail(message=None, exit_status=None):\n \"\"\"Prints the specified message and exits the program with the specified\n exit status.\n\n \"\"\"\n print('Error:', message, file=sys.stderr)\n sys.exit(exit_status or 1)": 2919, "def _from_list_dict(cls, list_dic):\n \"\"\"Takes a list of dict like objects and uses `champ_id` field as Id\"\"\"\n return cls({_convert_id(dic[cls.CHAMP_ID]): dict(dic) for dic in list_dic})": 2920, "def get_filesize(self, pdf):\n \"\"\"Compute the filesize of the PDF\n \"\"\"\n try:\n filesize = float(pdf.get_size())\n return filesize / 1024\n except (POSKeyError, TypeError):\n return 0": 2921, "def parse(filename):\n \"\"\"Parse ASDL from the given file and return a Module node describing it.\"\"\"\n with open(filename) as f:\n parser = ASDLParser()\n return parser.parse(f.read())": 2922, "def set_timeout(scope, timeout):\n \"\"\"\n Defines the time after which Exscript fails if it does not receive a\n prompt from the remote host.\n\n :type timeout: int\n :param timeout: The timeout in seconds.\n \"\"\"\n conn = scope.get('__connection__')\n conn.set_timeout(int(timeout[0]))\n return True": 2923, "def send_file(self, local_path, remote_path, user='root', unix_mode=None):\n \"\"\"Upload a local file on the remote host.\n \"\"\"\n self.enable_user(user)\n return self.ssh_pool.send_file(user, local_path, remote_path, unix_mode=unix_mode)": 2924, "def _fill_array_from_list(the_list, the_array):\n \"\"\"Fill an `array` from a `list`\"\"\"\n for i, val in enumerate(the_list):\n the_array[i] = val\n return the_array": 2925, "def assign_to(self, obj):\n \"\"\"Assign `x` and `y` to an object that has properties `x` and `y`.\"\"\"\n obj.x = self.x\n obj.y = self.y": 2926, "def BROADCAST_FILTER_NOT(func):\n \"\"\"\n Composes the passed filters into an and-joined filter.\n \"\"\"\n return lambda u, command, *args, **kwargs: not func(u, command, *args, **kwargs)": 2927, "def filter_list_by_indices(lst, indices):\n \"\"\"Return a modified list containing only the indices indicated.\n\n Args:\n lst: Original list of values\n indices: List of indices to keep from the original list\n\n Returns:\n list: Filtered list of values\n\n \"\"\"\n return [x for i, x in enumerate(lst) if i in indices]": 2928, "def registered_filters_list(self):\n \"\"\"\n Return the list of registered filters (as a list of strings).\n\n The list **only** includes registered filters (**not** the predefined :program:`Jinja2` filters).\n\n \"\"\"\n return [filter_name for filter_name in self.__jinja2_environment.filters.keys() if filter_name not in self.__jinja2_predefined_filters ]": 2929, "def get_average_color(colors):\n \"\"\"Calculate the average color from the list of colors, where each color\n is a 3-tuple of (r, g, b) values.\n \"\"\"\n c = reduce(color_reducer, colors)\n total = len(colors)\n return tuple(v / total for v in c)": 2930, "def is_valid_file(parser, arg):\n \"\"\"Check if arg is a valid file that already exists on the file system.\"\"\"\n arg = os.path.abspath(arg)\n if not os.path.exists(arg):\n parser.error(\"The file %s does not exist!\" % arg)\n else:\n return arg": 2931, "def user_exists(username):\n \"\"\"Check if a user exists\"\"\"\n try:\n pwd.getpwnam(username)\n user_exists = True\n except KeyError:\n user_exists = False\n return user_exists": 2932, "def clear(self):\n \"\"\"Remove all items.\"\"\"\n self._fwdm.clear()\n self._invm.clear()\n self._sntl.nxt = self._sntl.prv = self._sntl": 2933, "def get_months_apart(d1, d2):\n \"\"\"\n Get amount of months between dates\n http://stackoverflow.com/a/4040338\n \"\"\"\n\n return (d1.year - d2.year)*12 + d1.month - d2.month": 2934, "def Gaussian(x, a, x0, sigma, y0):\n \"\"\"Gaussian peak\n\n Inputs:\n -------\n ``x``: independent variable\n ``a``: scaling factor (extremal value)\n ``x0``: center\n ``sigma``: half width at half maximum\n ``y0``: additive constant\n\n Formula:\n --------\n ``a*exp(-(x-x0)^2)/(2*sigma^2)+y0``\n \"\"\"\n return a * np.exp(-(x - x0) ** 2 / (2 * sigma ** 2)) + y0": 2935, "def _increment(self, *args):\n \"\"\"Move the slider only by increment given by resolution.\"\"\"\n value = self._var.get()\n if self._resolution:\n value = self._start + int(round((value - self._start) / self._resolution)) * self._resolution\n self._var.set(value)\n self.display_value(value)": 2936, "def clear(self):\n \"\"\"Clear the displayed image.\"\"\"\n self._imgobj = None\n try:\n # See if there is an image on the canvas\n self.canvas.delete_object_by_tag(self._canvas_img_tag)\n self.redraw()\n except KeyError:\n pass": 2937, "def make_2d(ary):\n \"\"\"Convert any array into a 2d numpy array.\n\n In case the array is already more than 2 dimensional, will ravel the\n dimensions after the first.\n \"\"\"\n dim_0, *_ = np.atleast_1d(ary).shape\n return ary.reshape(dim_0, -1, order=\"F\")": 2938, "def is_executable(path):\n \"\"\"Returns whether a path names an existing executable file.\"\"\"\n return os.path.isfile(path) and os.access(path, os.X_OK)": 2939, "def run (self):\n \"\"\"Handle keyboard interrupt and other errors.\"\"\"\n try:\n self.run_checked()\n except KeyboardInterrupt:\n thread.interrupt_main()\n except Exception:\n self.internal_error()": 2940, "def callPlaybook(self, playbook, ansibleArgs, wait=True, tags=[\"all\"]):\n \"\"\"\n Run a playbook.\n\n :param playbook: An Ansible playbook to run.\n :param ansibleArgs: Arguments to pass to the playbook.\n :param wait: Wait for the play to finish if true.\n :param tags: Control tags for the play.\n \"\"\"\n playbook = os.path.join(self.playbooks, playbook) # Path to playbook being executed\n verbosity = \"-vvvvv\" if logger.isEnabledFor(logging.DEBUG) else \"-v\"\n command = [\"ansible-playbook\", verbosity, \"--tags\", \",\".join(tags), \"--extra-vars\"]\n command.append(\" \".join([\"=\".join(i) for i in ansibleArgs.items()])) # Arguments being passed to playbook\n command.append(playbook)\n\n logger.debug(\"Executing Ansible call `%s`\", \" \".join(command))\n p = subprocess.Popen(command)\n if wait:\n p.communicate()\n if p.returncode != 0:\n # FIXME: parse error codes\n raise RuntimeError(\"Ansible reported an error when executing playbook %s\" % playbook)": 2941, "def wait_until_exit(self):\n \"\"\" Wait until all the threads are finished.\n\n \"\"\"\n [t.join() for t in self.threads]\n\n self.threads = list()": 2942, "def cleanup_storage(*args):\n \"\"\"Clean up processes after SIGTERM or SIGINT is received.\"\"\"\n ShardedClusters().cleanup()\n ReplicaSets().cleanup()\n Servers().cleanup()\n sys.exit(0)": 2943, "def get_csrf_token(response):\n \"\"\"\n Extract the CSRF token out of the \"Set-Cookie\" header of a response.\n \"\"\"\n cookie_headers = [\n h.decode('ascii') for h in response.headers.getlist(\"Set-Cookie\")\n ]\n if not cookie_headers:\n return None\n csrf_headers = [\n h for h in cookie_headers if h.startswith(\"csrftoken=\")\n ]\n if not csrf_headers:\n return None\n match = re.match(\"csrftoken=([^ ;]+);\", csrf_headers[-1])\n return match.group(1)": 2944, "def exception_format():\n \"\"\"\n Convert exception info into a string suitable for display.\n \"\"\"\n return \"\".join(traceback.format_exception(\n sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]\n ))": 2945, "def ttl(self):\n \"\"\"how long you should cache results for cacheable queries\"\"\"\n ret = 3600\n cn = self.get_process()\n if \"ttl\" in cn:\n ret = cn[\"ttl\"]\n return ret": 2946, "def move_back(self, dt):\n \"\"\" If called after an update, the sprite can move back\n \"\"\"\n self._position = self._old_position\n self.rect.topleft = self._position\n self.feet.midbottom = self.rect.midbottom": 2947, "def is_empty(self):\n \"\"\"Checks for an empty image.\n \"\"\"\n if(((self.channels == []) and (not self.shape == (0, 0))) or\n ((not self.channels == []) and (self.shape == (0, 0)))):\n raise RuntimeError(\"Channels-shape mismatch.\")\n return self.channels == [] and self.shape == (0, 0)": 2948, "def update_not_existing_kwargs(to_update, update_from):\n \"\"\"\n This function updates the keyword aguments from update_from in\n to_update, only if the keys are not set in to_update.\n\n This is used for updated kwargs from the default dicts.\n \"\"\"\n if to_update is None:\n to_update = {}\n to_update.update({k:v for k,v in update_from.items() if k not in to_update})\n return to_update": 2949, "def insert_slash(string, every=2):\n \"\"\"insert_slash insert / every 2 char\"\"\"\n return os.path.join(string[i:i+every] for i in xrange(0, len(string), every))": 2950, "def circles_pycairo(width, height, color):\n \"\"\" Implementation of circle border with PyCairo. \"\"\"\n\n cairo_color = color / rgb(255, 255, 255)\n\n surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)\n ctx = cairo.Context(surface)\n\n # draw a circle in the center\n ctx.new_path()\n ctx.set_source_rgb(cairo_color.red, cairo_color.green, cairo_color.blue)\n ctx.arc(width / 2, height / 2, width / 2, 0, 2 * pi)\n ctx.fill()\n\n surface.write_to_png('circles.png')": 2951, "def combinations(l):\n \"\"\"Pure-Python implementation of itertools.combinations(l, 2).\"\"\"\n result = []\n for x in xrange(len(l) - 1):\n ls = l[x + 1:]\n for y in ls:\n result.append((l[x], y))\n return result": 2952, "def _get_history_next(self):\n \"\"\" callback function for key down \"\"\"\n if self._has_history:\n ret = self._input_history.return_history(1)\n self.string = ret\n self._curs_pos = len(ret)": 2953, "def set_user_password(environment, parameter, password):\n \"\"\"\n Sets a user's password in the keyring storage\n \"\"\"\n username = '%s:%s' % (environment, parameter)\n return password_set(username, password)": 2954, "def R_rot_3d(th):\n \"\"\"Return a 3-dimensional rotation matrix.\n\n Parameters\n ----------\n th: array, shape (n, 3)\n Angles about which to rotate along each axis.\n\n Returns\n -------\n R: array, shape (n, 3, 3)\n \"\"\"\n sx, sy, sz = np.sin(th).T\n cx, cy, cz = np.cos(th).T\n R = np.empty((len(th), 3, 3), dtype=np.float)\n\n R[:, 0, 0] = cy * cz\n R[:, 0, 1] = -cy * sz\n R[:, 0, 2] = sy\n\n R[:, 1, 0] = sx * sy * cz + cx * sz\n R[:, 1, 1] = -sx * sy * sz + cx * cz\n R[:, 1, 2] = -sx * cy\n\n R[:, 2, 0] = -cx * sy * cz + sx * sz\n R[:, 2, 1] = cx * sy * sz + sx * cz\n R[:, 2, 2] = cx * cy\n return R": 2955, "def read_dict_from_file(file_path):\n \"\"\"\n Read a dictionary of strings from a file\n \"\"\"\n with open(file_path) as file:\n lines = file.read().splitlines()\n\n obj = {}\n for line in lines:\n key, value = line.split(':', maxsplit=1)\n obj[key] = eval(value)\n\n return obj": 2956, "def calc_list_average(l):\n \"\"\"\n Calculates the average value of a list of numbers\n Returns a float\n \"\"\"\n total = 0.0\n for value in l:\n total += value\n return total / len(l)": 2957, "def do_rewind(self, line):\n \"\"\"\n rewind\n \"\"\"\n self.print_response(\"Rewinding from frame %s to 0\" % self.bot._frame)\n self.bot._frame = 0": 2958, "def _file_exists(path, filename):\n \"\"\"Checks if the filename exists under the path.\"\"\"\n return os.path.isfile(os.path.join(path, filename))": 2959, "def unproject(self, xy):\n \"\"\"\n Returns the coordinates from position in meters\n \"\"\"\n (x, y) = xy\n lng = x/EARTH_RADIUS * RAD_TO_DEG\n lat = 2 * atan(exp(y/EARTH_RADIUS)) - pi/2 * RAD_TO_DEG\n return (lng, lat)": 2960, "def _cosine(a, b):\n \"\"\" Return the len(a & b) / len(a) \"\"\"\n return 1. * len(a & b) / (math.sqrt(len(a)) * math.sqrt(len(b)))": 2961, "def count(self, X):\n \"\"\"\n Called from the fit method, this method gets all the\n words from the corpus and their corresponding frequency\n counts.\n\n Parameters\n ----------\n\n X : ndarray or masked ndarray\n Pass in the matrix of vectorized documents, can be masked in\n order to sum the word frequencies for only a subset of documents.\n\n Returns\n -------\n\n counts : array\n A vector containing the counts of all words in X (columns)\n\n \"\"\"\n # Sum on axis 0 (by columns), each column is a word\n # Convert the matrix to an array\n # Squeeze to remove the 1 dimension objects (like ravel)\n return np.squeeze(np.asarray(X.sum(axis=0)))": 2962, "def get_current_frames():\n \"\"\"Return current threads prepared for \n further processing.\n \"\"\"\n return dict(\n (thread_id, {'frame': thread2list(frame), 'time': None})\n for thread_id, frame in sys._current_frames().items()\n )": 2963, "def _replace_none(self, aDict):\n \"\"\" Replace all None values in a dict with 'none' \"\"\"\n for k, v in aDict.items():\n if v is None:\n aDict[k] = 'none'": 2964, "def _get_image_numpy_dtype(self):\n \"\"\"\n Get the numpy dtype for the image\n \"\"\"\n try:\n ftype = self._info['img_equiv_type']\n npy_type = _image_bitpix2npy[ftype]\n except KeyError:\n raise KeyError(\"unsupported fits data type: %d\" % ftype)\n\n return npy_type": 2965, "def _get_item_position(self, idx):\n \"\"\"Return a tuple of (start, end) indices of an item from its index.\"\"\"\n start = 0 if idx == 0 else self._index[idx - 1] + 1\n end = self._index[idx]\n return start, end": 2966, "def warn(self, text):\n\t\t\"\"\" Ajout d'un message de log de type WARN \"\"\"\n\t\tself.logger.warn(\"{}{}\".format(self.message_prefix, text))": 2967, "def get_model_index_properties(instance, index):\n \"\"\"Return the list of properties specified for a model in an index.\"\"\"\n mapping = get_index_mapping(index)\n doc_type = instance._meta.model_name.lower()\n return list(mapping[\"mappings\"][doc_type][\"properties\"].keys())": 2968, "def copy(self):\n \"\"\"Return a copy of this list with each element copied to new memory\n \"\"\"\n out = type(self)()\n for series in self:\n out.append(series.copy())\n return out": 2969, "def markdown_to_text(body):\n \"\"\"Converts markdown to text.\n\n Args:\n body: markdown (or plaintext, or maybe HTML) input\n\n Returns:\n Plaintext with all tags and frills removed\n \"\"\"\n # Turn our input into HTML\n md = markdown.markdown(body, extensions=[\n 'markdown.extensions.extra'\n ])\n\n # Safely parse HTML so that we don't have to parse it ourselves\n soup = BeautifulSoup(md, 'html.parser')\n\n # Return just the text of the parsed HTML\n return soup.get_text()": 2970, "def HttpResponse401(request, template=KEY_AUTH_401_TEMPLATE,\ncontent=KEY_AUTH_401_CONTENT, content_type=KEY_AUTH_401_CONTENT_TYPE):\n \"\"\"\n HTTP response for not-authorized access (status code 403)\n \"\"\"\n return AccessFailedResponse(request, template, content, content_type, status=401)": 2971, "def objectproxy_realaddress(obj):\n \"\"\"\n Obtain a real address as an integer from an objectproxy.\n \"\"\"\n voidp = QROOT.TPython.ObjectProxy_AsVoidPtr(obj)\n return C.addressof(C.c_char.from_buffer(voidp))": 2972, "def GetMountpoints():\n \"\"\"List all the filesystems mounted on the system.\"\"\"\n devices = {}\n\n for filesys in GetFileSystems():\n devices[filesys.f_mntonname] = (filesys.f_mntfromname, filesys.f_fstypename)\n\n return devices": 2973, "def _GetValue(self, name):\n \"\"\"Returns the TextFSMValue object natching the requested name.\"\"\"\n for value in self.values:\n if value.name == name:\n return value": 2974, "def owner(self):\n \"\"\"\n Username of document creator\n \"\"\"\n if self._owner:\n return self._owner\n elif not self.abstract:\n return self.read_meta()._owner\n\n raise EmptyDocumentException()": 2975, "def is_iterable(value):\n \"\"\"must be an iterable (list, array, tuple)\"\"\"\n return isinstance(value, np.ndarray) or isinstance(value, list) or isinstance(value, tuple), value": 2976, "def leaf_nodes(self):\n \"\"\"\n Return an interable of nodes with no edges pointing at them. This is\n helpful to find all nodes without dependencies.\n \"\"\"\n # Now contains all nodes that contain dependencies.\n deps = {item for sublist in self.edges.values() for item in sublist}\n # contains all nodes *without* any dependencies (leaf nodes)\n return self.nodes - deps": 2977, "def check_color(cls, raw_image):\n \"\"\"\n Just check if raw_image is completely white.\n http://stackoverflow.com/questions/14041562/python-pil-detect-if-an-image-is-completely-black-or-white\n \"\"\"\n # sum(img.convert(\"L\").getextrema()) in (0, 2)\n extrema = raw_image.convert(\"L\").getextrema()\n if extrema == (255, 255): # all white\n raise cls.MonoImageException": 2978, "def findMin(arr):\n \"\"\"\n in comparison to argrelmax() more simple and reliable peak finder\n \"\"\"\n out = np.zeros(shape=arr.shape, dtype=bool)\n _calcMin(arr, out)\n return out": 2979, "def get_property(self, property_name):\n \"\"\"\n Get a property's value.\n\n property_name -- the property to get the value of\n\n Returns the properties value, if found, else None.\n \"\"\"\n prop = self.find_property(property_name)\n if prop:\n return prop.get_value()\n\n return None": 2980, "def byte2int(s, index=0):\n \"\"\"Get the ASCII int value of a character in a string.\n\n :param s: a string\n :param index: the position of desired character\n\n :return: ASCII int value\n \"\"\"\n if six.PY2:\n return ord(s[index])\n return s[index]": 2981, "def indent(text, amount, ch=' '):\n \"\"\"Indents a string by the given amount of characters.\"\"\"\n padding = amount * ch\n return ''.join(padding+line for line in text.splitlines(True))": 2982, "def _get_minidom_tag_value(station, tag_name):\n \"\"\"get a value from a tag (if it exists)\"\"\"\n tag = station.getElementsByTagName(tag_name)[0].firstChild\n if tag:\n return tag.nodeValue\n\n return None": 2983, "def interpolate_slice(slice_rows, slice_cols, interpolator):\n \"\"\"Interpolate the given slice of the larger array.\"\"\"\n fine_rows = np.arange(slice_rows.start, slice_rows.stop, slice_rows.step)\n fine_cols = np.arange(slice_cols.start, slice_cols.stop, slice_cols.step)\n return interpolator(fine_cols, fine_rows)": 2984, "def _getVirtualScreenRect(self):\n \"\"\" The virtual screen is the bounding box containing all monitors.\n\n Not all regions in the virtual screen are actually visible. The (0,0) coordinate\n is the top left corner of the primary screen rather than the whole bounding box, so\n some regions of the virtual screen may have negative coordinates if another screen\n is positioned in Windows as further to the left or above the primary screen.\n\n Returns the rect as (x, y, w, h)\n \"\"\"\n SM_XVIRTUALSCREEN = 76 # Left of virtual screen\n SM_YVIRTUALSCREEN = 77 # Top of virtual screen\n SM_CXVIRTUALSCREEN = 78 # Width of virtual screen\n SM_CYVIRTUALSCREEN = 79 # Height of virtual screen\n\n return (self._user32.GetSystemMetrics(SM_XVIRTUALSCREEN), \\\n self._user32.GetSystemMetrics(SM_YVIRTUALSCREEN), \\\n self._user32.GetSystemMetrics(SM_CXVIRTUALSCREEN), \\\n self._user32.GetSystemMetrics(SM_CYVIRTUALSCREEN))": 2985, "def resample(grid, wl, flux):\n \"\"\" Resample spectrum onto desired grid \"\"\"\n flux_rs = (interpolate.interp1d(wl, flux))(grid)\n return flux_rs": 2986, "def pythonise(id, encoding='ascii'):\n \"\"\"Return a Python-friendly id\"\"\"\n replace = {'-': '_', ':': '_', '/': '_'}\n func = lambda id, pair: id.replace(pair[0], pair[1])\n id = reduce(func, replace.iteritems(), id)\n id = '_%s' % id if id[0] in string.digits else id\n return id.encode(encoding)": 2987, "def getEventTypeNameFromEnum(self, eType):\n \"\"\"returns the name of an EVREvent enum value\"\"\"\n\n fn = self.function_table.getEventTypeNameFromEnum\n result = fn(eType)\n return result": 2988, "def bbox(img):\n \"\"\"Find the bounding box around nonzero elements in the given array\n\n Copied from https://stackoverflow.com/a/31402351/5703449 .\n\n Returns:\n rowmin, rowmax, colmin, colmax\n \"\"\"\n rows = np.any(img, axis=1)\n cols = np.any(img, axis=0)\n rmin, rmax = np.where(rows)[0][[0, -1]]\n cmin, cmax = np.where(cols)[0][[0, -1]]\n\n return rmin, rmax, cmin, cmax": 2989, "def query_proc_row(procname, args=(), factory=None):\n \"\"\"\n Execute a stored procedure. Returns the first row of the result set,\n or `None`.\n \"\"\"\n for row in query_proc(procname, args, factory):\n return row\n return None": 2990, "def hex_escape(bin_str):\n \"\"\"\n Hex encode a binary string\n \"\"\"\n printable = string.ascii_letters + string.digits + string.punctuation + ' '\n return ''.join(ch if ch in printable else r'0x{0:02x}'.format(ord(ch)) for ch in bin_str)": 2991, "def get_files(dir_name):\n \"\"\"Simple directory walker\"\"\"\n return [(os.path.join('.', d), [os.path.join(d, f) for f in files]) for d, _, files in os.walk(dir_name)]": 2992, "def get_highlighted_code(name, code, type='terminal'):\n \"\"\"\n If pygments are available on the system\n then returned output is colored. Otherwise\n unchanged content is returned.\n \"\"\"\n import logging\n try:\n import pygments\n pygments\n except ImportError:\n return code\n from pygments import highlight\n from pygments.lexers import guess_lexer_for_filename, ClassNotFound\n from pygments.formatters import TerminalFormatter\n\n try:\n lexer = guess_lexer_for_filename(name, code)\n formatter = TerminalFormatter()\n content = highlight(code, lexer, formatter)\n except ClassNotFound:\n logging.debug(\"Couldn't guess Lexer, will not use pygments.\")\n content = code\n return content": 2993, "def pretty_xml(data):\n \"\"\"Return a pretty formated xml\n \"\"\"\n parsed_string = minidom.parseString(data.decode('utf-8'))\n return parsed_string.toprettyxml(indent='\\t', encoding='utf-8')": 2994, "def get_chunks(source, chunk_len):\n \"\"\" Returns an iterator over 'chunk_len' chunks of 'source' \"\"\"\n return (source[i: i + chunk_len] for i in range(0, len(source), chunk_len))": 2995, "def prepare_path(path):\n \"\"\"\n Path join helper method\n Join paths if list passed\n\n :type path: str|unicode|list\n :rtype: str|unicode\n \"\"\"\n if type(path) == list:\n return os.path.join(*path)\n return path": 2996, "def is_valid_data(obj):\n \"\"\"Check if data is JSON serializable.\n \"\"\"\n if obj:\n try:\n tmp = json.dumps(obj, default=datetime_encoder)\n del tmp\n except (TypeError, UnicodeDecodeError):\n return False\n return True": 2997, "def _deserialize_datetime(self, data):\n \"\"\"Take any values coming in as a datetime and deserialize them\n\n \"\"\"\n for key in data:\n if isinstance(data[key], dict):\n if data[key].get('type') == 'datetime':\n data[key] = \\\n datetime.datetime.fromtimestamp(data[key]['value'])\n return data": 2998, "def set_float(val):\n \"\"\" utility to set a floating value,\n useful for converting from strings \"\"\"\n out = None\n if not val in (None, ''):\n try:\n out = float(val)\n except ValueError:\n return None\n if numpy.isnan(out):\n out = default\n return out": 2999, "def parse_list(cls, api, json_list):\n \"\"\"\n Parse a list of JSON objects into\n a result set of model instances.\n \"\"\"\n results = []\n for json_obj in json_list:\n if json_obj:\n obj = cls.parse(api, json_obj)\n results.append(obj)\n\n return results": 3000, "def test():\n \"\"\"Test program for telnetlib.\n\n Usage: python telnetlib.py [-d] ... [host [port]]\n\n Default host is localhost; default port is 23.\n\n \"\"\"\n debuglevel = 0\n while sys.argv[1:] and sys.argv[1] == '-d':\n debuglevel = debuglevel + 1\n del sys.argv[1]\n host = 'localhost'\n if sys.argv[1:]:\n host = sys.argv[1]\n port = 0\n if sys.argv[2:]:\n portstr = sys.argv[2]\n try:\n port = int(portstr)\n except ValueError:\n port = socket.getservbyname(portstr, 'tcp')\n tn = Telnet()\n tn.set_debuglevel(debuglevel)\n tn.open(host, port)\n tn.interact()\n tn.close()": 3001, "def with_headers(self, headers):\n \"\"\"Sets multiple headers on the request and returns the request itself.\n\n Keyword arguments:\n headers -- a dict-like object which contains the headers to set.\n \"\"\"\n for key, value in headers.items():\n self.with_header(key, value)\n return self": 3002, "def normalize_matrix(matrix):\n \"\"\"Fold all values of the matrix into [0, 1].\"\"\"\n abs_matrix = np.abs(matrix.copy())\n return abs_matrix / abs_matrix.max()": 3003, "def process_result_value(self, value, dialect):\n \"\"\"convert value from json to a python object\"\"\"\n if value is not None:\n value = simplejson.loads(value)\n return value": 3004, "def lmx_h1k_f64k():\n \"\"\"HParams for training languagemodel_lm1b32k_packed. 880M Params.\"\"\"\n hparams = lmx_base()\n hparams.hidden_size = 1024\n hparams.filter_size = 65536\n hparams.batch_size = 2048\n return hparams": 3005, "def extend(self, item):\n \"\"\"Extend the list with another list. Each member of the list must be\n a string.\"\"\"\n if not isinstance(item, list):\n raise TypeError(\n 'You can only extend lists with lists. '\n 'You supplied \\\"%s\\\"' % type(item))\n for entry in item:\n if not isinstance(entry, str):\n raise TypeError(\n 'Members of this object must be strings. '\n 'You supplied \\\"%s\\\"' % type(entry))\n list.append(self, entry)": 3006, "def prettifysql(sql):\n \"\"\"Returns a prettified version of the SQL as a list of lines to help\n in creating a useful diff between two SQL statements.\"\"\"\n pretty = []\n for line in sql.split('\\n'):\n pretty.extend([\"%s,\\n\" % x for x in line.split(',')])\n return pretty": 3007, "def print_datetime_object(dt):\n \"\"\"prints a date-object\"\"\"\n print(dt)\n print('ctime :', dt.ctime())\n print('tuple :', dt.timetuple())\n print('ordinal:', dt.toordinal())\n print('Year :', dt.year)\n print('Mon :', dt.month)\n print('Day :', dt.day)": 3008, "def str_time_to_day_seconds(time):\n \"\"\"\n Converts time strings to integer seconds\n :param time: %H:%M:%S string\n :return: integer seconds\n \"\"\"\n t = str(time).split(':')\n seconds = int(t[0]) * 3600 + int(t[1]) * 60 + int(t[2])\n return seconds": 3009, "def _first_and_last_element(arr):\n \"\"\"Returns first and last element of numpy array or sparse matrix.\"\"\"\n if isinstance(arr, np.ndarray) or hasattr(arr, 'data'):\n # numpy array or sparse matrix with .data attribute\n data = arr.data if sparse.issparse(arr) else arr\n return data.flat[0], data.flat[-1]\n else:\n # Sparse matrices without .data attribute. Only dok_matrix at\n # the time of writing, in this case indexing is fast\n return arr[0, 0], arr[-1, -1]": 3010, "def load(cls, fname):\n \"\"\" Loads the dictionary from json file\n :param fname: file to load from\n :return: loaded dictionary\n \"\"\"\n with open(fname) as f:\n return Config(**json.load(f))": 3011, "def show_correlation_matrix(self, correlation_matrix):\n \"\"\"Shows the given correlation matrix as image\n\n :param correlation_matrix: Correlation matrix of features\n \"\"\"\n cr_plot.create_correlation_matrix_plot(\n correlation_matrix, self.title, self.headers_to_test\n )\n pyplot.show()": 3012, "def load(path):\n \"\"\"Loads a pushdb maintained in a properties file at the given path.\"\"\"\n with open(path, 'r') as props:\n properties = Properties.load(props)\n return PushDb(properties)": 3013, "def get_height_for_line(self, lineno):\n \"\"\"\n Return the height of the given line.\n (The height that it would take, if this line became visible.)\n \"\"\"\n if self.wrap_lines:\n return self.ui_content.get_height_for_line(lineno, self.window_width)\n else:\n return 1": 3014, "def load(filename):\n \"\"\"Load a pickled obj from the filesystem.\n\n You better know what you expect from the given pickle, because we don't check it.\n\n Args:\n filename (str): The filename we load the object from.\n\n Returns:\n The object we were able to unpickle, else None.\n \"\"\"\n if not os.path.exists(filename):\n LOG.error(\"load object - File '%s' does not exist.\", filename)\n return None\n\n obj = None\n with open(filename, 'rb') as obj_file:\n obj = dill.load(obj_file)\n return obj": 3015, "def toggle_word_wrap(self):\n \"\"\"\n Toggles document word wrap.\n\n :return: Method success.\n :rtype: bool\n \"\"\"\n\n self.setWordWrapMode(not self.wordWrapMode() and QTextOption.WordWrap or QTextOption.NoWrap)\n return True": 3016, "async def load_unicode(reader):\n \"\"\"\n Loads UTF8 string\n :param reader:\n :return:\n \"\"\"\n ivalue = await load_uvarint(reader)\n fvalue = bytearray(ivalue)\n await reader.areadinto(fvalue)\n return str(fvalue, 'utf8')": 3017, "def _openResources(self):\n \"\"\" Uses numpy.load to open the underlying file\n \"\"\"\n arr = np.load(self._fileName, allow_pickle=ALLOW_PICKLE)\n check_is_an_array(arr)\n self._array = arr": 3018, "def load(self, path):\n \"\"\"Load the pickled model weights.\"\"\"\n with io.open(path, 'rb') as fin:\n self.weights = pickle.load(fin)": 3019, "def _IsDirectory(parent, item):\n \"\"\"Helper that returns if parent/item is a directory.\"\"\"\n return tf.io.gfile.isdir(os.path.join(parent, item))": 3020, "def elem_find(self, field, value):\n \"\"\"\n Return the indices of elements whose field first satisfies the given values\n\n ``value`` should be unique in self.field.\n This function does not check the uniqueness.\n\n :param field: name of the supplied field\n :param value: value of field of the elemtn to find\n :return: idx of the elements\n :rtype: list, int, float, str\n \"\"\"\n if isinstance(value, (int, float, str)):\n value = [value]\n\n f = list(self.__dict__[field])\n uid = np.vectorize(f.index)(value)\n return self.get_idx(uid)": 3021, "def camel_case(self, snake_case):\n \"\"\" Convert snake case to camel case \"\"\"\n components = snake_case.split('_')\n return components[0] + \"\".join(x.title() for x in components[1:])": 3022, "def simple_memoize(callable_object):\n \"\"\"Simple memoization for functions without keyword arguments.\n\n This is useful for mapping code objects to module in this context.\n inspect.getmodule() requires a number of system calls, which may slow down\n the tracing considerably. Caching the mapping from code objects (there is\n *one* code object for each function, regardless of how many simultaneous\n activations records there are).\n\n In this context we can ignore keyword arguments, but a generic memoizer\n ought to take care of that as well.\n \"\"\"\n\n cache = dict()\n\n def wrapper(*rest):\n if rest not in cache:\n cache[rest] = callable_object(*rest)\n return cache[rest]\n\n return wrapper": 3023, "def buttonUp(self, button=mouse.LEFT):\n \"\"\" Releases the specified mouse button.\n\n Use Mouse.LEFT, Mouse.MIDDLE, Mouse.RIGHT\n \"\"\"\n self._lock.acquire()\n mouse.release(button)\n self._lock.release()": 3024, "def moving_average(array, n=3):\n \"\"\"\n Calculates the moving average of an array.\n\n Parameters\n ----------\n array : array\n The array to have the moving average taken of\n n : int\n The number of points of moving average to take\n \n Returns\n -------\n MovingAverageArray : array\n The n-point moving average of the input array\n \"\"\"\n ret = _np.cumsum(array, dtype=float)\n ret[n:] = ret[n:] - ret[:-n]\n return ret[n - 1:] / n": 3025, "def make_stream_handler(graph, formatter):\n \"\"\"\n Create the stream handler. Used for console/debug output.\n\n \"\"\"\n return {\n \"class\": graph.config.logging.stream_handler.class_,\n \"formatter\": formatter,\n \"level\": graph.config.logging.level,\n \"stream\": graph.config.logging.stream_handler.stream,\n }": 3026, "def GetLoggingLocation():\n \"\"\"Search for and return the file and line number from the log collector.\n\n Returns:\n (pathname, lineno, func_name) The full path, line number, and function name\n for the logpoint location.\n \"\"\"\n frame = inspect.currentframe()\n this_file = frame.f_code.co_filename\n frame = frame.f_back\n while frame:\n if this_file == frame.f_code.co_filename:\n if 'cdbg_logging_location' in frame.f_locals:\n ret = frame.f_locals['cdbg_logging_location']\n if len(ret) != 3:\n return (None, None, None)\n return ret\n frame = frame.f_back\n return (None, None, None)": 3027, "def _set_axis_limits(self, which, lims, d, scale, reverse=False):\n \"\"\"Private method for setting axis limits.\n\n Sets the axis limits on each axis for an individual plot.\n\n Args:\n which (str): The indicator of which part of the plots\n to adjust. This currently handles `x` and `y`.\n lims (len-2 list of floats): The limits for the axis.\n d (float): Amount to increment by between the limits.\n scale (str): Scale of the axis. Either `log` or `lin`.\n reverse (bool, optional): If True, reverse the axis tick marks. Default is False.\n\n \"\"\"\n setattr(self.limits, which + 'lims', lims)\n setattr(self.limits, 'd' + which, d)\n setattr(self.limits, which + 'scale', scale)\n\n if reverse:\n setattr(self.limits, 'reverse_' + which + '_axis', True)\n return": 3028, "def osx_clipboard_get():\n \"\"\" Get the clipboard's text on OS X.\n \"\"\"\n p = subprocess.Popen(['pbpaste', '-Prefer', 'ascii'],\n stdout=subprocess.PIPE)\n text, stderr = p.communicate()\n # Text comes in with old Mac \\r line endings. Change them to \\n.\n text = text.replace('\\r', '\\n')\n return text": 3029, "def colorize(string, color, *args, **kwargs):\n \"\"\"\n Implements string formatting along with color specified in colorama.Fore\n \"\"\"\n string = string.format(*args, **kwargs)\n return color + string + colorama.Fore.RESET": 3030, "def unpickle_stats(stats):\n \"\"\"Unpickle a pstats.Stats object\"\"\"\n stats = cPickle.loads(stats)\n stats.stream = True\n return stats": 3031, "def set_executable(filename):\n \"\"\"Set the exectuable bit on the given filename\"\"\"\n st = os.stat(filename)\n os.chmod(filename, st.st_mode | stat.S_IEXEC)": 3032, "def create_search_url(self):\n \"\"\" Generates (urlencoded) query string from stored key-values tuples\n\n :returns: A string containing all arguments in a url-encoded format\n \"\"\"\n\n url = '?'\n for key, value in self.arguments.items():\n url += '%s=%s&' % (quote_plus(key), quote_plus(value))\n self.url = url[:-1]\n return self.url": 3033, "def append_user_agent(self, user_agent):\n \"\"\"Append text to the User-Agent header for the request.\n\n Use this method to update the User-Agent header by appending the\n given string to the session's User-Agent header separated by a space.\n\n :param user_agent: A string to append to the User-Agent header\n :type user_agent: str\n \"\"\"\n old_ua = self.session.headers.get('User-Agent', '')\n ua = old_ua + ' ' + user_agent\n self.session.headers['User-Agent'] = ua.strip()": 3034, "def makedirs(path):\n \"\"\"\n Create directories if they do not exist, otherwise do nothing.\n\n Return path for convenience\n \"\"\"\n if not os.path.isdir(path):\n os.makedirs(path)\n return path": 3035, "def server(port):\n \"\"\"Start the Django dev server.\"\"\"\n args = ['python', 'manage.py', 'runserver']\n if port:\n args.append(port)\n run.main(args)": 3036, "def check(modname):\n \"\"\"Check if required dependency is installed\"\"\"\n for dependency in DEPENDENCIES:\n if dependency.modname == modname:\n return dependency.check()\n else:\n raise RuntimeError(\"Unkwown dependency %s\" % modname)": 3037, "def generate_dumper(self, mapfile, names):\n \"\"\"\n Build dumpdata commands\n \"\"\"\n return self.build_template(mapfile, names, self._dumpdata_template)": 3038, "def health_check(self):\n \"\"\"Uses head object to make sure the file exists in S3.\"\"\"\n logger.debug('Health Check on S3 file for: {namespace}'.format(\n namespace=self.namespace\n ))\n\n try:\n self.client.head_object(Bucket=self.bucket_name, Key=self.data_file)\n return True\n except ClientError as e:\n logger.debug('Error encountered with S3. Assume unhealthy')": 3039, "def maxlevel(lst):\n \"\"\"Return maximum nesting depth\"\"\"\n maxlev = 0\n def f(lst, level):\n nonlocal maxlev\n if isinstance(lst, list):\n level += 1\n maxlev = max(level, maxlev)\n for item in lst:\n f(item, level)\n f(lst, 0)\n return maxlev": 3040, "def peak_memory_usage():\n \"\"\"Return peak memory usage in MB\"\"\"\n if sys.platform.startswith('win'):\n p = psutil.Process()\n return p.memory_info().peak_wset / 1024 / 1024\n\n mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss\n factor_mb = 1 / 1024\n if sys.platform == 'darwin':\n factor_mb = 1 / (1024 * 1024)\n return mem * factor_mb": 3041, "def is_clicked(self, MouseStateType):\n \"\"\"\n Did the user depress and release the button to signify a click?\n MouseStateType is the button to query. Values found under StateTypes.py\n \"\"\"\n return self.previous_mouse_state.query_state(MouseStateType) and (\n not self.current_mouse_state.query_state(MouseStateType))": 3042, "def listunion(ListOfLists):\n \"\"\"\n Take the union of a list of lists.\n\n Take a Python list of Python lists::\n\n [[l11,l12, ...], [l21,l22, ...], ... , [ln1, ln2, ...]]\n\n and return the aggregated list::\n\n [l11,l12, ..., l21, l22 , ...]\n\n For a list of two lists, e.g. `[a, b]`, this is like::\n\n a.extend(b)\n\n **Parameters**\n\n **ListOfLists** : Python list\n\n Python list of Python lists.\n\n **Returns**\n\n **u** : Python list\n\n Python list created by taking the union of the\n lists in `ListOfLists`.\n\n \"\"\"\n u = []\n for s in ListOfLists:\n if s != None:\n u.extend(s)\n return u": 3043, "def _check_for_duplicate_sequence_names(self, fasta_file_path):\n \"\"\"Test if the given fasta file contains sequences with duplicate\n sequence names.\n\n Parameters\n ----------\n fasta_file_path: string\n path to file that is to be checked\n\n Returns\n -------\n The name of the first duplicate sequence found, else False.\n\n \"\"\"\n found_sequence_names = set()\n for record in SeqIO.parse(fasta_file_path, 'fasta'):\n name = record.name\n if name in found_sequence_names:\n return name\n found_sequence_names.add(name)\n return False": 3044, "def dict_merge(set1, set2):\n \"\"\"Joins two dictionaries.\"\"\"\n return dict(list(set1.items()) + list(set2.items()))": 3045, "def alter_change_column(self, table, column, field):\n \"\"\"Support change columns.\"\"\"\n return self._update_column(table, column, lambda a, b: b)": 3046, "def update_loan_entry(database, entry):\n \"\"\"Update a record of a loan report in the provided database.\n\n @param db: The MongoDB database to operate on. The loans collection will be\n used from this database.\n @type db: pymongo.database.Database\n @param entry: The entry to insert into the database, updating the entry with\n the same recordID if one exists.\n @type entry: dict\n \"\"\"\n entry = clean_entry(entry)\n database.loans.update(\n {'recordID': entry['recordID']},\n {'$set': entry},\n upsert=True\n )": 3047, "def json_obj_to_cursor(self, json):\n \"\"\"(Deprecated) Converts a JSON object to a mongo db cursor\n\n :param str json: A json string\n :returns: dictionary with ObjectId type\n :rtype: dict\n \"\"\"\n cursor = json_util.loads(json)\n if \"id\" in json:\n cursor[\"_id\"] = ObjectId(cursor[\"id\"])\n del cursor[\"id\"]\n\n return cursor": 3048, "def check_permission_safety(path):\n \"\"\"Check if the file at the given path is safe to use as a state file.\n\n This checks that group and others have no permissions on the file and that the current user is\n the owner.\n \"\"\"\n f_stats = os.stat(path)\n return (f_stats.st_mode & (stat.S_IRWXG | stat.S_IRWXO)) == 0 and f_stats.st_uid == os.getuid()": 3049, "def erase(self):\n \"\"\"White out the progress bar.\"\"\"\n with self._at_last_line():\n self.stream.write(self._term.clear_eol)\n self.stream.flush()": 3050, "def set_cursor(self, x, y):\n \"\"\"\n Sets the cursor to the desired position.\n\n :param x: X position\n :param y: Y position\n \"\"\"\n curses.curs_set(1)\n self.screen.move(y, x)": 3051, "def close( self ):\n \"\"\"\n Close the db and release memory\n \"\"\"\n if self.db is not None:\n self.db.commit()\n self.db.close()\n self.db = None\n\n return": 3052, "def compute_partition_size(result, processes):\n \"\"\"\n Attempts to compute the partition size to evenly distribute work across processes. Defaults to\n 1 if the length of result cannot be determined.\n\n :param result: Result to compute on\n :param processes: Number of processes to use\n :return: Best partition size\n \"\"\"\n try:\n return max(math.ceil(len(result) / processes), 1)\n except TypeError:\n return 1": 3053, "def __iadd__(self, other_model):\n \"\"\"Incrementally add the content of another model to this model (+=).\n\n Copies of all the reactions in the other model are added to this\n model. The objective is the sum of the objective expressions for the\n two models.\n \"\"\"\n warn('use model.merge instead', DeprecationWarning)\n return self.merge(other_model, objective='sum', inplace=True)": 3054, "def machine_info():\n \"\"\"Retrieve core and memory information for the current machine.\n \"\"\"\n import psutil\n BYTES_IN_GIG = 1073741824.0\n free_bytes = psutil.virtual_memory().total\n return [{\"memory\": float(\"%.1f\" % (free_bytes / BYTES_IN_GIG)), \"cores\": multiprocessing.cpu_count(),\n \"name\": socket.gethostname()}]": 3055, "def is_value_type_valid_for_exact_conditions(self, value):\n \"\"\" Method to validate if the value is valid for exact match type evaluation.\n\n Args:\n value: Value to validate.\n\n Returns:\n Boolean: True if value is a string, boolean, or number. Otherwise False.\n \"\"\"\n # No need to check for bool since bool is a subclass of int\n if isinstance(value, string_types) or isinstance(value, (numbers.Integral, float)):\n return True\n\n return False": 3056, "def _root(self):\n \"\"\"Attribute referencing the root node of the tree.\n\n :returns: the root node of the tree containing this instance.\n :rtype: Node\n \"\"\"\n _n = self\n while _n.parent:\n _n = _n.parent\n return _n": 3057, "def pair_strings_sum_formatter(a, b):\n \"\"\"\n Formats the sum of a and b.\n\n Note\n ----\n Both inputs are numbers already converted to strings.\n\n \"\"\"\n if b[:1] == \"-\":\n return \"{0} - {1}\".format(a, b[1:])\n return \"{0} + {1}\".format(a, b)": 3058, "def drop_all_tables(self):\n \"\"\"Drop all tables in the database\"\"\"\n for table_name in self.table_names():\n self.execute_sql(\"DROP TABLE %s\" % table_name)\n self.connection.commit()": 3059, "def Cinv(self):\n \"\"\"Inverse of the noise covariance.\"\"\"\n try:\n return np.linalg.inv(self.c)\n except np.linalg.linalg.LinAlgError:\n print('Warning: non-invertible noise covariance matrix c.')\n return np.eye(self.c.shape[0])": 3060, "def _method_scope(input_layer, name):\n \"\"\"Creates a nested set of name and id scopes and avoids repeats.\"\"\"\n global _in_method_scope\n # pylint: disable=protected-access\n\n with input_layer.g.as_default(), \\\n scopes.var_and_name_scope(\n None if _in_method_scope else input_layer._scope), \\\n scopes.var_and_name_scope((name, None)) as (scope, var_scope):\n was_in_method_scope = _in_method_scope\n yield scope, var_scope\n _in_method_scope = was_in_method_scope": 3061, "def is_serializable(obj):\n \"\"\"Return `True` if the given object conforms to the Serializable protocol.\n\n :rtype: bool\n \"\"\"\n if inspect.isclass(obj):\n return Serializable.is_serializable_type(obj)\n return isinstance(obj, Serializable) or hasattr(obj, '_asdict')": 3062, "def Pyramid(pos=(0, 0, 0), s=1, height=1, axis=(0, 0, 1), c=\"dg\", alpha=1):\n \"\"\"\n Build a pyramid of specified base size `s` and `height`, centered at `pos`.\n \"\"\"\n return Cone(pos, s, height, axis, c, alpha, 4)": 3063, "def run(self):\n \"\"\"\n Runs the unit test framework. Can be overridden to run anything.\n Returns True on passing and False on failure.\n \"\"\"\n try:\n import nose\n arguments = [sys.argv[0]] + list(self.test_args)\n return nose.run(argv=arguments)\n except ImportError:\n print()\n print(\"*** Nose library missing. Please install it. ***\")\n print()\n raise": 3064, "def get_wordnet_syns(word):\n \"\"\"\n Utilize wordnet (installed with nltk) to get synonyms for words\n word is the input word\n returns a list of unique synonyms\n \"\"\"\n synonyms = []\n regex = r\"_\"\n pat = re.compile(regex)\n synset = nltk.wordnet.wordnet.synsets(word)\n for ss in synset:\n for swords in ss.lemma_names:\n synonyms.append(pat.sub(\" \", swords.lower()))\n synonyms = f7(synonyms)\n return synonyms": 3065, "def vals2bins(vals,res=100):\n \"\"\"Maps values to bins\n Args:\n values (list or list of lists) - list of values to map to colors\n res (int) - resolution of the color map (default: 100)\n Returns:\n list of numbers representing bins\n \"\"\"\n # flatten if list of lists\n if any(isinstance(el, list) for el in vals):\n vals = list(itertools.chain(*vals))\n return list(np.digitize(vals, np.linspace(np.min(vals), np.max(vals)+1, res+1)) - 1)": 3066, "def _decode_request(self, encoded_request):\n \"\"\"Decode an request previously encoded\"\"\"\n obj = self.serializer.loads(encoded_request)\n return request_from_dict(obj, self.spider)": 3067, "def unit_vector(x):\n \"\"\"Return a unit vector in the same direction as x.\"\"\"\n y = np.array(x, dtype='float')\n return y/norm(y)": 3068, "def register_type(cls, name):\n \"\"\"Register `name` as a type to validate as an instance of class `cls`.\"\"\"\n x = TypeDefinition(name, (cls,), ())\n Validator.types_mapping[name] = x": 3069, "def pairwise_indices(self):\n \"\"\"ndarray containing tuples of pairwise indices.\"\"\"\n return np.array([sig.pairwise_indices for sig in self.values]).T": 3070, "def printmp(msg):\n \"\"\"Print temporarily, until next print overrides it.\n \"\"\"\n filler = (80 - len(msg)) * ' '\n print(msg + filler, end='\\r')\n sys.stdout.flush()": 3071, "def _numpy_bytes_to_char(arr):\n \"\"\"Like netCDF4.stringtochar, but faster and more flexible.\n \"\"\"\n # ensure the array is contiguous\n arr = np.array(arr, copy=False, order='C', dtype=np.string_)\n return arr.reshape(arr.shape + (1,)).view('S1')": 3072, "def delete(self, row):\n \"\"\"Delete a track value\"\"\"\n i = self._get_key_index(row)\n del self.keys[i]": 3073, "def _sanitize(text):\n \"\"\"Return sanitized Eidos text field for human readability.\"\"\"\n d = {'-LRB-': '(', '-RRB-': ')'}\n return re.sub('|'.join(d.keys()), lambda m: d[m.group(0)], text)": 3074, "def read_mm_header(fd, byte_order, dtype, count):\n \"\"\"Read MM_HEADER tag from file and return as numpy.rec.array.\"\"\"\n return numpy.rec.fromfile(fd, MM_HEADER, 1, byteorder=byte_order)[0]": 3075, "def as_html(self):\n \"\"\"Generate HTML to display map.\"\"\"\n if not self._folium_map:\n self.draw()\n return self._inline_map(self._folium_map, self._width, self._height)": 3076, "def name(self):\n \"\"\"A unique name for this scraper.\"\"\"\n return ''.join('_%s' % c if c.isupper() else c for c in self.__class__.__name__).strip('_').lower()": 3077, "def _is_date_data(self, data_type):\n \"\"\"Private method for determining if a data record is of type DATE.\"\"\"\n dt = DATA_TYPES[data_type]\n if isinstance(self.data, dt['type']):\n self.type = data_type.upper()\n self.len = None\n return True": 3078, "def part(z, s):\n r\"\"\"Get the real or imaginary part of a complex number.\"\"\"\n if sage_included:\n if s == 1: return np.real(z)\n elif s == -1: return np.imag(z)\n elif s == 0:\n return z\n else:\n if s == 1: return z.real\n elif s == -1: return z.imag\n elif s == 0: return z": 3079, "def seq_include(records, filter_regex):\n \"\"\"\n Filter any sequences who's seq does not match the filter. Ignore case.\n \"\"\"\n regex = re.compile(filter_regex)\n for record in records:\n if regex.search(str(record.seq)):\n yield record": 3080, "def get_image(self, source):\n \"\"\"\n Given a file-like object, loads it up into a PIL.Image object\n and returns it.\n\n :param file source: A file-like object to load the image from.\n :rtype: PIL.Image\n :returns: The loaded image.\n \"\"\"\n buf = StringIO(source.read())\n return Image.open(buf)": 3081, "def tokenize_words(self, text):\n \"\"\"Tokenize an input string into a list of words (with punctuation removed).\"\"\"\n return [\n self.strip_punctuation(word) for word in text.split(' ')\n if self.strip_punctuation(word)\n ]": 3082, "def GaussianBlur(X, ksize_width, ksize_height, sigma_x, sigma_y):\n \"\"\"Apply Gaussian blur to the given data.\n\n Args:\n X: data to blur\n kernel_size: Gaussian kernel size\n stddev: Gaussian kernel standard deviation (in both X and Y directions)\n \"\"\"\n return image_transform(\n X,\n cv2.GaussianBlur,\n ksize=(ksize_width, ksize_height),\n sigmaX=sigma_x,\n sigmaY=sigma_y\n )": 3083, "def zoom_cv(x,z):\n \"\"\" Zoom the center of image x by a factor of z+1 while retaining the original image size and proportion. \"\"\"\n if z==0: return x\n r,c,*_ = x.shape\n M = cv2.getRotationMatrix2D((c/2,r/2),0,z+1.)\n return cv2.warpAffine(x,M,(c,r))": 3084, "def warp(self, warp_matrix, img, iflag=cv2.INTER_NEAREST):\n \"\"\" Function to warp input image given an estimated 2D linear transformation\n\n :param warp_matrix: Linear 2x3 matrix to use to linearly warp the input images\n :type warp_matrix: ndarray\n :param img: Image to be warped with estimated transformation\n :type img: ndarray\n :param iflag: Interpolation flag, specified interpolation using during resampling of warped image\n :type iflag: cv2.INTER_*\n :return: Warped image using the linear matrix\n \"\"\"\n\n height, width = img.shape[:2]\n warped_img = np.zeros_like(img, dtype=img.dtype)\n\n # Check if image to warp is 2D or 3D. If 3D need to loop over channels\n if (self.interpolation_type == InterpolationType.LINEAR) or img.ndim == 2:\n warped_img = cv2.warpAffine(img.astype(np.float32), warp_matrix, (width, height),\n flags=iflag).astype(img.dtype)\n\n elif img.ndim == 3:\n for idx in range(img.shape[-1]):\n warped_img[..., idx] = cv2.warpAffine(img[..., idx].astype(np.float32), warp_matrix, (width, height),\n flags=iflag).astype(img.dtype)\n else:\n raise ValueError('Image has incorrect number of dimensions: {}'.format(img.ndim))\n\n return warped_img": 3085, "def __exit__(self, type, value, traceback):\n \"\"\"When the `with` statement ends.\"\"\"\n\n if not self.asarfile:\n return\n\n self.asarfile.close()\n self.asarfile = None": 3086, "def set_stop_handler(self):\n \"\"\"\n Initializes functions that are invoked when the user or OS wants to kill this process.\n :return:\n \"\"\"\n signal.signal(signal.SIGTERM, self.graceful_stop)\n signal.signal(signal.SIGABRT, self.graceful_stop)\n signal.signal(signal.SIGINT, self.graceful_stop)": 3087, "def get_table_metadata(engine, table):\n \"\"\" Extract all useful infos from the given table\n\n Args:\n engine: SQLAlchemy connection engine\n table: table name\n\n Returns:\n Dictionary of infos\n \"\"\"\n metadata = MetaData()\n metadata.reflect(bind=engine, only=[table])\n table_metadata = Table(table, metadata, autoload=True)\n return table_metadata": 3088, "def _import(module, cls):\n \"\"\"\n A messy way to import library-specific classes.\n TODO: I should really make a factory class or something, but I'm lazy.\n Plus, factories remind me a lot of java...\n \"\"\"\n global Scanner\n\n try:\n cls = str(cls)\n mod = __import__(str(module), globals(), locals(), [cls], 1)\n Scanner = getattr(mod, cls)\n except ImportError:\n pass": 3089, "def autopage(self):\n \"\"\"Iterate through results from all pages.\n\n :return: all results\n :rtype: generator\n \"\"\"\n while self.items:\n yield from self.items\n self.items = self.fetch_next()": 3090, "def find(command, on):\n \"\"\"Find the command usage.\"\"\"\n output_lines = parse_man_page(command, on)\n click.echo(''.join(output_lines))": 3091, "def FromString(self, string):\n \"\"\"Parse a bool from a string.\"\"\"\n if string.lower() in (\"false\", \"no\", \"n\"):\n return False\n\n if string.lower() in (\"true\", \"yes\", \"y\"):\n return True\n\n raise TypeValueError(\"%s is not recognized as a boolean value.\" % string)": 3092, "def to_datetime(value):\n \"\"\"Converts a string to a datetime.\"\"\"\n if value is None:\n return None\n\n if isinstance(value, six.integer_types):\n return parser.parse(value)\n return parser.isoparse(value)": 3093, "def word_to_id(self, word):\n \"\"\"Returns the integer word id of a word string.\"\"\"\n if word in self.vocab:\n return self.vocab[word]\n else:\n return self.unk_id": 3094, "def run(args):\n \"\"\"Process command line arguments and walk inputs.\"\"\"\n raw_arguments = get_arguments(args[1:])\n process_arguments(raw_arguments)\n walk.run()\n return True": 3095, "def reload_localzone():\n \"\"\"Reload the cached localzone. You need to call this if the timezone has changed.\"\"\"\n global _cache_tz\n _cache_tz = pytz.timezone(get_localzone_name())\n utils.assert_tz_offset(_cache_tz)\n return _cache_tz": 3096, "def OnPasteAs(self, event):\n \"\"\"Clipboard paste as event handler\"\"\"\n\n data = self.main_window.clipboard.get_clipboard()\n key = self.main_window.grid.actions.cursor\n\n with undo.group(_(\"Paste As...\")):\n self.main_window.actions.paste_as(key, data)\n\n self.main_window.grid.ForceRefresh()\n\n event.Skip()": 3097, "def getoutput_pexpect(self, cmd):\n \"\"\"Run a command and return its stdout/stderr as a string.\n\n Parameters\n ----------\n cmd : str\n A command to be executed in the system shell.\n\n Returns\n -------\n output : str\n A string containing the combination of stdout and stderr from the\n subprocess, in whatever order the subprocess originally wrote to its\n file descriptors (so the order of the information in this string is the\n correct order as would be seen if running the command in a terminal).\n \"\"\"\n try:\n return pexpect.run(self.sh, args=['-c', cmd]).replace('\\r\\n', '\\n')\n except KeyboardInterrupt:\n print('^C', file=sys.stderr, end='')": 3098, "def get_stripped_file_lines(filename):\n \"\"\"\n Return lines of a file with whitespace removed\n \"\"\"\n try:\n lines = open(filename).readlines()\n except FileNotFoundError:\n fatal(\"Could not open file: {!r}\".format(filename))\n\n return [line.strip() for line in lines]": 3099, "def unpickle(pickle_file):\n \"\"\"Unpickle a python object from the given path.\"\"\"\n pickle = None\n with open(pickle_file, \"rb\") as pickle_f:\n pickle = dill.load(pickle_f)\n if not pickle:\n LOG.error(\"Could not load python object from file\")\n return pickle": 3100, "def get():\n \"\"\" Get local facts about this machine.\n\n Returns:\n json-compatible dict with all facts of this host\n \"\"\"\n result = runCommand('facter --json', raise_error_on_fail=True)\n json_facts = result[1]\n facts = json.loads(json_facts)\n return facts": 3101, "def highlight_region(plt, start_x, end_x):\n \"\"\"\n Highlight a region on the chart between the specified start and end x-co-ordinates.\n param pyplot plt: matplotlibk pyplot which contains the charts to be highlighted\n param string start_x : epoch time millis\n param string end_x : epoch time millis\n \"\"\"\n start_x = convert_to_mdate(start_x)\n end_x = convert_to_mdate(end_x)\n plt.axvspan(start_x, end_x, color=CONSTANTS.HIGHLIGHT_COLOR, alpha=CONSTANTS.HIGHLIGHT_ALPHA)": 3102, "def load_search_freq(fp=SEARCH_FREQ_JSON):\n \"\"\"\n Load the search_freq from JSON file\n \"\"\"\n try:\n with open(fp) as f:\n return Counter(json.load(f))\n except FileNotFoundError:\n return Counter()": 3103, "def barv(d, plt, title=None, rotation='vertical'):\n \"\"\"A convenience function for plotting a vertical bar plot from a Counter\"\"\"\n labels = sorted(d, key=d.get, reverse=True)\n index = range(len(labels))\n plt.xticks(index, labels, rotation=rotation)\n plt.bar(index, [d[v] for v in labels])\n\n if title is not None:\n plt.title(title)": 3104, "def blocking(func, *args, **kwargs):\n \"\"\"Run a function that uses blocking IO.\n\n The function is run in the IO thread pool.\n \"\"\"\n pool = get_io_pool()\n fut = pool.submit(func, *args, **kwargs)\n return fut.result()": 3105, "def get_longest_orf(orfs):\n \"\"\"Find longest ORF from the given list of ORFs.\"\"\"\n sorted_orf = sorted(orfs, key=lambda x: len(x['sequence']), reverse=True)[0]\n return sorted_orf": 3106, "def _next_token(self, skipws=True):\n \"\"\"Increment _token to the next token and return it.\"\"\"\n self._token = next(self._tokens).group(0)\n return self._next_token() if skipws and self._token.isspace() else self._token": 3107, "def Print(self, output_writer):\n \"\"\"Prints a human readable version of the filter.\n\n Args:\n output_writer (CLIOutputWriter): output writer.\n \"\"\"\n if self._filters:\n output_writer.Write('Filters:\\n')\n for file_entry_filter in self._filters:\n file_entry_filter.Print(output_writer)": 3108, "def __call__(self, _):\n \"\"\"Print the current iteration.\"\"\"\n if self.iter % self.step == 0:\n print(self.fmt.format(self.iter), **self.kwargs)\n\n self.iter += 1": 3109, "def print_bintree(tree, indent=' '):\n \"\"\"print a binary tree\"\"\"\n for n in sorted(tree.keys()):\n print \"%s%s\" % (indent * depth(n,tree), n)": 3110, "def parse_cookies(self, req, name, field):\n \"\"\"Pull the value from the cookiejar.\"\"\"\n return core.get_value(req.COOKIES, name, field)": 3111, "def cycle_focus(self):\n \"\"\"\n Cycle through all windows.\n \"\"\"\n windows = self.windows()\n new_index = (windows.index(self.active_window) + 1) % len(windows)\n self.active_window = windows[new_index]": 3112, "def __call__(self, _):\n \"\"\"Update the progressbar.\"\"\"\n if self.iter % self.step == 0:\n self.pbar.update(self.step)\n\n self.iter += 1": 3113, "def int32_to_negative(int32):\n \"\"\"Checks if a suspicious number (e.g. ligand position) is in fact a negative number represented as a\n 32 bit integer and returns the actual number.\n \"\"\"\n dct = {}\n if int32 == 4294967295: # Special case in some structures (note, this is just a workaround)\n return -1\n for i in range(-1000, -1):\n dct[np.uint32(i)] = i\n if int32 in dct:\n return dct[int32]\n else:\n return int32": 3114, "def acknowledge_time(self):\n \"\"\"\n Processor time when the alarm was acknowledged.\n\n :type: :class:`~datetime.datetime`\n \"\"\"\n if (self.is_acknowledged and\n self._proto.acknowledgeInfo.HasField('acknowledgeTime')):\n return parse_isostring(self._proto.acknowledgeInfo.acknowledgeTime)\n return None": 3115, "def use_theme(theme):\n \"\"\"Make the given theme current.\n\n There are two included themes: light_theme, dark_theme.\n \"\"\"\n global current\n current = theme\n import scene\n if scene.current is not None:\n scene.current.stylize()": 3116, "def packagenameify(s):\n \"\"\"\n Makes a package name\n \"\"\"\n return ''.join(w if w in ACRONYMS else w.title() for w in s.split('.')[-1:])": 3117, "def store_many(self, sql, values):\n \"\"\"Abstraction over executemany method\"\"\"\n cursor = self.get_cursor()\n cursor.executemany(sql, values)\n self.conn.commit()": 3118, "def hide(self):\n \"\"\"Hides the main window of the terminal and sets the visible\n flag to False.\n \"\"\"\n if not HidePrevention(self.window).may_hide():\n return\n self.hidden = True\n self.get_widget('window-root').unstick()\n self.window.hide()": 3119, "def isBlockComment(self, line, column):\n \"\"\"Check if text at given position is a block comment.\n\n If language is not known, or text is not parsed yet, ``False`` is returned\n \"\"\"\n return self._highlighter is not None and \\\n self._highlighter.isBlockComment(self.document().findBlockByNumber(line), column)": 3120, "def handle_qbytearray(obj, encoding):\n \"\"\"Qt/Python2/3 compatibility helper.\"\"\"\n if isinstance(obj, QByteArray):\n obj = obj.data()\n\n return to_text_string(obj, encoding=encoding)": 3121, "def _obj_cursor_to_dictionary(self, cursor):\n \"\"\"Handle conversion of pymongo cursor into a JSON object formatted for UI consumption\n\n :param dict cursor: a mongo document that should be converted to primitive types for the client code\n :returns: a primitive dictionary\n :rtype: dict\n \"\"\"\n if not cursor:\n return cursor\n\n cursor = json.loads(json.dumps(cursor, cls=BSONEncoder))\n\n if cursor.get(\"_id\"):\n cursor[\"id\"] = cursor.get(\"_id\")\n del cursor[\"_id\"]\n\n return cursor": 3122, "def get_range(self, start=None, stop=None):\n\t\t\"\"\"Return a RangeMap for the range start to stop.\n\n\t\tReturns:\n\t\t\tA RangeMap\n\t\t\"\"\"\n\t\treturn self.from_iterable(self.ranges(start, stop))": 3123, "def LinSpace(start, stop, num):\n \"\"\"\n Linspace op.\n \"\"\"\n return np.linspace(start, stop, num=num, dtype=np.float32),": 3124, "def _ratelimited_get(self, *args, **kwargs):\n \"\"\"Perform get request, handling rate limiting.\"\"\"\n with self._ratelimiter:\n resp = self.session.get(*args, **kwargs)\n\n # It's possible that Space-Track will return HTTP status 500 with a\n # query rate limit violation. This can happen if a script is cancelled\n # before it has finished sleeping to satisfy the rate limit and it is\n # started again.\n #\n # Let's catch this specific instance and retry once if it happens.\n if resp.status_code == 500:\n # Let's only retry if the error page tells us it's a rate limit\n # violation.\n if 'violated your query rate limit' in resp.text:\n # Mimic the RateLimiter callback behaviour.\n until = time.time() + self._ratelimiter.period\n t = threading.Thread(target=self._ratelimit_callback, args=(until,))\n t.daemon = True\n t.start()\n time.sleep(self._ratelimiter.period)\n\n # Now retry\n with self._ratelimiter:\n resp = self.session.get(*args, **kwargs)\n\n return resp": 3125, "def close(self):\n \"\"\"Close child subprocess\"\"\"\n if self._subprocess is not None:\n os.killpg(self._subprocess.pid, signal.SIGTERM)\n self._subprocess = None": 3126, "def split_comment(cls, code):\n \"\"\" Removes comments (#...) from python code. \"\"\"\n if '#' not in code: return code\n #: Remove comments only (leave quoted strings as they are)\n subf = lambda m: '' if m.group(0)[0]=='#' else m.group(0)\n return re.sub(cls.re_pytokens, subf, code)": 3127, "def scale_image(image, new_width):\n \"\"\"Resizes an image preserving the aspect ratio.\n \"\"\"\n (original_width, original_height) = image.size\n aspect_ratio = original_height/float(original_width)\n new_height = int(aspect_ratio * new_width)\n\n # This scales it wider than tall, since characters are biased\n new_image = image.resize((new_width*2, new_height))\n return new_image": 3128, "def readme():\n \"\"\"Try converting the README to an RST document. Return it as is on failure.\"\"\"\n try:\n import pypandoc\n readme_content = pypandoc.convert('README.md', 'rst')\n except(IOError, ImportError):\n print(\"Warning: no pypandoc module found.\")\n try:\n readme_content = open('README.md').read()\n except IOError:\n readme_content = ''\n return readme_content": 3129, "def _fast_read(self, infile):\n \"\"\"Function for fast reading from sensor files.\"\"\"\n infile.seek(0)\n return(int(infile.read().decode().strip()))": 3130, "def _read_json_file(self, json_file):\n \"\"\" Helper function to read JSON file as OrderedDict \"\"\"\n\n self.log.debug(\"Reading '%s' JSON file...\" % json_file)\n\n with open(json_file, 'r') as f:\n return json.load(f, object_pairs_hook=OrderedDict)": 3131, "def get_list_from_file(file_name):\n \"\"\"read the lines from a file into a list\"\"\"\n with open(file_name, mode='r', encoding='utf-8') as f1:\n lst = f1.readlines()\n return lst": 3132, "def kick(self, channel, nick, comment=\"\"):\n \"\"\"Send a KICK command.\"\"\"\n self.send_items('KICK', channel, nick, comment and ':' + comment)": 3133, "def read_data(file, endian, num=1):\n \"\"\"\n Read a given number of 32-bits unsigned integers from the given file\n with the given endianness.\n \"\"\"\n res = struct.unpack(endian + 'L' * num, file.read(num * 4))\n if len(res) == 1:\n return res[0]\n return res": 3134, "def hstrlen(self, name, key):\n \"\"\"\n Return the number of bytes stored in the value of ``key``\n within hash ``name``\n \"\"\"\n with self.pipe as pipe:\n return pipe.hstrlen(self.redis_key(name), key)": 3135, "def get_default_preds():\n \"\"\"dynamically build autocomplete options based on an external file\"\"\"\n g = ontospy.Ontospy(rdfsschema, text=True, verbose=False, hide_base_schemas=False)\n classes = [(x.qname, x.bestDescription()) for x in g.all_classes]\n properties = [(x.qname, x.bestDescription()) for x in g.all_properties]\n commands = [('exit', 'exits the terminal'), ('show', 'show current buffer')]\n return rdfschema + owlschema + classes + properties + commands": 3136, "def changed(self):\n \"\"\"Returns dict of fields that changed since save (with old values)\"\"\"\n return dict(\n (field, self.previous(field))\n for field in self.fields\n if self.has_changed(field)\n )": 3137, "def _get_info(self, host, port, unix_socket, auth):\n \"\"\"Return info dict from specified Redis instance\n\n:param str host: redis host\n:param int port: redis port\n:rtype: dict\n\n \"\"\"\n\n client = self._client(host, port, unix_socket, auth)\n if client is None:\n return None\n\n info = client.info()\n del client\n return info": 3138, "def extract_table_names(query):\n \"\"\" Extract table names from an SQL query. \"\"\"\n # a good old fashioned regex. turns out this worked better than actually parsing the code\n tables_blocks = re.findall(r'(?:FROM|JOIN)\\s+(\\w+(?:\\s*,\\s*\\w+)*)', query, re.IGNORECASE)\n tables = [tbl\n for block in tables_blocks\n for tbl in re.findall(r'\\w+', block)]\n return set(tables)": 3139, "def _npiter(arr):\n \"\"\"Wrapper for iterating numpy array\"\"\"\n for a in np.nditer(arr, flags=[\"refs_ok\"]):\n c = a.item()\n if c is not None:\n yield c": 3140, "def pages(self):\n \"\"\"Get pages, reloading the site if needed.\"\"\"\n rev = self.db.get('site:rev')\n if int(rev) != self.revision:\n self.reload_site()\n\n return self._pages": 3141, "def logx_linear(x, a, b):\n \"\"\"logx linear\n\n Parameters\n ----------\n x: int\n a: float\n b: float\n\n Returns\n -------\n float\n a * np.log(x) + b\n \"\"\"\n x = np.log(x)\n return a*x + b": 3142, "def get_cube(name):\n \"\"\" Load the named cube from the current registered ``CubeManager``. \"\"\"\n manager = get_manager()\n if not manager.has_cube(name):\n raise NotFound('No such cube: %r' % name)\n return manager.get_cube(name)": 3143, "def mark(self, lineno, count=1):\n \"\"\"Mark a given source line as executed count times.\n\n Multiple calls to mark for the same lineno add up.\n \"\"\"\n self.sourcelines[lineno] = self.sourcelines.get(lineno, 0) + count": 3144, "def dedupFasta(reads):\n \"\"\"\n Remove sequence duplicates (based on sequence) from FASTA.\n\n @param reads: a C{dark.reads.Reads} instance.\n @return: a generator of C{dark.reads.Read} instances with no duplicates.\n \"\"\"\n seen = set()\n add = seen.add\n for read in reads:\n hash_ = md5(read.sequence.encode('UTF-8')).digest()\n if hash_ not in seen:\n add(hash_)\n yield read": 3145, "def pop (self, key):\n \"\"\"Remove key from dict and return value.\"\"\"\n if key in self._keys:\n self._keys.remove(key)\n super(ListDict, self).pop(key)": 3146, "def isolate_element(self, x):\n \"\"\"Isolates `x` from its equivalence class.\"\"\"\n members = list(self.members(x))\n self.delete_set(x)\n self.union(*(v for v in members if v != x))": 3147, "def focusInEvent(self, event):\n \"\"\"Reimplement Qt method to send focus change notification\"\"\"\n self.focus_changed.emit()\n return super(ControlWidget, self).focusInEvent(event)": 3148, "def __pop_top_frame(self):\n \"\"\"Pops the top frame off the frame stack.\"\"\"\n popped = self.__stack.pop()\n if self.__stack:\n self.__stack[-1].process_subframe(popped)": 3149, "def close_stream(self):\n\t\t\"\"\" Closes the stream. Performs cleanup. \"\"\"\n\t\tself.keep_listening = False\n\t\tself.stream.stop()\n\t\tself.stream.close()": 3150, "def strip_html(string, keep_tag_content=False):\n \"\"\"\n Remove html code contained into the given string.\n\n :param string: String to manipulate.\n :type string: str\n :param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default).\n :type keep_tag_content: bool\n :return: String with html removed.\n :rtype: str\n \"\"\"\n r = HTML_TAG_ONLY_RE if keep_tag_content else HTML_RE\n return r.sub('', string)": 3151, "def print_log(text, *colors):\n \"\"\"Print a log message to standard error.\"\"\"\n sys.stderr.write(sprint(\"{}: {}\".format(script_name, text), *colors) + \"\\n\")": 3152, "def remove_property(self, key=None, value=None):\n \"\"\"Remove all properties matching both key and value.\n\n :param str key: Key of the property.\n :param str value: Value of the property.\n \"\"\"\n for k, v in self.properties[:]:\n if (key is None or key == k) and (value is None or value == v):\n del(self.properties[self.properties.index((k, v))])": 3153, "def fail_print(error):\n \"\"\"Print an error in red text.\n Parameters\n error (HTTPError)\n Error object to print.\n \"\"\"\n print(COLORS.fail, error.message, COLORS.end)\n print(COLORS.fail, error.errors, COLORS.end)": 3154, "def generic_add(a, b):\n print\n \"\"\"Simple function to add two numbers\"\"\"\n logger.info('Called generic_add({}, {})'.format(a, b))\n return a + b": 3155, "def pretty_print_post(req):\n \"\"\"Helper to print a \"prepared\" query. Useful to debug a POST query.\n\n However pay attention at the formatting used in\n this function because it is programmed to be pretty\n printed and may differ from the actual request.\n \"\"\"\n print(('{}\\n{}\\n{}\\n\\n{}'.format(\n '-----------START-----------',\n req.method + ' ' + req.url,\n '\\n'.join('{}: {}'.format(k, v) for k, v in list(req.headers.items())),\n req.body,\n )))": 3156, "def object_type_repr(obj):\n \"\"\"Returns the name of the object's type. For some recognized\n singletons the name of the object is returned instead. (For\n example for `None` and `Ellipsis`).\n \"\"\"\n if obj is None:\n return 'None'\n elif obj is Ellipsis:\n return 'Ellipsis'\n if obj.__class__.__module__ == '__builtin__':\n name = obj.__class__.__name__\n else:\n name = obj.__class__.__module__ + '.' + obj.__class__.__name__\n return '%s object' % name": 3157, "def __call__(self, r):\n \"\"\"Update the request headers.\"\"\"\n r.headers['Authorization'] = 'JWT {jwt}'.format(jwt=self.token)\n return r": 3158, "def head(self, path, query=None, data=None, redirects=True):\n \"\"\"\n HEAD request wrapper for :func:`request()`\n \"\"\"\n return self.request('HEAD', path, query, None, redirects)": 3159, "def session(self):\n \"\"\"A context manager for this client's session.\n\n This function closes the current session when this client goes out of\n scope.\n \"\"\"\n self._session = requests.session()\n yield\n self._session.close()\n self._session = None": 3160, "def Exponential(x, a, tau, y0):\n \"\"\"Exponential function\n\n Inputs:\n -------\n ``x``: independent variable\n ``a``: scaling factor\n ``tau``: time constant\n ``y0``: additive constant\n\n Formula:\n --------\n ``a*exp(x/tau)+y0``\n \"\"\"\n return np.exp(x / tau) * a + y0": 3161, "def send_post(self, url, data, remove_header=None):\n \"\"\" Send a POST request\n \"\"\"\n return self.send_request(method=\"post\", url=url, data=data, remove_header=remove_header)": 3162, "def inverseHistogram(hist, bin_range):\n \"\"\"sample data from given histogram and min, max values within range\n\n Returns:\n np.array: data that would create the same histogram as given\n \"\"\"\n data = hist.astype(float) / np.min(hist[np.nonzero(hist)])\n new_data = np.empty(shape=np.sum(data, dtype=int))\n i = 0\n xvals = np.linspace(bin_range[0], bin_range[1], len(data))\n for d, x in zip(data, xvals):\n new_data[i:i + d] = x\n i += int(d)\n return new_data": 3163, "async def set_http_proxy(cls, url: typing.Optional[str]):\n \"\"\"See `get_http_proxy`.\"\"\"\n await cls.set_config(\"http_proxy\", \"\" if url is None else url)": 3164, "def get_db_version(session):\n \"\"\"\n :param session: actually it is a sqlalchemy session\n :return: version number\n \"\"\"\n value = session.query(ProgramInformation.value).filter(ProgramInformation.name == \"db_version\").scalar()\n return int(value)": 3165, "def _rnd_datetime(self, start, end):\n \"\"\"Internal random datetime generator.\n \"\"\"\n return self.from_utctimestamp(\n random.randint(\n int(self.to_utctimestamp(start)),\n int(self.to_utctimestamp(end)),\n )\n )": 3166, "def __getattr__(self, name):\n \"\"\" For attributes not found in self, redirect\n to the properties dictionary \"\"\"\n\n try:\n return self.__dict__[name]\n except KeyError:\n if hasattr(self._properties,name):\n return getattr(self._properties, name)": 3167, "def stats(self):\n \"\"\"\n Return a new raw REST interface to stats resources\n\n :rtype: :py:class:`ns1.rest.stats.Stats`\n \"\"\"\n import ns1.rest.stats\n return ns1.rest.stats.Stats(self.config)": 3168, "def restore_default_settings():\n \"\"\" Restore settings to default values. \n \"\"\"\n global __DEFAULTS\n __DEFAULTS.CACHE_DIR = defaults.CACHE_DIR\n __DEFAULTS.SET_SEED = defaults.SET_SEED\n __DEFAULTS.SEED = defaults.SEED\n logging.info('Settings reverted to their default values.')": 3169, "def set_mem_per_proc(self, mem_mb):\n \"\"\"Set the memory per process in megabytes\"\"\"\n super().set_mem_per_proc(mem_mb)\n self.qparams[\"mem_per_cpu\"] = self.mem_per_proc": 3170, "def logout():\n \"\"\" Log out the active user\n \"\"\"\n flogin.logout_user()\n next = flask.request.args.get('next')\n return flask.redirect(next or flask.url_for(\"user\"))": 3171, "def dict_pick(dictionary, allowed_keys):\n \"\"\"\n Return a dictionary only with keys found in `allowed_keys`\n \"\"\"\n return {key: value for key, value in viewitems(dictionary) if key in allowed_keys}": 3172, "def click(self):\n \"\"\"Click the element\n\n :returns: page element instance\n \"\"\"\n try:\n self.wait_until_clickable().web_element.click()\n except StaleElementReferenceException:\n # Retry if element has changed\n self.web_element.click()\n return self": 3173, "def standard_db_name(file_column_name):\n \"\"\"return a standard name by following rules:\n 1. find all regular expression partners ((IDs)|(ID)|([A-Z][a-z]+)|([A-Z]{2,}))\n 2. lower very part and join again with _\n This method is only used if values in table[model]['columns'] are str\n\n :param str file_column_name: name of column in file\n :return: standard name\n :rtype: str\n \"\"\"\n found = id_re.findall(file_column_name)\n\n if not found:\n return file_column_name\n\n return '_'.join(x[0].lower() for x in found)": 3174, "def edge_index(self):\n \"\"\"A map to look up the index of a edge\"\"\"\n return dict((edge, index) for index, edge in enumerate(self.edges))": 3175, "def remove_instance(self, item):\n \"\"\"Remove `instance` from model\"\"\"\n self.instances.remove(item)\n self.remove_item(item)": 3176, "def success_response(**data):\n \"\"\"Return a generic success response.\"\"\"\n data_out = {}\n data_out[\"status\"] = \"success\"\n data_out.update(data)\n js = dumps(data_out, default=date_handler)\n return Response(js, status=200, mimetype=\"application/json\")": 3177, "def copy_to_temp(object):\n \"\"\"\n Copy file-like object to temp file and return\n path.\n \"\"\"\n temp_file = NamedTemporaryFile(delete=False)\n _copy_and_close(object, temp_file)\n return temp_file.name": 3178, "def get_short_url(self):\n \"\"\" Returns short version of topic url (without page number) \"\"\"\n return reverse('post_short_url', args=(self.forum.slug, self.slug, self.id))": 3179, "def text_cleanup(data, key, last_type):\n \"\"\" I strip extra whitespace off multi-line strings if they are ready to be stripped!\"\"\"\n if key in data and last_type == STRING_TYPE:\n data[key] = data[key].strip()\n return data": 3180, "def replace(s, replace):\n \"\"\"Replace multiple values in a string\"\"\"\n for r in replace:\n s = s.replace(*r)\n return s": 3181, "def convert(name):\n \"\"\"Convert CamelCase to underscore\n\n Parameters\n ----------\n name : str\n Camelcase string\n\n Returns\n -------\n name : str\n Converted name\n \"\"\" \n s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', name)\n return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()": 3182, "def to_comment(value):\n \"\"\"\n Builds a comment.\n \"\"\"\n if value is None:\n return\n if len(value.split('\\n')) == 1:\n return \"* \" + value\n else:\n return '\\n'.join([' * ' + l for l in value.split('\\n')[:-1]])": 3183, "def str_from_file(path):\n \"\"\"\n Return file contents as string.\n\n \"\"\"\n with open(path) as f:\n s = f.read().strip()\n return s": 3184, "def stop_server(self):\n \"\"\"\n Stop receiving connections, wait for all tasks to end, and then \n terminate the server.\n \"\"\"\n self.stop = True\n while self.task_count:\n time.sleep(END_RESP)\n self.terminate = True": 3185, "def is_writable_by_others(filename):\n \"\"\"Check if file or directory is world writable.\"\"\"\n mode = os.stat(filename)[stat.ST_MODE]\n return mode & stat.S_IWOTH": 3186, "def write(self):\n \"\"\"Write content back to file.\"\"\"\n with open(self.path, 'w') as file_:\n file_.write(self.content)": 3187, "def _summarize_object_type(model):\n \"\"\"\n This function returns the summary for a given model\n \"\"\"\n # the fields for the service's model\n model_fields = {field.name: field for field in list(model.fields())}\n # summarize the model\n return {\n 'fields': [{\n 'name': key,\n 'type': type(convert_peewee_field(value)).__name__\n } for key, value in model_fields.items()\n ]\n }": 3188, "def fetch_hg_push_log(repo_name, repo_url):\n \"\"\"\n Run a HgPushlog etl process\n \"\"\"\n newrelic.agent.add_custom_parameter(\"repo_name\", repo_name)\n process = HgPushlogProcess()\n process.run(repo_url + '/json-pushes/?full=1&version=2', repo_name)": 3189, "def main():\n \"\"\"\n Commandline interface to average parameters.\n \"\"\"\n setup_main_logger(console=True, file_logging=False)\n params = argparse.ArgumentParser(description=\"Averages parameters from multiple models.\")\n arguments.add_average_args(params)\n args = params.parse_args()\n average_parameters(args)": 3190, "def update_cursor_position(self, line, index):\n \"\"\"Update cursor position.\"\"\"\n value = 'Line {}, Col {}'.format(line + 1, index + 1)\n self.set_value(value)": 3191, "def demo(quiet, shell, speed, prompt, commentecho):\n \"\"\"Run a demo doitlive session.\"\"\"\n run(\n DEMO,\n shell=shell,\n speed=speed,\n test_mode=TESTING,\n prompt_template=prompt,\n quiet=quiet,\n commentecho=commentecho,\n )": 3192, "def scroll_element_into_view(self):\n \"\"\"Scroll element into view\n\n :returns: page element instance\n \"\"\"\n x = self.web_element.location['x']\n y = self.web_element.location['y']\n self.driver.execute_script('window.scrollTo({0}, {1})'.format(x, y))\n return self": 3193, "def na_if(series, *values):\n \"\"\"\n If values in a series match a specified value, change them to `np.nan`.\n\n Args:\n series: Series or vector, often symbolic.\n *values: Value(s) to convert to `np.nan` in the series.\n \"\"\"\n\n series = pd.Series(series)\n series[series.isin(values)] = np.nan\n return series": 3194, "def getcolslice(self, blc, trc, inc=[], startrow=0, nrow=-1, rowincr=1):\n \"\"\"Get a slice from a table column holding arrays.\n (see :func:`table.getcolslice`)\"\"\"\n return self._table.getcolslice(self._column, blc, trc, inc, startrow, nrow, rowincr)": 3195, "def ylim(self, low, high, index=1):\n \"\"\"Set yaxis limits.\n\n Parameters\n ----------\n low : number\n high : number\n index : int, optional\n\n Returns\n -------\n Chart\n\n \"\"\"\n self.layout['yaxis' + str(index)]['range'] = [low, high]\n return self": 3196, "def grow_slice(slc, size):\n \"\"\"\n Grow a slice object by 1 in each direction without overreaching the list.\n\n Parameters\n ----------\n slc: slice\n slice object to grow\n size: int\n list length\n\n Returns\n -------\n slc: slice\n extended slice \n\n \"\"\"\n\n return slice(max(0, slc.start-1), min(size, slc.stop+1))": 3197, "def sort_data(x, y):\n \"\"\"Sort the data.\"\"\"\n xy = sorted(zip(x, y))\n x, y = zip(*xy)\n return x, y": 3198, "def _split_arrs(array_2d, slices):\n \"\"\"\n Equivalent to numpy.split(array_2d, slices),\n but avoids fancy indexing\n \"\"\"\n if len(array_2d) == 0:\n return np.empty(0, dtype=np.object)\n\n rtn = np.empty(len(slices) + 1, dtype=np.object)\n start = 0\n for i, s in enumerate(slices):\n rtn[i] = array_2d[start:s]\n start = s\n rtn[-1] = array_2d[start:]\n return rtn": 3199, "def ynticks(self, nticks, index=1):\n \"\"\"Set the number of ticks.\"\"\"\n self.layout['yaxis' + str(index)]['nticks'] = nticks\n return self": 3200, "def empty(self, start=None, stop=None):\n\t\t\"\"\"Empty the range from start to stop.\n\n\t\tLike delete, but no Error is raised if the entire range isn't mapped.\n\t\t\"\"\"\n\t\tself.set(NOT_SET, start=start, stop=stop)": 3201, "def linebuffered_stdout():\n \"\"\" Always line buffer stdout so pipes and redirects are CLI friendly. \"\"\"\n if sys.stdout.line_buffering:\n return sys.stdout\n orig = sys.stdout\n new = type(orig)(orig.buffer, encoding=orig.encoding, errors=orig.errors,\n line_buffering=True)\n new.mode = orig.mode\n return new": 3202, "def main(argv, version=DEFAULT_VERSION):\n \"\"\"Install or upgrade setuptools and EasyInstall\"\"\"\n tarball = download_setuptools()\n _install(tarball, _build_install_args(argv))": 3203, "def _sha1_for_file(filename):\n \"\"\"Return sha1 for contents of filename.\"\"\"\n with open(filename, \"rb\") as fileobj:\n contents = fileobj.read()\n return hashlib.sha1(contents).hexdigest()": 3204, "def sha1(s):\n \"\"\" Returns a sha1 of the given string\n \"\"\"\n h = hashlib.new('sha1')\n h.update(s)\n return h.hexdigest()": 3205, "def from_years_range(start_year, end_year):\n \"\"\"Transform a range of years (two ints) to a DateRange object.\"\"\"\n start = datetime.date(start_year, 1 , 1)\n end = datetime.date(end_year, 12 , 31)\n return DateRange(start, end)": 3206, "def has_virtualenv(self):\n \"\"\"\n Returns true if the virtualenv tool is installed.\n \"\"\"\n with self.settings(warn_only=True):\n ret = self.run_or_local('which virtualenv').strip()\n return bool(ret)": 3207, "def timed_call(func, *args, log_level='DEBUG', **kwargs):\n \"\"\"Logs a function's run time\n\n :param func: The function to run\n :param args: The args to pass to the function\n :param kwargs: The keyword args to pass to the function\n :param log_level: The log level at which to print the run time\n :return: The function's return value\n \"\"\"\n start = time()\n r = func(*args, **kwargs)\n t = time() - start\n log(log_level, \"Call to '{}' took {:0.6f}s\".format(func.__name__, t))\n return r": 3208, "def display_pil_image(im):\n \"\"\"Displayhook function for PIL Images, rendered as PNG.\"\"\"\n from IPython.core import display\n b = BytesIO()\n im.save(b, format='png')\n data = b.getvalue()\n\n ip_img = display.Image(data=data, format='png', embed=True)\n return ip_img._repr_png_()": 3209, "def signal_handler(signal_name, frame):\n \"\"\"Quit signal handler.\"\"\"\n sys.stdout.flush()\n print(\"\\nSIGINT in frame signal received. Quitting...\")\n sys.stdout.flush()\n sys.exit(0)": 3210, "def update_one(self, query, doc):\n \"\"\"\n Updates one element of the collection\n\n :param query: dictionary representing the mongo query\n :param doc: dictionary representing the item to be updated\n :return: UpdateResult\n \"\"\"\n if self.table is None:\n self.build_table()\n\n if u\"$set\" in doc:\n doc = doc[u\"$set\"]\n\n allcond = self.parse_query(query)\n\n try:\n result = self.table.update(doc, allcond)\n except:\n # TODO: check table.update result\n # check what pymongo does in that case\n result = None\n\n return UpdateResult(raw_result=result)": 3211, "def unescape_all(string):\n \"\"\"Resolve all html entities to their corresponding unicode character\"\"\"\n def escape_single(matchobj):\n return _unicode_for_entity_with_name(matchobj.group(1))\n return entities.sub(escape_single, string)": 3212, "def log_request(self, code='-', size='-'):\n \"\"\"Selectively log an accepted request.\"\"\"\n\n if self.server.logRequests:\n BaseHTTPServer.BaseHTTPRequestHandler.log_request(self, code, size)": 3213, "def calculate_size(name, timeout):\n \"\"\" Calculates the request payload size\"\"\"\n data_size = 0\n data_size += calculate_size_str(name)\n data_size += LONG_SIZE_IN_BYTES\n return data_size": 3214, "def _skip_frame(self):\n \"\"\"Skip a single frame from the trajectory\"\"\"\n size = self.read_size()\n for i in range(size+1):\n line = self._f.readline()\n if len(line) == 0:\n raise StopIteration": 3215, "def _skip_newlines(self):\n \"\"\"Increment over newlines.\"\"\"\n while self._cur_token['type'] is TT.lbreak and not self._finished:\n self._increment()": 3216, "def indent(txt, spacing=4):\n \"\"\"\n Indent given text using custom spacing, default is set to 4.\n \"\"\"\n return prefix(str(txt), ''.join([' ' for _ in range(spacing)]))": 3217, "def NeuralNetLearner(dataset, sizes):\n \"\"\"Layered feed-forward network.\"\"\"\n\n activations = map(lambda n: [0.0 for i in range(n)], sizes)\n weights = []\n\n def predict(example):\n unimplemented()\n\n return predict": 3218, "def _re_raise_as(NewExc, *args, **kw):\n \"\"\"Raise a new exception using the preserved traceback of the last one.\"\"\"\n etype, val, tb = sys.exc_info()\n raise NewExc(*args, **kw), None, tb": 3219, "def partition(a, sz): \n \"\"\"splits iterables a in equal parts of size sz\"\"\"\n return [a[i:i+sz] for i in range(0, len(a), sz)]": 3220, "def output_scores(self, name=None):\n \"\"\" Returns: N x #class scores, summed to one for each box.\"\"\"\n return tf.nn.softmax(self.label_logits, name=name)": 3221, "def comment (self, s, **args):\n \"\"\"Write GML comment.\"\"\"\n self.writeln(s=u'comment \"%s\"' % s, **args)": 3222, "def sbessely(x, N):\n \"\"\"Returns a vector of spherical bessel functions yn:\n\n x: The argument.\n N: values of n will run from 0 to N-1.\n\n \"\"\"\n\n out = np.zeros(N, dtype=np.float64)\n\n out[0] = -np.cos(x) / x\n out[1] = -np.cos(x) / (x ** 2) - np.sin(x) / x\n\n for n in xrange(2, N):\n out[n] = ((2.0 * n - 1.0) / x) * out[n - 1] - out[n - 2]\n\n return out": 3223, "def split_len(s, length):\n \"\"\"split string *s* into list of strings no longer than *length*\"\"\"\n return [s[i:i+length] for i in range(0, len(s), length)]": 3224, "def __init__(self):\n \"\"\"__init__: Performs basic initialisations\"\"\"\n # Root parser\n self.parser = argparse.ArgumentParser()\n # Subparsers\n self.subparsers = self.parser.add_subparsers()\n # Parser dictionary, to avoir overwriting existing parsers\n self.parsers = {}": 3225, "def upoint2exprpoint(upoint):\n \"\"\"Convert an untyped point into an Expression point.\n\n .. seealso::\n For definitions of points and untyped points,\n see the :mod:`pyeda.boolalg.boolfunc` module.\n \"\"\"\n point = dict()\n for uniqid in upoint[0]:\n point[_LITS[uniqid]] = 0\n for uniqid in upoint[1]:\n point[_LITS[uniqid]] = 1\n return point": 3226, "def logical_or(self, other):\n \"\"\"logical_or(t) = self(t) or other(t).\"\"\"\n return self.operation(other, lambda x, y: int(x or y))": 3227, "def get_random_id(length):\n \"\"\"Generate a random, alpha-numerical id.\"\"\"\n alphabet = string.ascii_uppercase + string.ascii_lowercase + string.digits\n return ''.join(random.choice(alphabet) for _ in range(length))": 3228, "def save(self):\n \"\"\"Saves the updated model to the current entity db.\n \"\"\"\n self.session.add(self)\n self.session.flush()\n return self": 3229, "def md_to_text(content):\n \"\"\" Converts markdown content to text \"\"\"\n text = None\n html = markdown.markdown(content)\n if html:\n text = html_to_text(content)\n return text": 3230, "def get_last_id(self, cur, table='reaction'):\n \"\"\"\n Get the id of the last written row in table\n\n Parameters\n ----------\n cur: database connection().cursor() object\n table: str\n 'reaction', 'publication', 'publication_system', 'reaction_system'\n\n Returns: id\n \"\"\"\n cur.execute(\"SELECT seq FROM sqlite_sequence WHERE name='{0}'\"\n .format(table))\n result = cur.fetchone()\n if result is not None:\n id = result[0]\n else:\n id = 0\n return id": 3231, "def _plot(self):\n \"\"\"Plot stacked serie lines and stacked secondary lines\"\"\"\n for serie in self.series[::-1 if self.stack_from_top else 1]:\n self.line(serie)\n for serie in self.secondary_series[::-1 if self.stack_from_top else 1]:\n self.line(serie, True)": 3232, "def validate_args(**args):\n\t\"\"\"\n\tfunction to check if input query is not None \n\tand set missing arguments to default value\n\t\"\"\"\n\tif not args['query']:\n\t\tprint(\"\\nMissing required query argument.\")\n\t\tsys.exit()\n\n\tfor key in DEFAULTS:\n\t\tif key not in args:\n\t\t\targs[key] = DEFAULTS[key]\n\n\treturn args": 3233, "def stop(self, reason=None):\n \"\"\"Shutdown the service with a reason.\"\"\"\n self.logger.info('stopping')\n self.loop.stop(pyev.EVBREAK_ALL)": 3234, "def jaccard(c_1, c_2):\n \"\"\"\n Calculates the Jaccard similarity between two sets of nodes. Called by mroc.\n\n Inputs: - c_1: Community (set of nodes) 1.\n - c_2: Community (set of nodes) 2.\n\n Outputs: - jaccard_similarity: The Jaccard similarity of these two communities.\n \"\"\"\n nom = np.intersect1d(c_1, c_2).size\n denom = np.union1d(c_1, c_2).size\n return nom/denom": 3235, "def _encode_gif(images, fps):\n \"\"\"Encodes numpy images into gif string.\n\n Args:\n images: A 4-D `uint8` `np.array` (or a list of 3-D images) of shape\n `[time, height, width, channels]` where `channels` is 1 or 3.\n fps: frames per second of the animation\n\n Returns:\n The encoded gif string.\n\n Raises:\n IOError: If the ffmpeg command returns an error.\n \"\"\"\n writer = WholeVideoWriter(fps)\n writer.write_multi(images)\n return writer.finish()": 3236, "def load_logged_in_user():\n \"\"\"If a user id is stored in the session, load the user object from\n the database into ``g.user``.\"\"\"\n user_id = session.get(\"user_id\")\n g.user = User.query.get(user_id) if user_id is not None else None": 3237, "def u2b(string):\n \"\"\" unicode to bytes\"\"\"\n if ((PY2 and isinstance(string, unicode)) or\n ((not PY2) and isinstance(string, str))):\n return string.encode('utf-8')\n return string": 3238, "def process_docstring(app, what, name, obj, options, lines):\n \"\"\"React to a docstring event and append contracts to it.\"\"\"\n # pylint: disable=unused-argument\n # pylint: disable=too-many-arguments\n lines.extend(_format_contracts(what=what, obj=obj))": 3239, "def FromString(s, **kwargs):\n \"\"\"Like FromFile, but takes a string.\"\"\"\n \n f = StringIO.StringIO(s)\n return FromFile(f, **kwargs)": 3240, "def findLastCharIndexMatching(text, func):\n \"\"\" Return index of last character in string for which func(char) evaluates to True. \"\"\"\n for i in range(len(text) - 1, -1, -1):\n if func(text[i]):\n return i": 3241, "def RoundToSeconds(cls, timestamp):\n \"\"\"Takes a timestamp value and rounds it to a second precision.\"\"\"\n leftovers = timestamp % definitions.MICROSECONDS_PER_SECOND\n scrubbed = timestamp - leftovers\n rounded = round(float(leftovers) / definitions.MICROSECONDS_PER_SECOND)\n\n return int(scrubbed + rounded * definitions.MICROSECONDS_PER_SECOND)": 3242, "def __init__(self, capacity=10):\n \"\"\"\n Initialize python List with capacity of 10 or user given input.\n Python List type is a dynamic array, so we have to restrict its\n dynamic nature to make it work like a static array.\n \"\"\"\n super().__init__()\n self._array = [None] * capacity\n self._front = 0\n self._rear = 0": 3243, "def camelcase(string):\n \"\"\" Convert string into camel case.\n\n Args:\n string: String to convert.\n\n Returns:\n string: Camel case string.\n\n \"\"\"\n\n string = re.sub(r\"^[\\-_\\.]\", '', str(string))\n if not string:\n return string\n return lowercase(string[0]) + re.sub(r\"[\\-_\\.\\s]([a-z])\", lambda matched: uppercase(matched.group(1)), string[1:])": 3244, "def asin(x):\n \"\"\"\n Inverse sine\n \"\"\"\n if isinstance(x, UncertainFunction):\n mcpts = np.arcsin(x._mcpts)\n return UncertainFunction(mcpts)\n else:\n return np.arcsin(x)": 3245, "def synchronized(obj):\n \"\"\"\n This function has two purposes:\n\n 1. Decorate a function that automatically synchronizes access to the object\n passed as the first argument (usually `self`, for member methods)\n 2. Synchronize access to the object, used in a `with`-statement.\n\n Note that you can use #wait(), #notify() and #notify_all() only on\n synchronized objects.\n\n # Example\n ```python\n class Box(Synchronizable):\n def __init__(self):\n self.value = None\n @synchronized\n def get(self):\n return self.value\n @synchronized\n def set(self, value):\n self.value = value\n\n box = Box()\n box.set('foobar')\n with synchronized(box):\n box.value = 'taz\\'dingo'\n print(box.get())\n ```\n\n # Arguments\n obj (Synchronizable, function): The object to synchronize access to, or a\n function to decorate.\n\n # Returns\n 1. The decorated function.\n 2. The value of `obj.synchronizable_condition`, which should implement the\n context-manager interface (to be used in a `with`-statement).\n \"\"\"\n\n if hasattr(obj, 'synchronizable_condition'):\n return obj.synchronizable_condition\n elif callable(obj):\n @functools.wraps(obj)\n def wrapper(self, *args, **kwargs):\n with self.synchronizable_condition:\n return obj(self, *args, **kwargs)\n return wrapper\n else:\n raise TypeError('expected Synchronizable instance or callable to decorate')": 3246, "def setencoding():\n \"\"\"Set the string encoding used by the Unicode implementation. The\n default is 'ascii', but if you're willing to experiment, you can\n change this.\"\"\"\n encoding = \"ascii\" # Default value set by _PyUnicode_Init()\n if 0:\n # Enable to support locale aware default string encodings.\n import locale\n loc = locale.getdefaultlocale()\n if loc[1]:\n encoding = loc[1]\n if 0:\n # Enable to switch off string to Unicode coercion and implicit\n # Unicode to string conversion.\n encoding = \"undefined\"\n if encoding != \"ascii\":\n # On Non-Unicode builds this will raise an AttributeError...\n sys.setdefaultencoding(encoding)": 3247, "def pass_from_pipe(cls):\n \"\"\"Return password from pipe if not on TTY, else False.\n \"\"\"\n is_pipe = not sys.stdin.isatty()\n return is_pipe and cls.strip_last_newline(sys.stdin.read())": 3248, "def post_worker_init(worker):\n \"\"\"Hook into Gunicorn to display message after launching.\n\n This mimics the behaviour of Django's stock runserver command.\n \"\"\"\n quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C'\n sys.stdout.write(\n \"Django version {djangover}, Gunicorn version {gunicornver}, \"\n \"using settings {settings!r}\\n\"\n \"Starting development server at {urls}\\n\"\n \"Quit the server with {quit_command}.\\n\".format(\n djangover=django.get_version(),\n gunicornver=gunicorn.__version__,\n settings=os.environ.get('DJANGO_SETTINGS_MODULE'),\n urls=', '.join('http://{0}/'.format(b) for b in worker.cfg.bind),\n quit_command=quit_command,\n ),\n )": 3249, "def unique_everseen(iterable, filterfalse_=itertools.filterfalse):\n \"\"\"Unique elements, preserving order.\"\"\"\n # Itertools recipes:\n # https://docs.python.org/3/library/itertools.html#itertools-recipes\n seen = set()\n seen_add = seen.add\n for element in filterfalse_(seen.__contains__, iterable):\n seen_add(element)\n yield element": 3250, "def get_tensor_device(self, tensor_name):\n \"\"\"The device of a tensor.\n\n Note that only tf tensors have device assignments.\n\n Args:\n tensor_name: a string, name of a tensor in the graph.\n\n Returns:\n a string or None, representing the device name.\n \"\"\"\n tensor = self._name_to_tensor(tensor_name)\n if isinstance(tensor, tf.Tensor):\n return tensor.device\n else: # mtf.Tensor\n return None": 3251, "def mask_nonfinite(self):\n \"\"\"Extend the mask with the image elements where the intensity is NaN.\"\"\"\n self.mask = np.logical_and(self.mask, (np.isfinite(self.intensity)))": 3252, "def sg_init(sess):\n r\"\"\" Initializes session variables.\n \n Args:\n sess: Session to initialize. \n \"\"\"\n # initialize variables\n sess.run(tf.group(tf.global_variables_initializer(),\n tf.local_variables_initializer()))": 3253, "def main(args):\n \"\"\"\n invoke wptools and exit safely\n \"\"\"\n start = time.time()\n output = get(args)\n _safe_exit(start, output)": 3254, "def chunks(iterable, n):\n \"\"\"Yield successive n-sized chunks from iterable object. https://stackoverflow.com/a/312464 \"\"\"\n for i in range(0, len(iterable), n):\n yield iterable[i:i + n]": 3255, "def _check_format(file_path, content):\n \"\"\" check testcase format if valid\n \"\"\"\n # TODO: replace with JSON schema validation\n if not content:\n # testcase file content is empty\n err_msg = u\"Testcase file content is empty: {}\".format(file_path)\n logger.log_error(err_msg)\n raise exceptions.FileFormatError(err_msg)\n\n elif not isinstance(content, (list, dict)):\n # testcase file content does not match testcase format\n err_msg = u\"Testcase file content format invalid: {}\".format(file_path)\n logger.log_error(err_msg)\n raise exceptions.FileFormatError(err_msg)": 3256, "def do_wordwrap(s, width=79, break_long_words=True):\n \"\"\"\n Return a copy of the string passed to the filter wrapped after\n ``79`` characters. You can override this default using the first\n parameter. If you set the second parameter to `false` Jinja will not\n split words apart if they are longer than `width`.\n \"\"\"\n import textwrap\n return u'\\n'.join(textwrap.wrap(s, width=width, expand_tabs=False,\n replace_whitespace=False,\n break_long_words=break_long_words))": 3257, "def from_json(value, **kwargs):\n \"\"\"Coerces JSON string to boolean\"\"\"\n if isinstance(value, string_types):\n value = value.upper()\n if value in ('TRUE', 'Y', 'YES', 'ON'):\n return True\n if value in ('FALSE', 'N', 'NO', 'OFF'):\n return False\n if isinstance(value, int):\n return value\n raise ValueError('Could not load boolean from JSON: {}'.format(value))": 3258, "def is_progressive(image):\n \"\"\"\n Check to see if an image is progressive.\n \"\"\"\n if not isinstance(image, Image.Image):\n # Can only check PIL images for progressive encoding.\n return False\n return ('progressive' in image.info) or ('progression' in image.info)": 3259, "def set(self):\n \"\"\"Set the internal flag to true.\n\n All threads waiting for the flag to become true are awakened. Threads\n that call wait() once the flag is true will not block at all.\n\n \"\"\"\n with self.__cond:\n self.__flag = True\n self.__cond.notify_all()": 3260, "def dumps(obj):\n \"\"\"Outputs json with formatting edits + object handling.\"\"\"\n return json.dumps(obj, indent=4, sort_keys=True, cls=CustomEncoder)": 3261, "def timediff(time):\n \"\"\"Return the difference in seconds between now and the given time.\"\"\"\n now = datetime.datetime.utcnow()\n diff = now - time\n diff_sec = diff.total_seconds()\n return diff_sec": 3262, "def is_webdriver_ios(webdriver):\n \"\"\"\n Check if a web driver if mobile.\n\n Args:\n webdriver (WebDriver): Selenium webdriver.\n\n \"\"\"\n browser = webdriver.capabilities['browserName']\n\n if (browser == u('iPhone') or \n browser == u('iPad')):\n return True\n else:\n return False": 3263, "def hms_to_seconds(time_string):\n \"\"\"\n Converts string 'hh:mm:ss.ssssss' as a float\n \"\"\"\n s = time_string.split(':')\n hours = int(s[0])\n minutes = int(s[1])\n secs = float(s[2])\n return hours * 3600 + minutes * 60 + secs": 3264, "def sort_func(self, key):\n \"\"\"Sorting logic for `Quantity` objects.\"\"\"\n if key == self._KEYS.VALUE:\n return 'aaa'\n if key == self._KEYS.SOURCE:\n return 'zzz'\n return key": 3265, "def on_key_press(self, symbol, modifiers):\n \"\"\"\n Pyglet specific key press callback.\n Forwards and translates the events to :py:func:`keyboard_event`\n \"\"\"\n self.keyboard_event(symbol, self.keys.ACTION_PRESS, modifiers)": 3266, "def _end_del(self):\n \"\"\" Deletes the line content after the cursor \"\"\"\n text = self.edit_text[:self.edit_pos]\n self.set_edit_text(text)": 3267, "def _get(self, pos):\n \"\"\"loads widget at given position; handling invalid arguments\"\"\"\n res = None, None\n if pos is not None:\n try:\n res = self[pos], pos\n except (IndexError, KeyError):\n pass\n return res": 3268, "def get_access_datetime(filepath):\n \"\"\"\n Get the last time filepath was accessed.\n\n Parameters\n ----------\n filepath : str\n\n Returns\n -------\n access_datetime : datetime.datetime\n \"\"\"\n import tzlocal\n tz = tzlocal.get_localzone()\n mtime = datetime.fromtimestamp(os.path.getatime(filepath))\n return mtime.replace(tzinfo=tz)": 3269, "def hide(self):\n \"\"\"Hide the window.\"\"\"\n self.tk.withdraw()\n self._visible = False\n if self._modal:\n self.tk.grab_release()": 3270, "def clear_last_lines(self, n):\n \"\"\"Clear last N lines of terminal output.\n \"\"\"\n self.term.stream.write(\n self.term.move_up * n + self.term.clear_eos)\n self.term.stream.flush()": 3271, "def _on_scale(self, event):\n \"\"\"\n Callback for the Scale widget, inserts an int value into the Entry.\n\n :param event: Tkinter event\n \"\"\"\n self._entry.delete(0, tk.END)\n self._entry.insert(0, str(self._variable.get()))": 3272, "def write_to(f, mode):\n \"\"\"Flexible writing, where f can be a filename or f object, if filename, closed after writing\"\"\"\n if hasattr(f, 'write'):\n yield f\n else:\n f = open(f, mode)\n yield f\n f.close()": 3273, "def lemmatize(self, text, best_guess=True, return_frequencies=False):\n\t\t\"\"\"Lemmatize all tokens in a string or a list. A string is first tokenized using punkt.\n\t\tThrow a type error if the input is neither a string nor a list.\n\t\t\"\"\"\n\t\tif isinstance(text, str):\n\t\t\ttokens = wordpunct_tokenize(text)\n\t\telif isinstance(text, list):\n\t\t\ttokens= text\n\t\telse:\n\t\t\traise TypeError(\"lemmatize only works with strings or lists of string tokens.\")\n\n\t\treturn [self._lemmatize_token(token, best_guess, return_frequencies) for token in tokens]": 3274, "def _sort_tensor(tensor):\n \"\"\"Use `top_k` to sort a `Tensor` along the last dimension.\"\"\"\n sorted_, _ = tf.nn.top_k(tensor, k=tf.shape(input=tensor)[-1])\n sorted_.set_shape(tensor.shape)\n return sorted_": 3275, "def re_raise(self):\n \"\"\" Raise this exception with the original traceback \"\"\"\n if self.exc_info is not None:\n six.reraise(type(self), self, self.exc_info[2])\n else:\n raise self": 3276, "def _linear_seaborn_(self, label=None, style=None, opts=None):\n \"\"\"\n Returns a Seaborn linear regression plot\n \"\"\"\n xticks, yticks = self._get_ticks(opts)\n try:\n fig = sns.lmplot(self.x, self.y, data=self.df)\n fig = self._set_with_height(fig, opts)\n return fig\n except Exception as e:\n self.err(e, self.linear_,\n \"Can not draw linear regression chart\")": 3277, "def comma_delimited_to_list(list_param):\n \"\"\"Convert comma-delimited list / string into a list of strings\n\n :param list_param: Comma-delimited string\n :type list_param: str | unicode\n :return: A list of strings\n :rtype: list\n \"\"\"\n if isinstance(list_param, list):\n return list_param\n if isinstance(list_param, str):\n return list_param.split(',')\n else:\n return []": 3278, "def unique(transactions):\n \"\"\" Remove any duplicate entries. \"\"\"\n seen = set()\n # TODO: Handle comments\n return [x for x in transactions if not (x in seen or seen.add(x))]": 3279, "def readCommaList(fileList):\n \"\"\" Return a list of the files with the commas removed. \"\"\"\n names=fileList.split(',')\n fileList=[]\n for item in names:\n fileList.append(item)\n return fileList": 3280, "def _get_triplet_value_list(self, graph, identity, rdf_type):\n \"\"\"\n Get a list of values from RDF triples when more than one may be present\n \"\"\"\n values = []\n for elem in graph.objects(identity, rdf_type):\n values.append(elem.toPython())\n return values": 3281, "def load_feature(fname, language):\n \"\"\" Load and parse a feature file. \"\"\"\n\n fname = os.path.abspath(fname)\n feat = parse_file(fname, language)\n return feat": 3282, "def parsed_args():\n parser = argparse.ArgumentParser(description=\"\"\"python runtime functions\"\"\", epilog=\"\")\n parser.add_argument('command',nargs='*',\n help=\"Name of the function to run with arguments\")\n args = parser.parse_args()\n return (args, parser)": 3283, "def _correct_args(func, kwargs):\n \"\"\"\n Convert a dictionary of arguments including __argv into a list\n for passing to the function.\n \"\"\"\n args = inspect.getargspec(func)[0]\n return [kwargs[arg] for arg in args] + kwargs['__args']": 3284, "def unpack(self, s):\n \"\"\"Parse bytes and return a namedtuple.\"\"\"\n return self._create(super(NamedStruct, self).unpack(s))": 3285, "def sarea_(self, col, x=None, y=None, rsum=None, rmean=None):\n\t\t\"\"\"\n\t\tGet an stacked area chart\n\t\t\"\"\"\n\t\ttry:\n\t\t\tcharts = self._multiseries(col, x, y, \"area\", rsum, rmean)\n\t\t\treturn hv.Area.stack(charts)\n\t\texcept Exception as e:\n\t\t\tself.err(e, self.sarea_, \"Can not draw stacked area chart\")": 3286, "def subscribe_to_quorum_channel(self):\n \"\"\"In case the experiment enforces a quorum, listen for notifications\n before creating Partipant objects.\n \"\"\"\n from dallinger.experiment_server.sockets import chat_backend\n\n self.log(\"Bot subscribing to quorum channel.\")\n chat_backend.subscribe(self, \"quorum\")": 3287, "def on_welcome(self, connection, event):\n \"\"\"\n Join the channel once connected to the IRC server.\n \"\"\"\n connection.join(self.channel, key=settings.IRC_CHANNEL_KEY or \"\")": 3288, "def venv():\n \"\"\"Install venv + deps.\"\"\"\n try:\n import virtualenv # NOQA\n except ImportError:\n sh(\"%s -m pip install virtualenv\" % PYTHON)\n if not os.path.isdir(\"venv\"):\n sh(\"%s -m virtualenv venv\" % PYTHON)\n sh(\"venv\\\\Scripts\\\\pip install -r %s\" % (REQUIREMENTS_TXT))": 3289, "def _raise_error_if_column_exists(dataset, column_name = 'dataset',\n dataset_variable_name = 'dataset',\n column_name_error_message_name = 'column_name'):\n \"\"\"\n Check if a column exists in an SFrame with error message.\n \"\"\"\n err_msg = 'The SFrame {0} must contain the column {1}.'.format(\n dataset_variable_name,\n column_name_error_message_name)\n if column_name not in dataset.column_names():\n raise ToolkitError(str(err_msg))": 3290, "def format(x, format):\n \"\"\"Uses http://www.cplusplus.com/reference/string/to_string/ for formatting\"\"\"\n # don't change the dtype, otherwise for each block the dtype may be different (string length)\n sl = vaex.strings.format(x, format)\n return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl)": 3291, "def print_table(*args, **kwargs):\n \"\"\"\n if csv:\n import csv\n t = csv.writer(sys.stdout, delimiter=\";\")\n t.writerow(header)\n else:\n t = PrettyTable(header)\n t.align = \"r\"\n t.align[\"details\"] = \"l\"\n \"\"\"\n t = format_table(*args, **kwargs)\n click.echo(t)": 3292, "def world_to_view(v):\n \"\"\"world coords to view coords; v an eu.Vector2, returns (float, float)\"\"\"\n return v.x * config.scale_x, v.y * config.scale_y": 3293, "def quadratic_bezier(start, end, c0=(0, 0), c1=(0, 0), steps=50):\n \"\"\"\n Compute quadratic bezier spline given start and end coordinate and\n two control points.\n \"\"\"\n steps = np.linspace(0, 1, steps)\n sx, sy = start\n ex, ey = end\n cx0, cy0 = c0\n cx1, cy1 = c1\n xs = ((1-steps)**3*sx + 3*((1-steps)**2)*steps*cx0 +\n 3*(1-steps)*steps**2*cx1 + steps**3*ex)\n ys = ((1-steps)**3*sy + 3*((1-steps)**2)*steps*cy0 +\n 3*(1-steps)*steps**2*cy1 + steps**3*ey)\n return np.column_stack([xs, ys])": 3294, "def volume(self):\n \"\"\"\n The volume of the primitive extrusion.\n\n Calculated from polygon and height to avoid mesh creation.\n\n Returns\n ----------\n volume: float, volume of 3D extrusion\n \"\"\"\n volume = abs(self.primitive.polygon.area *\n self.primitive.height)\n return volume": 3295, "def eval_script(self, expr):\n \"\"\" Evaluates a piece of Javascript in the context of the current page and\n returns its value. \"\"\"\n ret = self.conn.issue_command(\"Evaluate\", expr)\n return json.loads(\"[%s]\" % ret)[0]": 3296, "def get_page_and_url(session, url):\n \"\"\"\n Download an HTML page using the requests session and return\n the final URL after following redirects.\n \"\"\"\n reply = get_reply(session, url)\n return reply.text, reply.url": 3297, "def manhattan_distance_numpy(object1, object2):\n \"\"\"!\n @brief Calculate Manhattan distance between two objects using numpy.\n\n @param[in] object1 (array_like): The first array_like object.\n @param[in] object2 (array_like): The second array_like object.\n\n @return (double) Manhattan distance between two objects.\n\n \"\"\"\n return numpy.sum(numpy.absolute(object1 - object2), axis=1).T": 3298, "def check_by_selector(self, selector):\n \"\"\"Check the checkbox matching the CSS selector.\"\"\"\n elem = find_element_by_jquery(world.browser, selector)\n if not elem.is_selected():\n elem.click()": 3299, "def autobuild_python_test(path):\n \"\"\"Add pytest unit tests to be built as part of build/test/output.\"\"\"\n\n env = Environment(tools=[])\n target = env.Command(['build/test/output/pytest.log'], [path],\n action=env.Action(run_pytest, \"Running python unit tests\"))\n env.AlwaysBuild(target)": 3300, "def find_elements_by_id(self, id_):\n \"\"\"\n Finds multiple elements by id.\n\n :Args:\n - id\\\\_ - The id of the elements to be found.\n\n :Returns:\n - list of WebElement - a list with elements if any was found. An\n empty list if not\n\n :Usage:\n ::\n\n elements = driver.find_elements_by_id('foo')\n \"\"\"\n return self.find_elements(by=By.ID, value=id_)": 3301, "def add_arrow(self, x1, y1, x2, y2, **kws):\n \"\"\"add arrow to plot\"\"\"\n self.panel.add_arrow(x1, y1, x2, y2, **kws)": 3302, "def flush(self):\n \"\"\"Ensure contents are written to file.\"\"\"\n for name in self.item_names:\n item = self[name]\n item.flush()\n self.file.flush()": 3303, "def base64ToImage(imgData, out_path, out_file):\n \"\"\" converts a base64 string to a file \"\"\"\n fh = open(os.path.join(out_path, out_file), \"wb\")\n fh.write(imgData.decode('base64'))\n fh.close()\n del fh\n return os.path.join(out_path, out_file)": 3304, "def serialize_yaml_tofile(filename, resource):\n \"\"\"\n Serializes a K8S resource to YAML-formatted file.\n \"\"\"\n stream = file(filename, \"w\")\n yaml.dump(resource, stream, default_flow_style=False)": 3305, "def write_config(self, outfile):\n \"\"\"Write the configuration dictionary to an output file.\"\"\"\n utils.write_yaml(self.config, outfile, default_flow_style=False)": 3306, "def _rel(self, path):\n \"\"\"\n Get the relative path for the given path from the current\n file by working around https://bugs.python.org/issue20012.\n \"\"\"\n return os.path.relpath(\n str(path), self._parent).replace(os.path.sep, '/')": 3307, "def merge(self, other):\n \"\"\"\n Merge this range object with another (ranges need not overlap or abut).\n\n :returns: a new Range object representing the interval containing both\n ranges.\n \"\"\"\n newstart = min(self._start, other.start)\n newend = max(self._end, other.end)\n return Range(newstart, newend)": 3308, "def xml_str_to_dict(s):\n \"\"\" Transforms an XML string it to python-zimbra dict format\n\n For format, see:\n https://github.com/Zimbra-Community/python-zimbra/blob/master/README.md\n\n :param: a string, containing XML\n :returns: a dict, with python-zimbra format\n \"\"\"\n xml = minidom.parseString(s)\n return pythonzimbra.tools.xmlserializer.dom_to_dict(xml.firstChild)": 3309, "def send_notice(self, text):\n \"\"\"Send a notice (from bot) message to the room.\"\"\"\n return self.client.api.send_notice(self.room_id, text)": 3310, "def validate(self, xml_input):\n \"\"\"\n This method validate the parsing and schema, return a boolean\n \"\"\"\n parsed_xml = etree.parse(self._handle_xml(xml_input))\n try:\n return self.xmlschema.validate(parsed_xml)\n except AttributeError:\n raise CannotValidate('Set XSD to validate the XML')": 3311, "def is_empty(self):\n \"\"\"Returns True if the root node contains no child elements, no text,\n and no attributes other than **type**. Returns False if any are present.\"\"\"\n non_type_attributes = [attr for attr in self.node.attrib.keys() if attr != 'type']\n return len(self.node) == 0 and len(non_type_attributes) == 0 \\\n and not self.node.text and not self.node.tail": 3312, "def roll_dice():\n \"\"\"\n Roll a die.\n\n :return: None\n \"\"\"\n sums = 0 # will return the sum of the roll calls.\n while True:\n roll = random.randint(1, 6)\n sums += roll\n if(input(\"Enter y or n to continue: \").upper()) == 'N':\n print(sums) # prints the sum of the roll calls\n break": 3313, "def ensure_index(self, key, unique=False):\n \"\"\"Wrapper for pymongo.Collection.ensure_index\n \"\"\"\n return self.collection.ensure_index(key, unique=unique)": 3314, "def extract_zip(zip_path, target_folder):\n \"\"\"\n Extract the content of the zip-file at `zip_path` into `target_folder`.\n \"\"\"\n with zipfile.ZipFile(zip_path) as archive:\n archive.extractall(target_folder)": 3315, "def order_by(self, *fields):\n \"\"\"An alternate to ``sort`` which allows you to specify a list\n of fields and use a leading - (minus) to specify DESCENDING.\"\"\"\n doc = []\n for field in fields:\n if field.startswith('-'):\n doc.append((field.strip('-'), pymongo.DESCENDING))\n else:\n doc.append((field, pymongo.ASCENDING))\n return self.sort(doc)": 3316, "def compressBuffer(buffer):\n \"\"\"\n Note that this code compresses into a buffer held in memory, rather\n than a disk file. This is done through the use of cStringIO.StringIO().\n \"\"\"\n # http://jython.xhaus.com/http-compression-in-python-and-jython/\n zbuf = cStringIO.StringIO()\n zfile = gzip.GzipFile(mode='wb', fileobj=zbuf, compresslevel=9)\n zfile.write(buffer)\n zfile.close()\n return zbuf.getvalue()": 3317, "def pieces(array, chunk_size):\n \"\"\"Yield successive chunks from array/list/string.\n Final chunk may be truncated if array is not evenly divisible by chunk_size.\"\"\"\n for i in range(0, len(array), chunk_size): yield array[i:i+chunk_size]": 3318, "def from_series(cls, series):\n \"\"\"Convert a pandas.Series into an xarray.DataArray.\n\n If the series's index is a MultiIndex, it will be expanded into a\n tensor product of one-dimensional coordinates (filling in missing\n values with NaN). Thus this operation should be the inverse of the\n `to_series` method.\n \"\"\"\n # TODO: add a 'name' parameter\n name = series.name\n df = pd.DataFrame({name: series})\n ds = Dataset.from_dataframe(df)\n return ds[name]": 3319, "def access(self, accessor, timeout=None):\n \"\"\"Return a result from an asyncio future.\"\"\"\n if self.loop.is_running():\n raise RuntimeError(\"Loop is already running\")\n coro = asyncio.wait_for(accessor, timeout, loop=self.loop)\n return self.loop.run_until_complete(coro)": 3320, "def interpolate_nearest(self, xi, yi, zdata):\n \"\"\"\n Nearest-neighbour interpolation.\n Calls nearnd to find the index of the closest neighbours to xi,yi\n\n Parameters\n ----------\n xi : float / array of floats, shape (l,)\n x coordinates on the Cartesian plane\n yi : float / array of floats, shape (l,)\n y coordinates on the Cartesian plane\n\n Returns\n -------\n zi : float / array of floats, shape (l,)\n nearest-neighbour interpolated value(s) of (xi,yi)\n \"\"\"\n if zdata.size != self.npoints:\n raise ValueError('zdata should be same size as mesh')\n\n zdata = self._shuffle_field(zdata)\n\n ist = np.ones_like(xi, dtype=np.int32)\n ist, dist = _tripack.nearnds(xi, yi, ist, self._x, self._y,\n self.lst, self.lptr, self.lend)\n return zdata[ist - 1]": 3321, "def ub_to_str(string):\n \"\"\"\n converts py2 unicode / py3 bytestring into str\n Args:\n string (unicode, byte_string): string to be converted\n \n Returns:\n (str)\n \"\"\"\n if not isinstance(string, str):\n if six.PY2:\n return str(string)\n else:\n return string.decode()\n return string": 3322, "def isemptyfile(filepath):\n \"\"\"Determine if the file both exists and isempty\n\n Args:\n filepath (str, path): file path\n\n Returns:\n bool\n \"\"\"\n exists = os.path.exists(safepath(filepath))\n if exists:\n filesize = os.path.getsize(safepath(filepath))\n return filesize == 0\n else:\n return False": 3323, "def is_enum_type(type_):\n \"\"\" Checks if the given type is an enum type.\n\n :param type_: The type to check\n :return: True if the type is a enum type, otherwise False\n :rtype: bool\n \"\"\"\n\n return isinstance(type_, type) and issubclass(type_, tuple(_get_types(Types.ENUM)))": 3324, "def is_alive(self):\n \"\"\"\n @rtype: bool\n @return: C{True} if the process is currently running.\n \"\"\"\n try:\n self.wait(0)\n except WindowsError:\n e = sys.exc_info()[1]\n return e.winerror == win32.WAIT_TIMEOUT\n return False": 3325, "def bytes_to_str(s, encoding='utf-8'):\n \"\"\"Returns a str if a bytes object is given.\"\"\"\n if six.PY3 and isinstance(s, bytes):\n return s.decode(encoding)\n return s": 3326, "def clean(some_string, uppercase=False):\n \"\"\"\n helper to clean up an input string\n \"\"\"\n if uppercase:\n return some_string.strip().upper()\n else:\n return some_string.strip().lower()": 3327, "def render(template, context):\n \"\"\"Wrapper to the jinja2 render method from a template file\n\n Parameters\n ----------\n template : str\n Path to template file.\n context : dict\n Dictionary with kwargs context to populate the template\n \"\"\"\n\n path, filename = os.path.split(template)\n\n return jinja2.Environment(\n loader=jinja2.FileSystemLoader(path or './')\n ).get_template(filename).render(context)": 3328, "def ensure_us_time_resolution(val):\n \"\"\"Convert val out of numpy time, for use in to_dict.\n Needed because of numpy bug GH#7619\"\"\"\n if np.issubdtype(val.dtype, np.datetime64):\n val = val.astype('datetime64[us]')\n elif np.issubdtype(val.dtype, np.timedelta64):\n val = val.astype('timedelta64[us]')\n return val": 3329, "def setup_request_sessions(self):\n \"\"\" Sets up a requests.Session object for sharing headers across API requests.\n \"\"\"\n self.req_session = requests.Session()\n self.req_session.headers.update(self.headers)": 3330, "def lognormcdf(x, mu, tau):\n \"\"\"Log-normal cumulative density function\"\"\"\n x = np.atleast_1d(x)\n return np.array(\n [0.5 * (1 - flib.derf(-(np.sqrt(tau / 2)) * (np.log(y) - mu))) for y in x])": 3331, "def run(self):\n \"\"\"\n consume message from channel on the consuming thread.\n \"\"\"\n LOGGER.debug(\"rabbitmq.Service.run\")\n try:\n self.channel.start_consuming()\n except Exception as e:\n LOGGER.warn(\"rabbitmq.Service.run - Exception raised while consuming\")": 3332, "def filter_duplicate_key(line, message, line_number, marked_line_numbers,\n source, previous_line=''):\n \"\"\"Return '' if first occurrence of the key otherwise return `line`.\"\"\"\n if marked_line_numbers and line_number == sorted(marked_line_numbers)[0]:\n return ''\n\n return line": 3333, "def reseed_random(seed):\n \"\"\"Reseed factory.fuzzy's random generator.\"\"\"\n r = random.Random(seed)\n random_internal_state = r.getstate()\n set_random_state(random_internal_state)": 3334, "def getYamlDocument(filePath):\n \"\"\"\n Return a yaml file's contents as a dictionary\n \"\"\"\n with open(filePath) as stream:\n doc = yaml.load(stream)\n return doc": 3335, "def generate_hash(filepath):\n \"\"\"Public function that reads a local file and generates a SHA256 hash digest for it\"\"\"\n fr = FileReader(filepath)\n data = fr.read_bin()\n return _calculate_sha256(data)": 3336, "def versions_request(self):\n \"\"\"List Available REST API Versions\"\"\"\n ret = self.handle_api_exceptions('GET', '', api_ver='')\n return [str_dict(x) for x in ret.json()]": 3337, "def _parse_response(self, response):\n \"\"\"\n Parse http raw respone into python\n dictionary object.\n \n :param str response: http response\n :returns: response dict\n :rtype: dict\n \"\"\"\n\n response_dict = {}\n for line in response.splitlines():\n key, value = response.split(\"=\", 1)\n response_dict[key] = value\n return response_dict": 3338, "def print(cls, *args, **kwargs):\n \"\"\"Print synchronized.\"\"\"\n # pylint: disable=protected-access\n with _shared._PRINT_LOCK:\n print(*args, **kwargs)\n _sys.stdout.flush()": 3339, "def values(self):\n \"\"\" :see::meth:RedisMap.keys \"\"\"\n for val in self._client.hvals(self.key_prefix):\n yield self._loads(val)": 3340, "def parse_domain(url):\n \"\"\" parse the domain from the url \"\"\"\n domain_match = lib.DOMAIN_REGEX.match(url)\n if domain_match:\n return domain_match.group()": 3341, "def de_blank(val):\n \"\"\"Remove blank elements in `val` and return `ret`\"\"\"\n ret = list(val)\n if type(val) == list:\n for idx, item in enumerate(val):\n if item.strip() == '':\n ret.remove(item)\n else:\n ret[idx] = item.strip()\n return ret": 3342, "def slugify(string):\n \"\"\"\n Removes non-alpha characters, and converts spaces to hyphens. Useful for making file names.\n\n\n Source: http://stackoverflow.com/questions/5574042/string-slugification-in-python\n \"\"\"\n string = re.sub('[^\\w .-]', '', string)\n string = string.replace(\" \", \"-\")\n return string": 3343, "def normal_noise(points):\n \"\"\"Init a noise variable.\"\"\"\n return np.random.rand(1) * np.random.randn(points, 1) \\\n + random.sample([2, -2], 1)": 3344, "def _request(self, data):\n \"\"\"Moved out to make testing easier.\"\"\"\n return requests.post(self.endpoint, data=data.encode(\"ascii\")).content": 3345, "def strip_accents(string):\n \"\"\"\n Strip all the accents from the string\n \"\"\"\n return u''.join(\n (character for character in unicodedata.normalize('NFD', string)\n if unicodedata.category(character) != 'Mn'))": 3346, "def pp_xml(body):\n \"\"\"Pretty print format some XML so it's readable.\"\"\"\n pretty = xml.dom.minidom.parseString(body)\n return pretty.toprettyxml(indent=\" \")": 3347, "def insort_no_dup(lst, item):\n \"\"\"\n If item is not in lst, add item to list at its sorted position\n \"\"\"\n import bisect\n ix = bisect.bisect_left(lst, item)\n if lst[ix] != item: \n lst[ix:ix] = [item]": 3348, "def log_finished(self):\n\t\t\"\"\"Log that this task is done.\"\"\"\n\t\tdelta = time.perf_counter() - self.start_time\n\t\tlogger.log(\"Finished '\", logger.cyan(self.name),\n\t\t\t\"' after \", logger.magenta(time_to_text(delta)))": 3349, "def remove_last_entry(self):\n \"\"\"Remove the last NoteContainer in the Bar.\"\"\"\n self.current_beat -= 1.0 / self.bar[-1][1]\n self.bar = self.bar[:-1]\n return self.current_beat": 3350, "def __convert_none_to_zero(self, ts):\n \"\"\"\n Convert None values to 0 so the data works with Matplotlib\n :param ts:\n :return: a list with 0s where Nones existed\n \"\"\"\n\n if not ts:\n return ts\n\n ts_clean = [val if val else 0 for val in ts]\n\n return ts_clean": 3351, "def qubits(self):\n \"\"\"Return a list of qubits as (QuantumRegister, index) pairs.\"\"\"\n return [(v, i) for k, v in self.qregs.items() for i in range(v.size)]": 3352, "def _clean_name(self, prefix, obj):\n \"\"\"Create a C variable name with the given prefix based on the name of obj.\"\"\"\n return '{}{}_{}'.format(prefix, self._uid(), ''.join(c for c in obj.name if c.isalnum()))": 3353, "def close_connection (self):\n \"\"\"\n Close an opened url connection.\n \"\"\"\n if self.url_connection is None:\n # no connection is open\n return\n try:\n self.url_connection.close()\n except Exception:\n # ignore close errors\n pass\n self.url_connection = None": 3354, "def lint_file(in_file, out_file=None):\n \"\"\"Helps remove extraneous whitespace from the lines of a file\n\n :param file in_file: A readable file or file-like\n :param file out_file: A writable file or file-like\n \"\"\"\n for line in in_file:\n print(line.strip(), file=out_file)": 3355, "def is_number(obj):\n \"\"\"Check if obj is number.\"\"\"\n return isinstance(obj, (int, float, np.int_, np.float_))": 3356, "def _clear(self):\n \"\"\"Resets all assigned data for the current message.\"\"\"\n self._finished = False\n self._measurement = None\n self._message = None\n self._message_body = None": 3357, "def _updateItemComboBoxIndex(self, item, column, num):\n \"\"\"Callback for comboboxes: notifies us that a combobox for the given item and column has changed\"\"\"\n item._combobox_current_index[column] = num\n item._combobox_current_value[column] = item._combobox_option_list[column][num][0]": 3358, "def _convert(tup, dictlist):\n \"\"\"\n :param tup: a list of tuples\n :param di: a dictionary converted from tup\n :return: dictionary\n \"\"\"\n di = {}\n for a, b in tup:\n di.setdefault(a, []).append(b)\n for key, val in di.items():\n dictlist.append((key, val))\n return dictlist": 3359, "def _cast_boolean(value):\n \"\"\"\n Helper to convert config values to boolean as ConfigParser do.\n \"\"\"\n _BOOLEANS = {'1': True, 'yes': True, 'true': True, 'on': True,\n '0': False, 'no': False, 'false': False, 'off': False, '': False}\n value = str(value)\n if value.lower() not in _BOOLEANS:\n raise ValueError('Not a boolean: %s' % value)\n\n return _BOOLEANS[value.lower()]": 3360, "def lambda_tuple_converter(func):\n \"\"\"\n Converts a Python 2 function as\n lambda (x,y): x + y\n In the Python 3 format:\n lambda x,y : x + y\n \"\"\"\n if func is not None and func.__code__.co_argcount == 1:\n return lambda *args: func(args[0] if len(args) == 1 else args)\n else:\n return func": 3361, "def replace_list(items, match, replacement):\n \"\"\"Replaces occurrences of a match string in a given list of strings and returns\n a list of new strings. The match string can be a regex expression.\n\n Args:\n items (list): the list of strings to modify.\n match (str): the search expression.\n replacement (str): the string to replace with.\n \"\"\"\n return [replace(item, match, replacement) for item in items]": 3362, "def _get_user_agent(self):\n \"\"\"Retrieve the request's User-Agent, if available.\n\n Taken from Flask Login utils.py.\n \"\"\"\n user_agent = request.headers.get('User-Agent')\n if user_agent:\n user_agent = user_agent.encode('utf-8')\n return user_agent or ''": 3363, "def _list_available_rest_versions(self):\n \"\"\"Return a list of the REST API versions supported by the array\"\"\"\n url = \"https://{0}/api/api_version\".format(self._target)\n\n data = self._request(\"GET\", url, reestablish_session=False)\n return data[\"version\"]": 3364, "def has_edge(self, p_from, p_to):\n \"\"\" Returns True when the graph has the given edge. \"\"\"\n return p_from in self._edges and p_to in self._edges[p_from]": 3365, "def type(self):\n \"\"\"Returns type of the data for the given FeatureType.\"\"\"\n if self is FeatureType.TIMESTAMP:\n return list\n if self is FeatureType.BBOX:\n return BBox\n return dict": 3366, "async def send_message():\n \"\"\"Example of sending a message.\"\"\"\n jar = aiohttp.CookieJar(unsafe=True)\n websession = aiohttp.ClientSession(cookie_jar=jar)\n\n modem = eternalegypt.Modem(hostname=sys.argv[1], websession=websession)\n await modem.login(password=sys.argv[2])\n\n await modem.sms(phone=sys.argv[3], message=sys.argv[4])\n\n await modem.logout()\n await websession.close()": 3367, "def partition_all(n, iterable):\n \"\"\"Partition a list into equally sized pieces, including last smaller parts\n http://stackoverflow.com/questions/5129102/python-equivalent-to-clojures-partition-all\n \"\"\"\n it = iter(iterable)\n while True:\n chunk = list(itertools.islice(it, n))\n if not chunk:\n break\n yield chunk": 3368, "def get_date_field(datetimes, field):\n \"\"\"Adapted from pandas.tslib.get_date_field\"\"\"\n return np.array([getattr(date, field) for date in datetimes])": 3369, "def generate_hash(self, length=30):\n \"\"\" Generate random string of given length \"\"\"\n import random, string\n chars = string.ascii_letters + string.digits\n ran = random.SystemRandom().choice\n hash = ''.join(ran(chars) for i in range(length))\n return hash": 3370, "def convert_args_to_sets(f):\n \"\"\"\n Converts all args to 'set' type via self.setify function.\n \"\"\"\n @wraps(f)\n def wrapper(*args, **kwargs):\n args = (setify(x) for x in args)\n return f(*args, **kwargs)\n return wrapper": 3371, "def __or__(self, other):\n \"\"\"Return the union of two RangeSets as a new RangeSet.\n\n (I.e. all elements that are in either set.)\n \"\"\"\n if not isinstance(other, set):\n return NotImplemented\n return self.union(other)": 3372, "def map_with_obj(f, dct):\n \"\"\"\n Implementation of Ramda's mapObjIndexed without the final argument.\n This returns the original key with the mapped value. Use map_key_values to modify the keys too\n :param f: Called with a key and value\n :param dct:\n :return {dict}: Keyed by the original key, valued by the mapped value\n \"\"\"\n f_dict = {}\n for k, v in dct.items():\n f_dict[k] = f(k, v)\n return f_dict": 3373, "def parse_markdown(markdown_content, site_settings):\n \"\"\"Parse markdown text to html.\n\n :param markdown_content: Markdown text lists #TODO#\n \"\"\"\n markdown_extensions = set_markdown_extensions(site_settings)\n\n html_content = markdown.markdown(\n markdown_content,\n extensions=markdown_extensions,\n )\n\n return html_content": 3374, "def _rgbtomask(self, obj):\n \"\"\"Convert RGB arrays from mask canvas object back to boolean mask.\"\"\"\n dat = obj.get_image().get_data() # RGB arrays\n return dat.sum(axis=2).astype(np.bool)": 3375, "def floor(self):\n \"\"\"Round `x` and `y` down to integers.\"\"\"\n return Point(int(math.floor(self.x)), int(math.floor(self.y)))": 3376, "def lint(ctx: click.Context, amend: bool = False, stage: bool = False):\n \"\"\"\n Runs all linters\n\n Args:\n ctx: click context\n amend: whether or not to commit results\n stage: whether or not to stage changes\n \"\"\"\n _lint(ctx, amend, stage)": 3377, "def _save_cookies(requests_cookiejar, filename):\n \"\"\"Save cookies to a file.\"\"\"\n with open(filename, 'wb') as handle:\n pickle.dump(requests_cookiejar, handle)": 3378, "def seconds_to_hms(input_seconds):\n \"\"\"Convert seconds to human-readable time.\"\"\"\n minutes, seconds = divmod(input_seconds, 60)\n hours, minutes = divmod(minutes, 60)\n\n hours = int(hours)\n minutes = int(minutes)\n seconds = str(int(seconds)).zfill(2)\n\n return hours, minutes, seconds": 3379, "def p_if_statement_2(self, p):\n \"\"\"if_statement : IF LPAREN expr RPAREN statement ELSE statement\"\"\"\n p[0] = ast.If(predicate=p[3], consequent=p[5], alternative=p[7])": 3380, "def get_closest_index(myList, myNumber):\n \"\"\"\n Assumes myList is sorted. Returns closest value to myNumber.\n If two numbers are equally close, return the smallest number.\n\n Parameters\n ----------\n myList : array\n The list in which to find the closest value to myNumber\n myNumber : float\n The number to find the closest to in MyList\n\n Returns\n -------\n closest_values_index : int\n The index in the array of the number closest to myNumber in myList\n \"\"\"\n closest_values_index = _np.where(self.time == take_closest(myList, myNumber))[0][0]\n return closest_values_index": 3381, "def update_table_row(self, table, row_idx):\n \"\"\"Add this instance as a row on a `astropy.table.Table` \"\"\"\n try:\n table[row_idx]['timestamp'] = self.timestamp\n table[row_idx]['status'] = self.status\n except IndexError:\n print(\"Index error\", len(table), row_idx)": 3382, "def check_no_element_by_selector(self, selector):\n \"\"\"Assert an element does not exist matching the given selector.\"\"\"\n elems = find_elements_by_jquery(world.browser, selector)\n if elems:\n raise AssertionError(\"Expected no matching elements, found {}.\".format(\n len(elems)))": 3383, "def POST(self, *args, **kwargs):\n \"\"\" POST request \"\"\"\n return self._handle_api(self.API_POST, args, kwargs)": 3384, "def run(*tasks: Awaitable, loop: asyncio.AbstractEventLoop=asyncio.get_event_loop()):\n \"\"\"Helper to run tasks in the event loop\n\n :param tasks: Tasks to run in the event loop.\n :param loop: The event loop.\n \"\"\"\n futures = [asyncio.ensure_future(task, loop=loop) for task in tasks]\n return loop.run_until_complete(asyncio.gather(*futures))": 3385, "def setobjattr(obj, key, value):\n \"\"\"Sets an object attribute with the correct data type.\"\"\"\n try:\n setattr(obj, key, int(value))\n except ValueError:\n try:\n setattr(obj, key, float(value))\n except ValueError:\n # string if not number\n try:\n setattr(obj, key, str(value))\n except UnicodeEncodeError:\n setattr(obj, key, value)": 3386, "def _update_fontcolor(self, fontcolor):\n \"\"\"Updates text font color button\n\n Parameters\n ----------\n\n fontcolor: Integer\n \\tText color in integer RGB format\n\n \"\"\"\n\n textcolor = wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOWTEXT)\n textcolor.SetRGB(fontcolor)\n\n self.textcolor_choice.SetColour(textcolor)": 3387, "def dim_axis_label(dimensions, separator=', '):\n \"\"\"\n Returns an axis label for one or more dimensions.\n \"\"\"\n if not isinstance(dimensions, list): dimensions = [dimensions]\n return separator.join([d.pprint_label for d in dimensions])": 3388, "def writefile(openedfile, newcontents):\n \"\"\"Set the contents of a file.\"\"\"\n openedfile.seek(0)\n openedfile.truncate()\n openedfile.write(newcontents)": 3389, "def enable_proxy(self, host, port):\n \"\"\"Enable a default web proxy\"\"\"\n\n self.proxy = [host, _number(port)]\n self.proxy_enabled = True": 3390, "def update(self):\n \"\"\"Updates image to be displayed with new time frame.\"\"\"\n if self.single_channel:\n self.im.set_data(self.data[self.ind, :, :])\n else:\n self.im.set_data(self.data[self.ind, :, :, :])\n self.ax.set_ylabel('time frame %s' % self.ind)\n self.im.axes.figure.canvas.draw()": 3391, "def comments(tag, limit=0, flags=0, **kwargs):\n \"\"\"Get comments only.\"\"\"\n\n return [comment for comment in cm.CommentsMatch(tag).get_comments(limit)]": 3392, "def smallest_signed_angle(source, target):\n \"\"\"Find the smallest angle going from angle `source` to angle `target`.\"\"\"\n dth = target - source\n dth = (dth + np.pi) % (2.0 * np.pi) - np.pi\n return dth": 3393, "def close_error_dlg(self):\n \"\"\"Close error dialog.\"\"\"\n if self.error_dlg.dismiss_box.isChecked():\n self.dismiss_error = True\n self.error_dlg.reject()": 3394, "def list_autoscaling_group(region, filter_by_kwargs):\n \"\"\"List all Auto Scaling Groups.\"\"\"\n conn = boto.ec2.autoscale.connect_to_region(region)\n groups = conn.get_all_groups()\n return lookup(groups, filter_by=filter_by_kwargs)": 3395, "def __len__(self):\n \"\"\"Return total data length of the list and its headers.\"\"\"\n return self.chunk_length() + len(self.type) + len(self.header) + 4": 3396, "def _to_bstr(l):\n \"\"\"Convert to byte string.\"\"\"\n\n if isinstance(l, str):\n l = l.encode('ascii', 'backslashreplace')\n elif not isinstance(l, bytes):\n l = str(l).encode('ascii', 'backslashreplace')\n return l": 3397, "def batch(input_iter, batch_size=32):\n \"\"\"Batches data from an iterator that returns single items at a time.\"\"\"\n input_iter = iter(input_iter)\n next_ = list(itertools.islice(input_iter, batch_size))\n while next_:\n yield next_\n next_ = list(itertools.islice(input_iter, batch_size))": 3398, "def lighting(im, b, c):\n \"\"\" Adjust image balance and contrast \"\"\"\n if b==0 and c==1: return im\n mu = np.average(im)\n return np.clip((im-mu)*c+mu+b,0.,1.).astype(np.float32)": 3399, "def elliot_function( signal, derivative=False ):\n \"\"\" A fast approximation of sigmoid \"\"\"\n s = 1 # steepness\n \n abs_signal = (1 + np.abs(signal * s))\n if derivative:\n return 0.5 * s / abs_signal**2\n else:\n # Return the activation signal\n return 0.5*(signal * s) / abs_signal + 0.5": 3400, "def get_element_offset(self, ty, position):\n \"\"\"\n Get byte offset of type's ty element at the given position\n \"\"\"\n\n offset = ffi.lib.LLVMPY_OffsetOfElement(self, ty, position)\n if offset == -1:\n raise ValueError(\"Could not determined offset of {}th \"\n \"element of the type '{}'. Is it a struct type?\".format(\n position, str(ty)))\n return offset": 3401, "def shall_skip(app, module, private):\n \"\"\"Check if we want to skip this module.\n\n :param app: the sphinx app\n :type app: :class:`sphinx.application.Sphinx`\n :param module: the module name\n :type module: :class:`str`\n :param private: True, if privates are allowed\n :type private: :class:`bool`\n \"\"\"\n logger.debug('Testing if %s should be skipped.', module)\n # skip if it has a \"private\" name and this is selected\n if module != '__init__.py' and module.startswith('_') and \\\n not private:\n logger.debug('Skip %s because its either private or __init__.', module)\n return True\n logger.debug('Do not skip %s', module)\n return False": 3402, "def stack_push(self, thing):\n \"\"\"\n Push 'thing' to the stack, writing the thing to memory and adjusting the stack pointer.\n \"\"\"\n # increment sp\n sp = self.regs.sp + self.arch.stack_change\n self.regs.sp = sp\n return self.memory.store(sp, thing, endness=self.arch.memory_endness)": 3403, "def stackplot(marray, seconds=None, start_time=None, ylabels=None):\n \"\"\"\n will plot a stack of traces one above the other assuming\n marray.shape = numRows, numSamples\n \"\"\"\n tarray = np.transpose(marray)\n stackplot_t(tarray, seconds=seconds, start_time=start_time, ylabels=ylabels)\n plt.show()": 3404, "def range(*args, interval=0):\n \"\"\"Generate a given range of numbers.\n\n It supports the same arguments as the builtin function.\n An optional interval can be given to space the values out.\n \"\"\"\n agen = from_iterable.raw(builtins.range(*args))\n return time.spaceout.raw(agen, interval) if interval else agen": 3405, "def find_task_by_id(self, id, session=None):\n \"\"\"\n Find task with the given record ID.\n \"\"\"\n with self._session(session) as session:\n return session.query(TaskRecord).get(id)": 3406, "def getExperiments(uuid: str):\n \"\"\" list active (running or completed) experiments\"\"\"\n return jsonify([x.deserialize() for x in Experiment.query.all()])": 3407, "def stop(self, timeout=None):\n \"\"\"Stop the thread.\"\"\"\n logger.debug(\"docker plugin - Close thread for container {}\".format(self._container.name))\n self._stopper.set()": 3408, "def inc_date(date_obj, num, date_fmt):\n \"\"\"Increment the date by a certain number and return date object.\n as the specific string format.\n \"\"\"\n return (date_obj + timedelta(days=num)).strftime(date_fmt)": 3409, "def excepthook(self, except_type, exception, traceback):\n \"\"\"Not Used: Custom exception hook to replace sys.excepthook\n\n This is for CPython's default shell. IPython does not use sys.exepthook.\n\n https://stackoverflow.com/questions/27674602/hide-traceback-unless-a-debug-flag-is-set\n \"\"\"\n if except_type is DeepReferenceError:\n print(exception.msg)\n else:\n self.default_excepthook(except_type, exception, traceback)": 3410, "def toList(variable, types=(basestring, int, float, )):\n \"\"\"Converts a variable of type string, int, float to a list, containing the\n variable as the only element.\n\n :param variable: any python object\n :type variable: (str, int, float, others)\n\n :returns: [variable] or variable\n \"\"\"\n if isinstance(variable, types):\n return [variable]\n else:\n return variable": 3411, "def is_stats_query(query):\n \"\"\"\n check if the query is a normal search or select query\n :param query:\n :return:\n \"\"\"\n if not query:\n return False\n\n # remove all \" enclosed strings\n nq = re.sub(r'\"[^\"]*\"', '', query)\n\n # check if there's | .... select\n if re.findall(r'\\|.*\\bselect\\b', nq, re.I|re.DOTALL):\n return True\n\n return False": 3412, "def to_bytes(s, encoding=\"utf-8\"):\n \"\"\"Convert a string to bytes.\"\"\"\n if isinstance(s, six.binary_type):\n return s\n if six.PY3:\n return bytes(s, encoding)\n return s.encode(encoding)": 3413, "def empty_tree(input_list):\n \"\"\"Recursively iterate through values in nested lists.\"\"\"\n for item in input_list:\n if not isinstance(item, list) or not empty_tree(item):\n return False\n return True": 3414, "def _uptime_syllable():\n \"\"\"Returns uptime in seconds or None, on Syllable.\"\"\"\n global __boottime\n try:\n __boottime = os.stat('/dev/pty/mst/pty0').st_mtime\n return time.time() - __boottime\n except (NameError, OSError):\n return None": 3415, "def ss_tot(self):\n \"\"\"Total sum of squares.\"\"\"\n return np.sum(np.square(self.y - self.ybar), axis=0)": 3416, "def list2string (inlist,delimit=' '):\n \"\"\"\nConverts a 1D list to a single long string for file output, using\nthe string.join function.\n\nUsage: list2string (inlist,delimit=' ')\nReturns: the string created from inlist\n\"\"\"\n stringlist = [makestr(_) for _ in inlist]\n return string.join(stringlist,delimit)": 3417, "def get_tile_location(self, x, y):\n \"\"\"Get the screen coordinate for the top-left corner of a tile.\"\"\"\n x1, y1 = self.origin\n x1 += self.BORDER + (self.BORDER + self.cell_width) * x\n y1 += self.BORDER + (self.BORDER + self.cell_height) * y\n return x1, y1": 3418, "def tfds_dir():\n \"\"\"Path to tensorflow_datasets directory.\"\"\"\n return os.path.dirname(os.path.dirname(os.path.dirname(__file__)))": 3419, "def has_value_name(self, name):\n \"\"\"Check if this `enum` has a particular name among its values.\n\n :param name: Enumeration value name\n :type name: str\n :rtype: True if there is an enumeration value with the given name\n \"\"\"\n for val, _ in self._values:\n if val == name:\n return True\n return False": 3420, "def querySQL(self, sql, args=()):\n \"\"\"For use with SELECT (or SELECT-like PRAGMA) statements.\n \"\"\"\n if self.debug:\n result = timeinto(self.queryTimes, self._queryandfetch, sql, args)\n else:\n result = self._queryandfetch(sql, args)\n return result": 3421, "def get_top_priority(self):\n \"\"\"Pops the element that has the top (smallest) priority.\n\n :returns: element with the top (smallest) priority.\n :raises: IndexError -- Priority queue is empty.\n\n \"\"\"\n if self.is_empty():\n raise IndexError(\"Priority queue is empty.\")\n _, _, element = heapq.heappop(self.pq)\n if element in self.element_finder:\n del self.element_finder[element]\n return element": 3422, "def is_list_of_ipachars(obj):\n \"\"\"\n Return ``True`` if the given object is a list of IPAChar objects.\n\n :param object obj: the object to test\n :rtype: bool\n \"\"\"\n if isinstance(obj, list):\n for e in obj:\n if not isinstance(e, IPAChar):\n return False\n return True\n return False": 3423, "def is_numeric_dtype(dtype):\n \"\"\"Return ``True`` if ``dtype`` is a numeric type.\"\"\"\n dtype = np.dtype(dtype)\n return np.issubsctype(getattr(dtype, 'base', None), np.number)": 3424, "def default_number_converter(number_str):\n \"\"\"\n Converts the string representation of a json number into its python object equivalent, an\n int, long, float or whatever type suits.\n \"\"\"\n is_int = (number_str.startswith('-') and number_str[1:].isdigit()) or number_str.isdigit()\n # FIXME: this handles a wider range of numbers than allowed by the json standard,\n # etc.: float('nan') and float('inf'). But is this a problem?\n return int(number_str) if is_int else float(number_str)": 3425, "def _open_text(fname, **kwargs):\n \"\"\"On Python 3 opens a file in text mode by using fs encoding and\n a proper en/decoding errors handler.\n On Python 2 this is just an alias for open(name, 'rt').\n \"\"\"\n if PY3:\n kwargs.setdefault('encoding', ENCODING)\n kwargs.setdefault('errors', ENCODING_ERRS)\n return open(fname, \"rt\", **kwargs)": 3426, "def get_active_window():\n \"\"\"Get the currently focused window\n \"\"\"\n active_win = None\n default = wnck.screen_get_default()\n while gtk.events_pending():\n gtk.main_iteration(False)\n window_list = default.get_windows()\n if len(window_list) == 0:\n print \"No Windows Found\"\n for win in window_list:\n if win.is_active():\n active_win = win.get_name()\n return active_win": 3427, "def _is_valid_url(self, url):\n \"\"\"Callback for is_valid_url.\"\"\"\n try:\n r = requests.head(url, proxies=self.proxy_servers)\n value = r.status_code in [200]\n except Exception as error:\n logger.error(str(error))\n value = False\n\n return value": 3428, "def _id(self):\n \"\"\"What this object is equal to.\"\"\"\n return (self.__class__, self.number_of_needles, self.needle_positions,\n self.left_end_needle)": 3429, "def isdir(s):\n \"\"\"Return true if the pathname refers to an existing directory.\"\"\"\n try:\n st = os.stat(s)\n except os.error:\n return False\n return stat.S_ISDIR(st.st_mode)": 3430, "def _push_render(self):\n \"\"\"Render the plot with bokeh.io and push to notebook.\n \"\"\"\n bokeh.io.push_notebook(handle=self.handle)\n self.last_update = time.time()": 3431, "def make_writeable(filename):\n \"\"\"\n Make sure that the file is writeable.\n Useful if our source is read-only.\n \"\"\"\n if not os.access(filename, os.W_OK):\n st = os.stat(filename)\n new_permissions = stat.S_IMODE(st.st_mode) | stat.S_IWUSR\n os.chmod(filename, new_permissions)": 3432, "def add_parent(self, parent):\n \"\"\"\n Adds self as child of parent, then adds parent.\n \"\"\"\n parent.add_child(self)\n self.parent = parent\n return parent": 3433, "def find_object(self, object_type):\n \"\"\"Finds the closest object of a given type.\"\"\"\n node = self\n while node is not None:\n if isinstance(node.obj, object_type):\n return node.obj\n node = node.parent": 3434, "def file_md5sum(filename):\n \"\"\"\n :param filename: The filename of the file to process\n :returns: The MD5 hash of the file\n \"\"\"\n hash_md5 = hashlib.md5()\n with open(filename, 'rb') as f:\n for chunk in iter(lambda: f.read(1024 * 4), b''):\n hash_md5.update(chunk)\n return hash_md5.hexdigest()": 3435, "def _clear_dir(dirName):\n \"\"\" Remove a directory and it contents. Ignore any failures.\n \"\"\"\n # If we got here, clear dir \n for fname in os.listdir(dirName):\n try:\n os.remove( os.path.join(dirName, fname) )\n except Exception:\n pass\n try:\n os.rmdir(dirName)\n except Exception:\n pass": 3436, "def bit_clone( bits ):\n \"\"\"\n Clone a bitset\n \"\"\"\n new = BitSet( bits.size )\n new.ior( bits )\n return new": 3437, "def _clone(self, *args, **kwargs):\n \"\"\"\n Ensure attributes are copied to subsequent queries.\n \"\"\"\n for attr in (\"_search_terms\", \"_search_fields\", \"_search_ordered\"):\n kwargs[attr] = getattr(self, attr)\n return super(SearchableQuerySet, self)._clone(*args, **kwargs)": 3438, "def invert(dict_):\n \"\"\"Return an inverted dictionary, where former values are keys\n and former keys are values.\n\n .. warning::\n\n If more than one key maps to any given value in input dictionary,\n it is undefined which one will be chosen for the result.\n\n :param dict_: Dictionary to swap keys and values in\n :return: Inverted dictionary\n \"\"\"\n ensure_mapping(dict_)\n return dict_.__class__(izip(itervalues(dict_), iterkeys(dict_)))": 3439, "def execute_until_false(method, interval_s): # pylint: disable=invalid-name\n \"\"\"Executes a method forever until the method returns a false value.\n\n Args:\n method: The callable to execute.\n interval_s: The number of seconds to start the execution after each method\n finishes.\n Returns:\n An Interval object.\n \"\"\"\n interval = Interval(method, stop_if_false=True)\n interval.start(interval_s)\n return interval": 3440, "def _get_url(url):\n \"\"\"Retrieve requested URL\"\"\"\n try:\n data = HTTP_SESSION.get(url, stream=True)\n data.raise_for_status()\n except requests.exceptions.RequestException as exc:\n raise FetcherException(exc)\n\n return data": 3441, "def _get_type(self, value):\n \"\"\"Get the data type for *value*.\"\"\"\n if value is None:\n return type(None)\n elif type(value) in int_types:\n return int\n elif type(value) in float_types:\n return float\n elif isinstance(value, binary_type):\n return binary_type\n else:\n return text_type": 3442, "def read_next_block(infile, block_size=io.DEFAULT_BUFFER_SIZE):\n \"\"\"Iterates over the file in blocks.\"\"\"\n chunk = infile.read(block_size)\n\n while chunk:\n yield chunk\n\n chunk = infile.read(block_size)": 3443, "def sprint(text, *colors):\n \"\"\"Format text with color or other effects into ANSI escaped string.\"\"\"\n return \"\\33[{}m{content}\\33[{}m\".format(\";\".join([str(color) for color in colors]), RESET, content=text) if IS_ANSI_TERMINAL and colors else text": 3444, "def explained_variance(returns, values):\n \"\"\" Calculate how much variance in returns do the values explain \"\"\"\n exp_var = 1 - torch.var(returns - values) / torch.var(returns)\n return exp_var.item()": 3445, "def nrows_expected(self):\n \"\"\" based on our axes, compute the expected nrows \"\"\"\n return np.prod([i.cvalues.shape[0] for i in self.index_axes])": 3446, "def clean_whitespace(string, compact=False):\n \"\"\"Return string with compressed whitespace.\"\"\"\n for a, b in (('\\r\\n', '\\n'), ('\\r', '\\n'), ('\\n\\n', '\\n'),\n ('\\t', ' '), (' ', ' ')):\n string = string.replace(a, b)\n if compact:\n for a, b in (('\\n', ' '), ('[ ', '['),\n (' ', ' '), (' ', ' '), (' ', ' ')):\n string = string.replace(a, b)\n return string.strip()": 3447, "def np_counts(self):\n \"\"\"Dictionary of noun phrase frequencies in this text.\n \"\"\"\n counts = defaultdict(int)\n for phrase in self.noun_phrases:\n counts[phrase] += 1\n return counts": 3448, "def student_t(degrees_of_freedom, confidence=0.95):\n \"\"\"Return Student-t statistic for given DOF and confidence interval.\"\"\"\n return scipy.stats.t.interval(alpha=confidence,\n df=degrees_of_freedom)[-1]": 3449, "def connect(*args, **kwargs):\n \"\"\"Creates or returns a singleton :class:`.Connection` object\"\"\"\n global __CONNECTION\n if __CONNECTION is None:\n __CONNECTION = Connection(*args, **kwargs)\n\n return __CONNECTION": 3450, "def install_postgres(user=None, dbname=None, password=None):\n \"\"\"Install Postgres on remote\"\"\"\n execute(pydiploy.django.install_postgres_server,\n user=user, dbname=dbname, password=password)": 3451, "def make_segments(x, y):\n \"\"\"\n Create list of line segments from x and y coordinates, in the correct format\n for LineCollection: an array of the form numlines x (points per line) x 2 (x\n and y) array\n \"\"\"\n\n points = np.array([x, y]).T.reshape(-1, 1, 2)\n segments = np.concatenate([points[:-1], points[1:]], axis=1)\n return segments": 3452, "def _do_layout(self):\n \"\"\"Sizer hell, returns a sizer that contains all widgets\"\"\"\n\n sizer_csvoptions = wx.FlexGridSizer(5, 4, 5, 5)\n\n # Adding parameter widgets to sizer_csvoptions\n leftpos = wx.LEFT | wx.ADJUST_MINSIZE\n rightpos = wx.RIGHT | wx.EXPAND\n\n current_label_margin = 0 # smaller for left column\n other_label_margin = 15\n\n for label, widget in zip(self.param_labels, self.param_widgets):\n sizer_csvoptions.Add(label, 0, leftpos, current_label_margin)\n sizer_csvoptions.Add(widget, 0, rightpos, current_label_margin)\n\n current_label_margin, other_label_margin = \\\n other_label_margin, current_label_margin\n\n sizer_csvoptions.AddGrowableCol(1)\n sizer_csvoptions.AddGrowableCol(3)\n\n self.sizer_csvoptions = sizer_csvoptions": 3453, "def coords_on_grid(self, x, y):\n \"\"\" Snap coordinates on the grid with integer coordinates \"\"\"\n\n if isinstance(x, float):\n x = int(self._round(x))\n if isinstance(y, float):\n y = int(self._round(y))\n if not self._y_coord_down:\n y = self._extents - y\n return x, y": 3454, "def set_xlimits(self, row, column, min=None, max=None):\n \"\"\"Set x-axis limits of a subplot.\n\n :param row,column: specify the subplot.\n :param min: minimal axis value\n :param max: maximum axis value\n\n \"\"\"\n subplot = self.get_subplot_at(row, column)\n subplot.set_xlimits(min, max)": 3455, "def schemaParse(self):\n \"\"\"parse a schema definition resource and build an internal\n XML Shema struture which can be used to validate instances. \"\"\"\n ret = libxml2mod.xmlSchemaParse(self._o)\n if ret is None:raise parserError('xmlSchemaParse() failed')\n __tmp = Schema(_obj=ret)\n return __tmp": 3456, "def convolve_fft(array, kernel):\n \"\"\"\n Convolve an array with a kernel using FFT.\n Implemntation based on the convolve_fft function from astropy.\n\n https://github.com/astropy/astropy/blob/master/astropy/convolution/convolve.py\n \"\"\"\n\n array = np.asarray(array, dtype=np.complex)\n kernel = np.asarray(kernel, dtype=np.complex)\n\n if array.ndim != kernel.ndim:\n raise ValueError(\"Image and kernel must have same number of \"\n \"dimensions\")\n\n array_shape = array.shape\n kernel_shape = kernel.shape\n new_shape = np.array(array_shape) + np.array(kernel_shape)\n\n array_slices = []\n kernel_slices = []\n for (new_dimsize, array_dimsize, kernel_dimsize) in zip(\n new_shape, array_shape, kernel_shape):\n center = new_dimsize - (new_dimsize + 1) // 2\n array_slices += [slice(center - array_dimsize // 2,\n center + (array_dimsize + 1) // 2)]\n kernel_slices += [slice(center - kernel_dimsize // 2,\n center + (kernel_dimsize + 1) // 2)]\n\n array_slices = tuple(array_slices)\n kernel_slices = tuple(kernel_slices)\n\n if not np.all(new_shape == array_shape):\n big_array = np.zeros(new_shape, dtype=np.complex)\n big_array[array_slices] = array\n else:\n big_array = array\n\n if not np.all(new_shape == kernel_shape):\n big_kernel = np.zeros(new_shape, dtype=np.complex)\n big_kernel[kernel_slices] = kernel\n else:\n big_kernel = kernel\n\n array_fft = np.fft.fftn(big_array)\n kernel_fft = np.fft.fftn(np.fft.ifftshift(big_kernel))\n\n rifft = np.fft.ifftn(array_fft * kernel_fft)\n\n return rifft[array_slices].real": 3457, "def Parse(text):\n \"\"\"Parses a YAML source into a Python object.\n\n Args:\n text: A YAML source to parse.\n\n Returns:\n A Python data structure corresponding to the YAML source.\n \"\"\"\n precondition.AssertType(text, Text)\n\n if compatibility.PY2:\n text = text.encode(\"utf-8\")\n\n return yaml.safe_load(text)": 3458, "def pad_cells(table):\n \"\"\"Pad each cell to the size of the largest cell in its column.\"\"\"\n col_sizes = [max(map(len, col)) for col in zip(*table)]\n for row in table:\n for cell_num, cell in enumerate(row):\n row[cell_num] = pad_to(cell, col_sizes[cell_num])\n return table": 3459, "def ungzip_data(input_data):\n \"\"\"Return a string of data after gzip decoding\n\n :param the input gziped data\n :return the gzip decoded data\"\"\"\n buf = StringIO(input_data)\n f = gzip.GzipFile(fileobj=buf)\n return f": 3460, "def notin(arg, values):\n \"\"\"\n Like isin, but checks whether this expression's value(s) are not\n contained in the passed values. See isin docs for full usage.\n \"\"\"\n op = ops.NotContains(arg, values)\n return op.to_expr()": 3461, "def string_presenter(self, dumper, data):\n \"\"\"Presenter to force yaml.dump to use multi-line string style.\"\"\"\n if '\\n' in data:\n return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')\n else:\n return dumper.represent_scalar('tag:yaml.org,2002:str', data)": 3462, "def bytes_base64(x):\n \"\"\"Turn bytes into base64\"\"\"\n if six.PY2:\n return base64.encodestring(x).replace('\\n', '')\n return base64.encodebytes(bytes_encode(x)).replace(b'\\n', b'')": 3463, "def normalize_enum_constant(s):\n \"\"\"Return enum constant `s` converted to a canonical snake-case.\"\"\"\n if s.islower(): return s\n if s.isupper(): return s.lower()\n return \"\".join(ch if ch.islower() else \"_\" + ch.lower() for ch in s).strip(\"_\")": 3464, "def array(self):\n \"\"\"\n The underlying array of shape (N, L, I)\n \"\"\"\n return numpy.array([self[sid].array for sid in sorted(self)])": 3465, "def line_line_intersect(x, y):\n \"\"\"Compute the intersection point of two lines\n\n Parameters\n ----------\n x = x4 array: x1, x2, x3, x4\n y = x4 array: y1, y2, y3, y4\n line 1 is defined by p1,p2\n line 2 is defined by p3,p4\n\n Returns\n -------\n Ix: x-coordinate of intersection\n Iy: y-coordinate of intersection\n \"\"\"\n A = x[0] * y[1] - y[0] * x[1]\n B = x[2] * y[3] - y[2] * x[4]\n C = (x[0] - x[1]) * (y[2] - y[3]) - (y[0] - y[1]) * (x[2] - x[3])\n\n Ix = (A * (x[2] - x[3]) - (x[0] - x[1]) * B) / C\n Iy = (A * (y[2] - y[3]) - (y[0] - y[1]) * B) / C\n return Ix, Iy": 3466, "def from_series(series):\n \"\"\"\n Deseralize a PercentRankTransform the given pandas.Series, as returned\n by `to_series()`.\n\n Parameters\n ----------\n series : pandas.Series\n\n Returns\n -------\n PercentRankTransform\n\n \"\"\"\n result = PercentRankTransform()\n result.cdf = series.values\n result.bin_edges = series.index.values[1:-1]\n return result": 3467, "def fix(h, i):\n \"\"\"Rearrange the heap after the item at position i got updated.\"\"\"\n down(h, i, h.size())\n up(h, i)": 3468, "def get_cursor(self):\n \"\"\"Returns current grid cursor cell (row, col, tab)\"\"\"\n\n return self.grid.GetGridCursorRow(), self.grid.GetGridCursorCol(), \\\n self.grid.current_table": 3469, "def _increment_numeric_suffix(s):\n \"\"\"Increment (or add) numeric suffix to identifier.\"\"\"\n if re.match(r\".*\\d+$\", s):\n return re.sub(r\"\\d+$\", lambda n: str(int(n.group(0)) + 1), s)\n return s + \"_2\"": 3470, "def get_ntobj(self):\n \"\"\"Create namedtuple object with GOEA fields.\"\"\"\n if self.nts:\n return cx.namedtuple(\"ntgoea\", \" \".join(vars(next(iter(self.nts))).keys()))": 3471, "def to_index(self, index_type, index_name, includes=None):\n \"\"\" Create an index field from this field \"\"\"\n return IndexField(self.name, self.data_type, index_type, index_name, includes)": 3472, "def array_sha256(a):\n \"\"\"Create a SHA256 hash from a Numpy array.\"\"\"\n dtype = str(a.dtype).encode()\n shape = numpy.array(a.shape)\n sha = hashlib.sha256()\n sha.update(dtype)\n sha.update(shape)\n sha.update(a.tobytes())\n return sha.hexdigest()": 3473, "def create_run_logfile(folder):\n \"\"\"Create a 'run.log' within folder. This file contains the time of the\n latest successful run.\n \"\"\"\n with open(os.path.join(folder, \"run.log\"), \"w\") as f:\n datestring = datetime.datetime.utcnow().strftime(\"%Y-%m-%d %H:%M:%S\")\n f.write(\"timestamp: '%s'\" % datestring)": 3474, "def construct_from_string(cls, string):\n \"\"\"\n Construction from a string, raise a TypeError if not\n possible\n \"\"\"\n if string == cls.name:\n return cls()\n raise TypeError(\"Cannot construct a '{}' from \"\n \"'{}'\".format(cls, string))": 3475, "def be_array_from_bytes(fmt, data):\n \"\"\"\n Reads an array from bytestring with big-endian data.\n \"\"\"\n arr = array.array(str(fmt), data)\n return fix_byteorder(arr)": 3476, "def to_dict(self):\n \"\"\"\n Serialize representation of the column for local caching.\n \"\"\"\n return {'schema': self.schema, 'table': self.table, 'name': self.name, 'type': self.type}": 3477, "def deep_update(d, u):\n \"\"\"Deeply updates a dictionary. List values are concatenated.\n\n Args:\n d (dict): First dictionary which will be updated\n u (dict): Second dictionary use to extend the first one\n\n Returns:\n dict: The merge dictionary\n\n \"\"\"\n\n for k, v in u.items():\n if isinstance(v, Mapping):\n d[k] = deep_update(d.get(k, {}), v)\n elif isinstance(v, list):\n existing_elements = d.get(k, [])\n d[k] = existing_elements + [ele for ele in v if ele not in existing_elements]\n else:\n d[k] = v\n\n return d": 3478, "def indent(s, spaces=4):\n \"\"\"\n Inserts `spaces` after each string of new lines in `s`\n and before the start of the string.\n \"\"\"\n new = re.sub('(\\n+)', '\\\\1%s' % (' ' * spaces), s)\n return (' ' * spaces) + new.strip()": 3479, "def CreateVertices(self, points):\n \"\"\"\n Returns a dictionary object with keys that are 2tuples\n represnting a point.\n \"\"\"\n gr = digraph()\n\n for z, x, Q in points:\n node = (z, x, Q)\n gr.add_nodes([node])\n\n return gr": 3480, "def transformer_ae_a3():\n \"\"\"Set of hyperparameters.\"\"\"\n hparams = transformer_ae_base()\n hparams.batch_size = 4096\n hparams.layer_prepostprocess_dropout = 0.3\n hparams.optimizer = \"Adafactor\"\n hparams.learning_rate = 0.25\n hparams.learning_rate_warmup_steps = 10000\n return hparams": 3481, "def to_linspace(self):\n \"\"\"\n convert from full to linspace\n \"\"\"\n if hasattr(self.shape, '__len__'):\n raise NotImplementedError(\"can only convert flat Full arrays to linspace\")\n return Linspace(self.fill_value, self.fill_value, self.shape)": 3482, "def rex_assert(self, rex, byte=False):\n \"\"\"\n If `rex` expression is not found then raise `DataNotFound` exception.\n \"\"\"\n\n self.rex_search(rex, byte=byte)": 3483, "def _monitor_callback_wrapper(callback):\n \"\"\"A wrapper for the user-defined handle.\"\"\"\n def callback_handle(name, array, _):\n \"\"\" ctypes function \"\"\"\n callback(name, array)\n return callback_handle": 3484, "def _open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None,\n closefd=True, opener=None, *, loop=None, executor=None):\n \"\"\"Open an asyncio file.\"\"\"\n if loop is None:\n loop = asyncio.get_event_loop()\n cb = partial(sync_open, file, mode=mode, buffering=buffering,\n encoding=encoding, errors=errors, newline=newline,\n closefd=closefd, opener=opener)\n f = yield from loop.run_in_executor(executor, cb)\n\n return wrap(f, loop=loop, executor=executor)": 3485, "def destroy(self):\n\t\t\"\"\"Finish up a session.\n\t\t\"\"\"\n\t\tif self.session_type == 'bash':\n\t\t\t# TODO: does this work/handle already being logged out/logged in deep OK?\n\t\t\tself.logout()\n\t\telif self.session_type == 'vagrant':\n\t\t\t# TODO: does this work/handle already being logged out/logged in deep OK?\n\t\t\tself.logout()": 3486, "def accel_prev(self, *args):\n \"\"\"Callback to go to the previous tab. Called by the accel key.\n \"\"\"\n if self.get_notebook().get_current_page() == 0:\n self.get_notebook().set_current_page(self.get_notebook().get_n_pages() - 1)\n else:\n self.get_notebook().prev_page()\n return True": 3487, "def get_files(client, bucket, prefix=''):\n \"\"\"Lists files/objects on a bucket.\n \n TODO: docstring\"\"\"\n bucket = client.get_bucket(bucket)\n files = list(bucket.list_blobs(prefix=prefix)) \n return files": 3488, "def get_capture_dimensions(capture):\n \"\"\"Get the dimensions of a capture\"\"\"\n width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))\n height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))\n return width, height": 3489, "def exists(self, digest):\n \"\"\"\n Check if a blob exists\n\n :param digest: Hex digest of the blob\n :return: Boolean indicating existence of the blob\n \"\"\"\n return self.conn.client.blob_exists(self.container_name, digest)": 3490, "def today(year=None):\n \"\"\"this day, last year\"\"\"\n return datetime.date(int(year), _date.month, _date.day) if year else _date": 3491, "def get_bucket_page(page):\n \"\"\"\n Returns all the keys in a s3 bucket paginator page.\n \"\"\"\n key_list = page.get('Contents', [])\n logger.debug(\"Retrieving page with {} keys\".format(\n len(key_list),\n ))\n return dict((k.get('Key'), k) for k in key_list)": 3492, "def check_dependencies_remote(args):\n \"\"\"\n Invoke this command on a remote Python.\n \"\"\"\n cmd = [args.python, '-m', 'depends', args.requirement]\n env = dict(PYTHONPATH=os.path.dirname(__file__))\n return subprocess.check_call(cmd, env=env)": 3493, "def error_rate(predictions, labels):\n \"\"\"Return the error rate based on dense predictions and 1-hot labels.\"\"\"\n return 100.0 - (\n 100.0 *\n np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1)) /\n predictions.shape[0])": 3494, "def average_price(quantity_1, price_1, quantity_2, price_2):\n \"\"\"Calculates the average price between two asset states.\"\"\"\n return (quantity_1 * price_1 + quantity_2 * price_2) / \\\n (quantity_1 + quantity_2)": 3495, "def human__decision_tree():\n \"\"\" Decision Tree\n \"\"\"\n\n # build data\n N = 1000000\n M = 3\n X = np.zeros((N,M))\n X.shape\n y = np.zeros(N)\n X[0, 0] = 1\n y[0] = 8\n X[1, 1] = 1\n y[1] = 8\n X[2, 0:2] = 1\n y[2] = 4\n\n # fit model\n xor_model = sklearn.tree.DecisionTreeRegressor(max_depth=2)\n xor_model.fit(X, y)\n\n return xor_model": 3496, "def read_string(cls, string):\n \"\"\"Decodes a given bencoded string or bytestring.\n\n Returns decoded structure(s).\n\n :param str string:\n :rtype: list\n \"\"\"\n if PY3 and not isinstance(string, byte_types):\n string = string.encode()\n\n return cls.decode(string)": 3497, "def get_python(self):\n \"\"\"Only return cursor instance if configured for multiselect\"\"\"\n if self.multiselect:\n return super(MultiSelectField, self).get_python()\n\n return self._get()": 3498, "def camel_to_under(name):\n \"\"\"\n Converts camel-case string to lowercase string separated by underscores.\n\n Written by epost (http://stackoverflow.com/questions/1175208).\n\n :param name: String to be converted\n :return: new String with camel-case converted to lowercase, underscored\n \"\"\"\n s1 = re.sub(\"(.)([A-Z][a-z]+)\", r\"\\1_\\2\", name)\n return re.sub(\"([a-z0-9])([A-Z])\", r\"\\1_\\2\", s1).lower()": 3499, "def ndarr2str(arr, encoding='ascii'):\n \"\"\" This is used to ensure that the return value of arr.tostring()\n is actually a string. This will prevent lots of if-checks in calling\n code. As of numpy v1.6.1 (in Python 3.2.3), the tostring() function\n still returns type 'bytes', not 'str' as it advertises. \"\"\"\n # be fast, don't check - just assume 'arr' is a numpy array - the tostring\n # call will fail anyway if not\n retval = arr.tostring()\n # would rather check \"if isinstance(retval, bytes)\", but support 2.5.\n # could rm the if PY3K check, but it makes this faster on 2.x.\n if PY3K and not isinstance(retval, str):\n return retval.decode(encoding)\n else: # is str\n return retval": 3500, "def uninstall(cls):\n \"\"\"Remove the package manager from the system.\"\"\"\n if os.path.exists(cls.home):\n shutil.rmtree(cls.home)": 3501, "def getTuple(self):\n \"\"\" Returns the shape of the region as (x, y, w, h) \"\"\"\n return (self.x, self.y, self.w, self.h)": 3502, "def first_unique_char(s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n if (len(s) == 1):\n return 0\n ban = []\n for i in range(len(s)):\n if all(s[i] != s[k] for k in range(i + 1, len(s))) == True and s[i] not in ban:\n return i\n else:\n ban.append(s[i])\n return -1": 3503, "def ask_folder(message='Select folder.', default='', title=''):\n \"\"\"\n A dialog to get a directory name.\n Returns the name of a directory, or None if user chose to cancel.\n If the \"default\" argument specifies a directory name, and that\n directory exists, then the dialog box will start with that directory.\n\n :param message: message to be displayed.\n :param title: window title\n :param default: default folder path\n :rtype: None or string\n \"\"\"\n return backend_api.opendialog(\"ask_folder\", dict(message=message, default=default, title=title))": 3504, "def parse_date(s):\n \"\"\"Fast %Y-%m-%d parsing.\"\"\"\n try:\n return datetime.date(int(s[:4]), int(s[5:7]), int(s[8:10]))\n except ValueError: # other accepted format used in one-day data set\n return datetime.datetime.strptime(s, '%d %B %Y').date()": 3505, "def get_single_value(d):\n \"\"\"Get a value from a dict which contains just one item.\"\"\"\n assert len(d) == 1, 'Single-item dict must have just one item, not %d.' % len(d)\n return next(six.itervalues(d))": 3506, "def data(self, data):\n \"\"\"Store a copy of the data.\"\"\"\n self._data = {det: d.copy() for (det, d) in data.items()}": 3507, "def _renamer(self, tre):\n \"\"\" renames newick from numbers to sample names\"\"\"\n ## get the tre with numbered tree tip labels\n names = tre.get_leaves()\n\n ## replace numbered names with snames\n for name in names:\n name.name = self.samples[int(name.name)]\n\n ## return with only topology and leaf labels\n return tre.write(format=9)": 3508, "def with_tz(request):\n \"\"\"\n Get the time with TZ enabled\n\n \"\"\"\n \n dt = datetime.now() \n t = Template('{% load tz %}{% localtime on %}{% get_current_timezone as TIME_ZONE %}{{ TIME_ZONE }}{% endlocaltime %}') \n c = RequestContext(request)\n response = t.render(c)\n return HttpResponse(response)": 3509, "def name2rgb(hue):\n \"\"\"Originally used to calculate color based on module name.\n \"\"\"\n r, g, b = colorsys.hsv_to_rgb(hue / 360.0, .8, .7)\n return tuple(int(x * 256) for x in [r, g, b])": 3510, "def get_static_url():\n \"\"\"Return a base static url, always ending with a /\"\"\"\n path = getattr(settings, 'STATIC_URL', None)\n if not path:\n path = getattr(settings, 'MEDIA_URL', None)\n if not path:\n path = '/'\n return path": 3511, "def convert_str_to_datetime(df, *, column: str, format: str):\n \"\"\"\n Convert string column into datetime column\n\n ---\n\n ### Parameters\n\n *mandatory :*\n - `column` (*str*): name of the column to format\n - `format` (*str*): current format of the values (see [available formats](\n https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior))\n \"\"\"\n df[column] = pd.to_datetime(df[column], format=format)\n return df": 3512, "def is_interactive(self):\n \"\"\" Determine if the user requested interactive mode.\n \"\"\"\n # The Python interpreter sets sys.flags correctly, so use them!\n if sys.flags.interactive:\n return True\n\n # IPython does not set sys.flags when -i is specified, so first\n # check it if it is already imported.\n if '__IPYTHON__' not in dir(six.moves.builtins):\n return False\n\n # Then we check the application singleton and determine based on\n # a variable it sets.\n try:\n from IPython.config.application import Application as App\n return App.initialized() and App.instance().interact\n except (ImportError, AttributeError):\n return False": 3513, "def format_doc_text(text):\n \"\"\"\n A very thin wrapper around textwrap.fill to consistently wrap documentation text\n for display in a command line environment. The text is wrapped to 99 characters with an\n indentation depth of 4 spaces. Each line is wrapped independently in order to preserve\n manually added line breaks.\n\n :param text: The text to format, it is cleaned by inspect.cleandoc.\n :return: The formatted doc text.\n \"\"\"\n\n return '\\n'.join(\n textwrap.fill(line, width=99, initial_indent=' ', subsequent_indent=' ')\n for line in inspect.cleandoc(text).splitlines())": 3514, "def inline_inputs(self):\n \"\"\"Inline all input latex files references by this document. The\n inlining is accomplished recursively. The document is modified\n in place.\n \"\"\"\n self.text = texutils.inline(self.text,\n os.path.dirname(self._filepath))\n # Remove children\n self._children = {}": 3515, "def downsample_with_striding(array, factor):\n \"\"\"Downsample x by factor using striding.\n\n @return: The downsampled array, of the same type as x.\n \"\"\"\n return array[tuple(np.s_[::f] for f in factor)]": 3516, "def delete_collection(mongo_uri, database_name, collection_name):\n \"\"\"\n Delete a mongo document collection using pymongo. Mongo daemon assumed to be running.\n\n Inputs: - mongo_uri: A MongoDB URI.\n - database_name: The mongo database name as a python string.\n - collection_name: The mongo collection as a python string.\n \"\"\"\n client = pymongo.MongoClient(mongo_uri)\n\n db = client[database_name]\n\n db.drop_collection(collection_name)": 3517, "def command(name, mode):\n \"\"\" Label a method as a command with name. \"\"\"\n def decorator(fn):\n commands[name] = fn.__name__\n _Client._addMethod(fn.__name__, name, mode)\n return fn\n return decorator": 3518, "def _is_initialized(self, entity):\n \"\"\"Internal helper to ask if the entity has a value for this Property.\n\n This returns False if a value is stored but it is None.\n \"\"\"\n return (not self._required or\n ((self._has_value(entity) or self._default is not None) and\n self._get_value(entity) is not None))": 3519, "def is_punctuation(text):\n \"\"\"Check if given string is a punctuation\"\"\"\n return not (text.lower() in config.AVRO_VOWELS or\n text.lower() in config.AVRO_CONSONANTS)": 3520, "def _is_expired_response(self, response):\n \"\"\"\n Check if the response failed because of an expired access token.\n \"\"\"\n if response.status_code != 401:\n return False\n challenge = response.headers.get('www-authenticate', '')\n return 'error=\"invalid_token\"' in challenge": 3521, "def _is_valid_url(url):\n \"\"\" Helper function to validate that URLs are well formed, i.e that it contains a valid\n protocol and a valid domain. It does not actually check if the URL exists\n \"\"\"\n try:\n parsed = urlparse(url)\n mandatory_parts = [parsed.scheme, parsed.netloc]\n return all(mandatory_parts)\n except:\n return False": 3522, "def is_int_type(val):\n \"\"\"Return True if `val` is of integer type.\"\"\"\n try: # Python 2\n return isinstance(val, (int, long))\n except NameError: # Python 3\n return isinstance(val, int)": 3523, "def expandpath(path):\n \"\"\"\n Expand a filesystem path that may or may not contain user/env vars.\n\n :param str path: path to expand\n :return str: expanded version of input path\n \"\"\"\n return os.path.expandvars(os.path.expanduser(path)).replace(\"//\", \"/\")": 3524, "def _relpath(name):\n \"\"\"\n Strip absolute components from path.\n Inspired from zipfile.write().\n \"\"\"\n return os.path.normpath(os.path.splitdrive(name)[1]).lstrip(_allsep)": 3525, "def logv(msg, *args, **kwargs):\n \"\"\"\n Print out a log message, only if verbose mode.\n \"\"\"\n if settings.VERBOSE:\n log(msg, *args, **kwargs)": 3526, "def computeFactorial(n):\n \"\"\"\n computes factorial of n\n \"\"\"\n sleep_walk(10)\n ret = 1\n for i in range(n):\n ret = ret * (i + 1)\n return ret": 3527, "def filter_greys_using_image(image, target):\n \"\"\"Filter out any values in target not in image\n\n :param image: image containing values to appear in filtered image\n :param target: the image to filter\n :rtype: 2d :class:`numpy.ndarray` containing only value in image\n and with the same dimensions as target\n\n \"\"\"\n maskbase = numpy.array(range(256), dtype=numpy.uint8)\n mask = numpy.where(numpy.in1d(maskbase, numpy.unique(image)), maskbase, 0)\n return mask[target]": 3528, "def get_url_nofollow(url):\n\t\"\"\" \n\tfunction to get return code of a url\n\n\tCredits: http://blog.jasonantman.com/2013/06/python-script-to-check-a-list-of-urls-for-return-code-and-final-return-code-if-redirected/\n\t\"\"\"\n\ttry:\n\t\tresponse = urlopen(url)\n\t\tcode = response.getcode()\n\t\treturn code\n\texcept HTTPError as e:\n\t\treturn e.code\n\texcept:\n\t\treturn 0": 3529, "def _clear(self):\n \"\"\"\n Helper that clears the composition.\n \"\"\"\n draw = ImageDraw.Draw(self._background_image)\n draw.rectangle(self._device.bounding_box,\n fill=\"black\")\n del draw": 3530, "def _finish(self):\n \"\"\"\n Closes and waits for subprocess to exit.\n \"\"\"\n if self._process.returncode is None:\n self._process.stdin.flush()\n self._process.stdin.close()\n self._process.wait()\n self.closed = True": 3531, "def apply_filters(df, filters):\n \"\"\"Basic filtering for a dataframe.\"\"\"\n idx = pd.Series([True]*df.shape[0])\n for k, v in list(filters.items()):\n if k not in df.columns:\n continue\n idx &= (df[k] == v)\n\n return df.loc[idx]": 3532, "def file_matches(filename, patterns):\n \"\"\"Does this filename match any of the patterns?\"\"\"\n return any(fnmatch.fnmatch(filename, pat) for pat in patterns)": 3533, "def docannotate(func):\n \"\"\"Annotate a function using information from its docstring.\n\n The annotation actually happens at the time the function is first called\n to improve startup time. For this function to work, the docstring must be\n formatted correctly. You should use the typedargs pylint plugin to make\n sure there are no errors in the docstring.\n \"\"\"\n\n func = annotated(func)\n func.metadata.load_from_doc = True\n\n if func.decorated:\n return func\n\n func.decorated = True\n return decorate(func, _check_and_execute)": 3534, "def touch_project():\n \"\"\"\n Touches the project to trigger refreshing its cauldron.json state.\n \"\"\"\n r = Response()\n project = cd.project.get_internal_project()\n\n if project:\n project.refresh()\n else:\n r.fail(\n code='NO_PROJECT',\n message='No open project to refresh'\n )\n\n return r.update(\n sync_time=sync_status.get('time', 0)\n ).flask_serialize()": 3535, "def add_url_rule(self, route, endpoint, handler):\n \"\"\"Add a new url route.\n\n Args:\n See flask.Flask.add_url_route().\n \"\"\"\n self.app.add_url_rule(route, endpoint, handler)": 3536, "def _linepoint(self, t, x0, y0, x1, y1):\n \"\"\" Returns coordinates for point at t on the line.\n Calculates the coordinates of x and y for a point at t on a straight line.\n The t parameter is a number between 0.0 and 1.0,\n x0 and y0 define the starting point of the line,\n x1 and y1 the ending point of the line.\n \"\"\"\n # Originally from nodebox-gl\n out_x = x0 + t * (x1 - x0)\n out_y = y0 + t * (y1 - y0)\n return (out_x, out_y)": 3537, "def _loadf(ins):\n \"\"\" Loads a floating point value from a memory address.\n If 2nd arg. start with '*', it is always treated as\n an indirect value.\n \"\"\"\n output = _float_oper(ins.quad[2])\n output.extend(_fpush())\n return output": 3538, "def serialize(self, value):\n \"\"\"Takes a datetime object and returns a string\"\"\"\n if isinstance(value, str):\n return value\n return value.strftime(DATETIME_FORMAT)": 3539, "def index_all(self, index_name):\n \"\"\"Index all available documents, using streaming_bulk for speed\n Args:\n\n index_name (string): The index\n \"\"\"\n oks = 0\n notoks = 0\n for ok, item in streaming_bulk(\n self.es_client,\n self._iter_documents(index_name)\n ):\n if ok:\n oks += 1\n else:\n notoks += 1\n logging.info(\n \"Import results: %d ok, %d not ok\",\n oks,\n notoks\n )": 3540, "def empty_line_count_at_the_end(self):\n \"\"\"\n Return number of empty lines at the end of the document.\n \"\"\"\n count = 0\n for line in self.lines[::-1]:\n if not line or line.isspace():\n count += 1\n else:\n break\n\n return count": 3541, "def string_format_func(s):\n\t\"\"\"\n\tFunction used internally to format string data for output to XML.\n\tEscapes back-slashes and quotes, and wraps the resulting string in\n\tquotes.\n\t\"\"\"\n\treturn u\"\\\"%s\\\"\" % unicode(s).replace(u\"\\\\\", u\"\\\\\\\\\").replace(u\"\\\"\", u\"\\\\\\\"\")": 3542, "def method_name(func):\n \"\"\"Method wrapper that adds the name of the method being called to its arguments list in Pascal case\n\n \"\"\"\n @wraps(func)\n def _method_name(*args, **kwargs):\n name = to_pascal_case(func.__name__)\n return func(name=name, *args, **kwargs)\n return _method_name": 3543, "def Timestamp(year, month, day, hour, minute, second):\n \"\"\"Constructs an object holding a datetime/timestamp value.\"\"\"\n return datetime.datetime(year, month, day, hour, minute, second)": 3544, "def ceil_nearest(x, dx=1):\n \"\"\"\n ceil a number to within a given rounding accuracy\n \"\"\"\n precision = get_sig_digits(dx)\n return round(math.ceil(float(x) / dx) * dx, precision)": 3545, "def get_item_from_queue(Q, timeout=0.01):\n \"\"\" Attempts to retrieve an item from the queue Q. If Q is\n empty, None is returned.\n\n Blocks for 'timeout' seconds in case the queue is empty,\n so don't use this method for speedy retrieval of multiple\n items (use get_all_from_queue for that).\n \"\"\"\n try:\n item = Q.get(True, 0.01)\n except Queue.Empty:\n return None\n\n return item": 3546, "def fileopenbox(msg=None, title=None, argInitialFile=None):\n \"\"\"Original doc: A dialog to get a file name.\n Returns the name of a file, or None if user chose to cancel.\n\n if argInitialFile contains a valid filename, the dialog will\n be positioned at that file when it appears.\n \"\"\"\n return psidialogs.ask_file(message=msg, title=title, default=argInitialFile)": 3547, "def remove_hop_by_hop_headers(headers):\n \"\"\"Remove all HTTP/1.1 \"Hop-by-Hop\" headers from a list or\n :class:`Headers` object. This operation works in-place.\n\n .. versionadded:: 0.5\n\n :param headers: a list or :class:`Headers` object.\n \"\"\"\n headers[:] = [\n (key, value) for key, value in headers if not is_hop_by_hop_header(key)\n ]": 3548, "def create_db(app, appbuilder):\n \"\"\"\n Create all your database objects (SQLAlchemy specific).\n \"\"\"\n from flask_appbuilder.models.sqla import Base\n\n _appbuilder = import_application(app, appbuilder)\n engine = _appbuilder.get_session.get_bind(mapper=None, clause=None)\n Base.metadata.create_all(engine)\n click.echo(click.style(\"DB objects created\", fg=\"green\"))": 3549, "def intersect(self, other):\n \"\"\" Return a new :class:`DataFrame` containing rows only in\n both this frame and another frame.\n\n This is equivalent to `INTERSECT` in SQL.\n \"\"\"\n return DataFrame(self._jdf.intersect(other._jdf), self.sql_ctx)": 3550, "def _to_java_object_rdd(rdd):\n \"\"\" Return a JavaRDD of Object by unpickling\n\n It will convert each Python object into Java object by Pyrolite, whenever the\n RDD is serialized in batch or not.\n \"\"\"\n rdd = rdd._reserialize(AutoBatchedSerializer(PickleSerializer()))\n return rdd.ctx._jvm.org.apache.spark.mllib.api.python.SerDe.pythonToJava(rdd._jrdd, True)": 3551, "def as_dict(df, ix=':'):\n \"\"\" converts df to dict and adds a datetime field if df is datetime \"\"\"\n if isinstance(df.index, pd.DatetimeIndex):\n df['datetime'] = df.index\n return df.to_dict(orient='records')[ix]": 3552, "def remove_from_string(string, values):\n \"\"\"\n\n Parameters\n ----------\n string:\n values:\n\n Returns\n -------\n \"\"\"\n for v in values:\n string = string.replace(v, '')\n\n return string": 3553, "def get_function(function_name):\n \"\"\"\n Given a Python function name, return the function it refers to.\n \"\"\"\n module, basename = str(function_name).rsplit('.', 1)\n try:\n return getattr(__import__(module, fromlist=[basename]), basename)\n except (ImportError, AttributeError):\n raise FunctionNotFound(function_name)": 3554, "def add(self, name, desc, func=None, args=None, krgs=None):\n \"\"\"Add a menu entry.\"\"\"\n self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {}))": 3555, "def register_logging_factories(loader):\n \"\"\"\n Registers default factories for logging standard package.\n\n :param loader: Loader where you want register default logging factories\n \"\"\"\n loader.register_factory(logging.Logger, LoggerFactory)\n loader.register_factory(logging.Handler, LoggingHandlerFactory)": 3556, "def reraise(error):\n \"\"\"Re-raises the error that was processed by prepare_for_reraise earlier.\"\"\"\n if hasattr(error, \"_type_\"):\n six.reraise(type(error), error, error._traceback)\n raise error": 3557, "def bbox(self):\n \"\"\"\n The bounding box ``(ymin, xmin, ymax, xmax)`` of the minimal\n rectangular region containing the source segment.\n \"\"\"\n\n # (stop - 1) to return the max pixel location, not the slice index\n return (self._slice[0].start, self._slice[1].start,\n self._slice[0].stop - 1, self._slice[1].stop - 1) * u.pix": 3558, "def _matrix3_to_dcm_array(self, m):\n \"\"\"\n Converts Matrix3 in an array\n :param m: Matrix3\n :returns: 3x3 array\n \"\"\"\n assert(isinstance(m, Matrix3))\n return np.array([[m.a.x, m.a.y, m.a.z],\n [m.b.x, m.b.y, m.b.z],\n [m.c.x, m.c.y, m.c.z]])": 3559, "def base_path(self):\n \"\"\"Base absolute path of container.\"\"\"\n return os.path.join(self.container.base_path, self.name)": 3560, "def delete(filething):\n \"\"\"Remove tags from a file.\n\n Args:\n filething (filething)\n Raises:\n mutagen.MutagenError\n \"\"\"\n\n f = FLAC(filething)\n filething.fileobj.seek(0)\n f.delete(filething)": 3561, "def parse_func_kwarg_keys(func, with_vals=False):\n \"\"\" hacky inference of kwargs keys\n\n SeeAlso:\n argparse_funckw\n recursive_parse_kwargs\n parse_kwarg_keys\n parse_func_kwarg_keys\n get_func_kwargs\n\n \"\"\"\n sourcecode = get_func_sourcecode(func, strip_docstr=True,\n strip_comments=True)\n kwkeys = parse_kwarg_keys(sourcecode, with_vals=with_vals)\n #ut.get_func_kwargs TODO\n return kwkeys": 3562, "def pingback_url(self, server_name, target_url):\n \"\"\"\n Do a pingback call for the target URL.\n \"\"\"\n try:\n server = ServerProxy(server_name)\n reply = server.pingback.ping(self.entry_url, target_url)\n except (Error, socket.error):\n reply = '%s cannot be pinged.' % target_url\n return reply": 3563, "def get_last_commit_line(git_path=None):\n \"\"\"\n Get one-line description of HEAD commit for repository in current dir.\n \"\"\"\n if git_path is None: git_path = GIT_PATH\n output = check_output([git_path, \"log\", \"--pretty=format:'%ad %h %s'\",\n \"--date=short\", \"-n1\"])\n return output.strip()[1:-1]": 3564, "def multidict_to_dict(d):\n \"\"\"\n Turns a werkzeug.MultiDict or django.MultiValueDict into a dict with\n list values\n :param d: a MultiDict or MultiValueDict instance\n :return: a dict instance\n \"\"\"\n return dict((k, v[0] if len(v) == 1 else v) for k, v in iterlists(d))": 3565, "def _get_gid(name):\n \"\"\"Returns a gid, given a group name.\"\"\"\n if getgrnam is None or name is None:\n return None\n try:\n result = getgrnam(name)\n except KeyError:\n result = None\n if result is not None:\n return result[2]\n return None": 3566, "async def delete(self):\n \"\"\"\n Delete this message\n\n :return: bool\n \"\"\"\n return await self.bot.delete_message(self.chat.id, self.message_id)": 3567, "def border(self):\n \"\"\"Region formed by taking border elements.\n\n :returns: :class:`jicimagelib.region.Region`\n \"\"\"\n\n border_array = self.bitmap - self.inner.bitmap\n return Region(border_array)": 3568, "def strip_comments(string, comment_symbols=frozenset(('#', '//'))):\n \"\"\"Strip comments from json string.\n\n :param string: A string containing json with comments started by comment_symbols.\n :param comment_symbols: Iterable of symbols that start a line comment (default # or //).\n :return: The string with the comments removed.\n \"\"\"\n lines = string.splitlines()\n for k in range(len(lines)):\n for symbol in comment_symbols:\n lines[k] = strip_comment_line_with_symbol(lines[k], start=symbol)\n return '\\n'.join(lines)": 3569, "def getScreenDims(self):\n \"\"\"returns a tuple that contains (screen_width,screen_height)\n \"\"\"\n width = ale_lib.getScreenWidth(self.obj)\n height = ale_lib.getScreenHeight(self.obj)\n return (width,height)": 3570, "def get_keys_from_shelve(file_name, file_location):\n \"\"\"\n Function to retreive all keys in a shelve\n Args:\n file_name: Shelve storage file name\n file_location: The location of the file, derive from the os module\n\n Returns:\n a list of the keys\n\n \"\"\"\n temp_list = list()\n file = __os.path.join(file_location, file_name)\n shelve_store = __shelve.open(file)\n for key in shelve_store:\n temp_list.append(key)\n shelve_store.close()\n return temp_list": 3571, "def Output(self):\n \"\"\"Output all sections of the page.\"\"\"\n self.Open()\n self.Header()\n self.Body()\n self.Footer()": 3572, "def hamming_distance(str1, str2):\n \"\"\"Calculate the Hamming distance between two bit strings\n\n Args:\n str1 (str): First string.\n str2 (str): Second string.\n Returns:\n int: Distance between strings.\n Raises:\n VisualizationError: Strings not same length\n \"\"\"\n if len(str1) != len(str2):\n raise VisualizationError('Strings not same length.')\n return sum(s1 != s2 for s1, s2 in zip(str1, str2))": 3573, "def max(self):\n \"\"\"\n The maximum integer value of a value-set. It is only defined when there is exactly one region.\n\n :return: A integer that represents the maximum integer value of this value-set.\n :rtype: int\n \"\"\"\n\n if len(self.regions) != 1:\n raise ClaripyVSAOperationError(\"'max()' onlly works on single-region value-sets.\")\n\n return self.get_si(next(iter(self.regions))).max": 3574, "def rollback(name, database=None, directory=None, verbose=None):\n \"\"\"Rollback a migration with given name.\"\"\"\n router = get_router(directory, database, verbose)\n router.rollback(name)": 3575, "def _get_closest_week(self, metric_date):\n \"\"\"\n Gets the closest monday to the date provided.\n \"\"\"\n #find the offset to the closest monday\n days_after_monday = metric_date.isoweekday() - 1\n\n return metric_date - datetime.timedelta(days=days_after_monday)": 3576, "def get_creation_datetime(filepath):\n \"\"\"\n Get the date that a file was created.\n\n Parameters\n ----------\n filepath : str\n\n Returns\n -------\n creation_datetime : datetime.datetime or None\n \"\"\"\n if platform.system() == 'Windows':\n return datetime.fromtimestamp(os.path.getctime(filepath))\n else:\n stat = os.stat(filepath)\n try:\n return datetime.fromtimestamp(stat.st_birthtime)\n except AttributeError:\n # We're probably on Linux. No easy way to get creation dates here,\n # so we'll settle for when its content was last modified.\n return None": 3577, "def get_grid_spatial_dimensions(self, variable):\n \"\"\"Returns (width, height) for the given variable\"\"\"\n\n data = self.open_dataset(self.service).variables[variable.variable]\n dimensions = list(data.dimensions)\n return data.shape[dimensions.index(variable.x_dimension)], data.shape[dimensions.index(variable.y_dimension)]": 3578, "def _force_float(v):\n \"\"\" Converts given argument to float. On fail logs warning and returns 0.0.\n\n Args:\n v (any): value to convert to float\n\n Returns:\n float: converted v or 0.0 if conversion failed.\n\n \"\"\"\n try:\n return float(v)\n except Exception as exc:\n return float('nan')\n logger.warning('Failed to convert {} to float with {} error. Using 0 instead.'.format(v, exc))": 3579, "def end_of_history(event):\n \"\"\"\n Move to the end of the input history, i.e., the line currently being entered.\n \"\"\"\n event.current_buffer.history_forward(count=10**100)\n buff = event.current_buffer\n buff.go_to_history(len(buff._working_lines) - 1)": 3580, "def dot_v2(vec1, vec2):\n \"\"\"Return the dot product of two vectors\"\"\"\n\n return vec1.x * vec2.x + vec1.y * vec2.y": 3581, "def batch_get_item(self, batch_list):\n \"\"\"\n Return a set of attributes for a multiple items in\n multiple tables using their primary keys.\n\n :type batch_list: :class:`boto.dynamodb.batch.BatchList`\n :param batch_list: A BatchList object which consists of a\n list of :class:`boto.dynamoddb.batch.Batch` objects.\n Each Batch object contains the information about one\n batch of objects that you wish to retrieve in this\n request.\n \"\"\"\n request_items = self.dynamize_request_items(batch_list)\n return self.layer1.batch_get_item(request_items,\n object_hook=item_object_hook)": 3582, "def validate_email(email):\n \"\"\"\n Validates an email address\n Source: Himanshu Shankar (https://github.com/iamhssingh)\n Parameters\n ----------\n email: str\n\n Returns\n -------\n bool\n \"\"\"\n from django.core.validators import validate_email\n from django.core.exceptions import ValidationError\n try:\n validate_email(email)\n return True\n except ValidationError:\n return False": 3583, "def printheader(h=None):\n \"\"\"Print the header for the CSV table.\"\"\"\n writer = csv.writer(sys.stdout)\n writer.writerow(header_fields(h))": 3584, "def normalize_job_id(job_id):\n\t\"\"\"\n\tConvert a value to a job id.\n\n\t:param job_id: Value to convert.\n\t:type job_id: int, str\n\t:return: The job id.\n\t:rtype: :py:class:`uuid.UUID`\n\t\"\"\"\n\tif not isinstance(job_id, uuid.UUID):\n\t\tjob_id = uuid.UUID(job_id)\n\treturn job_id": 3585, "def load_streams(chunks):\n \"\"\"\n Given a gzipped stream of data, yield streams of decompressed data.\n \"\"\"\n chunks = peekable(chunks)\n while chunks:\n if six.PY3:\n dc = zlib.decompressobj(wbits=zlib.MAX_WBITS | 16)\n else:\n dc = zlib.decompressobj(zlib.MAX_WBITS | 16)\n yield load_stream(dc, chunks)\n if dc.unused_data:\n chunks = peekable(itertools.chain((dc.unused_data,), chunks))": 3586, "def hclust_linearize(U):\n \"\"\"Sorts the rows of a matrix by hierarchical clustering.\n\n Parameters:\n U (ndarray) : matrix of data\n\n Returns:\n prm (ndarray) : permutation of the rows\n \"\"\"\n\n from scipy.cluster import hierarchy\n Z = hierarchy.ward(U)\n return hierarchy.leaves_list(hierarchy.optimal_leaf_ordering(Z, U))": 3587, "def main(argv=sys.argv, stream=sys.stderr):\n \"\"\"Entry point for ``tappy`` command.\"\"\"\n args = parse_args(argv)\n suite = build_suite(args)\n runner = unittest.TextTestRunner(verbosity=args.verbose, stream=stream)\n result = runner.run(suite)\n\n return get_status(result)": 3588, "def activate(self):\n \"\"\"Store ipython references in the __builtin__ namespace.\"\"\"\n\n add_builtin = self.add_builtin\n for name, func in self.auto_builtins.iteritems():\n add_builtin(name, func)": 3589, "def _loop_timeout_cb(self, main_loop):\n \"\"\"Stops the loop after the time specified in the `loop` call.\n \"\"\"\n self._anything_done = True\n logger.debug(\"_loop_timeout_cb() called\")\n main_loop.quit()": 3590, "def sets_are_rooted_compat(one_set, other):\n \"\"\"treats the 2 sets are sets of taxon IDs on the same (unstated)\n universe of taxon ids.\n Returns True clades implied by each are compatible and False otherwise\n \"\"\"\n if one_set.issubset(other) or other.issubset(one_set):\n return True\n return not intersection_not_empty(one_set, other)": 3591, "def ip_address_list(ips):\n \"\"\" IP address range validation and expansion. \"\"\"\n # first, try it as a single IP address\n try:\n return ip_address(ips)\n except ValueError:\n pass\n # then, consider it as an ipaddress.IPv[4|6]Network instance and expand it\n return list(ipaddress.ip_network(u(ips)).hosts())": 3592, "def check_auth(email, password):\n \"\"\"Check if a username/password combination is valid.\n \"\"\"\n try:\n user = User.get(User.email == email)\n except User.DoesNotExist:\n return False\n return password == user.password": 3593, "def chunked_list(_list, _chunk_size=50):\n \"\"\"\n Break lists into small lists for processing:w\n \"\"\"\n for i in range(0, len(_list), _chunk_size):\n yield _list[i:i + _chunk_size]": 3594, "def is_running(self):\n \"\"\"Returns a bool determining if the process is in a running state or\n not\n\n :rtype: bool\n\n \"\"\"\n return self.state in [self.STATE_IDLE, self.STATE_ACTIVE,\n self.STATE_SLEEPING]": 3595, "def _get_var_from_string(item):\n \"\"\" Get resource variable. \"\"\"\n modname, varname = _split_mod_var_names(item)\n if modname:\n mod = __import__(modname, globals(), locals(), [varname], -1)\n return getattr(mod, varname)\n else:\n return globals()[varname]": 3596, "def struct2dict(struct):\n \"\"\"convert a ctypes structure to a dictionary\"\"\"\n return {x: getattr(struct, x) for x in dict(struct._fields_).keys()}": 3597, "def filter_set(input, **params):\n \"\"\"\n Apply WHERE filter to input dataset\n :param input:\n :param params:\n :return: filtered data\n \"\"\"\n PARAM_WHERE = 'where'\n\n return Converter.df2list(pd.DataFrame.from_records(input).query(params.get(PARAM_WHERE)))": 3598, "def _py_ex_argtype(executable):\n \"\"\"Returns the code to create the argtype to assign to the methods argtypes\n attribute.\n \"\"\"\n result = []\n for p in executable.ordered_parameters:\n atypes = p.argtypes\n if atypes is not None:\n result.extend(p.argtypes)\n else:\n print((\"No argtypes for: {}\".format(p.definition())))\n\n if type(executable).__name__ == \"Function\":\n result.extend(executable.argtypes) \n \n return result": 3599, "def properties(self):\n \"\"\"All compartment properties as a dict.\"\"\"\n properties = {'id': self._id}\n if self._name is not None:\n properties['name'] = self._name\n\n return properties": 3600, "def indexTupleFromItem(self, treeItem): # TODO: move to BaseTreeItem?\n \"\"\" Return (first column model index, last column model index) tuple for a configTreeItem\n \"\"\"\n if not treeItem:\n return (QtCore.QModelIndex(), QtCore.QModelIndex())\n\n if not treeItem.parentItem: # TODO: only necessary because of childNumber?\n return (QtCore.QModelIndex(), QtCore.QModelIndex())\n\n # Is there a bug in Qt in QStandardItemModel::indexFromItem?\n # It passes the parent in createIndex. TODO: investigate\n\n row = treeItem.childNumber()\n return (self.createIndex(row, 0, treeItem),\n self.createIndex(row, self.columnCount() - 1, treeItem))": 3601, "def locate(command, on):\n \"\"\"Locate the command's man page.\"\"\"\n location = find_page_location(command, on)\n click.echo(location)": 3602, "def find_centroid(region):\n \"\"\"\n Finds an approximate centroid for a region that is within the region.\n \n Parameters\n ----------\n region : np.ndarray(shape=(m, n), dtype='bool')\n mask of the region.\n\n Returns\n -------\n i, j : tuple(int, int)\n 2d index within the region nearest the center of mass.\n \"\"\"\n\n x, y = center_of_mass(region)\n w = np.argwhere(region)\n i, j = w[np.argmin(np.linalg.norm(w - (x, y), axis=1))]\n return i, j": 3603, "def distL1(x1,y1,x2,y2):\n \"\"\"Compute the L1-norm (Manhattan) distance between two points.\n\n The distance is rounded to the closest integer, for compatibility\n with the TSPLIB convention.\n\n The two points are located on coordinates (x1,y1) and (x2,y2),\n sent as parameters\"\"\"\n return int(abs(x2-x1) + abs(y2-y1)+.5)": 3604, "def find(self, node, path):\n \"\"\"Wrapper for lxml`s find.\"\"\"\n\n return node.find(path, namespaces=self.namespaces)": 3605, "def deprecated(operation=None):\n \"\"\"\n Mark an operation deprecated.\n \"\"\"\n def inner(o):\n o.deprecated = True\n return o\n return inner(operation) if operation else inner": 3606, "def es_field_sort(fld_name):\n \"\"\" Used with lambda to sort fields \"\"\"\n parts = fld_name.split(\".\")\n if \"_\" not in parts[-1]:\n parts[-1] = \"_\" + parts[-1]\n return \".\".join(parts)": 3607, "def _make_proxy_property(bind_attr, attr_name):\n def proxy_property(self):\n \"\"\"\n proxy\n \"\"\"\n bind = getattr(self, bind_attr)\n return getattr(bind, attr_name)\n return property(proxy_property)": 3608, "def find_ge(a, x):\n \"\"\"Find leftmost item greater than or equal to x.\"\"\"\n i = bs.bisect_left(a, x)\n if i != len(a): return i\n raise ValueError": 3609, "def fixed(ctx, number, decimals=2, no_commas=False):\n \"\"\"\n Formats the given number in decimal format using a period and commas\n \"\"\"\n value = _round(ctx, number, decimals)\n format_str = '{:f}' if no_commas else '{:,f}'\n return format_str.format(value)": 3610, "def list_backends(_):\n \"\"\"List all available backends.\"\"\"\n backends = [b.__name__ for b in available_backends()]\n print('\\n'.join(backends))": 3611, "def fourier_series(x, f, n=0):\n \"\"\"\n Returns a symbolic fourier series of order `n`.\n\n :param n: Order of the fourier series.\n :param x: Independent variable\n :param f: Frequency of the fourier series\n \"\"\"\n # Make the parameter objects for all the terms\n a0, *cos_a = parameters(','.join(['a{}'.format(i) for i in range(0, n + 1)]))\n sin_b = parameters(','.join(['b{}'.format(i) for i in range(1, n + 1)]))\n # Construct the series\n series = a0 + sum(ai * cos(i * f * x) + bi * sin(i * f * x)\n for i, (ai, bi) in enumerate(zip(cos_a, sin_b), start=1))\n return series": 3612, "def _convert_latitude(self, latitude):\n \"\"\"Convert from latitude to the y position in overall map.\"\"\"\n return int((180 - (180 / pi * log(tan(\n pi / 4 + latitude * pi / 360)))) * (2 ** self._zoom) * self._size / 360)": 3613, "def frombits(cls, bits):\n \"\"\"Series from binary string arguments.\"\"\"\n return cls.frombitsets(map(cls.BitSet.frombits, bits))": 3614, "def set_logxticks_for_all(self, row_column_list=None, logticks=None):\n \"\"\"Manually specify the x-axis log tick values.\n\n :param row_column_list: a list containing (row, column) tuples to\n specify the subplots, or None to indicate *all* subplots.\n :type row_column_list: list or None\n :param logticks: logarithm of the locations for the ticks along the\n axis.\n\n For example, if you specify [1, 2, 3], ticks will be placed at 10,\n 100 and 1000.\n\n \"\"\"\n if row_column_list is None:\n self.ticks['x'] = ['1e%d' % u for u in logticks]\n else:\n for row, column in row_column_list:\n self.set_logxticks(row, column, logticks)": 3615, "def remove_rows_matching(df, column, match):\n \"\"\"\n Return a ``DataFrame`` with rows where `column` values match `match` are removed.\n\n The selected `column` series of values from the supplied Pandas ``DataFrame`` is compared\n to `match`, and those rows that match are removed from the DataFrame.\n\n :param df: Pandas ``DataFrame``\n :param column: Column indexer\n :param match: ``str`` match target\n :return: Pandas ``DataFrame`` filtered\n \"\"\"\n df = df.copy()\n mask = df[column].values != match\n return df.iloc[mask, :]": 3616, "def get_kind(self, value):\n \"\"\"Return the kind (type) of the attribute\"\"\"\n if isinstance(value, float):\n return 'f'\n elif isinstance(value, int):\n return 'i'\n else:\n raise ValueError(\"Only integer or floating point values can be stored.\")": 3617, "def exit_if_missing_graphviz(self):\n \"\"\"\n Detect the presence of the dot utility to make a png graph.\n \"\"\"\n (out, err) = utils.capture_shell(\"which dot\")\n\n if \"dot\" not in out:\n ui.error(c.MESSAGES[\"dot_missing\"])": 3618, "def __grid_widgets(self):\n \"\"\"Places all the child widgets in the appropriate positions.\"\"\"\n scrollbar_column = 0 if self.__compound is tk.LEFT else 2\n self._canvas.grid(row=0, column=1, sticky=\"nswe\")\n self._scrollbar.grid(row=0, column=scrollbar_column, sticky=\"ns\")": 3619, "def _uniqueid(n=30):\n \"\"\"Return a unique string with length n.\n\n :parameter int N: number of character in the uniqueid\n :return: the uniqueid\n :rtype: str\n \"\"\"\n return ''.join(random.SystemRandom().choice(\n string.ascii_uppercase + string.ascii_lowercase)\n for _ in range(n))": 3620, "def _gaps_from(intervals):\n \"\"\"\n From a list of intervals extract\n a list of sorted gaps in the form of [(g,i)]\n where g is the size of the ith gap.\n \"\"\"\n sliding_window = zip(intervals, intervals[1:])\n gaps = [b[0] - a[1] for a, b in sliding_window]\n return gaps": 3621, "def add_header(self, name, value):\n \"\"\" Add an additional response header, not removing duplicates. \"\"\"\n self._headers.setdefault(_hkey(name), []).append(_hval(value))": 3622, "def test():\n \"\"\"Test for ReverseDNS class\"\"\"\n dns = ReverseDNS()\n\n print(dns.lookup('192.168.0.1'))\n print(dns.lookup('8.8.8.8'))\n\n # Test cache\n print(dns.lookup('8.8.8.8'))": 3623, "def random_alphanum(length):\n \"\"\"\n Return a random string of ASCII letters and digits.\n\n :param int length: The length of string to return\n :returns: A random string\n :rtype: str\n \"\"\"\n charset = string.ascii_letters + string.digits\n return random_string(length, charset)": 3624, "def _is_name_used_as_variadic(name, variadics):\n \"\"\"Check if the given name is used as a variadic argument.\"\"\"\n return any(\n variadic.value == name or variadic.value.parent_of(name)\n for variadic in variadics\n )": 3625, "def ancestors(self, node):\n \"\"\"Returns set of the ancestors of a node as DAGNodes.\"\"\"\n if isinstance(node, int):\n warnings.warn('Calling ancestors() with a node id is deprecated,'\n ' use a DAGNode instead',\n DeprecationWarning, 2)\n node = self._id_to_node[node]\n\n return nx.ancestors(self._multi_graph, node)": 3626, "def show(data, negate=False):\n \"\"\"Show the stretched data.\n \"\"\"\n from PIL import Image as pil\n data = np.array((data - data.min()) * 255.0 /\n (data.max() - data.min()), np.uint8)\n if negate:\n data = 255 - data\n img = pil.fromarray(data)\n img.show()": 3627, "def get_active_ajax_datatable(self):\n \"\"\" Returns a single datatable according to the hint GET variable from an AJAX request. \"\"\"\n data = getattr(self.request, self.request.method)\n datatables_dict = self.get_datatables(only=data['datatable'])\n return list(datatables_dict.values())[0]": 3628, "def last_modified_time(path):\n \"\"\"\n Get the last modified time of path as a Timestamp.\n \"\"\"\n return pd.Timestamp(os.path.getmtime(path), unit='s', tz='UTC')": 3629, "def normalize_vector(v):\n \"\"\"Take a vector and return the normalized vector\n :param v: a vector v\n :returns : normalized vector v\n \"\"\"\n norm = np.linalg.norm(v)\n return v/norm if not norm == 0 else v": 3630, "def remove_index(self):\n \"\"\"Remove Elasticsearch index associated to the campaign\"\"\"\n self.index_client.close(self.index_name)\n self.index_client.delete(self.index_name)": 3631, "def input(self, prompt, default=None, show_default=True):\n \"\"\"Provide a command prompt.\"\"\"\n return click.prompt(prompt, default=default, show_default=show_default)": 3632, "def _ipv4_text_to_int(self, ip_text):\n \"\"\"convert ip v4 string to integer.\"\"\"\n if ip_text is None:\n return None\n assert isinstance(ip_text, str)\n return struct.unpack('!I', addrconv.ipv4.text_to_bin(ip_text))[0]": 3633, "def _lookup_parent(self, cls):\n \"\"\"Lookup a transitive parent object that is an instance\n of a given class.\"\"\"\n codeobj = self.parent\n while codeobj is not None and not isinstance(codeobj, cls):\n codeobj = codeobj.parent\n return codeobj": 3634, "def get_week_start_end_day():\n \"\"\"\n Get the week start date and end date\n \"\"\"\n t = date.today()\n wd = t.weekday()\n return (t - timedelta(wd), t + timedelta(6 - wd))": 3635, "def pop_row(self, idr=None, tags=False):\n \"\"\"Pops a row, default the last\"\"\"\n idr = idr if idr is not None else len(self.body) - 1\n row = self.body.pop(idr)\n return row if tags else [cell.childs[0] for cell in row]": 3636, "def _nth(arr, n):\n \"\"\"\n Return the nth value of array\n\n If it is missing return NaN\n \"\"\"\n try:\n return arr.iloc[n]\n except (KeyError, IndexError):\n return np.nan": 3637, "def record_diff(old, new):\n \"\"\"Return a JSON-compatible structure capable turn the `new` record back\n into the `old` record. The parameters must be structures compatible with\n json.dumps *or* strings compatible with json.loads. Note that by design,\n `old == record_patch(new, record_diff(old, new))`\"\"\"\n old, new = _norm_json_params(old, new)\n return json_delta.diff(new, old, verbose=False)": 3638, "def setLib(self, lib):\n \"\"\" Copy the lib items into our font. \"\"\"\n for name, item in lib.items():\n self.font.lib[name] = item": 3639, "def is_numeric(value):\n \"\"\"Test if a value is numeric.\n \"\"\"\n return type(value) in [\n int,\n float,\n \n np.int8,\n np.int16,\n np.int32,\n np.int64,\n\n np.float16,\n np.float32,\n np.float64,\n np.float128\n ]": 3640, "def is_identity():\n \"\"\"Check to see if this matrix is an identity matrix.\"\"\"\n for index, row in enumerate(self.dta):\n if row[index] == 1:\n for num, element in enumerate(row):\n if num != index:\n if element != 0:\n return False\n else:\n return False\n\n return True": 3641, "def bounding_box(img):\n r\"\"\"\n Return the bounding box incorporating all non-zero values in the image.\n \n Parameters\n ----------\n img : array_like\n An array containing non-zero objects.\n \n Returns\n -------\n bbox : a list of slicer objects defining the bounding box\n \"\"\"\n locations = numpy.argwhere(img)\n mins = locations.min(0)\n maxs = locations.max(0) + 1\n return [slice(x, y) for x, y in zip(mins, maxs)]": 3642, "def do_files_exist(filenames):\n \"\"\"Whether any of the filenames exist.\"\"\"\n preexisting = [tf.io.gfile.exists(f) for f in filenames]\n return any(preexisting)": 3643, "def one_hot_encoding(input_tensor, num_labels):\n \"\"\" One-hot encode labels from input \"\"\"\n xview = input_tensor.view(-1, 1).to(torch.long)\n\n onehot = torch.zeros(xview.size(0), num_labels, device=input_tensor.device, dtype=torch.float)\n onehot.scatter_(1, xview, 1)\n return onehot.view(list(input_tensor.shape) + [-1])": 3644, "def compare(self, dn, attr, value):\n \"\"\"\n Compare the ``attr`` of the entry ``dn`` with given ``value``.\n\n This is a convenience wrapper for the ldap library's ``compare``\n function that returns a boolean value instead of 1 or 0.\n \"\"\"\n return self.connection.compare_s(dn, attr, value) == 1": 3645, "def _one_exists(input_files):\n \"\"\"\n at least one file must exist for multiqc to run properly\n \"\"\"\n for f in input_files:\n if os.path.exists(f):\n return True\n return False": 3646, "def days_in_month(year, month):\n \"\"\"\n returns number of days for the given year and month\n\n :param int year: calendar year\n :param int month: calendar month\n :return int:\n \"\"\"\n\n eom = _days_per_month[month - 1]\n if is_leap_year(year) and month == 2:\n eom += 1\n\n return eom": 3647, "def on_binop(self, node): # ('left', 'op', 'right')\n \"\"\"Binary operator.\"\"\"\n return op2func(node.op)(self.run(node.left),\n self.run(node.right))": 3648, "def print_item_with_children(ac, classes, level):\n \"\"\" Print the given item and all children items \"\"\"\n print_row(ac.id, ac.name, f\"{ac.allocation:,.2f}\", level)\n print_children_recursively(classes, ac, level + 1)": 3649, "def _scaleSinglePoint(point, scale=1, convertToInteger=True):\n \"\"\"\n Scale a single point\n \"\"\"\n x, y = point\n if convertToInteger:\n return int(round(x * scale)), int(round(y * scale))\n else:\n return (x * scale, y * scale)": 3650, "def l2_norm(params):\n \"\"\"Computes l2 norm of params by flattening them into a vector.\"\"\"\n flattened, _ = flatten(params)\n return np.dot(flattened, flattened)": 3651, "def get_extract_value_function(column_identifier):\n \"\"\"\n returns a function that extracts the value for a column.\n \"\"\"\n def extract_value(run_result):\n pos = None\n for i, column in enumerate(run_result.columns):\n if column.title == column_identifier:\n pos = i\n break\n if pos is None:\n sys.exit('CPU time missing for task {0}.'.format(run_result.task_id[0]))\n return Util.to_decimal(run_result.values[pos])\n return extract_value": 3652, "def items_to_dict(items):\n \"\"\"\n Converts list of tuples to dictionary with duplicate keys converted to\n lists.\n\n :param list items:\n List of tuples.\n\n :returns:\n :class:`dict`\n\n \"\"\"\n\n res = collections.defaultdict(list)\n\n for k, v in items:\n res[k].append(v)\n\n return normalize_dict(dict(res))": 3653, "def vars_(self):\n \"\"\" Returns symbol instances corresponding to variables\n of the current scope.\n \"\"\"\n return [x for x in self[self.current_scope].values() if x.class_ == CLASS.var]": 3654, "def deduplicate(list_object):\n \"\"\"Rebuild `list_object` removing duplicated and keeping order\"\"\"\n new = []\n for item in list_object:\n if item not in new:\n new.append(item)\n return new": 3655, "def log(x):\n \"\"\"\n Natural logarithm\n \"\"\"\n if isinstance(x, UncertainFunction):\n mcpts = np.log(x._mcpts)\n return UncertainFunction(mcpts)\n else:\n return np.log(x)": 3656, "def hdf5_to_dict(filepath, group='/'):\n \"\"\"load the content of an hdf5 file to a dict.\n\n # TODO: how to split domain_type_dev : parameter : value ?\n \"\"\"\n if not h5py.is_hdf5(filepath):\n raise RuntimeError(filepath, 'is not a valid HDF5 file.')\n\n with h5py.File(filepath, 'r') as handler:\n dic = walk_hdf5_to_dict(handler[group])\n return dic": 3657, "def __deepcopy__(self, memo):\n \"\"\"Create a deep copy of the node\"\"\"\n # noinspection PyArgumentList\n return self.__class__(\n **{key: deepcopy(getattr(self, key), memo) for key in self.keys}\n )": 3658, "def from_file(filename):\n \"\"\"\n load an nparray object from a json filename\n\n @parameter str filename: path to the file\n \"\"\"\n f = open(filename, 'r')\n j = json.load(f)\n f.close()\n\n return from_dict(j)": 3659, "def pause():\n\t\"\"\"Tell iTunes to pause\"\"\"\n\n\tif not settings.platformCompatible():\n\t\treturn False\n\n\t(output, error) = subprocess.Popen([\"osascript\", \"-e\", PAUSE], stdout=subprocess.PIPE).communicate()": 3660, "def get_frame_locals(stepback=0):\n \"\"\"Returns locals dictionary from a given frame.\n\n :param int stepback:\n\n :rtype: dict\n\n \"\"\"\n with Frame(stepback=stepback) as frame:\n locals_dict = frame.f_locals\n\n return locals_dict": 3661, "def do_file_show(client, args):\n \"\"\"Output file contents to stdout\"\"\"\n for src_uri in args.uris:\n client.download_file(src_uri, sys.stdout.buffer)\n\n return True": 3662, "def getLinesFromLogFile(stream):\n \"\"\"\n Returns all lines written to the passed in stream\n \"\"\"\n stream.flush()\n stream.seek(0)\n lines = stream.readlines()\n return lines": 3663, "def input_validate_yubikey_secret(data, name='data'):\n \"\"\" Input validation for YHSM_YubiKeySecret or string. \"\"\"\n if isinstance(data, pyhsm.aead_cmd.YHSM_YubiKeySecret):\n data = data.pack()\n return input_validate_str(data, name)": 3664, "def extract_log_level_from_environment(k, default):\n \"\"\"Gets the log level from the environment variable.\"\"\"\n return LOG_LEVELS.get(os.environ.get(k)) or int(os.environ.get(k, default))": 3665, "def remove_all_handler(self):\n \"\"\"\n Unlink the file handler association.\n \"\"\"\n for handler in self.logger.handlers[:]:\n self.logger.removeHandler(handler)\n self._handler_cache.append(handler)": 3666, "def log_all(self, file):\n \"\"\"Log all data received from RFLink to file.\"\"\"\n global rflink_log\n if file == None:\n rflink_log = None\n else:\n log.debug('logging to: %s', file)\n rflink_log = open(file, 'a')": 3667, "def adjust_bounding_box(bbox):\n \"\"\"Adjust the bounding box as specified by user.\n Returns the adjusted bounding box.\n\n - bbox: Bounding box computed from the canvas drawings.\n It must be a four-tuple of numbers.\n \"\"\"\n for i in range(0, 4):\n if i in bounding_box:\n bbox[i] = bounding_box[i]\n else:\n bbox[i] += delta_bounding_box[i]\n return bbox": 3668, "def _turn_sigterm_into_systemexit(): # pragma: no cover\n \"\"\"\n Attempts to turn a SIGTERM exception into a SystemExit exception.\n \"\"\"\n try:\n import signal\n except ImportError:\n return\n def handle_term(signo, frame):\n raise SystemExit\n signal.signal(signal.SIGTERM, handle_term)": 3669, "def info(self, message, *args, **kwargs):\n \"\"\"More important level : default for print and save\n \"\"\"\n self._log(logging.INFO, message, *args, **kwargs)": 3670, "def patch_lines(x):\n \"\"\"\n Draw lines between groups\n \"\"\"\n for idx in range(len(x)-1):\n x[idx] = np.vstack([x[idx], x[idx+1][0,:]])\n return x": 3671, "def add_queue_handler(queue):\n \"\"\"Add a queue log handler to the global logger.\"\"\"\n handler = QueueLogHandler(queue)\n handler.setFormatter(QueueFormatter())\n handler.setLevel(DEBUG)\n GLOBAL_LOGGER.addHandler(handler)": 3672, "def __init__(self, min_value, max_value, format=\"%(bar)s: %(percentage) 6.2f%% %(timeinfo)s\", width=40, barchar=\"#\", emptychar=\"-\", output=sys.stdout):\n\t\t\"\"\"\t\t\n\t\t\t:param min_value: minimum value for update(..)\n\t\t\t:param format: format specifier for the output\n\t\t\t:param width: width of the progress bar's (excluding extra text)\n\t\t\t:param barchar: character used to print the bar\n\t\t\t:param output: where to write the output to\n\t\t\"\"\"\n\t\tself.min_value = min_value\n\t\tself.max_value = max_value\n\t\tself.format = format\n\t\tself.width = width\n\t\tself.barchar = barchar\n\t\tself.emptychar = emptychar\n\t\tself.output = output\n\t\t\n\t\tself.firsttime = True\n\t\tself.prevtime = time.time()\n\t\tself.starttime = self.prevtime\n\t\tself.prevfraction = 0\n\t\tself.firsttimedone = False\n\t\tself.value = self.min_value": 3673, "def consts(self):\n \"\"\"The constants referenced in this code object.\n \"\"\"\n # We cannot use a set comprehension because consts do not need\n # to be hashable.\n consts = []\n append_const = consts.append\n for instr in self.instrs:\n if isinstance(instr, LOAD_CONST) and instr.arg not in consts:\n append_const(instr.arg)\n return tuple(consts)": 3674, "def __add__(self, other):\n \"\"\"Left addition.\"\"\"\n return chaospy.poly.collection.arithmetics.add(self, other)": 3675, "def gaussian_noise(x, severity=1):\n \"\"\"Gaussian noise corruption to images.\n\n Args:\n x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].\n severity: integer, severity of corruption.\n\n Returns:\n numpy array, image with uint8 pixels in [0,255]. Added Gaussian noise.\n \"\"\"\n c = [.08, .12, 0.18, 0.26, 0.38][severity - 1]\n x = np.array(x) / 255.\n x_clip = np.clip(x + np.random.normal(size=x.shape, scale=c), 0, 1) * 255\n return around_and_astype(x_clip)": 3676, "def decode_mysql_string_literal(text):\n \"\"\"\n Removes quotes and decodes escape sequences from given MySQL string literal\n returning the result.\n\n :param text: MySQL string literal, with the quotes still included.\n :type text: str\n\n :return: Given string literal with quotes removed and escape sequences\n decoded.\n :rtype: str\n \"\"\"\n assert text.startswith(\"'\")\n assert text.endswith(\"'\")\n\n # Ditch quotes from the string literal.\n text = text[1:-1]\n\n return MYSQL_STRING_ESCAPE_SEQUENCE_PATTERN.sub(\n unescape_single_character,\n text,\n )": 3677, "def ensure_dir(f):\n \"\"\" Ensure a a file exists and if not make the relevant path \"\"\"\n d = os.path.dirname(f)\n if not os.path.exists(d):\n os.makedirs(d)": 3678, "def calculate_bbox_area(bbox, rows, cols):\n \"\"\"Calculate the area of a bounding box in pixels.\"\"\"\n bbox = denormalize_bbox(bbox, rows, cols)\n x_min, y_min, x_max, y_max = bbox[:4]\n area = (x_max - x_min) * (y_max - y_min)\n return area": 3679, "def tearDown(self):\n \"\"\" Clean up environment\n\n \"\"\"\n if self.sdkobject and self.sdkobject.id:\n self.sdkobject.delete()\n self.sdkobject.id = None": 3680, "def _get_log_prior_cl_func(self):\n \"\"\"Get the CL log prior compute function.\n\n Returns:\n str: the compute function for computing the log prior.\n \"\"\"\n return SimpleCLFunction.from_string('''\n mot_float_type _computeLogPrior(local const mot_float_type* x, void* data){\n return ''' + self._log_prior_func.get_cl_function_name() + '''(x, data);\n }\n ''', dependencies=[self._log_prior_func])": 3681, "def datetime_match(data, dts):\n \"\"\"\n matching of datetimes in time columns for data filtering\n \"\"\"\n dts = dts if islistable(dts) else [dts]\n if any([not isinstance(i, datetime.datetime) for i in dts]):\n error_msg = (\n \"`time` can only be filtered by datetimes\"\n )\n raise TypeError(error_msg)\n return data.isin(dts)": 3682, "def to_camel(s):\n \"\"\"\n :param string s: under_scored string to be CamelCased\n :return: CamelCase version of input\n :rtype: str\n \"\"\"\n # r'(?!^)_([a-zA-Z]) original regex wasn't process first groups\n return re.sub(r'_([a-zA-Z])', lambda m: m.group(1).upper(), '_' + s)": 3683, "def _process_legend(self):\n \"\"\"\n Disables legends if show_legend is disabled.\n \"\"\"\n for l in self.handles['plot'].legend:\n l.items[:] = []\n l.border_line_alpha = 0\n l.background_fill_alpha = 0": 3684, "def snake_to_camel(name):\n \"\"\"Takes a snake_field_name and returns a camelCaseFieldName\n\n Args:\n name (str): E.g. snake_field_name or SNAKE_FIELD_NAME\n\n Returns:\n str: camelCase converted name. E.g. capsFieldName\n \"\"\"\n ret = \"\".join(x.title() for x in name.split(\"_\"))\n ret = ret[0].lower() + ret[1:]\n return ret": 3685, "def set_scale(self, scale, no_reset=False):\n \"\"\"Scale the image in a channel.\n Also see :meth:`zoom_to`.\n\n Parameters\n ----------\n scale : tuple of float\n Scaling factors for the image in the X and Y axes.\n\n no_reset : bool\n Do not reset ``autozoom`` setting.\n\n \"\"\"\n return self.scale_to(*scale[:2], no_reset=no_reset)": 3686, "def nested_update(d, u):\n \"\"\"Merge two nested dicts.\n\n Nested dicts are sometimes used for representing various recursive structures. When\n updating such a structure, it may be convenient to present the updated data as a\n corresponding recursive structure. This function will then apply the update.\n\n Args:\n d: dict\n dict that will be updated in-place. May or may not contain nested dicts.\n\n u: dict\n dict with contents that will be merged into ``d``. May or may not contain\n nested dicts.\n\n \"\"\"\n for k, v in list(u.items()):\n if isinstance(v, collections.Mapping):\n r = nested_update(d.get(k, {}), v)\n d[k] = r\n else:\n d[k] = u[k]\n return d": 3687, "def std_datestr(self, datestr):\n \"\"\"Reformat a date string to standard format.\n \"\"\"\n return date.strftime(\n self.str2date(datestr), self.std_dateformat)": 3688, "def from_string(cls, s):\n \"\"\"Return a `Status` instance from its string representation.\"\"\"\n for num, text in cls._STATUS2STR.items():\n if text == s:\n return cls(num)\n else:\n raise ValueError(\"Wrong string %s\" % s)": 3689, "def update(self, dictionary=None, **kwargs):\n \"\"\"\n Adds/overwrites all the keys and values from the dictionary.\n \"\"\"\n if not dictionary == None: kwargs.update(dictionary)\n for k in list(kwargs.keys()): self[k] = kwargs[k]": 3690, "def create_cursor(self, name=None):\n \"\"\"\n Returns an active connection cursor to the database.\n \"\"\"\n return Cursor(self.client_connection, self.connection, self.djongo_connection)": 3691, "def _possibly_convert_objects(values):\n \"\"\"Convert arrays of datetime.datetime and datetime.timedelta objects into\n datetime64 and timedelta64, according to the pandas convention.\n \"\"\"\n return np.asarray(pd.Series(values.ravel())).reshape(values.shape)": 3692, "def plot3d_init(fignum):\n \"\"\"\n initializes 3D plot\n \"\"\"\n from mpl_toolkits.mplot3d import Axes3D\n fig = plt.figure(fignum)\n ax = fig.add_subplot(111, projection='3d')\n return ax": 3693, "def apply(self, func, workers=1, job_size=10000):\n \"\"\"Apply `func` to lines of text in parallel or sequential.\n\n Args:\n func : a function that takes a list of lines.\n \"\"\"\n if workers == 1:\n for lines in self.iter_chunks(job_size):\n yield func(lines)\n else:\n with ProcessPoolExecutor(max_workers=workers) as executor:\n for result in executor.map(func, self.iter_chunks(job_size)):\n yield result": 3694, "def multiprocess_mapping(func, iterable):\n \"\"\"Multiprocess mapping the given function on the given iterable.\n\n This only works in Linux and Mac systems since Windows has no forking capability. On Windows we fall back on\n single processing. Also, if we reach memory limits we fall back on single cpu processing.\n\n Args:\n func (func): the function to apply\n iterable (iterable): the iterable with the elements we want to apply the function on\n \"\"\"\n if os.name == 'nt': # In Windows there is no fork.\n return list(map(func, iterable))\n try:\n p = multiprocessing.Pool()\n return_data = list(p.imap(func, iterable))\n p.close()\n p.join()\n return return_data\n except OSError:\n return list(map(func, iterable))": 3695, "def imapchain(*a, **kwa):\n \"\"\" Like map but also chains the results. \"\"\"\n\n imap_results = map( *a, **kwa )\n return itertools.chain( *imap_results )": 3696, "def get(self, queue_get):\n \"\"\"\n to get states from multiprocessing.queue\n \"\"\"\n if isinstance(queue_get, (tuple, list)):\n self.result.extend(queue_get)": 3697, "def match_empty(self, el):\n \"\"\"Check if element is empty (if requested).\"\"\"\n\n is_empty = True\n for child in self.get_children(el, tags=False):\n if self.is_tag(child):\n is_empty = False\n break\n elif self.is_content_string(child) and RE_NOT_EMPTY.search(child):\n is_empty = False\n break\n return is_empty": 3698, "def issubset(self, other):\n \"\"\"Report whether another set contains this RangeSet.\"\"\"\n self._binary_sanity_check(other)\n return set.issubset(self, other)": 3699, "def __neg__(self):\n \"\"\"Unary negation\"\"\"\n return self.__class__(self[0], self._curve.p()-self[1], self._curve)": 3700, "def str_is_well_formed(xml_str):\n \"\"\"\n Args:\n xml_str : str\n DataONE API XML doc.\n\n Returns:\n bool: **True** if XML doc is well formed.\n \"\"\"\n try:\n str_to_etree(xml_str)\n except xml.etree.ElementTree.ParseError:\n return False\n else:\n return True": 3701, "def to_dotfile(G: nx.DiGraph, filename: str):\n \"\"\" Output a networkx graph to a DOT file. \"\"\"\n A = to_agraph(G)\n A.write(filename)": 3702, "def are_in_interval(s, l, r, border = 'included'):\n \"\"\"\n Checks whether all number in the sequence s lie inside the interval formed by\n l and r.\n \"\"\"\n return numpy.all([IntensityRangeStandardization.is_in_interval(x, l, r, border) for x in s])": 3703, "def is_unix_like(platform=None):\n \"\"\"Returns whether the given platform is a Unix-like platform with the usual\n Unix filesystem. When the parameter is omitted, it defaults to ``sys.platform``\n \"\"\"\n platform = platform or sys.platform\n platform = platform.lower()\n return platform.startswith(\"linux\") or platform.startswith(\"darwin\") or \\\n platform.startswith(\"cygwin\")": 3704, "def normalize(name):\n \"\"\"Normalize name for the Statsd convention\"\"\"\n\n # Name should not contain some specials chars (issue #1068)\n ret = name.replace(':', '')\n ret = ret.replace('%', '')\n ret = ret.replace(' ', '_')\n\n return ret": 3705, "def accel_next(self, *args):\n \"\"\"Callback to go to the next tab. Called by the accel key.\n \"\"\"\n if self.get_notebook().get_current_page() + 1 == self.get_notebook().get_n_pages():\n self.get_notebook().set_current_page(0)\n else:\n self.get_notebook().next_page()\n return True": 3706, "def _arrayFromBytes(dataBytes, metadata):\n \"\"\"Generates and returns a numpy array from raw data bytes.\n\n :param bytes: raw data bytes as generated by ``numpy.ndarray.tobytes()``\n :param metadata: a dictionary containing the data type and optionally the\n shape parameter to reconstruct a ``numpy.array`` from the raw data\n bytes. ``{\"dtype\": \"float64\", \"shape\": (2, 3)}``\n\n :returns: ``numpy.array``\n \"\"\"\n array = numpy.fromstring(dataBytes, dtype=numpy.typeDict[metadata['dtype']])\n if 'shape' in metadata:\n array = array.reshape(metadata['shape'])\n return array": 3707, "def _read_stream_for_size(stream, buf_size=65536):\n \"\"\"Reads a stream discarding the data read and returns its size.\"\"\"\n size = 0\n while True:\n buf = stream.read(buf_size)\n size += len(buf)\n if not buf:\n break\n return size": 3708, "def setupLogFile(self):\n\t\t\"\"\"Set up the logging file for a new session- include date and some whitespace\"\"\"\n\t\tself.logWrite(\"\\n###############################################\")\n\t\tself.logWrite(\"calcpkg.py log from \" + str(datetime.datetime.now()))\n\t\tself.changeLogging(True)": 3709, "def get_oauth_token():\n \"\"\"Retrieve a simple OAuth Token for use with the local http client.\"\"\"\n url = \"{0}/token\".format(DEFAULT_ORIGIN[\"Origin\"])\n r = s.get(url=url)\n return r.json()[\"t\"]": 3710, "def connected_socket(address, timeout=3):\n \"\"\" yields a connected socket \"\"\"\n sock = socket.create_connection(address, timeout)\n yield sock\n sock.close()": 3711, "def delete_index(index):\n \"\"\"Delete index entirely (removes all documents and mapping).\"\"\"\n logger.info(\"Deleting search index: '%s'\", index)\n client = get_client()\n return client.indices.delete(index=index)": 3712, "def time2seconds(t):\n \"\"\"Returns seconds since 0h00.\"\"\"\n return t.hour * 3600 + t.minute * 60 + t.second + float(t.microsecond) / 1e6": 3713, "def clear(self):\n \"\"\"Remove all nodes and edges from the graph.\n\n Unlike the regular networkx implementation, this does *not*\n remove the graph's name. But all the other graph, node, and\n edge attributes go away.\n\n \"\"\"\n self.adj.clear()\n self.node.clear()\n self.graph.clear()": 3714, "def mouse_get_pos():\n \"\"\"\n\n :return:\n \"\"\"\n p = POINT()\n AUTO_IT.AU3_MouseGetPos(ctypes.byref(p))\n return p.x, p.y": 3715, "def Date(value):\n \"\"\"Custom type for managing dates in the command-line.\"\"\"\n from datetime import datetime\n try:\n return datetime(*reversed([int(val) for val in value.split('/')]))\n except Exception as err:\n raise argparse.ArgumentTypeError(\"invalid date '%s'\" % value)": 3716, "def pad_hex(value, bit_size):\n \"\"\"\n Pads a hex string up to the given bit_size\n \"\"\"\n value = remove_0x_prefix(value)\n return add_0x_prefix(value.zfill(int(bit_size / 4)))": 3717, "def parse_host_port (host_port):\n \"\"\"Parse a host:port string into separate components.\"\"\"\n host, port = urllib.splitport(host_port.strip())\n if port is not None:\n if urlutil.is_numeric_port(port):\n port = int(port)\n return host, port": 3718, "def get_in_samples(samples, fn):\n \"\"\"\n for a list of samples, return the value of a global option\n \"\"\"\n for sample in samples:\n sample = to_single_data(sample)\n if fn(sample, None):\n return fn(sample)\n return None": 3719, "def clean_markdown(text):\n \"\"\"\n Parse markdown sintaxt to html.\n \"\"\"\n result = text\n\n if isinstance(text, str):\n result = ''.join(\n BeautifulSoup(markdown(text), 'lxml').findAll(text=True))\n\n return result": 3720, "def _connection_failed(self, error=\"Error not specified!\"):\n \"\"\"Clean up after connection failure detected.\"\"\"\n if not self._error:\n LOG.error(\"Connection failed: %s\", str(error))\n self._error = error": 3721, "def read_proto_object(fobj, klass):\n \"\"\"Read a block of data and parse using the given protobuf object.\"\"\"\n log.debug('%s chunk', klass.__name__)\n obj = klass()\n obj.ParseFromString(read_block(fobj))\n log.debug('Header: %s', str(obj))\n return obj": 3722, "def run_command(cmd, *args):\n \"\"\"\n Runs command on the system with given ``args``.\n \"\"\"\n command = ' '.join((cmd, args))\n p = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)\n stdout, stderr = p.communicate()\n return p.retcode, stdout, stderr": 3723, "def _render_table(data, fields=None):\n \"\"\" Helper to render a list of dictionaries as an HTML display object. \"\"\"\n return IPython.core.display.HTML(datalab.utils.commands.HtmlBuilder.render_table(data, fields))": 3724, "def _value_to_color(value, cmap):\n \"\"\"Convert a value in the range [0,1] to an RGB tuple using a colormap.\"\"\"\n cm = plt.get_cmap(cmap)\n rgba = cm(value)\n return [int(round(255*v)) for v in rgba[0:3]]": 3725, "def register(linter):\n \"\"\"Register the reporter classes with the linter.\"\"\"\n linter.register_reporter(TextReporter)\n linter.register_reporter(ParseableTextReporter)\n linter.register_reporter(VSTextReporter)\n linter.register_reporter(ColorizedTextReporter)": 3726, "def _put_header(self):\n \"\"\" Standard first line in a PDF. \"\"\"\n self.session._out('%%PDF-%s' % self.pdf_version)\n if self.session.compression:\n self.session.buffer += '%' + chr(235) + chr(236) + chr(237) + chr(238) + \"\\n\"": 3727, "def fix_call(callable, *args, **kw):\n \"\"\"\n Call ``callable(*args, **kw)`` fixing any type errors that come out.\n \"\"\"\n try:\n val = callable(*args, **kw)\n except TypeError:\n exc_info = fix_type_error(None, callable, args, kw)\n reraise(*exc_info)\n return val": 3728, "def topk(arg, k, by=None):\n \"\"\"\n Returns\n -------\n topk : TopK filter expression\n \"\"\"\n op = ops.TopK(arg, k, by=by)\n return op.to_expr()": 3729, "def flatten( iterables ):\n \"\"\" Flatten an iterable, except for string elements. \"\"\"\n for it in iterables:\n if isinstance(it, str):\n yield it\n else:\n for element in it:\n yield element": 3730, "def read(self):\n \"\"\"https://picamera.readthedocs.io/en/release-1.13/recipes1.html#capturing-to-a-pil-image\"\"\"\n stream = BytesIO()\n self.cam.capture(stream, format='png')\n # \"Rewind\" the stream to the beginning so we can read its content\n stream.seek(0)\n return Image.open(stream)": 3731, "def focus(self):\n \"\"\"\n Call this to give this Widget the input focus.\n \"\"\"\n self._has_focus = True\n self._frame.move_to(self._x, self._y, self._h)\n if self._on_focus is not None:\n self._on_focus()": 3732, "def random_numbers(n):\n \"\"\"\n Generate a random string from 0-9\n :param n: length of the string\n :return: the random string\n \"\"\"\n return ''.join(random.SystemRandom().choice(string.digits) for _ in range(n))": 3733, "def generate_uuid():\n \"\"\"Generate a UUID.\"\"\"\n r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes)\n return r_uuid.decode().replace('=', '')": 3734, "def oplot(self, x, y, **kw):\n \"\"\"generic plotting method, overplotting any existing plot \"\"\"\n self.panel.oplot(x, y, **kw)": 3735, "def pprint(self, stream=None, indent=1, width=80, depth=None):\n \"\"\"\n Pretty print the underlying literal Python object\n \"\"\"\n pp.pprint(to_literal(self), stream, indent, width, depth)": 3736, "def get_base_dir():\n \"\"\"\n Return the base directory\n \"\"\"\n return os.path.split(os.path.abspath(os.path.dirname(__file__)))[0]": 3737, "def diff(file_, imports):\n \"\"\"Display the difference between modules in a file and imported modules.\"\"\"\n modules_not_imported = compare_modules(file_, imports)\n\n logging.info(\"The following modules are in {} but do not seem to be imported: \"\n \"{}\".format(file_, \", \".join(x for x in modules_not_imported)))": 3738, "def get_combined_size(tiles):\n \"\"\"Calculate combined size of tiles.\"\"\"\n # TODO: Refactor calculating layout to avoid repetition.\n columns, rows = calc_columns_rows(len(tiles))\n tile_size = tiles[0].image.size\n return (tile_size[0] * columns, tile_size[1] * rows)": 3739, "def cli(env):\n \"\"\"Show current configuration.\"\"\"\n\n settings = config.get_settings_from_client(env.client)\n env.fout(config.config_table(settings))": 3740, "def show():\n \"\"\"Show (print out) current environment variables.\"\"\"\n env = get_environment()\n\n for key, val in sorted(env.env.items(), key=lambda item: item[0]):\n click.secho('%s = %s' % (key, val))": 3741, "def _prtstr(self, obj, dashes):\n \"\"\"Print object information using a namedtuple and a format pattern.\"\"\"\n self.prt.write('{DASHES:{N}}'.format(\n DASHES=self.fmt_dashes.format(DASHES=dashes, ID=obj.item_id),\n N=self.dash_len))\n self.prt.write(\"{INFO}\\n\".format(INFO=str(obj)))": 3742, "def globlookup(pattern, root):\n \"\"\"globlookup finds filesystem objects whose relative path matches the\n given pattern.\n\n :param pattern: The pattern to wish to match relative filepaths to.\n :param root: The root director to search within.\n\n \"\"\"\n for subdir, dirnames, filenames in os.walk(root):\n d = subdir[len(root) + 1:]\n files = (os.path.join(d, f) for f in filenames)\n for f in fnmatch.filter(files, pattern):\n yield f": 3743, "def debug(ftn, txt):\n \"\"\"Used for debugging.\"\"\"\n if debug_p:\n sys.stdout.write(\"{0}.{1}:{2}\\n\".format(modname, ftn, txt))\n sys.stdout.flush()": 3744, "def _prtfmt(self, item_id, dashes):\n \"\"\"Print object information using a namedtuple and a format pattern.\"\"\"\n ntprt = self.id2nt[item_id]\n dct = ntprt._asdict()\n self.prt.write('{DASHES:{N}}'.format(\n DASHES=self.fmt_dashes.format(DASHES=dashes, ID=self.nm2prtfmt['ID'].format(**dct)),\n N=self.dash_len))\n self.prt.write(\"{INFO}\\n\".format(INFO=self.nm2prtfmt['ITEM'].format(**dct)))": 3745, "def imp_print(self, text, end):\n\t\t\"\"\"Directly send utf8 bytes to stdout\"\"\"\n\t\tsys.stdout.write((text + end).encode(\"utf-8\"))": 3746, "def _strip_namespace(self, xml):\n \"\"\"strips any namespaces from an xml string\"\"\"\n p = re.compile(b\"xmlns=*[\\\"\\\"][^\\\"\\\"]*[\\\"\\\"]\")\n allmatches = p.finditer(xml)\n for match in allmatches:\n xml = xml.replace(match.group(), b\"\")\n return xml": 3747, "def ave_list_v3(vec_list):\n \"\"\"Return the average vector of a list of vectors.\"\"\"\n\n vec = Vec3(0, 0, 0)\n for v in vec_list:\n vec += v\n num_vecs = float(len(vec_list))\n vec = Vec3(vec.x / num_vecs, vec.y / num_vecs, vec.z / num_vecs)\n return vec": 3748, "def lastmod(self, author):\n \"\"\"Return the last modification of the entry.\"\"\"\n lastitems = EntryModel.objects.published().order_by('-modification_date').filter(author=author).only('modification_date')\n return lastitems[0].modification_date": 3749, "def calculate_size(name, data_list):\n \"\"\" Calculates the request payload size\"\"\"\n data_size = 0\n data_size += calculate_size_str(name)\n data_size += INT_SIZE_IN_BYTES\n for data_list_item in data_list:\n data_size += calculate_size_data(data_list_item)\n return data_size": 3750, "def message_from_string(s, *args, **kws):\n \"\"\"Parse a string into a Message object model.\n\n Optional _class and strict are passed to the Parser constructor.\n \"\"\"\n from future.backports.email.parser import Parser\n return Parser(*args, **kws).parsestr(s)": 3751, "def IsErrorSuppressedByNolint(category, linenum):\n \"\"\"Returns true if the specified error category is suppressed on this line.\n\n Consults the global error_suppressions map populated by\n ParseNolintSuppressions/ResetNolintSuppressions.\n\n Args:\n category: str, the category of the error.\n linenum: int, the current line number.\n Returns:\n bool, True iff the error should be suppressed due to a NOLINT comment.\n \"\"\"\n return (linenum in _error_suppressions.get(category, set()) or\n linenum in _error_suppressions.get(None, set()))": 3752, "def _raise_if_wrong_file_signature(stream):\n \"\"\" Reads the 4 first bytes of the stream to check that is LASF\"\"\"\n file_sig = stream.read(len(headers.LAS_FILE_SIGNATURE))\n if file_sig != headers.LAS_FILE_SIGNATURE:\n raise errors.PylasError(\n \"File Signature ({}) is not {}\".format(file_sig, headers.LAS_FILE_SIGNATURE)\n )": 3753, "def loss(loss_value):\n \"\"\"Calculates aggregated mean loss.\"\"\"\n total_loss = tf.Variable(0.0, False)\n loss_count = tf.Variable(0, False)\n total_loss_update = tf.assign_add(total_loss, loss_value)\n loss_count_update = tf.assign_add(loss_count, 1)\n loss_op = total_loss / tf.cast(loss_count, tf.float32)\n return [total_loss_update, loss_count_update], loss_op": 3754, "def create_app():\n \"\"\"Create a Qt application.\"\"\"\n global QT_APP\n QT_APP = QApplication.instance()\n if QT_APP is None: # pragma: no cover\n QT_APP = QApplication(sys.argv)\n return QT_APP": 3755, "def get_last_or_frame_exception():\n \"\"\"Intended to be used going into post mortem routines. If\n sys.last_traceback is set, we will return that and assume that\n this is what post-mortem will want. If sys.last_traceback has not\n been set, then perhaps we *about* to raise an error and are\n fielding an exception. So assume that sys.exc_info()[2]\n is where we want to look.\"\"\"\n\n try:\n if inspect.istraceback(sys.last_traceback):\n # We do have a traceback so prefer that.\n return sys.last_type, sys.last_value, sys.last_traceback\n except AttributeError:\n pass\n return sys.exc_info()": 3756, "def dt_to_qdatetime(dt):\n \"\"\"Convert a python datetime.datetime object to QDateTime\n\n :param dt: the datetime object\n :type dt: :class:`datetime.datetime`\n :returns: the QDateTime conversion\n :rtype: :class:`QtCore.QDateTime`\n :raises: None\n \"\"\"\n return QtCore.QDateTime(QtCore.QDate(dt.year, dt.month, dt.day),\n QtCore.QTime(dt.hour, dt.minute, dt.second))": 3757, "def done(self, result):\n \"\"\"save the geometry before dialog is close to restore it later\"\"\"\n self._geometry = self.geometry()\n QtWidgets.QDialog.done(self, result)": 3758, "def resize(self, width, height):\n \"\"\"\n Pyqt specific resize callback.\n \"\"\"\n if not self.fbo:\n return\n\n # pyqt reports sizes in actual buffer size\n self.width = width // self.widget.devicePixelRatio()\n self.height = height // self.widget.devicePixelRatio()\n self.buffer_width = width\n self.buffer_height = height\n\n super().resize(width, height)": 3759, "def unique_(self, col):\n \"\"\"\n Returns unique values in a column\n \"\"\"\n try:\n df = self.df.drop_duplicates(subset=[col], inplace=False)\n return list(df[col])\n except Exception as e:\n self.err(e, \"Can not select unique data\")": 3760, "def deinit(self):\n \"\"\"Deinitialises the PulseIn and releases any hardware and software\n resources for reuse.\"\"\"\n # Clean up after ourselves\n self._process.terminate()\n procs.remove(self._process)\n self._mq.remove()\n queues.remove(self._mq)": 3761, "def exec_rabbitmqctl(self, command, args=[], rabbitmqctl_opts=['-q']):\n \"\"\"\n Execute a ``rabbitmqctl`` command inside a running container.\n\n :param command: the command to run\n :param args: a list of args for the command\n :param rabbitmqctl_opts:\n a list of extra options to pass to ``rabbitmqctl``\n :returns: a tuple of the command exit code and output\n \"\"\"\n cmd = ['rabbitmqctl'] + rabbitmqctl_opts + [command] + args\n return self.inner().exec_run(cmd)": 3762, "def gen_random_string(str_len):\n \"\"\" generate random string with specified length\n \"\"\"\n return ''.join(\n random.choice(string.ascii_letters + string.digits) for _ in range(str_len))": 3763, "def uniform_noise(points):\n \"\"\"Init a uniform noise variable.\"\"\"\n return np.random.rand(1) * np.random.uniform(points, 1) \\\n + random.sample([2, -2], 1)": 3764, "def SampleSum(dists, n):\n \"\"\"Draws a sample of sums from a list of distributions.\n\n dists: sequence of Pmf or Cdf objects\n n: sample size\n\n returns: new Pmf of sums\n \"\"\"\n pmf = MakePmfFromList(RandomSum(dists) for i in xrange(n))\n return pmf": 3765, "def highlight_words(string, keywords, cls_name='highlighted'):\n \"\"\" Given an list of words, this function highlights the matched words in the given string. \"\"\"\n\n if not keywords:\n return string\n if not string:\n return ''\n include, exclude = get_text_tokenizer(keywords)\n highlighted = highlight_text(include, string, cls_name, words=True)\n return highlighted": 3766, "def get_env_default(self, variable, default):\n \"\"\"\n Fetch environment variables, returning a default if not found\n \"\"\"\n if variable in os.environ:\n env_var = os.environ[variable]\n else:\n env_var = default\n return env_var": 3767, "def api_home(request, key=None, hproPk=None):\n \"\"\"Show the home page for the API with all methods\"\"\"\n\n if not check_api_key(request, key, hproPk):\n return HttpResponseForbidden\n\n return render_to_response('plugIt/api.html', {}, context_instance=RequestContext(request))": 3768, "def get_as_string(self, s3_path, encoding='utf-8'):\n \"\"\"\n Get the contents of an object stored in S3 as string.\n\n :param s3_path: URL for target S3 location\n :param encoding: Encoding to decode bytes to string\n :return: File contents as a string\n \"\"\"\n content = self.get_as_bytes(s3_path)\n return content.decode(encoding)": 3769, "def backward_delete_word(self, e): # (Control-Rubout)\n u\"\"\"Delete the character behind the cursor. A numeric argument means\n to kill the characters instead of deleting them.\"\"\"\n self.l_buffer.backward_delete_word(self.argument_reset)\n self.finalize()": 3770, "def load_tiff(file):\n \"\"\"\n Load a geotiff raster keeping ndv values using a masked array\n\n Usage:\n data = load_tiff(file)\n \"\"\"\n ndv, xsize, ysize, geot, projection, datatype = get_geo_info(file)\n data = gdalnumeric.LoadFile(file)\n data = np.ma.masked_array(data, mask=data == ndv, fill_value=ndv)\n return data": 3771, "def do_EOF(self, args):\n \"\"\"Exit on system end of file character\"\"\"\n if _debug: ConsoleCmd._debug(\"do_EOF %r\", args)\n return self.do_exit(args)": 3772, "def stats(self):\n \"\"\" shotcut to pull out useful info for interactive use \"\"\"\n printDebug(\"Classes.....: %d\" % len(self.all_classes))\n printDebug(\"Properties..: %d\" % len(self.all_properties))": 3773, "def kwargs_to_string(kwargs):\n \"\"\"\n Given a set of kwargs, turns them into a string which can then be passed to a command.\n :param kwargs: kwargs from a function call.\n :return: outstr: A string, which is '' if no kwargs were given, and the kwargs in string format otherwise.\n \"\"\"\n outstr = ''\n for arg in kwargs:\n outstr += ' -{} {}'.format(arg, kwargs[arg])\n return outstr": 3774, "def as_dict(self):\n \"\"\"Return all child objects in nested dict.\"\"\"\n dicts = [x.as_dict for x in self.children]\n return {'{0} {1}'.format(self.name, self.value): dicts}": 3775, "def get(self, key):\n \"\"\"Get a value from the cache.\n\n Returns None if the key is not in the cache.\n \"\"\"\n value = redis_conn.get(key)\n\n if value is not None:\n value = pickle.loads(value)\n\n return value": 3776, "def __contains__(self, key):\n \"\"\"Return ``True`` if *key* is present, else ``False``.\"\"\"\n pickled_key = self._pickle_key(key)\n return bool(self.redis.hexists(self.key, pickled_key))": 3777, "def get_instance(key, expire=None):\n \"\"\"Return an instance of RedisSet.\"\"\"\n global _instances\n try:\n instance = _instances[key]\n except KeyError:\n instance = RedisSet(\n key,\n _redis,\n expire=expire\n )\n _instances[key] = instance\n\n return instance": 3778, "def tag(self, nerdoc):\n \"\"\"Tag the given document.\n Parameters\n ----------\n nerdoc: estnltk.estner.Document\n The document to be tagged.\n\n Returns\n -------\n labels: list of lists of str\n Predicted token Labels for each sentence in the document\n \"\"\"\n\n labels = []\n for snt in nerdoc.sentences:\n xseq = [t.feature_list() for t in snt]\n yseq = self.tagger.tag(xseq)\n labels.append(yseq)\n return labels": 3779, "def on_IOError(self, e):\n \"\"\" Handle an IOError exception. \"\"\"\n\n sys.stderr.write(\"Error: %s: \\\"%s\\\"\\n\" % (e.strerror, e.filename))": 3780, "def _namematcher(regex):\n \"\"\"Checks if a target name matches with an input regular expression.\"\"\"\n\n matcher = re_compile(regex)\n\n def match(target):\n target_name = getattr(target, '__name__', '')\n result = matcher.match(target_name)\n return result\n\n return match": 3781, "def error(self, text):\n\t\t\"\"\" Ajout d'un message de log de type ERROR \"\"\"\n\t\tself.logger.error(\"{}{}\".format(self.message_prefix, text))": 3782, "def select_from_array(cls, array, identifier):\n \"\"\"Return a region from a numpy array.\n \n :param array: :class:`numpy.ndarray`\n :param identifier: value representing the region to select in the array\n :returns: :class:`jicimagelib.region.Region`\n \"\"\"\n\n base_array = np.zeros(array.shape)\n array_coords = np.where(array == identifier)\n base_array[array_coords] = 1\n\n return cls(base_array)": 3783, "def register_service(self, service):\n \"\"\"\n Register service into the system. Called by Services.\n \"\"\"\n if service not in self.services:\n self.services.append(service)": 3784, "def separator(self, menu=None):\n \"\"\"Add a separator\"\"\"\n self.gui.get_menu(menu or self.menu).addSeparator()": 3785, "def as_list(callable):\n \"\"\"Convert a scalar validator in a list validator\"\"\"\n @wraps(callable)\n def wrapper(value_iter):\n return [callable(value) for value in value_iter]\n\n return wrapper": 3786, "def _listify(collection):\n \"\"\"This is a workaround where Collections are no longer iterable\n when using JPype.\"\"\"\n new_list = []\n for index in range(len(collection)):\n new_list.append(collection[index])\n return new_list": 3787, "def log_leave(event, nick, channel):\n\t\"\"\"\n\tLog a quit or part event.\n\t\"\"\"\n\tif channel not in pmxbot.config.log_channels:\n\t\treturn\n\tParticipantLogger.store.log(nick, channel, event.type)": 3788, "def not_matching_list(self):\n \"\"\"\n Return a list of string which don't match the\n given regex.\n \"\"\"\n\n pre_result = comp(self.regex)\n\n return [x for x in self.data if not pre_result.search(str(x))]": 3789, "def guess_title(basename):\n \"\"\" Attempt to guess the title from the filename \"\"\"\n\n base, _ = os.path.splitext(basename)\n return re.sub(r'[ _-]+', r' ', base).title()": 3790, "def cast_int(x):\n \"\"\"\n Cast unknown type into integer\n\n :param any x:\n :return int:\n \"\"\"\n try:\n x = int(x)\n except ValueError:\n try:\n x = x.strip()\n except AttributeError as e:\n logger_misc.warn(\"parse_str: AttributeError: String not number or word, {}, {}\".format(x, e))\n return x": 3791, "def do_striptags(value):\n \"\"\"Strip SGML/XML tags and replace adjacent whitespace by one space.\n \"\"\"\n if hasattr(value, '__html__'):\n value = value.__html__()\n return Markup(unicode(value)).striptags()": 3792, "def reduce_multiline(string):\n \"\"\"\n reduces a multiline string to a single line of text.\n\n\n args:\n string: the text to reduce\n \"\"\"\n string = str(string)\n return \" \".join([item.strip()\n for item in string.split(\"\\n\")\n if item.strip()])": 3793, "def scatterplot_matrix(df, features, downsample_frac=None, figsize=(15, 15)):\n \"\"\"\n Plot a scatterplot matrix for a list of features, colored by target value.\n\n Example: `scatterplot_matrix(X, X.columns.tolist(), downsample_frac=0.01)`\n\n Args:\n df: Pandas dataframe containing the target column (named 'target').\n features: The list of features to include in the correlation plot.\n downsample_frac: Dataframe downsampling rate (0.1 to include 10% of the dataset).\n figsize: The size of the plot.\n \"\"\"\n\n if downsample_frac:\n df = df.sample(frac=downsample_frac)\n\n plt.figure(figsize=figsize)\n sns.pairplot(df[features], hue='target')\n plt.show()": 3794, "def cleanup(self):\n \"\"\"Forcefully delete objects from memory\n\n In an ideal world, this shouldn't be necessary. Garbage\n collection guarantees that anything without reference\n is automatically removed.\n\n However, because this application is designed to be run\n multiple times from the same interpreter process, extra\n case must be taken to ensure there are no memory leaks.\n\n Explicitly deleting objects shines a light on where objects\n may still be referenced in the form of an error. No errors\n means this was uneccesary, but that's ok.\n\n \"\"\"\n\n for instance in self.context:\n del(instance)\n\n for plugin in self.plugins:\n del(plugin)": 3795, "def clean_strings(iterable):\n \"\"\"\n Take a list of strings and clear whitespace \n on each one. If a value in the list is not a \n string pass it through untouched.\n\n Args:\n iterable: mixed list\n\n Returns: \n mixed list\n \"\"\"\n retval = []\n for val in iterable:\n try:\n retval.append(val.strip())\n except(AttributeError):\n retval.append(val)\n return retval": 3796, "def __call__(self, factory_name, *args, **kwargs):\n \"\"\"Create object.\"\"\"\n return self.factories[factory_name](*args, **kwargs)": 3797, "def get_language_parameter(request, query_language_key='language', object=None, default=None):\n \"\"\"\n Get the language parameter from the current request.\n \"\"\"\n # This is the same logic as the django-admin uses.\n # The only difference is the origin of the request parameter.\n if not is_multilingual_project():\n # By default, the objects are stored in a single static language.\n # This makes the transition to multilingual easier as well.\n # The default language can operate as fallback language too.\n return default or appsettings.PARLER_LANGUAGES.get_default_language()\n else:\n # In multilingual mode, take the provided language of the request.\n code = request.GET.get(query_language_key)\n\n if not code:\n # forms: show first tab by default\n code = default or appsettings.PARLER_LANGUAGES.get_first_language()\n\n return normalize_language_code(code)": 3798, "def replaceNewlines(string, newlineChar):\n\t\"\"\"There's probably a way to do this with string functions but I was lazy.\n\t\tReplace all instances of \\r or \\n in a string with something else.\"\"\"\n\tif newlineChar in string:\n\t\tsegments = string.split(newlineChar)\n\t\tstring = \"\"\n\t\tfor segment in segments:\n\t\t\tstring += segment\n\treturn string": 3799, "def onRightUp(self, event=None):\n \"\"\" right button up: put back to cursor mode\"\"\"\n if event is None:\n return\n self.cursor_mode_action('rightup', event=event)\n self.ForwardEvent(event=event.guiEvent)": 3800, "def geturl(self):\n \"\"\"\n Returns the URL that was the source of this response.\n If the request that generated this response redirected, this method\n will return the final redirect location.\n \"\"\"\n if self.retries is not None and len(self.retries.history):\n return self.retries.history[-1].redirect_location\n else:\n return self._request_url": 3801, "def rest_put_stream(self, url, stream, headers=None, session=None, verify=True, cert=None):\n \"\"\"\n Perform a chunked PUT request to url with requests.session\n This is specifically to upload files.\n \"\"\"\n res = session.put(url, headers=headers, data=stream, verify=verify, cert=cert)\n return res.text, res.status_code": 3802, "def from_file(cls, path, encoding, dialect, fields, converters, field_index):\n \"\"\"Read delimited text from a text file.\"\"\"\n\n return cls(open(path, 'r', encoding=encoding), dialect, fields, converters, field_index)": 3803, "def _reset_bind(self):\n \"\"\"Internal utility function to reset binding.\"\"\"\n self.binded = False\n self._buckets = {}\n self._curr_module = None\n self._curr_bucket_key = None": 3804, "def reset_params(self):\n \"\"\"Reset all parameters to their default values.\"\"\"\n self.__params = dict([p, None] for p in self.param_names)\n self.set_params(self.param_defaults)": 3805, "def _parse_return(cls, result):\n \"\"\"Extract the result, return value and context from a result object\n \"\"\"\n\n return_value = None\n success = result['result']\n context = result['context']\n\n if 'return_value' in result:\n return_value = result['return_value']\n\n return success, return_value, context": 3806, "def unbroadcast_numpy_to(array, shape):\n \"\"\"Reverse the broadcasting operation.\n\n Args:\n array: An array.\n shape: A shape that could have been broadcasted to the shape of array.\n\n Returns:\n Array with dimensions summed to match `shape`.\n \"\"\"\n axis = create_unbroadcast_axis(shape, numpy.shape(array))\n return numpy.reshape(numpy.sum(array, axis=axis), shape)": 3807, "def do_stc_disconnectall(self, s):\n \"\"\"Remove connections to all chassis (test ports) in this session.\"\"\"\n if self._not_joined():\n return\n try:\n self._stc.disconnectall()\n except resthttp.RestHttpError as e:\n print(e)\n return\n print('OK')": 3808, "def _get_data(self):\n \"\"\"\n Extracts the session data from cookie.\n \"\"\"\n cookie = self.adapter.cookies.get(self.name)\n return self._deserialize(cookie) if cookie else {}": 3809, "def grandparent_path(self):\n \"\"\" return grandparent's path string \"\"\"\n return os.path.basename(os.path.join(self.path, '../..'))": 3810, "def print_err(*args, end='\\n'):\n \"\"\"Similar to print, but prints to stderr.\n \"\"\"\n print(*args, end=end, file=sys.stderr)\n sys.stderr.flush()": 3811, "def ensure_newline(self):\n \"\"\"\n use before any custom printing when using the progress iter to ensure\n your print statement starts on a new line instead of at the end of a\n progress line\n \"\"\"\n DECTCEM_SHOW = '\\033[?25h' # show cursor\n AT_END = DECTCEM_SHOW + '\\n'\n if not self._cursor_at_newline:\n self.write(AT_END)\n self._cursor_at_newline = True": 3812, "def _run_parallel_process_with_profiling(self, start_path, stop_path, queue, filename):\n \"\"\"\n wrapper for usage of profiling\n \"\"\"\n runctx('Engine._run_parallel_process(self, start_path, stop_path, queue)', globals(), locals(), filename)": 3813, "def round_sig(x, sig):\n \"\"\"Round the number to the specified number of significant figures\"\"\"\n return round(x, sig - int(floor(log10(abs(x)))) - 1)": 3814, "def sleep(self, time):\n \"\"\"\n Perform an asyncio sleep for the time specified in seconds. T\n his method should be used in place of time.sleep()\n\n :param time: time in seconds\n :returns: No return value\n \"\"\"\n try:\n task = asyncio.ensure_future(self.core.sleep(time))\n self.loop.run_until_complete(task)\n\n except asyncio.CancelledError:\n pass\n except RuntimeError:\n pass": 3815, "def _power(ctx, number, power):\n \"\"\"\n Returns the result of a number raised to a power\n \"\"\"\n return decimal_pow(conversions.to_decimal(number, ctx), conversions.to_decimal(power, ctx))": 3816, "def safe_mkdir_for(path, clean=False):\n \"\"\"Ensure that the parent directory for a file is present.\n\n If it's not there, create it. If it is, no-op.\n \"\"\"\n safe_mkdir(os.path.dirname(path), clean=clean)": 3817, "def save_cache(data, filename):\n \"\"\"Save cookies to a file.\"\"\"\n with open(filename, 'wb') as handle:\n pickle.dump(data, handle)": 3818, "def path(self):\n \"\"\"\n Return the path always without the \\\\?\\ prefix.\n \"\"\"\n path = super(WindowsPath2, self).path\n if path.startswith(\"\\\\\\\\?\\\\\"):\n return path[4:]\n return path": 3819, "def date(start, end):\n \"\"\"Get a random date between two dates\"\"\"\n\n stime = date_to_timestamp(start)\n etime = date_to_timestamp(end)\n\n ptime = stime + random.random() * (etime - stime)\n\n return datetime.date.fromtimestamp(ptime)": 3820, "def _pick_attrs(attrs, keys):\n \"\"\" Return attrs with keys in keys list\n \"\"\"\n return dict((k, v) for k, v in attrs.items() if k in keys)": 3821, "def fix_dashes(string):\n \"\"\"Fix bad Unicode special dashes in string.\"\"\"\n string = string.replace(u'\\u05BE', '-')\n string = string.replace(u'\\u1806', '-')\n string = string.replace(u'\\u2E3A', '-')\n string = string.replace(u'\\u2E3B', '-')\n string = unidecode(string)\n return re.sub(r'--+', '-', string)": 3822, "def _indexes(arr):\n \"\"\" Returns the list of all indexes of the given array.\n\n Currently works for one and two-dimensional arrays\n\n \"\"\"\n myarr = np.array(arr)\n if myarr.ndim == 1:\n return list(range(len(myarr)))\n elif myarr.ndim == 2:\n return tuple(itertools.product(list(range(arr.shape[0])),\n list(range(arr.shape[1]))))\n else:\n raise NotImplementedError('Only supporting arrays of dimension 1 and 2 as yet.')": 3823, "def copy(self):\n \"\"\"Create an identical (deep) copy of this element.\"\"\"\n result = self.space.element()\n result.assign(self)\n return result": 3824, "async def send(self, data):\n \"\"\" Add data to send queue. \"\"\"\n self.writer.write(data)\n await self.writer.drain()": 3825, "def cli(yamlfile, format, output):\n \"\"\" Generate an OWL representation of a biolink model \"\"\"\n print(OwlSchemaGenerator(yamlfile, format).serialize(output=output))": 3826, "def serialize(self, value, **kwargs):\n \"\"\"Serialize every item of the list.\"\"\"\n return [self.item_type.serialize(val, **kwargs) for val in value]": 3827, "def to_monthly(series, method='ffill', how='end'):\n \"\"\"\n Convenience method that wraps asfreq_actual\n with 'M' param (method='ffill', how='end').\n \"\"\"\n return series.asfreq_actual('M', method=method, how=how)": 3828, "def dispatch(self):\n \"\"\"Wraps the dispatch method to add session support.\"\"\"\n try:\n webapp2.RequestHandler.dispatch(self)\n finally:\n self.session_store.save_sessions(self.response)": 3829, "def restart_program():\n \"\"\"\n DOES NOT WORK WELL WITH MOPIDY\n Hack from\n https://www.daniweb.com/software-development/python/code/260268/restart-your-python-program\n to support updating the settings, since mopidy is not able to do that yet\n Restarts the current program\n Note: this function does not return. Any cleanup action (like\n saving data) must be done before calling this function\n \"\"\"\n\n python = sys.executable\n os.execl(python, python, * sys.argv)": 3830, "def _cpu(self):\n \"\"\"Record CPU usage.\"\"\"\n value = int(psutil.cpu_percent())\n set_metric(\"cpu\", value, category=self.category)\n gauge(\"cpu\", value)": 3831, "def roundClosestValid(val, res, decimals=None):\n \"\"\" round to closest resolution \"\"\"\n if decimals is None and \".\" in str(res):\n decimals = len(str(res).split('.')[1])\n\n return round(round(val / res) * res, decimals)": 3832, "def unpack2D(_x):\n \"\"\"\n Helper function for splitting 2D data into x and y component to make\n equations simpler\n \"\"\"\n _x = np.atleast_2d(_x)\n x = _x[:, 0]\n y = _x[:, 1]\n return x, y": 3833, "def set_xlimits(self, min=None, max=None):\n \"\"\"Set limits for the x-axis.\n\n :param min: minimum value to be displayed. If None, it will be\n calculated.\n :param max: maximum value to be displayed. If None, it will be\n calculated.\n\n \"\"\"\n self.limits['xmin'] = min\n self.limits['xmax'] = max": 3834, "def open(self, flag=\"c\"):\n \"\"\"Open handle\n\n set protocol=2 to fix python3\n\n .. versionadded:: 1.3.1\n \"\"\"\n return shelve.open(os.path.join(gettempdir(), self.index), flag=flag, protocol=2)": 3835, "def normalise_key(self, key):\n \"\"\"Make sure key is a valid python attribute\"\"\"\n key = key.replace('-', '_')\n if key.startswith(\"noy_\"):\n key = key[4:]\n return key": 3836, "def getFieldsColumnLengths(self):\n \"\"\"\n Gets the maximum length of each column in the field table\n \"\"\"\n nameLen = 0\n descLen = 0\n for f in self.fields:\n nameLen = max(nameLen, len(f['title']))\n descLen = max(descLen, len(f['description']))\n return (nameLen, descLen)": 3837, "def close(self, wait=False):\n \"\"\"Close session, shutdown pool.\"\"\"\n self.session.close()\n self.pool.shutdown(wait=wait)": 3838, "def rand_elem(seq, n=None):\n \"\"\"returns a random element from seq n times. If n is None, it continues indefinitly\"\"\"\n return map(random.choice, repeat(seq, n) if n is not None else repeat(seq))": 3839, "def impute_data(self,x):\n \"\"\"Imputes data set containing Nan values\"\"\"\n imp = Imputer(missing_values='NaN', strategy='mean', axis=0)\n return imp.fit_transform(x)": 3840, "def pwm(host, seq, m1, m2, m3, m4):\n \"\"\"\n Sends control values directly to the engines, overriding control loops.\n\n Parameters:\n seq -- sequence number\n m1 -- Integer: front left command\n m2 -- Integer: front right command\n m3 -- Integer: back right command\n m4 -- Integer: back left command\n \"\"\"\n at(host, 'PWM', seq, [m1, m2, m3, m4])": 3841, "def _return_comma_list(self, l):\n \"\"\" get a list and return a string with comma separated list values\n Examples ['to', 'ta'] will return 'to,ta'.\n \"\"\"\n if isinstance(l, (text_type, int)):\n return l\n\n if not isinstance(l, list):\n raise TypeError(l, ' should be a list of integers, \\\nnot {0}'.format(type(l)))\n\n str_ids = ','.join(str(i) for i in l)\n\n return str_ids": 3842, "def symmetrise(matrix, tri='upper'):\n \"\"\"\n Will copy the selected (upper or lower) triangle of a square matrix\n to the opposite side, so that the matrix is symmetrical.\n Alters in place.\n \"\"\"\n if tri == 'upper':\n tri_fn = np.triu_indices\n else:\n tri_fn = np.tril_indices\n size = matrix.shape[0]\n matrix[tri_fn(size)[::-1]] = matrix[tri_fn(size)]\n return matrix": 3843, "def main():\n \"\"\"Ideally we shouldn't lose the first second of events\"\"\"\n time.sleep(1)\n with Input() as input_generator:\n for e in input_generator:\n print(repr(e))": 3844, "def sort_key(val):\n \"\"\"Sort key for sorting keys in grevlex order.\"\"\"\n return numpy.sum((max(val)+1)**numpy.arange(len(val)-1, -1, -1)*val)": 3845, "def setDictDefaults (d, defaults):\n \"\"\"Sets all defaults for the given dictionary to those contained in a\n second defaults dictionary. This convenience method calls:\n\n d.setdefault(key, value)\n\n for each key and value in the given defaults dictionary.\n \"\"\"\n for key, val in defaults.items():\n d.setdefault(key, val)\n\n return d": 3846, "def set_proxy(proxy_url, transport_proxy=None):\n \"\"\"Create the proxy to PyPI XML-RPC Server\"\"\"\n global proxy, PYPI_URL\n PYPI_URL = proxy_url\n proxy = xmlrpc.ServerProxy(\n proxy_url,\n transport=RequestsTransport(proxy_url.startswith('https://')),\n allow_none=True)": 3847, "def value_to_python(self, value):\n \"\"\"\n Converts the input single value into the expected Python data type,\n raising django.core.exceptions.ValidationError if the data can't be\n converted. Returns the converted value. Subclasses should override\n this.\n \"\"\"\n if not isinstance(value, bytes):\n raise tldap.exceptions.ValidationError(\"should be a bytes\")\n value = value.decode(\"utf_8\")\n return value": 3848, "def show(self, title=''):\n \"\"\"\n Display Bloch sphere and corresponding data sets.\n \"\"\"\n self.render(title=title)\n if self.fig:\n plt.show(self.fig)": 3849, "def _split(value):\n \"\"\"Split input/output value into two values.\"\"\"\n if isinstance(value, str):\n # iterable, but not meant for splitting\n return value, value\n try:\n invalue, outvalue = value\n except TypeError:\n invalue = outvalue = value\n except ValueError:\n raise ValueError(\"Only single values and pairs are allowed\")\n return invalue, outvalue": 3850, "def _split_batches(self, data, batch_size):\n \"\"\"Yield successive n-sized chunks from l.\"\"\"\n for i in range(0, len(data), batch_size):\n yield data[i : i + batch_size]": 3851, "def solve(A, x):\n \"\"\"Solves a linear equation system with a matrix of shape (n, n) and an\n array of shape (n, ...). The output has the same shape as the second\n argument.\n \"\"\"\n # https://stackoverflow.com/a/48387507/353337\n x = numpy.asarray(x)\n return numpy.linalg.solve(A, x.reshape(x.shape[0], -1)).reshape(x.shape)": 3852, "def callproc(self, name, params, param_types=None):\n \"\"\"Calls a procedure.\n\n :param name: the name of the procedure\n :param params: a list or tuple of parameters to pass to the procedure.\n :param param_types: a list or tuple of type names. If given, each param will be cast via\n sql_writers typecast method. This is useful to disambiguate procedure calls\n when several parameters are null and therefore cause overload resoluation\n issues.\n :return: a 2-tuple of (cursor, params)\n \"\"\"\n\n if param_types:\n placeholders = [self.sql_writer.typecast(self.sql_writer.to_placeholder(), t)\n for t in param_types]\n else:\n placeholders = [self.sql_writer.to_placeholder() for p in params]\n\n # TODO: This may be Postgres specific...\n qs = \"select * from {0}({1});\".format(name, \", \".join(placeholders))\n return self.execute(qs, params), params": 3853, "def clear_all(self):\n \"\"\"Delete all Labels.\"\"\"\n logger.info(\"Clearing ALL Labels and LabelKeys.\")\n self.session.query(Label).delete(synchronize_session=\"fetch\")\n self.session.query(LabelKey).delete(synchronize_session=\"fetch\")": 3854, "def primary_keys_full(cls):\n \"\"\"Get primary key properties for a SQLAlchemy cls.\n Taken from marshmallow_sqlalchemy\n \"\"\"\n mapper = cls.__mapper__\n return [\n mapper.get_property_by_column(column)\n for column in mapper.primary_key\n ]": 3855, "def has_permission(user, permission_name):\n \"\"\"Check if a user has a given permission.\"\"\"\n if user and user.is_superuser:\n return True\n\n return permission_name in available_perm_names(user)": 3856, "def save(self, *args, **kwargs):\n \"\"\"Saves an animation\n\n A wrapper around :meth:`matplotlib.animation.Animation.save`\n \"\"\"\n self.timeline.index -= 1 # required for proper starting point for save\n self.animation.save(*args, **kwargs)": 3857, "def println(msg):\n \"\"\"\n Convenience function to print messages on a single line in the terminal\n \"\"\"\n sys.stdout.write(msg)\n sys.stdout.flush()\n sys.stdout.write('\\x08' * len(msg))\n sys.stdout.flush()": 3858, "def nothread_quit(self, arg):\n \"\"\" quit command when there's just one thread. \"\"\"\n\n self.debugger.core.stop()\n self.debugger.core.execution_status = 'Quit command'\n raise Mexcept.DebuggerQuit": 3859, "def exit(self):\n \"\"\"Stop the simple WSGI server running the appliation.\"\"\"\n if self._server is not None:\n self._server.shutdown()\n self._server.server_close()\n self._server = None": 3860, "def graph_key_from_tag(tag, entity_index):\n \"\"\"Returns a key from a tag entity\n\n Args:\n tag (tag) : this is the tag selected to get the key from\n entity_index (int) : this is the index of the tagged entity\n\n Returns:\n str : String representing the key for the given tagged entity.\n \"\"\"\n start_token = tag.get('start_token')\n entity = tag.get('entities', [])[entity_index]\n return str(start_token) + '-' + entity.get('key') + '-' + str(entity.get('confidence'))": 3861, "def measure_string(self, text, fontname, fontsize, encoding=0):\n \"\"\"Measure length of a string for a Base14 font.\"\"\"\n return _fitz.Tools_measure_string(self, text, fontname, fontsize, encoding)": 3862, "def __is__(cls, s):\n \"\"\"Test if string matches this argument's format.\"\"\"\n return s.startswith(cls.delims()[0]) and s.endswith(cls.delims()[1])": 3863, "def _print(self, msg, flush=False, end=\"\\n\"):\n \"\"\"Helper function to print connection status messages when in verbose mode.\"\"\"\n if self._verbose:\n print2(msg, end=end, flush=flush)": 3864, "def info(self, text):\n\t\t\"\"\" Ajout d'un message de log de type INFO \"\"\"\n\t\tself.logger.info(\"{}{}\".format(self.message_prefix, text))": 3865, "def write_document(doc, fnm):\n \"\"\"Write a Text document to file.\n\n Parameters\n ----------\n doc: Text\n The document to save.\n fnm: str\n The filename to save the document\n \"\"\"\n with codecs.open(fnm, 'wb', 'ascii') as f:\n f.write(json.dumps(doc, indent=2))": 3866, "def highpass(cutoff):\n \"\"\"\n This strategy uses an exponential approximation for cut-off frequency\n calculation, found by matching the one-pole Laplace lowpass filter\n and mirroring the resulting filter to get a highpass.\n \"\"\"\n R = thub(exp(cutoff - pi), 2)\n return (1 - R) / (1 + R * z ** -1)": 3867, "def exists(self):\n \"\"\"Check whether the cluster already exists.\n\n For example:\n\n .. literalinclude:: snippets.py\n :start-after: [START bigtable_check_cluster_exists]\n :end-before: [END bigtable_check_cluster_exists]\n\n :rtype: bool\n :returns: True if the table exists, else False.\n \"\"\"\n client = self._instance._client\n try:\n client.instance_admin_client.get_cluster(name=self.name)\n return True\n # NOTE: There could be other exceptions that are returned to the user.\n except NotFound:\n return False": 3868, "def get_path_from_query_string(req):\n \"\"\"Gets path from query string\n\n Args:\n req (flask.request): Request object from Flask\n\n Returns:\n path (str): Value of \"path\" parameter from query string\n\n Raises:\n exceptions.UserError: If \"path\" is not found in query string\n \"\"\"\n if req.args.get('path') is None:\n raise exceptions.UserError('Path not found in query string')\n return req.args.get('path')": 3869, "def _squeeze(x, axis):\n \"\"\"A version of squeeze that works with dynamic axis.\"\"\"\n x = tf.convert_to_tensor(value=x, name='x')\n if axis is None:\n return tf.squeeze(x, axis=None)\n axis = tf.convert_to_tensor(value=axis, name='axis', dtype=tf.int32)\n axis += tf.zeros([1], dtype=axis.dtype) # Make axis at least 1d.\n keep_axis, _ = tf.compat.v1.setdiff1d(tf.range(0, tf.rank(x)), axis)\n return tf.reshape(x, tf.gather(tf.shape(input=x), keep_axis))": 3870, "def _handle_authentication_error(self):\n \"\"\"\n Return an authentication error.\n \"\"\"\n response = make_response('Access Denied')\n response.headers['WWW-Authenticate'] = self.auth.get_authenticate_header()\n response.status_code = 401\n return response": 3871, "def argmax(attrs, inputs, proto_obj):\n \"\"\"Returns indices of the maximum values along an axis\"\"\"\n axis = attrs.get('axis', 0)\n keepdims = attrs.get('keepdims', 1)\n argmax_op = symbol.argmax(inputs[0], axis=axis, keepdims=keepdims)\n # onnx argmax operator always expects int64 as output type\n cast_attrs = {'dtype': 'int64'}\n return 'cast', cast_attrs, argmax_op": 3872, "def predict(self, X):\n \"\"\"\n Apply transforms to the data, and predict with the final estimator\n\n Parameters\n ----------\n X : iterable\n Data to predict on. Must fulfill input requirements of first step\n of the pipeline.\n\n Returns\n -------\n yp : array-like\n Predicted transformed target\n \"\"\"\n Xt, _, _ = self._transform(X)\n return self._final_estimator.predict(Xt)": 3873, "def uniqify(cls, seq):\n \"\"\"Returns a unique list of seq\"\"\"\n seen = set()\n seen_add = seen.add\n return [ x for x in seq if x not in seen and not seen_add(x)]": 3874, "def vline(self, x, y, height, color):\n \"\"\"Draw a vertical line up to a given length.\"\"\"\n self.rect(x, y, 1, height, color, fill=True)": 3875, "def is_closed(self):\n \"\"\"\n Are all entities connected to other entities.\n\n Returns\n -----------\n closed : bool\n Every entity is connected at its ends\n \"\"\"\n closed = all(i == 2 for i in\n dict(self.vertex_graph.degree()).values())\n\n return closed": 3876, "def get_cell(self, index):\n \"\"\"\n For a single index and return the value\n\n :param index: index value\n :return: value\n \"\"\"\n i = sorted_index(self._index, index) if self._sort else self._index.index(index)\n return self._data[i]": 3877, "def __exit__(self, *exc_info):\n \"\"\"Close connection to NATS when used in a context manager\"\"\"\n\n self._loop.create_task(self._close(Client.CLOSED, True))": 3878, "def mcc(y, z):\n \"\"\"Matthews correlation coefficient\n \"\"\"\n tp, tn, fp, fn = contingency_table(y, z)\n return (tp * tn - fp * fn) / K.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn))": 3879, "def Binary(x):\n \"\"\"Return x as a binary type.\"\"\"\n if isinstance(x, text_type) and not (JYTHON or IRONPYTHON):\n return x.encode()\n return bytes(x)": 3880, "def value(self, progress_indicator):\n \"\"\" Interpolate linearly between start and end \"\"\"\n return interpolate.interpolate_linear_single(self.initial_value, self.final_value, progress_indicator)": 3881, "def focusNext(self, event):\n \"\"\"Set focus to next item in sequence\"\"\"\n try:\n event.widget.tk_focusNext().focus_set()\n except TypeError:\n # see tkinter equivalent code for tk_focusNext to see\n # commented original version\n name = event.widget.tk.call('tk_focusNext', event.widget._w)\n event.widget._nametowidget(str(name)).focus_set()": 3882, "def get_all_items(self):\n \"\"\"\n Returns all items in the combobox dictionary.\n \"\"\"\n return [self._widget.itemText(k) for k in range(self._widget.count())]": 3883, "def find_if_expression_as_statement(node):\n \"\"\"Finds an \"if\" expression as a statement\"\"\"\n return (\n isinstance(node, ast.Expr)\n and isinstance(node.value, ast.IfExp)\n )": 3884, "def nonlocal_check(self, original, loc, tokens):\n \"\"\"Check for Python 3 nonlocal statement.\"\"\"\n return self.check_py(\"3\", \"nonlocal statement\", original, loc, tokens)": 3885, "def add_bundled_jars():\n \"\"\"\n Adds the bundled jars to the JVM's classpath.\n \"\"\"\n # determine lib directory with jars\n rootdir = os.path.split(os.path.dirname(__file__))[0]\n libdir = rootdir + os.sep + \"lib\"\n\n # add jars from lib directory\n for l in glob.glob(libdir + os.sep + \"*.jar\"):\n if l.lower().find(\"-src.\") == -1:\n javabridge.JARS.append(str(l))": 3886, "def xyz2lonlat(x, y, z):\n \"\"\"Convert cartesian to lon lat.\"\"\"\n lon = xu.rad2deg(xu.arctan2(y, x))\n lat = xu.rad2deg(xu.arctan2(z, xu.sqrt(x**2 + y**2)))\n return lon, lat": 3887, "def jupytext_cli(args=None):\n \"\"\"Entry point for the jupytext script\"\"\"\n try:\n jupytext(args)\n except (ValueError, TypeError, IOError) as err:\n sys.stderr.write('[jupytext] Error: ' + str(err) + '\\n')\n exit(1)": 3888, "def load_jsonf(fpath, encoding):\n \"\"\"\n :param unicode fpath:\n :param unicode encoding:\n :rtype: dict | list\n \"\"\"\n with codecs.open(fpath, encoding=encoding) as f:\n return json.load(f)": 3889, "def pprint(self, ind):\n \"\"\"pretty prints the tree with indentation\"\"\"\n pp = pprint.PrettyPrinter(indent=ind)\n pp.pprint(self.tree)": 3890, "def _trim(self, somestr):\n \"\"\" Trim left-right given string \"\"\"\n tmp = RE_LSPACES.sub(\"\", somestr)\n tmp = RE_TSPACES.sub(\"\", tmp)\n return str(tmp)": 3891, "def keyPressEvent(self, event):\n \"\"\"\n Pyqt specific key press callback function.\n Translates and forwards events to :py:func:`keyboard_event`.\n \"\"\"\n self.keyboard_event(event.key(), self.keys.ACTION_PRESS, 0)": 3892, "def _try_join_cancelled_thread(thread):\n \"\"\"Join a thread, but if the thread doesn't terminate for some time, ignore it\n instead of waiting infinitely.\"\"\"\n thread.join(10)\n if thread.is_alive():\n logging.warning(\"Thread %s did not terminate within grace period after cancellation\",\n thread.name)": 3893, "def fit(self, X):\n \"\"\" Apply KMeans Clustering\n X: dataset with feature vectors\n \"\"\"\n self.centers_, self.labels_, self.sse_arr_, self.n_iter_ = \\\n _kmeans(X, self.n_clusters, self.max_iter, self.n_trials, self.tol)": 3894, "def projR(gamma, p):\n \"\"\"return the KL projection on the row constrints \"\"\"\n return np.multiply(gamma.T, p / np.maximum(np.sum(gamma, axis=1), 1e-10)).T": 3895, "def json_to_initkwargs(self, json_data, kwargs):\n \"\"\"Subclassing hook to specialize how JSON data is converted\n to keyword arguments\"\"\"\n if isinstance(json_data, basestring):\n json_data = json.loads(json_data)\n return json_to_initkwargs(self, json_data, kwargs)": 3896, "def delayed_close(self):\n \"\"\" Delayed close - won't close immediately, but on the next reactor\n loop. \"\"\"\n self.state = SESSION_STATE.CLOSING\n reactor.callLater(0, self.close)": 3897, "def urlize_twitter(text):\n \"\"\"\n Replace #hashtag and @username references in a tweet with HTML text.\n \"\"\"\n html = TwitterText(text).autolink.auto_link()\n return mark_safe(html.replace(\n 'twitter.com/search?q=', 'twitter.com/search/realtime/'))": 3898, "def decode_example(self, example):\n \"\"\"Reconstruct the image from the tf example.\"\"\"\n img = tf.image.decode_image(\n example, channels=self._shape[-1], dtype=tf.uint8)\n img.set_shape(self._shape)\n return img": 3899, "def load_db(file, db, verbose=True):\n \"\"\"\n Load :class:`mongomock.database.Database` from a local file.\n\n :param file: file path.\n :param db: instance of :class:`mongomock.database.Database`.\n :param verbose: bool, toggle on log.\n :return: loaded db.\n \"\"\"\n db_data = json.load(file, verbose=verbose)\n return _load(db_data, db)": 3900, "def get_time():\n \"\"\"Get time from a locally running NTP server\"\"\"\n\n time_request = '\\x1b' + 47 * '\\0'\n now = struct.unpack(\"!12I\", ntp_service.request(time_request, timeout=5.0).data.read())[10]\n return time.ctime(now - EPOCH_START)": 3901, "def plfit_lsq(x,y):\n \"\"\"\n Returns A and B in y=Ax^B\n http://mathworld.wolfram.com/LeastSquaresFittingPowerLaw.html\n \"\"\"\n n = len(x)\n btop = n * (log(x)*log(y)).sum() - (log(x)).sum()*(log(y)).sum()\n bbottom = n*(log(x)**2).sum() - (log(x).sum())**2\n b = btop / bbottom\n a = ( log(y).sum() - b * log(x).sum() ) / n\n\n A = exp(a)\n return A,b": 3902, "def open_usb_handle(self, port_num):\n \"\"\"open usb port\n\n Args:\n port_num: port number on the Cambrionix unit\n\n Return:\n usb handle\n \"\"\"\n serial = self.get_usb_serial(port_num)\n return local_usb.LibUsbHandle.open(serial_number=serial)": 3903, "def survival(value=t, lam=lam, f=failure):\n \"\"\"Exponential survival likelihood, accounting for censoring\"\"\"\n return sum(f * log(lam) - lam * value)": 3904, "def put_pidfile( pidfile_path, pid ):\n \"\"\"\n Put a PID into a pidfile\n \"\"\"\n with open( pidfile_path, \"w\" ) as f:\n f.write(\"%s\" % pid)\n os.fsync(f.fileno())\n\n return": 3905, "def _log_multivariate_normal_density_tied(X, means, covars):\n \"\"\"Compute Gaussian log-density at X for a tied model.\"\"\"\n cv = np.tile(covars, (means.shape[0], 1, 1))\n return _log_multivariate_normal_density_full(X, means, cv)": 3906, "def _eq(self, other):\n \"\"\"Compare two nodes for equality.\"\"\"\n return (self.type, self.value) == (other.type, other.value)": 3907, "def get_all_files(folder):\n \"\"\"\n Generator that loops through all absolute paths of the files within folder\n\n Parameters\n ----------\n folder: str\n Root folder start point for recursive search.\n\n Yields\n ------\n fpath: str\n Absolute path of one file in the folders\n \"\"\"\n for path, dirlist, filelist in os.walk(folder):\n for fn in filelist:\n yield op.join(path, fn)": 3908, "def _adjust_offset(self, real_wave_mfcc, algo_parameters):\n \"\"\"\n OFFSET\n \"\"\"\n self.log(u\"Called _adjust_offset\")\n self._apply_offset(offset=algo_parameters[0])": 3909, "def cols_str(columns):\n \"\"\"Concatenate list of columns into a string.\"\"\"\n cols = \"\"\n for c in columns:\n cols = cols + wrap(c) + ', '\n return cols[:-2]": 3910, "def _ws_on_close(self, ws: websocket.WebSocketApp):\n \"\"\"Callback for closing the websocket connection\n\n Args:\n ws: websocket connection (now closed)\n \"\"\"\n self.connected = False\n self.logger.error('Websocket closed')\n self._reconnect_websocket()": 3911, "def house_explosions():\n \"\"\"\n Data from http://indexed.blogspot.com/2007/12/meltdown-indeed.html\n \"\"\"\n chart = PieChart2D(int(settings.width * 1.7), settings.height)\n chart.add_data([10, 10, 30, 200])\n chart.set_pie_labels([\n 'Budding Chemists',\n 'Propane issues',\n 'Meth Labs',\n 'Attempts to escape morgage',\n ])\n chart.download('pie-house-explosions.png')": 3912, "def RecurseKeys(self):\n \"\"\"Recurses the subkeys starting with the key.\n\n Yields:\n WinRegistryKey: Windows Registry key.\n \"\"\"\n yield self\n for subkey in self.GetSubkeys():\n for key in subkey.RecurseKeys():\n yield key": 3913, "def matches(self, s):\n \"\"\"Whether the pattern matches anywhere in the string s.\"\"\"\n regex_matches = self.compiled_regex.search(s) is not None\n return not regex_matches if self.inverted else regex_matches": 3914, "def save_hdf(self,filename,path=''):\n \"\"\"Saves all relevant data to .h5 file; so state can be restored.\n \"\"\"\n self.dataframe.to_hdf(filename,'{}/df'.format(path))": 3915, "def copy_of_xml_element(elem):\n \"\"\"\n This method returns a shallow copy of a XML-Element.\n This method is for compatibility with Python 2.6 or earlier..\n In Python 2.7 you can use 'copyElem = elem.copy()' instead.\n \"\"\"\n\n copyElem = ElementTree.Element(elem.tag, elem.attrib)\n for child in elem:\n copyElem.append(child)\n return copyElem": 3916, "def __ror__(self, other):\n\t\t\"\"\"The main machinery of the Pipe, calling the chosen callable with the recorded arguments.\"\"\"\n\t\t\n\t\treturn self.callable(*(self.args + (other, )), **self.kwargs)": 3917, "def _flush(self, buffer):\n \"\"\"\n Flush the write buffers of the stream if applicable.\n\n Args:\n buffer (memoryview): Buffer content.\n \"\"\"\n container, obj = self._client_args\n with _handle_client_exception():\n self._client.put_object(container, obj, buffer)": 3918, "def transformer_tall_pretrain_lm_tpu_adafactor():\n \"\"\"Hparams for transformer on LM pretraining (with 64k vocab) on TPU.\"\"\"\n hparams = transformer_tall_pretrain_lm()\n update_hparams_for_tpu(hparams)\n hparams.max_length = 1024\n # For multi-problem on TPU we need it in absolute examples.\n hparams.batch_size = 8\n hparams.multiproblem_vocab_size = 2**16\n return hparams": 3919, "def api_test(method='GET', **response_kwargs):\n \"\"\" Decorator to ensure API calls are made and return expected data. \"\"\"\n\n method = method.lower()\n\n def api_test_factory(fn):\n @functools.wraps(fn)\n @mock.patch('requests.{}'.format(method))\n def execute_test(method_func, *args, **kwargs):\n method_func.return_value = MockResponse(**response_kwargs)\n\n expected_url, response = fn(*args, **kwargs)\n\n method_func.assert_called_once()\n assert_valid_api_call(method_func, expected_url)\n assert isinstance(response, JSONAPIParser)\n assert response.json_data is method_func.return_value.data\n\n return execute_test\n\n return api_test_factory": 3920, "def vertical_percent(plot, percent=0.1):\n \"\"\"\n Using the size of the y axis, return a fraction of that size.\n \"\"\"\n plot_bottom, plot_top = plot.get_ylim()\n return percent * (plot_top - plot_bottom)": 3921, "def _ParseYamlFromFile(filedesc):\n \"\"\"Parses given YAML file.\"\"\"\n content = filedesc.read()\n return yaml.Parse(content) or collections.OrderedDict()": 3922, "def get_axis(array, axis, slice_num):\n \"\"\"Returns a fixed axis\"\"\"\n\n slice_list = [slice(None)] * array.ndim\n slice_list[axis] = slice_num\n slice_data = array[tuple(slice_list)].T # transpose for proper orientation\n\n return slice_data": 3923, "def __init__(self, stream_start):\n \"\"\"Initializes a gzip member decompressor wrapper.\n\n Args:\n stream_start (int): offset to the compressed stream within the containing\n file object.\n \"\"\"\n self._decompressor = zlib_decompressor.DeflateDecompressor()\n self.last_read = stream_start\n self.uncompressed_offset = 0\n self._compressed_data = b''": 3924, "def changed(self, *value):\n \"\"\"Checks whether the value has changed since the last call.\"\"\"\n if self._last_checked_value != value:\n self._last_checked_value = value\n return True\n return False": 3925, "def get_server(address=None):\n \"\"\"Return an SMTP servername guess from outgoing email address.\"\"\"\n if address:\n domain = address.split(\"@\")[1]\n try:\n return SMTP_SERVERS[domain]\n except KeyError:\n return (\"smtp.\" + domain, 465)\n return (None, None)": 3926, "def nlevels(self):\n \"\"\"\n Get the number of factor levels for each categorical column.\n\n :returns: A list of the number of levels per column.\n \"\"\"\n levels = self.levels()\n return [len(l) for l in levels] if levels else 0": 3927, "def get_from_human_key(self, key):\n \"\"\"Return the key (aka database value) of a human key (aka Python identifier).\"\"\"\n if key in self._identifier_map:\n return self._identifier_map[key]\n raise KeyError(key)": 3928, "def find_path(self, start, end, grid):\n \"\"\"\n find a path from start to end node on grid using the A* algorithm\n :param start: start node\n :param end: end node\n :param grid: grid that stores all possible steps/tiles as 2D-list\n :return:\n \"\"\"\n start.g = 0\n start.f = 0\n return super(AStarFinder, self).find_path(start, end, grid)": 3929, "def parent_widget(self):\n \"\"\" Reimplemented to only return GraphicsItems \"\"\"\n parent = self.parent()\n if parent is not None and isinstance(parent, QtGraphicsItem):\n return parent.widget": 3930, "def reconnect(self):\n \"\"\"Reconnect to rabbitmq server\"\"\"\n import pika\n import pika.exceptions\n\n self.connection = pika.BlockingConnection(pika.URLParameters(self.amqp_url))\n self.channel = self.connection.channel()\n try:\n self.channel.queue_declare(self.name)\n except pika.exceptions.ChannelClosed:\n self.connection = pika.BlockingConnection(pika.URLParameters(self.amqp_url))\n self.channel = self.connection.channel()": 3931, "def indent(block, spaces):\n \"\"\" indents paragraphs of text for rst formatting \"\"\"\n new_block = ''\n for line in block.split('\\n'):\n new_block += spaces + line + '\\n'\n return new_block": 3932, "def __getattr__(self, name):\n \"\"\"Return wrapper to named api method.\"\"\"\n return functools.partial(self._obj.request, self._api_prefix + name)": 3933, "def minus(*args):\n \"\"\"Also, converts either to ints or to floats.\"\"\"\n if len(args) == 1:\n return -to_numeric(args[0])\n return to_numeric(args[0]) - to_numeric(args[1])": 3934, "def _remove_nonascii(self, df):\n \"\"\"Make copy and remove non-ascii characters from it.\"\"\"\n\n df_copy = df.copy(deep=True)\n for col in df_copy.columns:\n if (df_copy[col].dtype == np.dtype('O')):\n df_copy[col] = df[col].apply(\n lambda x: re.sub(r'[^\\x00-\\x7f]', r'', x) if isinstance(x, six.string_types) else x)\n\n return df_copy": 3935, "def read_numpy(fh, byteorder, dtype, count, offsetsize):\n \"\"\"Read tag data from file and return as numpy array.\"\"\"\n dtype = 'b' if dtype[-1] == 's' else byteorder+dtype[-1]\n return fh.read_array(dtype, count)": 3936, "def makeAnimation(self):\n \"\"\"Use pymovie to render (visual+audio)+text overlays.\n \"\"\"\n aclip=mpy.AudioFileClip(\"sound.wav\")\n self.iS=self.iS.set_audio(aclip)\n self.iS.write_videofile(\"mixedVideo.webm\",15,audio=True)\n print(\"wrote \"+\"mixedVideo.webm\")": 3937, "def getTopRight(self):\n \"\"\"\n Retrieves a tuple with the x,y coordinates of the upper right point of the ellipse. \n Requires the radius and the coordinates to be numbers\n \"\"\"\n return (float(self.get_cx()) + float(self.get_rx()), float(self.get_cy()) + float(self.get_ry()))": 3938, "def dfs_recursive(graph, node, seen):\n \"\"\"DFS, detect connected component, recursive implementation\n\n :param graph: directed graph in listlist or listdict format\n :param int node: to start graph exploration\n :param boolean-table seen: will be set true for the connected component\n containing node.\n :complexity: `O(|V|+|E|)`\n \"\"\"\n seen[node] = True\n for neighbor in graph[node]:\n if not seen[neighbor]:\n dfs_recursive(graph, neighbor, seen)": 3939, "def llen(self, name):\n \"\"\"\n Returns the length of the list.\n\n :param name: str the name of the redis key\n :return: Future()\n \"\"\"\n with self.pipe as pipe:\n return pipe.llen(self.redis_key(name))": 3940, "def mad(v):\n \"\"\"MAD -- Median absolute deviation. More robust than standard deviation.\n \"\"\"\n return np.median(np.abs(v - np.median(v)))": 3941, "def build(self, **kwargs):\n \"\"\"Build the lexer.\"\"\"\n self.lexer = ply.lex.lex(object=self, **kwargs)": 3942, "def _get_printable_columns(columns, row):\n \"\"\"Return only the part of the row which should be printed.\n \"\"\"\n if not columns:\n return row\n\n # Extract the column values, in the order specified.\n return tuple(row[c] for c in columns)": 3943, "def parse_json(filename):\n \"\"\" Parse a JSON file\n First remove comments and then use the json module package\n Comments look like :\n // ...\n or\n /*\n ...\n */\n \"\"\"\n # Regular expression for comments\n comment_re = re.compile(\n '(^)?[^\\S\\n]*/(?:\\*(.*?)\\*/[^\\S\\n]*|/[^\\n]*)($)?',\n re.DOTALL | re.MULTILINE\n )\n\n with open(filename) as f:\n content = ''.join(f.readlines())\n\n ## Looking for comments\n match = comment_re.search(content)\n while match:\n # single line comment\n content = content[:match.start()] + content[match.end():]\n match = comment_re.search(content)\n\n # Return json file\n return json.loads(content)": 3944, "def file_remove(self, path, filename):\n \"\"\"Check if filename exists and remove\n \"\"\"\n if os.path.isfile(path + filename):\n os.remove(path + filename)": 3945, "def strip_line(line, sep=os.linesep):\n \"\"\"\n Removes occurrence of character (sep) from a line of text\n \"\"\"\n\n try:\n return line.strip(sep)\n except TypeError:\n return line.decode('utf-8').strip(sep)": 3946, "def EvalBinomialPmf(k, n, p):\n \"\"\"Evaluates the binomial pmf.\n\n Returns the probabily of k successes in n trials with probability p.\n \"\"\"\n return scipy.stats.binom.pmf(k, n, p)": 3947, "def format_docstring(*args, **kwargs):\n \"\"\"\n Decorator for clean docstring formatting\n \"\"\"\n def decorator(func):\n func.__doc__ = getdoc(func).format(*args, **kwargs)\n return func\n return decorator": 3948, "def _tab(content):\n \"\"\"\n Helper funcation that converts text-based get response\n to tab separated values for additional manipulation.\n \"\"\"\n response = _data_frame(content).to_csv(index=False,sep='\\t')\n return response": 3949, "def is_iterable(obj):\n \"\"\"\n Are we being asked to look up a list of things, instead of a single thing?\n We check for the `__iter__` attribute so that this can cover types that\n don't have to be known by this module, such as NumPy arrays.\n\n Strings, however, should be considered as atomic values to look up, not\n iterables. The same goes for tuples, since they are immutable and therefore\n valid entries.\n\n We don't need to check for the Python 2 `unicode` type, because it doesn't\n have an `__iter__` attribute anyway.\n \"\"\"\n return (\n hasattr(obj, \"__iter__\")\n and not isinstance(obj, str)\n and not isinstance(obj, tuple)\n )": 3950, "def _get_set(self, key, operation, create=False):\n \"\"\"\n Get (and maybe create) a set by name.\n \"\"\"\n return self._get_by_type(key, operation, create, b'set', set())": 3951, "def replace(table, field, a, b, **kwargs):\n \"\"\"\n Convenience function to replace all occurrences of `a` with `b` under the\n given field. See also :func:`convert`.\n\n The ``where`` keyword argument can be given with a callable or expression\n which is evaluated on each row and which should return True if the\n conversion should be applied on that row, else False.\n\n \"\"\"\n\n return convert(table, field, {a: b}, **kwargs)": 3952, "def submit_the_only_form(self):\n \"\"\"\n Look for a form on the page and submit it.\n\n Asserts if more than one form exists.\n \"\"\"\n form = ElementSelector(world.browser, str('//form'))\n assert form, \"Cannot find a form on the page.\"\n form.submit()": 3953, "def get_args(method_or_func):\n \"\"\"Returns method or function arguments.\"\"\"\n try:\n # Python 3.0+\n args = list(inspect.signature(method_or_func).parameters.keys())\n except AttributeError:\n # Python 2.7\n args = inspect.getargspec(method_or_func).args\n return args": 3954, "def new_iteration(self, prefix):\n \"\"\"When inside a loop logger, created a new iteration\n \"\"\"\n # Flush data for the current iteration\n self.flush()\n\n # Fix prefix\n self.prefix[-1] = prefix\n self.reset_formatter()": 3955, "def askopenfilename(**kwargs):\n \"\"\"Return file name(s) from Tkinter's file open dialog.\"\"\"\n try:\n from Tkinter import Tk\n import tkFileDialog as filedialog\n except ImportError:\n from tkinter import Tk, filedialog\n root = Tk()\n root.withdraw()\n root.update()\n filenames = filedialog.askopenfilename(**kwargs)\n root.destroy()\n return filenames": 3956, "def serialisasi(self):\n \"\"\"Mengembalikan hasil serialisasi objek Makna ini.\n\n :returns: Dictionary hasil serialisasi\n :rtype: dict\n \"\"\"\n\n return {\n \"kelas\": self.kelas,\n \"submakna\": self.submakna,\n \"info\": self.info,\n \"contoh\": self.contoh\n }": 3957, "def accuracy(conf_matrix):\n \"\"\"\n Given a confusion matrix, returns the accuracy.\n Accuracy Definition: http://research.ics.aalto.fi/events/eyechallenge2005/evaluation.shtml\n \"\"\"\n total, correct = 0.0, 0.0\n for true_response, guess_dict in conf_matrix.items():\n for guess, count in guess_dict.items():\n if true_response == guess:\n correct += count\n total += count\n return correct/total": 3958, "def reversed_lines(path):\n \"\"\"Generate the lines of file in reverse order.\"\"\"\n with open(path, 'r') as handle:\n part = ''\n for block in reversed_blocks(handle):\n for c in reversed(block):\n if c == '\\n' and part:\n yield part[::-1]\n part = ''\n part += c\n if part: yield part[::-1]": 3959, "def chunk_sequence(sequence, chunk_length):\n \"\"\"Yield successive n-sized chunks from l.\"\"\"\n for index in range(0, len(sequence), chunk_length):\n yield sequence[index:index + chunk_length]": 3960, "def __round_time(self, dt):\n \"\"\"Round a datetime object to a multiple of a timedelta\n dt : datetime.datetime object, default now.\n \"\"\"\n round_to = self._resolution.total_seconds()\n seconds = (dt - dt.min).seconds\n rounding = (seconds + round_to / 2) // round_to * round_to\n return dt + timedelta(0, rounding - seconds, -dt.microsecond)": 3961, "def apply(self, node):\n \"\"\" Apply transformation and return if an update happened. \"\"\"\n new_node = self.run(node)\n return self.update, new_node": 3962, "def find_all(self, string, callback):\n\t\t\"\"\"\n\t\tWrapper on iter method, callback gets an iterator result\n\t\t\"\"\"\n\t\tfor index, output in self.iter(string):\n\t\t\tcallback(index, output)": 3963, "def compose(func_list):\n \"\"\"\n composion of preprocessing functions\n \"\"\"\n\n def f(G, bim):\n for func in func_list:\n G, bim = func(G, bim)\n return G, bim\n\n return f": 3964, "def Dump(obj):\n \"\"\"Stringifies a Python object into its YAML representation.\n\n Args:\n obj: A Python object to convert to YAML.\n\n Returns:\n A YAML representation of the given object.\n \"\"\"\n text = yaml.safe_dump(obj, default_flow_style=False, allow_unicode=True)\n\n if compatibility.PY2:\n text = text.decode(\"utf-8\")\n\n return text": 3965, "def parser():\n\n \"\"\"Return a parser for setting one or more configuration paths\"\"\"\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-c', '--config_paths', default=[], action='append',\n help='path to a configuration directory')\n return parser": 3966, "def on_pause(self):\n \"\"\"Sync the database with the current state of the game.\"\"\"\n self.engine.commit()\n self.strings.save()\n self.funcs.save()\n self.config.write()": 3967, "def createArgumentParser(description):\n \"\"\"\n Create an argument parser\n \"\"\"\n parser = argparse.ArgumentParser(\n description=description,\n formatter_class=SortedHelpFormatter)\n return parser": 3968, "def select_if(df, fun):\n \"\"\"Selects columns where fun(ction) is true\n Args:\n fun: a function that will be applied to columns\n \"\"\"\n\n def _filter_f(col):\n try:\n return fun(df[col])\n except:\n return False\n\n cols = list(filter(_filter_f, df.columns))\n return df[cols]": 3969, "def mouseMoveEvent(self, event):\n \"\"\" Handle the mouse move event for a drag operation.\n\n \"\"\"\n self.declaration.mouse_move_event(event)\n super(QtGraphicsView, self).mouseMoveEvent(event)": 3970, "def Diag(a):\n \"\"\"\n Diag op.\n \"\"\"\n r = np.zeros(2 * a.shape, dtype=a.dtype)\n for idx, v in np.ndenumerate(a):\n r[2 * idx] = v\n return r,": 3971, "def contains(self, element):\n \"\"\"\n Ensures :attr:`subject` contains *other*.\n \"\"\"\n self._run(unittest_case.assertIn, (element, self._subject))\n return ChainInspector(self._subject)": 3972, "def setup(self, proxystr='', prompting=True):\n \"\"\"\n Sets the proxy handler given the option passed on the command\n line. If an empty string is passed it looks at the HTTP_PROXY\n environment variable.\n \"\"\"\n self.prompting = prompting\n proxy = self.get_proxy(proxystr)\n if proxy:\n proxy_support = urllib2.ProxyHandler({\"http\": proxy, \"ftp\": proxy})\n opener = urllib2.build_opener(proxy_support, urllib2.CacheFTPHandler)\n urllib2.install_opener(opener)": 3973, "def assert_in(obj, seq, message=None, extra=None):\n \"\"\"Raises an AssertionError if obj is not in seq.\"\"\"\n assert obj in seq, _assert_fail_message(message, obj, seq, \"is not in\", extra)": 3974, "def assert_is_instance(value, types, message=None, extra=None):\n \"\"\"Raises an AssertionError if value is not an instance of type(s).\"\"\"\n assert isinstance(value, types), _assert_fail_message(\n message, value, types, \"is not an instance of\", extra\n )": 3975, "def delegate(self, fn, *args, **kwargs):\n \"\"\"Return the given operation as an asyncio future.\"\"\"\n callback = functools.partial(fn, *args, **kwargs)\n coro = self.loop.run_in_executor(self.subexecutor, callback)\n return asyncio.ensure_future(coro)": 3976, "def run_task(func):\n \"\"\"\n Decorator to wrap an async function in an event loop.\n Use for main sync interface methods.\n \"\"\"\n\n def _wrapped(*a, **k):\n loop = asyncio.get_event_loop()\n return loop.run_until_complete(func(*a, **k))\n\n return _wrapped": 3977, "def safe_repr(obj):\n \"\"\"\n Try to get ``__name__`` first, ``__class__.__name__`` second\n and finally, if we can't get anything acceptable, fallback\n to user a ``repr()`` call.\n \"\"\"\n name = getattr(obj, '__name__', getattr(obj.__class__, '__name__'))\n if name == 'ndict':\n name = 'dict'\n return name or repr(obj)": 3978, "async def smap(source, func, *more_sources):\n \"\"\"Apply a given function to the elements of one or several\n asynchronous sequences.\n\n Each element is used as a positional argument, using the same order as\n their respective sources. The generation continues until the shortest\n sequence is exhausted. The function is treated synchronously.\n\n Note: if more than one sequence is provided, they're awaited concurrently\n so that their waiting times don't add up.\n \"\"\"\n if more_sources:\n source = zip(source, *more_sources)\n async with streamcontext(source) as streamer:\n async for item in streamer:\n yield func(*item) if more_sources else func(item)": 3979, "def list_rds(region, filter_by_kwargs):\n \"\"\"List all RDS thingys.\"\"\"\n conn = boto.rds.connect_to_region(region)\n instances = conn.get_all_dbinstances()\n return lookup(instances, filter_by=filter_by_kwargs)": 3980, "def __init__(self, enumtype, index, key):\n \"\"\" Set up a new instance. \"\"\"\n self._enumtype = enumtype\n self._index = index\n self._key = key": 3981, "def get_url(self, routename, **kargs):\n \"\"\" Return a string that matches a named route \"\"\"\n return '/' + self.routes.build(routename, **kargs).split(';', 1)[1]": 3982, "def mean_cl_boot(series, n_samples=1000, confidence_interval=0.95,\n random_state=None):\n \"\"\"\n Bootstrapped mean with confidence limits\n \"\"\"\n return bootstrap_statistics(series, np.mean,\n n_samples=n_samples,\n confidence_interval=confidence_interval,\n random_state=random_state)": 3983, "def get_http_method(self, method):\n \"\"\"Gets the http method that will be called from the requests library\"\"\"\n return self.http_methods[method](self.url, **self.http_method_args)": 3984, "def __sort_up(self):\n\n \"\"\"Sort the updatable objects according to ascending order\"\"\"\n if self.__do_need_sort_up:\n self.__up_objects.sort(key=cmp_to_key(self.__up_cmp))\n self.__do_need_sort_up = False": 3985, "def _get_memoized_value(func, args, kwargs):\n \"\"\"Used internally by memoize decorator to get/store function results\"\"\"\n key = (repr(args), repr(kwargs))\n\n if not key in func._cache_dict:\n ret = func(*args, **kwargs)\n func._cache_dict[key] = ret\n\n return func._cache_dict[key]": 3986, "def locked_delete(self):\n \"\"\"Delete credentials from the SQLAlchemy datastore.\"\"\"\n filters = {self.key_name: self.key_value}\n self.session.query(self.model_class).filter_by(**filters).delete()": 3987, "def triangle_normal(a, b, c):\n \"\"\"Return a vector orthogonal to the given triangle\n\n Arguments:\n a, b, c -- three 3D numpy vectors\n \"\"\"\n normal = np.cross(a - c, b - c)\n norm = np.linalg.norm(normal)\n return normal/norm": 3988, "def distance_to_line(a, b, p):\n \"\"\"Closest distance between a line segment and a point\n\n Args:\n a ([float, float]): x and y coordinates. Line start\n b ([float, float]): x and y coordinates. Line end\n p ([float, float]): x and y coordinates. Point to compute the distance\n Returns:\n float\n \"\"\"\n return distance(closest_point(a, b, p), p)": 3989, "def post_ratelimited(protocol, session, url, headers, data, allow_redirects=False, stream=False):\n \"\"\"\n There are two error-handling policies implemented here: a fail-fast policy intended for stand-alone scripts which\n fails on all responses except HTTP 200. The other policy is intended for long-running tasks that need to respect\n rate-limiting errors from the server and paper over outages of up to 1 hour.\n\n Wrap POST requests in a try-catch loop with a lot of error handling logic and some basic rate-limiting. If a request\n fails, and some conditions are met, the loop waits in increasing intervals, up to 1 hour, before trying again. The\n reason for this is that servers often malfunction for short periods of time, either because of ongoing data\n migrations or other maintenance tasks, misconfigurations or heavy load, or because the connecting user has hit a\n throttling policy limit.\n\n If the loop exited early, consumers of this package that don't implement their own rate-limiting code could quickly\n swamp such a server with new requests. That would only make things worse. Instead, it's better if the request loop\n waits patiently until the server is functioning again.\n\n If the connecting user has hit a throttling policy, then the server will start to malfunction in many interesting\n ways, but never actually tell the user what is happening. There is no way to distinguish this situation from other\n malfunctions. The only cure is to stop making requests.\n\n The contract on sessions here is to return the session that ends up being used, or retiring the session if we\n intend to raise an exception. We give up on max_wait timeout, not number of retries.\n\n An additional resource on handling throttling policies and client back off strategies:\n https://msdn.microsoft.com/en-us/library/office/jj945066(v=exchg.150).aspx#bk_ThrottlingBatch\n \"\"\"\n thread_id = get_ident()\n wait = 10 # seconds\n retry = 0\n redirects = 0\n # In Python 2, we want this to be a 'str' object so logging doesn't break (all formatting arguments are 'str').\n # We activated 'unicode_literals' at the top of this file, so it would be a 'unicode' object unless we convert\n # to 'str' explicitly. This is a no-op for Python 3.\n log_msg = str('''\\\nRetry: %(retry)s\nWaited: %(wait)s\nTimeout: %(timeout)s\nSession: %(session_id)s\nThread: %(thread_id)s\nAuth type: %(auth)s\nURL: %(url)s\nHTTP adapter: %(adapter)s\nAllow redirects: %(allow_redirects)s\nStreaming: %(stream)s\nResponse time: %(response_time)s\nStatus code: %(status_code)s\nRequest headers: %(request_headers)s\nResponse headers: %(response_headers)s\nRequest data: %(xml_request)s\nResponse data: %(xml_response)s\n''')\n log_vals = dict(\n retry=retry,\n wait=wait,\n timeout=protocol.TIMEOUT,\n session_id=session.session_id,\n thread_id=thread_id,\n auth=session.auth,\n url=url,\n adapter=session.get_adapter(url),\n allow_redirects=allow_redirects,\n stream=stream,\n response_time=None,\n status_code=None,\n request_headers=headers,\n response_headers=None,\n xml_request=data,\n xml_response=None,\n )\n try:\n while True:\n _back_off_if_needed(protocol.credentials.back_off_until)\n log.debug('Session %s thread %s: retry %s timeout %s POST\\'ing to %s after %ss wait', session.session_id,\n thread_id, retry, protocol.TIMEOUT, url, wait)\n d_start = time_func()\n # Always create a dummy response for logging purposes, in case we fail in the following\n r = DummyResponse(url=url, headers={}, request_headers=headers)\n try:\n r = session.post(url=url, headers=headers, data=data, allow_redirects=False, timeout=protocol.TIMEOUT,\n stream=stream)\n except CONNECTION_ERRORS as e:\n log.debug('Session %s thread %s: connection error POST\\'ing to %s', session.session_id, thread_id, url)\n r = DummyResponse(url=url, headers={'TimeoutException': e}, request_headers=headers)\n finally:\n log_vals.update(\n retry=retry,\n wait=wait,\n session_id=session.session_id,\n url=str(r.url),\n response_time=time_func() - d_start,\n status_code=r.status_code,\n request_headers=r.request.headers,\n response_headers=r.headers,\n xml_response='[STREAMING]' if stream else r.content,\n )\n log.debug(log_msg, log_vals)\n if _may_retry_on_error(r, protocol, wait):\n log.info(\"Session %s thread %s: Connection error on URL %s (code %s). Cool down %s secs\",\n session.session_id, thread_id, r.url, r.status_code, wait)\n time.sleep(wait) # Increase delay for every retry\n retry += 1\n wait *= 2\n session = protocol.renew_session(session)\n continue\n if r.status_code in (301, 302):\n if stream:\n r.close()\n url, redirects = _redirect_or_fail(r, redirects, allow_redirects)\n continue\n break\n except (RateLimitError, RedirectError) as e:\n log.warning(e.value)\n protocol.retire_session(session)\n raise\n except Exception as e:\n # Let higher layers handle this. Add full context for better debugging.\n log.error(str('%s: %s\\n%s'), e.__class__.__name__, str(e), log_msg % log_vals)\n protocol.retire_session(session)\n raise\n if r.status_code == 500 and r.content and is_xml(r.content):\n # Some genius at Microsoft thinks it's OK to send a valid SOAP response as an HTTP 500\n log.debug('Got status code %s but trying to parse content anyway', r.status_code)\n elif r.status_code != 200:\n protocol.retire_session(session)\n try:\n _raise_response_errors(r, protocol, log_msg, log_vals) # Always raises an exception\n finally:\n if stream:\n r.close()\n log.debug('Session %s thread %s: Useful response from %s', session.session_id, thread_id, url)\n return r, session": 3990, "def get_previous_month(self):\n \"\"\"Returns date range for the previous full month.\"\"\"\n end = utils.get_month_start() - relativedelta(days=1)\n end = utils.to_datetime(end)\n start = utils.get_month_start(end)\n return start, end": 3991, "def _hue(color, **kwargs):\n \"\"\" Get hue value of HSL color.\n \"\"\"\n h = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[0]\n return NumberValue(h * 360.0)": 3992, "def stop(self):\n\t\t\"\"\" Stops the video stream and resets the clock. \"\"\"\n\n\t\tlogger.debug(\"Stopping playback\")\n\t\t# Stop the clock\n\t\tself.clock.stop()\n\t\t# Set plauyer status to ready\n\t\tself.status = READY": 3993, "def get_login_credentials(args):\n \"\"\"\n Gets the login credentials from the user, if not specified while invoking\n the script.\n @param args: arguments provided to the script.\n \"\"\"\n if not args.username:\n args.username = raw_input(\"Enter Username: \")\n if not args.password:\n args.password = getpass.getpass(\"Enter Password: \")": 3994, "def angle_to_cartesian(lon, lat):\n \"\"\"Convert spherical coordinates to cartesian unit vectors.\"\"\"\n theta = np.array(np.pi / 2. - lat)\n return np.vstack((np.sin(theta) * np.cos(lon),\n np.sin(theta) * np.sin(lon),\n np.cos(theta))).T": 3995, "def get_title(soup):\n \"\"\"Given a soup, pick out a title\"\"\"\n if soup.title:\n return soup.title.string\n if soup.h1:\n return soup.h1.string\n return ''": 3996, "def pad_image(arr, max_size=400):\n \"\"\"Pads an image to a square then resamples to max_size\"\"\"\n dim = np.max(arr.shape)\n img = np.zeros((dim, dim, 3), dtype=arr.dtype)\n xl = (dim - arr.shape[0]) // 2\n yl = (dim - arr.shape[1]) // 2\n img[xl:arr.shape[0]+xl, yl:arr.shape[1]+yl, :] = arr\n return resample_image(img, max_size=max_size)": 3997, "def _strptime(self, time_str):\n \"\"\"Convert an ISO 8601 formatted string in UTC into a\n timezone-aware datetime object.\"\"\"\n if time_str:\n # Parse UTC string into naive datetime, then add timezone\n dt = datetime.strptime(time_str, __timeformat__)\n return dt.replace(tzinfo=UTC())\n return None": 3998, "def _svd(cls, matrix, num_concepts=5):\n \"\"\"\n Perform singular value decomposition for dimensionality reduction of the input matrix.\n \"\"\"\n u, s, v = svds(matrix, k=num_concepts)\n return u, s, v": 3999, "def writer_acquire(self):\n \"\"\"Acquire the lock to write\"\"\"\n\n self._order_mutex.acquire()\n self._access_mutex.acquire()\n self._order_mutex.release()": 4000, "def _check_key(self, key):\n \"\"\"\n Ensures well-formedness of a key.\n \"\"\"\n if not len(key) == 2:\n raise TypeError('invalid key: %r' % key)\n elif key[1] not in TYPES:\n raise TypeError('invalid datatype: %s' % key[1])": 4001, "def required_attributes(element, *attributes):\n \"\"\"Check element for required attributes. Raise ``NotValidXmlException`` on error.\n\n :param element: ElementTree element\n :param attributes: list of attributes names to check\n :raises NotValidXmlException: if some argument is missing\n \"\"\"\n if not reduce(lambda still_valid, param: still_valid and param in element.attrib, attributes, True):\n raise NotValidXmlException(msg_err_missing_attributes(element.tag, *attributes))": 4002, "def _is_already_configured(configuration_details):\n \"\"\"Returns `True` when alias already in shell config.\"\"\"\n path = Path(configuration_details.path).expanduser()\n with path.open('r') as shell_config:\n return configuration_details.content in shell_config.read()": 4003, "def _is_one_arg_pos_call(call):\n \"\"\"Is this a call with exactly 1 argument,\n where that argument is positional?\n \"\"\"\n return isinstance(call, astroid.Call) and len(call.args) == 1 and not call.keywords": 4004, "def wait_and_join(self, task):\n \"\"\" Given a task, waits for it until it finishes\n :param task: Task\n :return:\n \"\"\"\n while not task.has_started:\n time.sleep(self._polling_time)\n task.thread.join()": 4005, "def url_syntax_check(url): # pragma: no cover\n \"\"\"\n Check the syntax of the given URL.\n\n :param url: The URL to check the syntax for.\n :type url: str\n\n :return: The syntax validity.\n :rtype: bool\n\n .. warning::\n If an empty or a non-string :code:`url` is given, we return :code:`None`.\n \"\"\"\n\n if url and isinstance(url, str):\n # The given URL is not empty nor None.\n # and\n # * The given URL is a string.\n\n # We silently load the configuration.\n load_config(True)\n\n return Check(url).is_url_valid()\n\n # We return None, there is nothing to check.\n return None": 4006, "def print_ldamodel_topic_words(topic_word_distrib, vocab, n_top=10, row_labels=DEFAULT_TOPIC_NAME_FMT):\n \"\"\"Print `n_top` values from a LDA model's topic-word distributions.\"\"\"\n print_ldamodel_distribution(topic_word_distrib, row_labels=row_labels, val_labels=vocab,\n top_n=n_top)": 4007, "def drop_trailing_zeros(num):\n \"\"\"\n Drops the trailing zeros in a float that is printed.\n \"\"\"\n txt = '%f' %(num)\n txt = txt.rstrip('0')\n if txt.endswith('.'):\n txt = txt[:-1]\n return txt": 4008, "def str_check(*args, func=None):\n \"\"\"Check if arguments are str type.\"\"\"\n func = func or inspect.stack()[2][3]\n for var in args:\n if not isinstance(var, (str, collections.UserString, collections.abc.Sequence)):\n name = type(var).__name__\n raise StringError(\n f'Function {func} expected str, {name} got instead.')": 4009, "def set_scrollbars_cb(self, w, tf):\n \"\"\"This callback is invoked when the user checks the 'Use Scrollbars'\n box in the preferences pane.\"\"\"\n scrollbars = 'on' if tf else 'off'\n self.t_.set(scrollbars=scrollbars)": 4010, "def is_closed(self):\n \"\"\" Check if session was closed. \"\"\"\n return (self.state == SESSION_STATE.CLOSED \n or self.state == SESSION_STATE.CLOSING)": 4011, "def _lookup_enum_in_ns(namespace, value):\n \"\"\"Return the attribute of namespace corresponding to value.\"\"\"\n for attribute in dir(namespace):\n if getattr(namespace, attribute) == value:\n return attribute": 4012, "def getConnectionStats(self):\n \"\"\"Returns dictionary with number of connections for each database.\n \n @return: Dictionary of database connection statistics.\n \n \"\"\"\n cur = self._conn.cursor()\n cur.execute(\"\"\"SELECT datname,numbackends FROM pg_stat_database;\"\"\")\n rows = cur.fetchall()\n if rows:\n return dict(rows)\n else:\n return {}": 4013, "def _check_model(obj, models=None):\n \"\"\"Checks object if it's a peewee model and unique.\"\"\"\n return isinstance(obj, type) and issubclass(obj, pw.Model) and hasattr(obj, '_meta')": 4014, "def setVolume(self, volume):\n \"\"\"Changes volume\"\"\"\n val = float(val)\n cmd = \"volume %s\" % val\n self._execute(cmd)": 4015, "def pool_args(function, sequence, kwargs):\n \"\"\"Return a single iterator of n elements of lists of length 3, given a sequence of len n.\"\"\"\n return zip(itertools.repeat(function), sequence, itertools.repeat(kwargs))": 4016, "def serve_dtool_directory(directory, port):\n \"\"\"Serve the datasets in a directory over HTTP.\"\"\"\n os.chdir(directory)\n server_address = (\"localhost\", port)\n httpd = DtoolHTTPServer(server_address, DtoolHTTPRequestHandler)\n httpd.serve_forever()": 4017, "def get_last_week_range(weekday_start=\"Sunday\"):\n \"\"\" Gets the date for the first and the last day of the previous complete week.\n\n :param weekday_start: Either \"Monday\" or \"Sunday\", indicating the first day of the week.\n :returns: A tuple containing two date objects, for the first and the last day of the week\n respectively.\n \"\"\"\n today = date.today()\n # Get the first day of the past complete week.\n start_of_week = snap_to_beginning_of_week(today, weekday_start) - timedelta(weeks=1)\n end_of_week = start_of_week + timedelta(days=6)\n return (start_of_week, end_of_week)": 4018, "def __check_success(resp):\n \"\"\" Check a JSON server response to see if it was successful\n\n :type resp: Dictionary (parsed JSON from response)\n :param resp: the response string\n\n :rtype: String\n :returns: the success message, if it exists\n\n :raises: APIError if the success message is not present\n\n\n \"\"\"\n\n if \"success\" not in resp.keys():\n try:\n raise APIError('200', 'Operation Failed', resp[\"error\"])\n except KeyError:\n raise APIError('200', 'Operation Failed', str(resp))\n return resp[\"success\"]": 4019, "def s3_connect(bucket_name, s3_access_key_id, s3_secret_key):\n \"\"\" Returns a Boto connection to the provided S3 bucket. \"\"\"\n conn = connect_s3(s3_access_key_id, s3_secret_key)\n try:\n return conn.get_bucket(bucket_name)\n except S3ResponseError as e:\n if e.status == 403:\n raise Exception(\"Bad Amazon S3 credentials.\")\n raise": 4020, "def short_action_string(self):\n \"\"\"\n Returns string with actor and verb, allowing target/object\n to be filled in manually.\n\n Example:\n [actor] [verb] or\n \"Joe cool posted a comment\"\n \"\"\"\n output = \"{0} \".format(self.actor)\n if self.override_string:\n output += self.override_string\n else:\n output += self.verb\n return output": 4021, "def _check_fields(self, x, y):\n\t\t\"\"\"\n\t\tCheck x and y fields parameters and initialize\n\t\t\"\"\"\n\t\tif x is None:\n\t\t\tif self.x is None:\n\t\t\t\tself.err(\n\t\t\t\t\tself._check_fields,\n\t\t\t\t\t\"X field is not set: please specify a parameter\")\n\t\t\t\treturn\n\t\t\tx = self.x\n\t\tif y is None:\n\t\t\tif self.y is None:\n\t\t\t\tself.err(\n\t\t\t\t\tself._check_fields,\n\t\t\t\t\t\"Y field is not set: please specify a parameter\")\n\t\t\t\treturn\n\t\t\ty = self.y\n\t\treturn x, y": 4022, "def _trace_full (frame, event, arg):\n \"\"\"Trace every executed line.\"\"\"\n if event == \"line\":\n _trace_line(frame, event, arg)\n else:\n _trace(frame, event, arg)\n return _trace_full": 4023, "def _remove_empty_items(d, required):\n \"\"\"Return a new dict with any empty items removed.\n\n Note that this is not a deep check. If d contains a dictionary which\n itself contains empty items, those are never checked.\n\n This method exists to make to_serializable() functions cleaner.\n We could revisit this some day, but for now, the serialized objects are\n stripped of empty values to keep the output YAML more compact.\n\n Args:\n d: a dictionary\n required: list of required keys (for example, TaskDescriptors always emit\n the \"task-id\", even if None)\n\n Returns:\n A dictionary with empty items removed.\n \"\"\"\n\n new_dict = {}\n for k, v in d.items():\n if k in required:\n new_dict[k] = v\n elif isinstance(v, int) or v:\n # \"if v\" would suppress emitting int(0)\n new_dict[k] = v\n\n return new_dict": 4024, "def previous_key(tuple_of_tuples, key):\n \"\"\"Returns the key which comes before the give key.\n\n It Processes a tuple of 2-element tuples and returns the key which comes\n before the given key.\n \"\"\"\n for i, t in enumerate(tuple_of_tuples):\n if t[0] == key:\n try:\n return tuple_of_tuples[i - 1][0]\n except IndexError:\n return None": 4025, "def translation(language):\n \"\"\"\n Return a translation object in the default 'django' domain.\n \"\"\"\n global _translations\n if language not in _translations:\n _translations[language] = Translations(language)\n return _translations[language]": 4026, "def get_common_elements(list1, list2):\n \"\"\"find the common elements in two lists. used to support auto align\n might be faster with sets\n\n Parameters\n ----------\n list1 : list\n a list of objects\n list2 : list\n a list of objects\n\n Returns\n -------\n list : list\n list of common objects shared by list1 and list2\n \n \"\"\"\n #result = []\n #for item in list1:\n # if item in list2:\n # result.append(item)\n #Return list(set(list1).intersection(set(list2)))\n set2 = set(list2)\n result = [item for item in list1 if item in set2]\n return result": 4027, "def cancel(self, event=None):\n \"\"\"Function called when Cancel-button clicked.\n\n This method returns focus to parent, and destroys the dialog.\n \"\"\"\n\n if self.parent != None:\n self.parent.focus_set()\n\n self.destroy()": 4028, "def on_close(self, ws):\n \"\"\" Called when websocket connection is closed\n \"\"\"\n log.debug(\"Closing WebSocket connection with {}\".format(self.url))\n if self.keepalive and self.keepalive.is_alive():\n self.keepalive.do_run = False\n self.keepalive.join()": 4029, "def close_database_session(session):\n \"\"\"Close connection with the database\"\"\"\n\n try:\n session.close()\n except OperationalError as e:\n raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0])": 4030, "def query_collision(collision_object):\n \"\"\"\n Check to see if the specified object is colliding with any of the objects currently in the Collision Manager\n Returns the first object we are colliding with if there was a collision and None if no collisions was found\n \"\"\"\n global collidable_objects\n # Note that we use a Brute Force approach for the time being.\n # It performs horribly under heavy loads, but it meets\n # our needs for the time being.\n for obj in collidable_objects:\n # Make sure we don't check ourself against ourself.\n if obj.obj_id is not collision_object.obj_id:\n if collision_object.is_colliding(obj):\n # A collision has been detected. Return the object that we are colliding with.\n return obj\n\n # No collision was noticed. Return None.\n return None": 4031, "def has_edit_permission(self, request):\n \"\"\" Can edit this object \"\"\"\n return request.user.is_authenticated and request.user.is_active and request.user.is_staff": 4032, "def get_labels(labels):\n \"\"\"Create unique labels.\"\"\"\n label_u = unique_labels(labels)\n label_u_line = [i + \"_line\" for i in label_u]\n return label_u, label_u_line": 4033, "def _stop_instance(self):\n \"\"\"Stop the instance.\"\"\"\n instance = self._get_instance()\n instance.stop()\n self._wait_on_instance('stopped', self.timeout)": 4034, "def get_codeblock(language, text):\n \"\"\" Generates rst codeblock for given text and language \"\"\"\n rst = \"\\n\\n.. code-block:: \" + language + \"\\n\\n\"\n for line in text.splitlines():\n rst += \"\\t\" + line + \"\\n\"\n\n rst += \"\\n\"\n return rst": 4035, "def xor(a, b):\n \"\"\"Bitwise xor on equal length bytearrays.\"\"\"\n return bytearray(i ^ j for i, j in zip(a, b))": 4036, "def compare(string1, string2):\n \"\"\"Compare two strings while protecting against timing attacks\n\n :param str string1: the first string\n :param str string2: the second string\n\n :returns: True if the strings are equal, False if not\n :rtype: :obj:`bool`\n \"\"\"\n if len(string1) != len(string2):\n return False\n result = True\n for c1, c2 in izip(string1, string2):\n result &= c1 == c2\n return result": 4037, "def register():\n \"\"\"\n Calls the shots, based on signals\n \"\"\"\n signals.article_generator_finalized.connect(link_source_files)\n signals.page_generator_finalized.connect(link_source_files)\n signals.page_writer_finalized.connect(write_source_files)": 4038, "def quit(self):\n \"\"\"\n Closes the browser and shuts down the WebKitGTKDriver executable\n that is started when starting the WebKitGTKDriver\n \"\"\"\n try:\n RemoteWebDriver.quit(self)\n except http_client.BadStatusLine:\n pass\n finally:\n self.service.stop()": 4039, "def shannon_entropy(p):\n \"\"\"Calculates shannon entropy in bits.\n\n Parameters\n ----------\n p : np.array\n array of probabilities\n\n Returns\n -------\n shannon entropy in bits\n \"\"\"\n return -np.sum(np.where(p!=0, p * np.log2(p), 0))": 4040, "def yum_install(self, packages, ignore_error=False):\n \"\"\"Install some packages on the remote host.\n\n :param packages: ist of packages to install.\n \"\"\"\n return self.run('yum install -y --quiet ' + ' '.join(packages), ignore_error=ignore_error, retry=5)": 4041, "def obj_to_string(obj, top=True):\n \"\"\"\n Turn an arbitrary object into a unicode string. If complex (dict/list/tuple), will be json-encoded.\n \"\"\"\n obj = prepare_for_json_encoding(obj)\n if type(obj) == six.text_type:\n return obj\n return json.dumps(obj)": 4042, "def _get_session():\n \"\"\"Return (and memoize) a database session\"\"\"\n session = getattr(g, '_session', None)\n if session is None:\n session = g._session = db.session()\n return session": 4043, "def writeCSV(data, headers, csvFile):\n \"\"\"Write data with column headers to a CSV.\"\"\"\n with open(csvFile, \"wb\") as f:\n writer = csv.writer(f, delimiter=\",\")\n writer.writerow(headers)\n writer.writerows(data)": 4044, "def _MakeExecutable(self, metadata_script):\n \"\"\"Add executable permissions to a file.\n\n Args:\n metadata_script: string, the path to the executable file.\n \"\"\"\n mode = os.stat(metadata_script).st_mode\n os.chmod(metadata_script, mode | stat.S_IEXEC)": 4045, "def build_code(self, lang, body):\n \"\"\"Wrap text with markdown specific flavour.\"\"\"\n self.out.append(\"```\" + lang)\n self.build_markdown(lang, body)\n self.out.append(\"```\")": 4046, "def default_diff(latest_config, current_config):\n \"\"\"Determine if two revisions have actually changed.\"\"\"\n # Pop off the fields we don't care about:\n pop_no_diff_fields(latest_config, current_config)\n\n diff = DeepDiff(\n latest_config,\n current_config,\n ignore_order=True\n )\n return diff": 4047, "def load_model_from_package(name, **overrides):\n \"\"\"Load a model from an installed package.\"\"\"\n cls = importlib.import_module(name)\n return cls.load(**overrides)": 4048, "def types(self):\n \"\"\"\n Return a list of all the variable types that exist in the\n Variables object.\n \"\"\"\n output = set()\n for var in self.values():\n if var.has_value():\n output.update(var.types())\n return list(output)": 4049, "def index():\n \"\"\" Display productpage with normal user and test user buttons\"\"\"\n global productpage\n\n table = json2html.convert(json = json.dumps(productpage),\n table_attributes=\"class=\\\"table table-condensed table-bordered table-hover\\\"\")\n\n return render_template('index.html', serviceTable=table)": 4050, "def send_request(self, *args, **kwargs):\n \"\"\"Wrapper for session.request\n Handle connection reset error even from pyopenssl\n \"\"\"\n try:\n return self.session.request(*args, **kwargs)\n except ConnectionError:\n self.session.close()\n return self.session.request(*args, **kwargs)": 4051, "def _windowsLdmodTargets(target, source, env, for_signature):\n \"\"\"Get targets for loadable modules.\"\"\"\n return _dllTargets(target, source, env, for_signature, 'LDMODULE')": 4052, "def enbw(wnd):\n \"\"\" Equivalent Noise Bandwidth in bins (Processing Gain reciprocal). \"\"\"\n return sum(el ** 2 for el in wnd) / sum(wnd) ** 2 * len(wnd)": 4053, "def __init__(self, collection, index_type_obj):\n \"\"\"\n Constructs wrapper for general index creation and deletion\n\n :param collection Collection\n :param index_type_obj BaseIndex Object of a index sub-class\n \"\"\"\n\n self.collection = collection\n self.index_type_obj = index_type_obj": 4054, "def setup(app):\n \"\"\"Allow this package to be used as Sphinx extension.\n This is also called from the top-level ``__init__.py``.\n\n :type app: sphinx.application.Sphinx\n \"\"\"\n from .patches import patch_django_for_autodoc\n\n # When running, make sure Django doesn't execute querysets\n patch_django_for_autodoc()\n\n # Generate docstrings for Django model fields\n # Register the docstring processor with sphinx\n app.connect('autodoc-process-docstring', improve_model_docstring)\n\n # influence skip rules\n app.connect(\"autodoc-skip-member\", autodoc_skip)": 4055, "def convertDatetime(t):\n \"\"\"\n Converts the specified datetime object into its appropriate protocol\n value. This is the number of milliseconds from the epoch.\n \"\"\"\n epoch = datetime.datetime.utcfromtimestamp(0)\n delta = t - epoch\n millis = delta.total_seconds() * 1000\n return int(millis)": 4056, "def coords_string_parser(self, coords):\n \"\"\"Pareses the address string into coordinates to match address_to_coords return object\"\"\"\n\n lat, lon = coords.split(',')\n return {\"lat\": lat.strip(), \"lon\": lon.strip(), \"bounds\": {}}": 4057, "def _iterable_to_varargs_method(func):\n \"\"\"decorator to convert a method taking a iterable to a *args one\"\"\"\n def wrapped(self, *args, **kwargs):\n return func(self, args, **kwargs)\n return wrapped": 4058, "def to_bin(data, width):\n \"\"\"\n Convert an unsigned integer to a numpy binary array with the first\n element the MSB and the last element the LSB.\n \"\"\"\n data_str = bin(data & (2**width-1))[2:].zfill(width)\n return [int(x) for x in tuple(data_str)]": 4059, "def __deepcopy__(self, memo):\n \"\"\"Improve deepcopy speed.\"\"\"\n return type(self)(value=self._value, enum_ref=self.enum_ref)": 4060, "def url(self, action, **kwargs):\n \"\"\" Construct and return the URL for a specific API service. \"\"\"\n # TODO : should be static method ?\n return self.URLS['BASE'] % self.URLS[action] % kwargs": 4061, "def __delitem__(self, key):\n\t\t\"\"\"Remove item with given key from the mapping.\n\n\t\tRuns in O(n), unless removing last item, then in O(1).\n\t\t\"\"\"\n\t\tindex, value = self._dict.pop(key)\n\t\tkey2, value2 = self._list.pop(index)\n\t\tassert key == key2\n\t\tassert value is value2\n\n\t\tself._fix_indices_after_delete(index)": 4062, "def restore_button_state(self):\n \"\"\"Helper to restore button state.\"\"\"\n self.parent.pbnNext.setEnabled(self.next_button_state)\n self.parent.pbnBack.setEnabled(self.back_button_state)": 4063, "def remove_this_tlink(self,tlink_id):\n \"\"\"\n Removes the tlink for the given tlink identifier\n @type tlink_id: string\n @param tlink_id: the tlink identifier to be removed\n \"\"\"\n for tlink in self.get_tlinks():\n if tlink.get_id() == tlink_id:\n self.node.remove(tlink.get_node())\n break": 4064, "def normalized_distance(self, image):\n \"\"\"Calculates the distance of a given image to the\n original image.\n\n Parameters\n ----------\n image : `numpy.ndarray`\n The image that should be compared to the original image.\n\n Returns\n -------\n :class:`Distance`\n The distance between the given image and the original image.\n\n \"\"\"\n return self.__distance(\n self.__original_image_for_distance,\n image,\n bounds=self.bounds())": 4065, "def _distance(coord1, coord2):\n \"\"\"\n Return the distance between two points, `coord1` and `coord2`. These\n parameters are assumed to be (x, y) tuples.\n \"\"\"\n xdist = coord1[0] - coord2[0]\n ydist = coord1[1] - coord2[1]\n return sqrt(xdist*xdist + ydist*ydist)": 4066, "def _decode(self, obj, context):\n \"\"\"\n Get the python representation of the obj\n \"\"\"\n return b''.join(map(int2byte, [c + 0x60 for c in bytearray(obj)])).decode(\"utf8\")": 4067, "def tpr(y, z):\n \"\"\"True positive rate `tp / (tp + fn)`\n \"\"\"\n tp, tn, fp, fn = contingency_table(y, z)\n return tp / (tp + fn)": 4068, "def is_descriptor_class(desc, include_abstract=False):\n r\"\"\"Check calculatable descriptor class or not.\n\n Returns:\n bool\n\n \"\"\"\n return (\n isinstance(desc, type)\n and issubclass(desc, Descriptor)\n and (True if include_abstract else not inspect.isabstract(desc))\n )": 4069, "def set_terminate_listeners(stream):\n \"\"\"Die on SIGTERM or SIGINT\"\"\"\n\n def stop(signum, frame):\n terminate(stream.listener)\n\n # Installs signal handlers for handling SIGINT and SIGTERM\n # gracefully.\n signal.signal(signal.SIGINT, stop)\n signal.signal(signal.SIGTERM, stop)": 4070, "def register(self, target):\n \"\"\"Registers url_rules on the blueprint\n \"\"\"\n for rule, options in self.url_rules:\n target.add_url_rule(rule, self.name, self.dispatch_request, **options)": 4071, "def check_hash_key(query_on, key):\n \"\"\"Only allows == against query_on.hash_key\"\"\"\n return (\n isinstance(key, BaseCondition) and\n (key.operation == \"==\") and\n (key.column is query_on.hash_key)\n )": 4072, "def load_files(files):\n \"\"\"Load and execute a python file.\"\"\"\n\n for py_file in files:\n LOG.debug(\"exec %s\", py_file)\n execfile(py_file, globals(), locals())": 4073, "def typescript_compile(source):\n \"\"\"Compiles the given ``source`` from TypeScript to ES5 using TypescriptServices.js\"\"\"\n with open(TS_COMPILER, 'r') as tsservices_js:\n return evaljs(\n (tsservices_js.read(),\n 'ts.transpile(dukpy.tscode, {options});'.format(options=TSC_OPTIONS)),\n tscode=source\n )": 4074, "def __init__(self):\n \"\"\"Initialize the state of the object\"\"\"\n self.state = self.STATE_INITIALIZING\n self.state_start = time.time()": 4075, "def is_break_tag(self, el):\n \"\"\"Check if tag is an element we should break on.\"\"\"\n\n name = el.name\n return name in self.break_tags or name in self.user_break_tags": 4076, "def ignored_regions(source):\n \"\"\"Return ignored regions like strings and comments in `source` \"\"\"\n return [(match.start(), match.end()) for match in _str.finditer(source)]": 4077, "def install_plugin(username, repo):\n \"\"\"Installs a Blended plugin from GitHub\"\"\"\n print(\"Installing plugin from \" + username + \"/\" + repo)\n\n pip.main(['install', '-U', \"git+git://github.com/\" +\n username + \"/\" + repo + \".git\"])": 4078, "def run_cmd(command, verbose=True, shell='/bin/bash'):\n \"\"\"internal helper function to run shell commands and get output\"\"\"\n process = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT, executable=shell)\n output = process.stdout.read().decode().strip().split('\\n')\n if verbose:\n # return full output including empty lines\n return output\n return [line for line in output if line.strip()]": 4079, "def gauss_box_model(x, amplitude=1.0, mean=0.0, stddev=1.0, hpix=0.5):\n \"\"\"Integrate a Gaussian profile.\"\"\"\n z = (x - mean) / stddev\n z2 = z + hpix / stddev\n z1 = z - hpix / stddev\n return amplitude * (norm.cdf(z2) - norm.cdf(z1))": 4080, "def safe_dump_all(documents, stream=None, **kwds):\n \"\"\"\n Serialize a sequence of Python objects into a YAML stream.\n Produce only basic YAML tags.\n If stream is None, return the produced string instead.\n \"\"\"\n return dump_all(documents, stream, Dumper=SafeDumper, **kwds)": 4081, "async def vc_check(ctx: commands.Context): # pylint: disable=unused-argument\n \"\"\"\n Check for whether VC is available in this bot.\n \"\"\"\n\n if not discord.voice_client.has_nacl:\n raise commands.CheckFailure(\"voice cannot be used because PyNaCl is not loaded\")\n\n if not discord.opus.is_loaded():\n raise commands.CheckFailure(\"voice cannot be used because libopus is not loaded\")\n\n return True": 4082, "def parse_value(self, value):\n \"\"\"Cast value to `bool`.\"\"\"\n parsed = super(BoolField, self).parse_value(value)\n return bool(parsed) if parsed is not None else None": 4083, "def __del__(self):\n \"\"\"Cleanup any active connections and free all DDEML resources.\"\"\"\n if self._hConv:\n DDE.Disconnect(self._hConv)\n if self._idInst:\n DDE.Uninitialize(self._idInst)": 4084, "def _init_glyph(self, plot, mapping, properties):\n \"\"\"\n Returns a Bokeh glyph object.\n \"\"\"\n properties = mpl_to_bokeh(properties)\n plot_method = self._plot_methods.get('batched' if self.batched else 'single')\n if isinstance(plot_method, tuple):\n # Handle alternative plot method for flipped axes\n plot_method = plot_method[int(self.invert_axes)]\n renderer = getattr(plot, plot_method)(**dict(properties, **mapping))\n return renderer, renderer.glyph": 4085, "def duplicated_rows(df, col_name):\n \"\"\" Return a DataFrame with the duplicated values of the column `col_name`\n in `df`.\"\"\"\n _check_cols(df, [col_name])\n\n dups = df[pd.notnull(df[col_name]) & df.duplicated(subset=[col_name])]\n return dups": 4086, "def determine_types(self):\n \"\"\" Determine ES type names from request data.\n\n In particular `request.matchdict['collections']` is used to\n determine types names. Its value is comma-separated sequence\n of collection names under which views have been registered.\n \"\"\"\n from nefertari.elasticsearch import ES\n collections = self.get_collections()\n resources = self.get_resources(collections)\n models = set([res.view.Model for res in resources])\n es_models = [mdl for mdl in models if mdl\n and getattr(mdl, '_index_enabled', False)]\n types = [ES.src2type(mdl.__name__) for mdl in es_models]\n return types": 4087, "def is_vector(inp):\n \"\"\" Returns true if the input can be interpreted as a 'true' vector\n\n Note\n ----\n Does only check dimensions, not if type is numeric\n\n Parameters\n ----------\n inp : numpy.ndarray or something that can be converted into ndarray\n\n Returns\n -------\n Boolean\n True for vectors: ndim = 1 or ndim = 2 and shape of one axis = 1\n False for all other arrays\n \"\"\"\n inp = np.asarray(inp)\n nr_dim = np.ndim(inp)\n if nr_dim == 1:\n return True\n elif (nr_dim == 2) and (1 in inp.shape):\n return True\n else:\n return False": 4088, "def mutating_method(func):\n \"\"\"Decorator for methods that are allowed to modify immutable objects\"\"\"\n def wrapper(self, *__args, **__kwargs):\n old_mutable = self._mutable\n self._mutable = True\n try:\n # Call the wrapped function\n return func(self, *__args, **__kwargs)\n finally:\n self._mutable = old_mutable\n return wrapper": 4089, "def _dump_enum(self, e, top=''):\n \"\"\"Dump single enum type.\n \n Keyword arguments:\n top -- top namespace\n \"\"\"\n self._print()\n self._print('enum {} {{'.format(e.name))\n self.defines.append('{}.{}'.format(top,e.name))\n \n self.tabs+=1\n for v in e.value:\n self._print('{} = {};'.format(v.name, v.number))\n self.tabs-=1\n self._print('}')": 4090, "def get_enum_from_name(self, enum_name):\n \"\"\"\n Return an enum from a name\n Args:\n enum_name (str): name of the enum\n Returns:\n Enum\n \"\"\"\n return next((e for e in self.enums if e.name == enum_name), None)": 4091, "def sed(match, replacement, path, modifiers=\"\"):\n \"\"\"\n Perform sed text substitution.\n \"\"\"\n cmd = \"sed -r -i 's/%s/%s/%s' %s\" % (match, replacement, modifiers, path)\n\n process = Subprocess(cmd, shell=True)\n ret, out, err = process.run(timeout=60)\n if ret:\n raise SubprocessError(\"Sed command failed!\")": 4092, "def euler(self):\n \"\"\"TODO DEPRECATE THIS?\"\"\"\n e_xyz = transformations.euler_from_matrix(self.rotation, 'sxyz')\n return np.array([180.0 / np.pi * a for a in e_xyz])": 4093, "def cleanup():\n \"\"\"Cleanup the output directory\"\"\"\n if _output_dir and os.path.exists(_output_dir):\n log.msg_warn(\"Cleaning up output directory at '{output_dir}' ...\"\n .format(output_dir=_output_dir))\n if not _dry_run:\n shutil.rmtree(_output_dir)": 4094, "def paste(cmd=paste_cmd, stdout=PIPE):\n \"\"\"Returns system clipboard contents.\n \"\"\"\n return Popen(cmd, stdout=stdout).communicate()[0].decode('utf-8')": 4095, "def apply_to_field_if_exists(effect, field_name, fn, default):\n \"\"\"\n Apply function to specified field of effect if it is not None,\n otherwise return default.\n \"\"\"\n value = getattr(effect, field_name, None)\n if value is None:\n return default\n else:\n return fn(value)": 4096, "def fuzzy_get_tuple(dict_obj, approximate_key, dict_keys=None, key_and_value=False, similarity=0.6, default=None):\n \"\"\"Find the closest matching key and/or value in a dictionary (must have all string keys!)\"\"\"\n return fuzzy_get(dict(('|'.join(str(k2) for k2 in k), v) for (k, v) in viewitems(dict_obj)),\n '|'.join(str(k) for k in approximate_key), dict_keys=dict_keys,\n key_and_value=key_and_value, similarity=similarity, default=default)": 4097, "def get_typecast_value(self, value, type):\n \"\"\" Helper method to determine actual value based on type of feature variable.\n\n Args:\n value: Value in string form as it was parsed from datafile.\n type: Type denoting the feature flag type.\n\n Return:\n Value type-casted based on type of feature variable.\n \"\"\"\n\n if type == entities.Variable.Type.BOOLEAN:\n return value == 'true'\n elif type == entities.Variable.Type.INTEGER:\n return int(value)\n elif type == entities.Variable.Type.DOUBLE:\n return float(value)\n else:\n return value": 4098, "def get_scalar_product(self, other):\n \"\"\"Returns the scalar product of this vector with the given\n other vector.\"\"\"\n return self.x*other.x+self.y*other.y": 4099, "def get_long_description():\n \"\"\"Convert the README file into the long description.\n \"\"\"\n with open(path.join(root_path, 'README.md'), encoding='utf-8') as f:\n long_description = f.read()\n return long_description": 4100, "def main(argv=None):\n \"\"\"Main command line interface.\"\"\"\n\n if argv is None:\n argv = sys.argv[1:]\n\n cli = CommandLineTool()\n return cli.run(argv)": 4101, "def __init__(self, function):\n\t\t\"\"\"function: to be called with each stream element as its\n\t\tonly argument\n\t\t\"\"\"\n\t\tsuper(filter, self).__init__()\n\t\tself.function = function": 4102, "def make_code_from_py(filename):\n \"\"\"Get source from `filename` and make a code object of it.\"\"\"\n # Open the source file.\n try:\n source_file = open_source(filename)\n except IOError:\n raise NoSource(\"No file to run: %r\" % filename)\n\n try:\n source = source_file.read()\n finally:\n source_file.close()\n\n # We have the source. `compile` still needs the last line to be clean,\n # so make sure it is, then compile a code object from it.\n if not source or source[-1] != '\\n':\n source += '\\n'\n code = compile(source, filename, \"exec\")\n\n return code": 4103, "def __init__(self):\n \"\"\"Initializes a filter object.\"\"\"\n super(FilterObject, self).__init__()\n self._filter_expression = None\n self._matcher = None": 4104, "def parse_fixed_width(types, lines):\n \"\"\"Parse a fixed width line.\"\"\"\n values = []\n line = []\n for width, parser in types:\n if not line:\n line = lines.pop(0).replace('\\n', '')\n\n values.append(parser(line[:width]))\n line = line[width:]\n\n return values": 4105, "def handle_request_parsing_error(err, req, schema, error_status_code, error_headers):\n \"\"\"webargs error handler that uses Flask-RESTful's abort function to return\n a JSON error response to the client.\n \"\"\"\n abort(error_status_code, errors=err.messages)": 4106, "def static_url(path, absolute=False):\n \"\"\" Shorthand for returning a URL for the requested static file.\n\n Arguments:\n\n path -- the path to the file (relative to the static files directory)\n absolute -- whether the link should be absolute or relative\n \"\"\"\n\n if os.sep != '/':\n path = '/'.join(path.split(os.sep))\n\n return flask.url_for('static', filename=path, _external=absolute)": 4107, "def get_site_name(request):\n \"\"\"Return the domain:port part of the URL without scheme.\n Eg: facebook.com, 127.0.0.1:8080, etc.\n \"\"\"\n urlparts = request.urlparts\n return ':'.join([urlparts.hostname, str(urlparts.port)])": 4108, "def jsonify(resource):\n \"\"\"Return a Flask ``Response`` object containing a\n JSON representation of *resource*.\n\n :param resource: The resource to act as the basis of the response\n \"\"\"\n\n response = flask.jsonify(resource.to_dict())\n response = add_link_headers(response, resource.links())\n return response": 4109, "def set_header(self, name, value):\n \"\"\" Create a new response header, replacing any previously defined\n headers with the same name. \"\"\"\n self._headers[_hkey(name)] = [_hval(value)]": 4110, "def get_mac_dot_app_dir(directory):\n \"\"\"Returns parent directory of mac .app\n\n Args:\n\n directory (str): Current directory\n\n Returns:\n\n (str): Parent directory of mac .app\n \"\"\"\n return os.path.dirname(os.path.dirname(os.path.dirname(directory)))": 4111, "def flush(self):\n \"\"\" Force commit changes to the file and stdout \"\"\"\n if not self.nostdout:\n self.stdout.flush()\n if self.file is not None:\n self.file.flush()": 4112, "def map_parameters(cls, params):\n \"\"\"Maps parameters to form field names\"\"\"\n\n d = {}\n for k, v in six.iteritems(params):\n d[cls.FIELD_MAP.get(k.lower(), k)] = v\n return d": 4113, "def RunSphinxAPIDoc(_):\n \"\"\"Runs sphinx-apidoc to auto-generate documentation.\"\"\"\n current_directory = os.path.abspath(os.path.dirname(__file__))\n module = os.path.join(current_directory, '..', 'plaso')\n api_directory = os.path.join(current_directory, 'sources', 'api')\n apidoc.main(['-o', api_directory, module, '--force'])": 4114, "def none(self):\n \"\"\"\n Returns an empty QuerySet.\n \"\"\"\n return EmptyQuerySet(model=self.model, using=self._using, connection=self._connection)": 4115, "def generate_device_id(steamid):\n \"\"\"Generate Android device id\n\n :param steamid: Steam ID\n :type steamid: :class:`.SteamID`, :class:`int`\n :return: android device id\n :rtype: str\n \"\"\"\n h = hexlify(sha1_hash(str(steamid).encode('ascii'))).decode('ascii')\n return \"android:%s-%s-%s-%s-%s\" % (h[:8], h[8:12], h[12:16], h[16:20], h[20:32])": 4116, "def __init__(self, token, editor=None):\n \"\"\"Create a GistAPI object\n\n Arguments:\n token: an authentication token\n editor: path to the editor to use when editing a gist\n\n \"\"\"\n self.token = token\n self.editor = editor\n self.session = requests.Session()": 4117, "def generate_id(self):\n \"\"\"Generate a fresh id\"\"\"\n if self.use_repeatable_ids:\n self.repeatable_id_counter += 1\n return 'autobaked-{}'.format(self.repeatable_id_counter)\n else:\n return str(uuid4())": 4118, "def lon_lat_bins(bb, coord_bin_width):\n \"\"\"\n Define bin edges for disaggregation histograms.\n\n Given bins data as provided by :func:`collect_bin_data`, this function\n finds edges of histograms, taking into account maximum and minimum values\n of magnitude, distance and coordinates as well as requested sizes/numbers\n of bins.\n \"\"\"\n west, south, east, north = bb\n west = numpy.floor(west / coord_bin_width) * coord_bin_width\n east = numpy.ceil(east / coord_bin_width) * coord_bin_width\n lon_extent = get_longitudinal_extent(west, east)\n lon_bins, _, _ = npoints_between(\n west, 0, 0, east, 0, 0,\n numpy.round(lon_extent / coord_bin_width + 1))\n lat_bins = coord_bin_width * numpy.arange(\n int(numpy.floor(south / coord_bin_width)),\n int(numpy.ceil(north / coord_bin_width) + 1))\n return lon_bins, lat_bins": 4119, "def object_to_json(obj):\n \"\"\"Convert object that cannot be natively serialized by python to JSON representation.\"\"\"\n if isinstance(obj, (datetime.datetime, datetime.date, datetime.time)):\n return obj.isoformat()\n return str(obj)": 4120, "def get_pid_list():\n \"\"\"Returns a list of PIDs currently running on the system.\"\"\"\n pids = [int(x) for x in os.listdir('/proc') if x.isdigit()]\n return pids": 4121, "def getRect(self):\n\t\t\"\"\"\n\t\tReturns the window bounds as a tuple of (x,y,w,h)\n\t\t\"\"\"\n\t\treturn (self.x, self.y, self.w, self.h)": 4122, "def get_shape(self):\n\t\t\"\"\"\n\t\tReturn a tuple of this array's dimensions. This is done by\n\t\tquerying the Dim children. Note that once it has been\n\t\tcreated, it is also possible to examine an Array object's\n\t\t.array attribute directly, and doing that is much faster.\n\t\t\"\"\"\n\t\treturn tuple(int(c.pcdata) for c in self.getElementsByTagName(ligolw.Dim.tagName))[::-1]": 4123, "def delaunay_2d(self, tol=1e-05, alpha=0.0, offset=1.0, bound=False):\n \"\"\"Apply a delaunay 2D filter along the best fitting plane. This\n extracts the grid's points and perfoms the triangulation on those alone.\n \"\"\"\n return PolyData(self.points).delaunay_2d(tol=tol, alpha=alpha, offset=offset, bound=bound)": 4124, "def forget_canvas(canvas):\n \"\"\" Forget about the given canvas. Used by the canvas when closed.\n \"\"\"\n cc = [c() for c in canvasses if c() is not None]\n while canvas in cc:\n cc.remove(canvas)\n canvasses[:] = [weakref.ref(c) for c in cc]": 4125, "def clean(dry_run='n'):\n \"\"\"Wipes compiled and cached python files. To simulate: pynt clean[dry_run=y]\"\"\"\n file_patterns = ['*.pyc', '*.pyo', '*~']\n dir_patterns = ['__pycache__']\n recursive_pattern_delete(project_paths.root, file_patterns, dir_patterns, dry_run=bool(dry_run.lower() == 'y'))": 4126, "def get_table_pos(self, tablename):\n \"\"\"\n :param str tablename: Name of table to get position of.\n :return: Upper left (row, col) coordinate of the named table.\n \"\"\"\n _table, (row, col) = self.__tables[tablename]\n return (row, col)": 4127, "def parse_text_to_dict(self, txt):\n \"\"\" \n takes a string and parses via NLP, ready for mapping\n \"\"\"\n op = {}\n print('TODO - import NLP, split into verbs / nouns')\n op['nouns'] = txt\n op['verbs'] = txt\n \n return op": 4128, "def off(self):\n \"\"\"Turn off curses\"\"\"\n self.win.keypad(0)\n curses.nocbreak()\n curses.echo()\n try:\n curses.curs_set(1)\n except:\n pass\n curses.endwin()": 4129, "def send_text(self, text):\n \"\"\"Send a plain text message to the room.\"\"\"\n return self.client.api.send_message(self.room_id, text)": 4130, "def _columns_for_table(table_name):\n \"\"\"\n Return all of the columns registered for a given table.\n\n Parameters\n ----------\n table_name : str\n\n Returns\n -------\n columns : dict of column wrappers\n Keys will be column names.\n\n \"\"\"\n return {cname: col\n for (tname, cname), col in _COLUMNS.items()\n if tname == table_name}": 4131, "def cos_sin_deg(deg):\n \"\"\"Return the cosine and sin for the given angle\n in degrees, with special-case handling of multiples\n of 90 for perfect right angles\n \"\"\"\n deg = deg % 360.0\n if deg == 90.0:\n return 0.0, 1.0\n elif deg == 180.0:\n return -1.0, 0\n elif deg == 270.0:\n return 0, -1.0\n rad = math.radians(deg)\n return math.cos(rad), math.sin(rad)": 4132, "def method_header(method_name, nogil=False, idx_as_arg=False):\n \"\"\"Returns the Cython method header for methods without arguments except\n `self`.\"\"\"\n if not config.FASTCYTHON:\n nogil = False\n header = 'cpdef inline void %s(self' % method_name\n header += ', int idx)' if idx_as_arg else ')'\n header += ' nogil:' if nogil else ':'\n return header": 4133, "def read_corpus(file_name):\n \"\"\"\n Read and return the data from a corpus json file.\n \"\"\"\n with io.open(file_name, encoding='utf-8') as data_file:\n return yaml.load(data_file)": 4134, "def find_mapping(es_url, index):\n \"\"\" Find the mapping given an index \"\"\"\n\n mapping = None\n\n backend = find_perceval_backend(es_url, index)\n\n if backend:\n mapping = backend.get_elastic_mappings()\n\n if mapping:\n logging.debug(\"MAPPING FOUND:\\n%s\", json.dumps(json.loads(mapping['items']), indent=True))\n return mapping": 4135, "def _gevent_patch():\n \"\"\"Patch the modules with gevent\n\n :return: Default is GEVENT. If it not supports gevent then return MULTITHREAD\n :rtype: int\n \"\"\"\n try:\n assert gevent\n assert grequests\n except NameError:\n logger.warn('gevent not exist, fallback to multiprocess...')\n return MULTITHREAD\n else:\n monkey.patch_all() # Must patch before get_photos_info\n return GEVENT": 4136, "def get_value(self, context):\n \"\"\"Run python eval on the input string.\"\"\"\n if self.value:\n return expressions.eval_string(self.value, context)\n else:\n # Empty input raises cryptic EOF syntax err, this more human\n # friendly\n raise ValueError('!py string expression is empty. It must be a '\n 'valid python expression instead.')": 4137, "def _spawn(self, func, *args, **kwargs):\n \"\"\"Spawn a handler function.\n\n Spawns the supplied ``func`` with ``*args`` and ``**kwargs``\n as a gevent greenlet.\n\n :param func: A callable to call.\n :param args: Arguments to ``func``.\n :param kwargs: Keyword arguments to ``func``.\n \"\"\"\n gevent.spawn(func, *args, **kwargs)": 4138, "def get_code_language(self):\n \"\"\"\n This is largely copied from bokeh.sphinxext.bokeh_plot.run\n \"\"\"\n js_source = self.get_js_source()\n if self.options.get(\"include_html\", False):\n resources = get_sphinx_resources(include_bokehjs_api=True)\n html_source = BJS_HTML.render(\n css_files=resources.css_files,\n js_files=resources.js_files,\n bjs_script=js_source)\n return [html_source, \"html\"]\n else:\n return [js_source, \"javascript\"]": 4139, "def set(self):\n \"\"\"Set the color as current OpenGL color\n \"\"\"\n glColor4f(self.r, self.g, self.b, self.a)": 4140, "def get_h5file(file_path, mode='r'):\n \"\"\" Return the h5py.File given its file path.\n\n Parameters\n ----------\n file_path: string\n HDF5 file path\n\n mode: string\n r Readonly, file must exist\n r+ Read/write, file must exist\n w Create file, truncate if exists\n w- Create file, fail if exists\n a Read/write if exists, create otherwise (default)\n\n Returns\n -------\n h5file: h5py.File\n \"\"\"\n if not op.exists(file_path):\n raise IOError('Could not find file {}.'.format(file_path))\n\n try:\n h5file = h5py.File(file_path, mode=mode)\n except:\n raise\n else:\n return h5file": 4141, "def distance_matrix(trains1, trains2, cos, tau):\n \"\"\"\n Return the *bipartite* (rectangular) distance matrix between the observations in the first and the second list.\n\n Convenience function; equivalent to ``dissimilarity_matrix(trains1, trains2, cos, tau, \"distance\")``. Refer to :func:`pymuvr.dissimilarity_matrix` for full documentation.\n \"\"\"\n return dissimilarity_matrix(trains1, trains2, cos, tau, \"distance\")": 4142, "def save_partial(self, obj):\n \"\"\"Partial objects do not serialize correctly in python2.x -- this fixes the bugs\"\"\"\n self.save_reduce(_genpartial, (obj.func, obj.args, obj.keywords))": 4143, "def _none_value(self):\n \"\"\"Get an appropriate \"null\" value for this field's type. This\n is used internally when setting the field to None.\n \"\"\"\n if self.out_type == int:\n return 0\n elif self.out_type == float:\n return 0.0\n elif self.out_type == bool:\n return False\n elif self.out_type == six.text_type:\n return u''": 4144, "def perform_permissions_check(self, user, obj, perms):\n \"\"\" Performs the permission check. \"\"\"\n return self.request.forum_permission_handler.can_download_files(obj, user)": 4145, "def serialize(self):\n \"\"\"Serialize the query to a structure using the query DSL.\"\"\"\n data = {'doc': self.doc}\n if isinstance(self.query, Query):\n data['query'] = self.query.serialize()\n return data": 4146, "def check_if_branch_exist(db, root_hash, key_prefix):\n \"\"\"\n Given a key prefix, return whether this prefix is\n the prefix of an existing key in the trie.\n \"\"\"\n validate_is_bytes(key_prefix)\n\n return _check_if_branch_exist(db, root_hash, encode_to_bin(key_prefix))": 4147, "def ensure_dtype_float(x, default=np.float64):\n r\"\"\"Makes sure that x is type of float\n\n \"\"\"\n if isinstance(x, np.ndarray):\n if x.dtype.kind == 'f':\n return x\n elif x.dtype.kind == 'i':\n return x.astype(default)\n else:\n raise TypeError('x is of type '+str(x.dtype)+' that cannot be converted to float')\n else:\n raise TypeError('x is not an array')": 4148, "def __str__(self):\n \"\"\"Returns a pretty-printed string for this object.\"\"\"\n return 'Output name: \"%s\" watts: %d type: \"%s\" id: %d' % (\n self._name, self._watts, self._output_type, self._integration_id)": 4149, "def _pad(self):\n \"\"\"Pads the output with an amount of indentation appropriate for the number of open element.\n\n This method does nothing if the indent value passed to the constructor is falsy.\n \"\"\"\n if self._indent:\n self.whitespace(self._indent * len(self._open_elements))": 4150, "def start(self):\n \"\"\"\n Starts the loop. Calling a running loop is an error.\n \"\"\"\n assert not self.has_started(), \"called start() on an active GeventLoop\"\n self._stop_event = Event()\n # note that we don't use safe_greenlets.spawn because we take care of it in _loop by ourselves\n self._greenlet = gevent.spawn(self._loop)": 4151, "def give_str(self):\n \"\"\"\n Give string representation of the callable.\n \"\"\"\n args = self._args[:]\n kwargs = self._kwargs\n return self._give_str(args, kwargs)": 4152, "def top_level(url, fix_protocol=True):\n \"\"\"Extract the top level domain from an URL.\"\"\"\n ext = tld.get_tld(url, fix_protocol=fix_protocol)\n toplevel = '.'.join(urlparse(url).netloc.split('.')[-2:]).split(\n ext)[0] + ext\n return toplevel": 4153, "def gen_api_key(username):\n \"\"\"\n Create a random API key for a user\n :param username:\n :return: Hex encoded SHA512 random string\n \"\"\"\n salt = str(os.urandom(64)).encode('utf-8')\n return hash_password(username, salt)": 4154, "def normalize(data):\n \"\"\"Normalize the data to be in the [0, 1] range.\n\n :param data:\n :return: normalized data\n \"\"\"\n out_data = data.copy()\n\n for i, sample in enumerate(out_data):\n out_data[i] /= sum(out_data[i])\n\n return out_data": 4155, "def caller_locals():\n \"\"\"Get the local variables in the caller's frame.\"\"\"\n import inspect\n frame = inspect.currentframe()\n try:\n return frame.f_back.f_back.f_locals\n finally:\n del frame": 4156, "def __repr__(self):\n \"\"\"Returns a stringified representation of this object.\"\"\"\n return str({'name': self._name, 'watts': self._watts,\n 'type': self._output_type, 'id': self._integration_id})": 4157, "def get_anchor_href(markup):\n \"\"\"\n Given HTML markup, return a list of hrefs for each anchor tag.\n \"\"\"\n soup = BeautifulSoup(markup, 'lxml')\n return ['%s' % link.get('href') for link in soup.find_all('a')]": 4158, "def _file_type(self, field):\n \"\"\" Returns file type for given file field.\n \n Args:\n field (str): File field\n\n Returns:\n string. File type\n \"\"\"\n type = mimetypes.guess_type(self._files[field])[0]\n return type.encode(\"utf-8\") if isinstance(type, unicode) else str(type)": 4159, "def download_file(save_path, file_url):\n \"\"\" Download file from http url link \"\"\"\n\n r = requests.get(file_url) # create HTTP response object\n\n with open(save_path, 'wb') as f:\n f.write(r.content)\n\n return save_path": 4160, "def onkeyup(self, key, keycode, ctrl, shift, alt):\n \"\"\"Called when user types and releases a key. \n The widget should be able to receive the focus in order to emit the event.\n Assign a 'tabindex' attribute to make it focusable.\n \n Args:\n key (str): the character value\n keycode (str): the numeric char code\n \"\"\"\n return (key, keycode, ctrl, shift, alt)": 4161, "def on_train_end(self, logs):\n \"\"\" Print training time at end of training \"\"\"\n duration = timeit.default_timer() - self.train_start\n print('done, took {:.3f} seconds'.format(duration))": 4162, "def postprocessor(prediction):\n \"\"\"Map prediction tensor to labels.\"\"\"\n prediction = prediction.data.numpy()[0]\n top_predictions = prediction.argsort()[-3:][::-1]\n return [labels[prediction] for prediction in top_predictions]": 4163, "def stop(self):\n \"\"\"Stop the progress bar.\"\"\"\n if self._progressing:\n self._progressing = False\n self._thread.join()": 4164, "def size_on_disk(self):\n \"\"\"\n :return: size of the entire schema in bytes\n \"\"\"\n return int(self.connection.query(\n \"\"\"\n SELECT SUM(data_length + index_length)\n FROM information_schema.tables WHERE table_schema='{db}'\n \"\"\".format(db=self.database)).fetchone()[0])": 4165, "def stop(self):\n \"\"\"Stops playback\"\"\"\n if self.isPlaying is True:\n self._execute(\"stop\")\n self._changePlayingState(False)": 4166, "def yvals(self):\n \"\"\"All y values\"\"\"\n return [\n val[1] for serie in self.series for val in serie.values\n if val[1] is not None\n ]": 4167, "def list_all(dev: Device):\n \"\"\"List all available API calls.\"\"\"\n for name, service in dev.services.items():\n click.echo(click.style(\"\\nService %s\" % name, bold=True))\n for method in service.methods:\n click.echo(\" %s\" % method.name)": 4168, "def yesno(prompt):\n \"\"\"Returns True if user answers 'y' \"\"\"\n prompt += \" [y/n]\"\n a = \"\"\n while a not in [\"y\", \"n\"]:\n a = input(prompt).lower()\n\n return a == \"y\"": 4169, "def get_power(self):\n \"\"\"Check if the device is on.\"\"\"\n power = (yield from self.handle_int(self.API.get('power')))\n return bool(power)": 4170, "def datetime_to_year_quarter(dt):\n \"\"\"\n Args:\n dt: a datetime\n Returns:\n tuple of the datetime's year and quarter\n \"\"\"\n year = dt.year\n quarter = int(math.ceil(float(dt.month)/3))\n return (year, quarter)": 4171, "def find_last_sublist(list_, sublist):\n \"\"\"Given a list, find the last occurance of a sublist within it.\n\n Returns:\n Index where the sublist starts, or None if there is no match.\n \"\"\"\n for i in reversed(range(len(list_) - len(sublist) + 1)):\n if list_[i] == sublist[0] and list_[i:i + len(sublist)] == sublist:\n return i\n return None": 4172, "def readline( file, skip_blank=False ):\n \"\"\"Read a line from provided file, skipping any blank or comment lines\"\"\"\n while 1:\n line = file.readline()\n #print \"every line: %r\" % line\n if not line: return None \n if line[0] != '#' and not ( skip_blank and line.isspace() ):\n return line": 4173, "def getWindowPID(self, hwnd):\n \"\"\" Gets the process ID that the specified window belongs to \"\"\"\n pid = ctypes.c_ulong()\n ctypes.windll.user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))\n return int(pid.value)": 4174, "def predecessors(self, node, graph=None):\n \"\"\" Returns a list of all predecessors of the given node \"\"\"\n if graph is None:\n graph = self.graph\n return [key for key in graph if node in graph[key]]": 4175, "def _index_range(self, version, symbol, from_version=None, **kwargs):\n \"\"\"\n Tuple describing range to read from the ndarray - closed:open\n \"\"\"\n from_index = None\n if from_version:\n from_index = from_version['up_to']\n return from_index, None": 4176, "def upload_file(token, channel_name, file_name):\n \"\"\" upload file to a channel \"\"\"\n\n slack = Slacker(token)\n\n slack.files.upload(file_name, channels=channel_name)": 4177, "def loads(cls, s):\n \"\"\"\n Load an instance of this class from YAML.\n\n \"\"\"\n with closing(StringIO(s)) as fileobj:\n return cls.load(fileobj)": 4178, "def _module_name_from_previous_frame(num_frames_back):\n \"\"\"\n Returns the module name associated with a frame `num_frames_back` in the\n call stack. This function adds 1 to account for itself, so `num_frames_back`\n should be given relative to the caller.\n \"\"\"\n frm = inspect.stack()[num_frames_back + 1]\n return inspect.getmodule(frm[0]).__name__": 4179, "def _multilingual(function, *args, **kwargs):\n \"\"\" Returns the value from the function with the given name in the given language module.\n By default, language=\"en\".\n \"\"\"\n return getattr(_module(kwargs.pop(\"language\", \"en\")), function)(*args, **kwargs)": 4180, "def infer_dtype_from(val, pandas_dtype=False):\n \"\"\"\n interpret the dtype from a scalar or array. This is a convenience\n routines to infer dtype from a scalar or an array\n\n Parameters\n ----------\n pandas_dtype : bool, default False\n whether to infer dtype including pandas extension types.\n If False, scalar/array belongs to pandas extension types is inferred as\n object\n \"\"\"\n if is_scalar(val):\n return infer_dtype_from_scalar(val, pandas_dtype=pandas_dtype)\n return infer_dtype_from_array(val, pandas_dtype=pandas_dtype)": 4181, "def allele_clusters(dists, t=0.025):\n \"\"\"Flat clusters from distance matrix\n\n Args:\n dists (numpy.array): pdist distance matrix\n t (float): fcluster (tree cutting) distance threshold\n\n Returns:\n dict of lists: cluster number to list of indices of distances in cluster\n \"\"\"\n clusters = fcluster(linkage(dists), 0.025, criterion='distance')\n cluster_idx = defaultdict(list)\n for idx, cl in enumerate(clusters):\n cluster_idx[cl].append(idx)\n return cluster_idx": 4182, "def nearest_intersection_idx(a, b):\n \"\"\"Determine the index of the point just before two lines with common x values.\n\n Parameters\n ----------\n a : array-like\n 1-dimensional array of y-values for line 1\n b : array-like\n 1-dimensional array of y-values for line 2\n\n Returns\n -------\n An array of indexes representing the index of the values\n just before the intersection(s) of the two lines.\n\n \"\"\"\n # Difference in the two y-value sets\n difference = a - b\n\n # Determine the point just before the intersection of the lines\n # Will return multiple points for multiple intersections\n sign_change_idx, = np.nonzero(np.diff(np.sign(difference)))\n\n return sign_change_idx": 4183, "def isPackage(file_path):\n \"\"\"\n Determine whether or not a given path is a (sub)package or not.\n \"\"\"\n return (os.path.isdir(file_path) and\n os.path.isfile(os.path.join(file_path, '__init__.py')))": 4184, "def __sub__(self, other):\n\t\t\"\"\"\n\t\tReturn a Cache containing the entries of self that are not in other.\n\t\t\"\"\"\n\t\treturn self.__class__([elem for elem in self if elem not in other])": 4185, "def add_ul(text, ul):\n \"\"\"Adds an unordered list to the readme\"\"\"\n text += \"\\n\"\n for li in ul:\n text += \"- \" + li + \"\\n\"\n text += \"\\n\"\n\n return text": 4186, "def load(file_object):\n \"\"\"\n Deserializes Java primitive data and objects serialized by ObjectOutputStream\n from a file-like object.\n \"\"\"\n marshaller = JavaObjectUnmarshaller(file_object)\n marshaller.add_transformer(DefaultObjectTransformer())\n return marshaller.readObject()": 4187, "def json_get_data(filename):\n \"\"\"Get data from json file\n \"\"\"\n with open(filename) as fp:\n json_data = json.load(fp)\n return json_data\n\n return False": 4188, "def respond_redirect(self, location='/'):\n\t\t\"\"\"\n\t\tRespond to the client with a 301 message and redirect them with\n\t\ta Location header.\n\n\t\t:param str location: The new location to redirect the client to.\n\t\t\"\"\"\n\t\tself.send_response(301)\n\t\tself.send_header('Content-Length', 0)\n\t\tself.send_header('Location', location)\n\t\tself.end_headers()\n\t\treturn": 4189, "def param (self, param, kwargs, default_value=False):\n \"\"\"gets a param from kwargs, or uses a default_value. if found, it's\n removed from kwargs\"\"\"\n if param in kwargs:\n value= kwargs[param]\n del kwargs[param]\n else:\n value= default_value\n setattr (self, param, value)": 4190, "def prefix_list(self, prefix, values):\n \"\"\"\n Add a prefix to a list of values.\n \"\"\"\n return list(map(lambda value: prefix + \" \" + value, values))": 4191, "def put(self, entity):\n \"\"\"Registers entity to put to datastore.\n\n Args:\n entity: an entity or model instance to put.\n \"\"\"\n actual_entity = _normalize_entity(entity)\n if actual_entity is None:\n return self.ndb_put(entity)\n self.puts.append(actual_entity)": 4192, "def _elapsed(self):\n \"\"\" Returns elapsed time at update. \"\"\"\n self.last_time = time.time()\n return self.last_time - self.start": 4193, "def limitReal(x, max_denominator=1000000):\n \"\"\"Creates an pysmt Real constant from x.\n\n Args:\n x (number): A number to be cast to a pysmt constant.\n max_denominator (int, optional): The maximum size of the denominator.\n Default 1000000.\n\n Returns:\n A Real constant with the given value and the denominator limited.\n\n \"\"\"\n f = Fraction(x).limit_denominator(max_denominator)\n return Real((f.numerator, f.denominator))": 4194, "def to_bipartite_matrix(A):\n \"\"\"Returns the adjacency matrix of a bipartite graph whose biadjacency\n matrix is `A`.\n\n `A` must be a NumPy array.\n\n If `A` has **m** rows and **n** columns, then the returned matrix has **m +\n n** rows and columns.\n\n \"\"\"\n m, n = A.shape\n return four_blocks(zeros(m, m), A, A.T, zeros(n, n))": 4195, "def vsh(cmd, *args, **kw):\n \"\"\" Execute a command installed into the active virtualenv.\n \"\"\"\n args = '\" \"'.join(i.replace('\"', r'\\\"') for i in args)\n easy.sh('\"%s\" \"%s\"' % (venv_bin(cmd), args))": 4196, "def str_to_num(str_value):\n \"\"\"Convert str_value to an int or a float, depending on the\n numeric value represented by str_value.\n\n \"\"\"\n str_value = str(str_value)\n try:\n return int(str_value)\n except ValueError:\n return float(str_value)": 4197, "def _maybe_cast_to_float64(da):\n \"\"\"Cast DataArrays to np.float64 if they are of type np.float32.\n\n Parameters\n ----------\n da : xr.DataArray\n Input DataArray\n\n Returns\n -------\n DataArray\n \"\"\"\n if da.dtype == np.float32:\n logging.warning('Datapoints were stored using the np.float32 datatype.'\n 'For accurate reduction operations using bottleneck, '\n 'datapoints are being cast to the np.float64 datatype.'\n ' For more information see: https://github.com/pydata/'\n 'xarray/issues/1346')\n return da.astype(np.float64)\n else:\n return da": 4198, "def dict_self(self):\n \"\"\"Return the self object attributes not inherited as dict.\"\"\"\n return {k: v for k, v in self.__dict__.items() if k in FSM_ATTRS}": 4199, "def closeEvent(self, event):\n \"\"\" Called when closing this window.\n \"\"\"\n logger.debug(\"closeEvent\")\n self.argosApplication.saveSettingsIfNeeded()\n self.finalize()\n self.argosApplication.removeMainWindow(self)\n event.accept()\n logger.debug(\"closeEvent accepted\")": 4200, "def get_tree_type(tree):\n \"\"\"\n returns the type of the (sub)tree: Root, Nucleus or Satellite\n\n Parameters\n ----------\n tree : nltk.tree.ParentedTree\n a tree representing a rhetorical structure (or a part of it)\n \"\"\"\n tree_type = tree.label()\n assert tree_type in SUBTREE_TYPES, \"tree_type: {}\".format(tree_type)\n return tree_type": 4201, "def from_json(s):\n \"\"\"Given a JSON-encoded message, build an object.\n\n \"\"\"\n d = json.loads(s)\n sbp = SBP.from_json_dict(d)\n return sbp": 4202, "def set_interface(interface, name=''):\n \"\"\"\n don't want to bother with a dsn? Use this method to make an interface available\n \"\"\"\n global interfaces\n\n if not interface: raise ValueError('interface is empty')\n\n # close down the interface before we discard it\n if name in interfaces:\n interfaces[name].close()\n\n interfaces[name] = interface": 4203, "def _varargs_to_iterable_method(func):\n \"\"\"decorator to convert a *args method to one taking a iterable\"\"\"\n def wrapped(self, iterable, **kwargs):\n return func(self, *iterable, **kwargs)\n return wrapped": 4204, "def _iterPoints(self, **kwargs):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n points = self.points\n count = len(points)\n index = 0\n while count:\n yield points[index]\n count -= 1\n index += 1": 4205, "def random_filename(path=None):\n \"\"\"Make a UUID-based file name which is extremely unlikely\n to exist already.\"\"\"\n filename = uuid4().hex\n if path is not None:\n filename = os.path.join(path, filename)\n return filename": 4206, "def _begins_with_one_of(sentence, parts_of_speech):\n \"\"\"Return True if the sentence or fragment begins with one of the parts of\n speech in the list, else False\"\"\"\n doc = nlp(sentence)\n if doc[0].tag_ in parts_of_speech:\n return True\n return False": 4207, "def is_element_present(self, strategy, locator):\n \"\"\"Checks whether an element is present.\n\n :param strategy: Location strategy to use. See :py:class:`~selenium.webdriver.common.by.By` or :py:attr:`~pypom.splinter_driver.ALLOWED_STRATEGIES`.\n :param locator: Location of target element.\n :type strategy: str\n :type locator: str\n :return: ``True`` if element is present, else ``False``.\n :rtype: bool\n\n \"\"\"\n return self.driver_adapter.is_element_present(strategy, locator, root=self.root)": 4208, "def OnDoubleClick(self, event):\n \"\"\"Double click on a given square in the map\"\"\"\n node = HotMapNavigator.findNodeAtPosition(self.hot_map, event.GetPosition())\n if node:\n wx.PostEvent( self, SquareActivationEvent( node=node, point=event.GetPosition(), map=self ) )": 4209, "def asMaskedArray(self):\n \"\"\" Creates converts to a masked array\n \"\"\"\n return ma.masked_array(data=self.data, mask=self.mask, fill_value=self.fill_value)": 4210, "def _is_readable(self, obj):\n \"\"\"Check if the argument is a readable file-like object.\"\"\"\n try:\n read = getattr(obj, 'read')\n except AttributeError:\n return False\n else:\n return is_method(read, max_arity=1)": 4211, "def _axes(self):\n \"\"\"Set the _force_vertical flag when rendering axes\"\"\"\n self.view._force_vertical = True\n super(HorizontalGraph, self)._axes()\n self.view._force_vertical = False": 4212, "def load_library(version):\n \"\"\"\n Load the correct module according to the version\n\n :type version: ``str``\n :param version: the version of the library to be loaded (e.g. '2.6')\n :rtype: module object\n \"\"\"\n check_version(version)\n module_name = SUPPORTED_LIBRARIES[version]\n lib = sys.modules.get(module_name)\n if lib is None:\n lib = importlib.import_module(module_name)\n return lib": 4213, "def remove(self, entry):\n \"\"\"Removes an entry\"\"\"\n try:\n list = self.cache[entry.key]\n list.remove(entry)\n except:\n pass": 4214, "def max_values(args):\n \"\"\" Return possible range for max function. \"\"\"\n return Interval(max(x.low for x in args), max(x.high for x in args))": 4215, "def stoplog(self):\n \"\"\" Stop logging.\n \n @return: 1 on success and 0 on error\n @rtype: integer\n \"\"\"\n if self._file_logger:\n self.logger.removeHandler(_file_logger)\n self._file_logger = None\n return 1": 4216, "def close_all():\n r\"\"\"Close all opened windows.\"\"\"\n\n # Windows can be closed by releasing all references to them so they can be\n # garbage collected. May not be necessary to call close().\n global _qtg_windows\n for window in _qtg_windows:\n window.close()\n _qtg_windows = []\n\n global _qtg_widgets\n for widget in _qtg_widgets:\n widget.close()\n _qtg_widgets = []\n\n global _plt_figures\n for fig in _plt_figures:\n _, plt, _ = _import_plt()\n plt.close(fig)\n _plt_figures = []": 4217, "def __setitem__(self, _ignored, return_value):\n \"\"\"Item assignment sets the return value and removes any side effect\"\"\"\n self.mock.return_value = return_value\n self.mock.side_effect = None": 4218, "def close(self):\n \"\"\"Closes the serial port.\"\"\"\n if self.pyb and self.pyb.serial:\n self.pyb.serial.close()\n self.pyb = None": 4219, "def assert_called(_mock_self):\n \"\"\"assert that the mock was called at least once\n \"\"\"\n self = _mock_self\n if self.call_count == 0:\n msg = (\"Expected '%s' to have been called.\" %\n self._mock_name or 'mock')\n raise AssertionError(msg)": 4220, "def _construct_from_json(self, rec):\n \"\"\" Construct this Dagobah instance from a JSON document. \"\"\"\n\n self.delete()\n\n for required_key in ['dagobah_id', 'created_jobs']:\n setattr(self, required_key, rec[required_key])\n\n for job_json in rec.get('jobs', []):\n self._add_job_from_spec(job_json)\n\n self.commit(cascade=True)": 4221, "def benchmark(store, n=10000):\n \"\"\"\n Iterates over all of the referreds, and then iterates over all of the\n referrers that refer to each one.\n\n Fairly item instantiation heavy.\n \"\"\"\n R = Referrer\n\n for referred in store.query(Referred):\n for _reference in store.query(R, R.reference == referred):\n pass": 4222, "def beautify(string, *args, **kwargs):\n\t\"\"\"\n\t\tConvenient interface to the ecstasy package.\n\n\t\tArguments:\n\t\t\tstring (str): The string to beautify with ecstasy.\n\t\t\targs (list): The positional arguments.\n\t\t\tkwargs (dict): The keyword ('always') arguments.\n\t\"\"\"\n\n\tparser = Parser(args, kwargs)\n\treturn parser.beautify(string)": 4223, "def combine(self, a, b):\n \"\"\"A generator that combines two iterables.\"\"\"\n\n for l in (a, b):\n for x in l:\n yield x": 4224, "def zoom_out(self):\n \"\"\"Decrease zoom factor and redraw TimeLine\"\"\"\n index = self._zoom_factors.index(self._zoom_factor)\n if index == 0:\n # Already zoomed out all the way\n return\n self._zoom_factor = self._zoom_factors[index - 1]\n if self._zoom_factors.index(self._zoom_factor) == 0:\n self._button_zoom_out.config(state=tk.DISABLED)\n self._button_zoom_in.config(state=tk.NORMAL)\n self.draw_timeline()": 4225, "def initialize_worker(self, process_num=None):\n \"\"\"\n reinitialize consumer for process in multiprocesing\n \"\"\"\n self.initialize(self.grid, self.num_of_paths, self.seed)": 4226, "def _unique_id(self, prefix):\n \"\"\"\n Generate a unique (within the graph) identifer\n internal to graph generation.\n \"\"\"\n _id = self._id_gen\n self._id_gen += 1\n return prefix + str(_id)": 4227, "def _cell(x):\n \"\"\"translate an array x into a MATLAB cell array\"\"\"\n x_no_none = [i if i is not None else \"\" for i in x]\n return array(x_no_none, dtype=np_object)": 4228, "def tick(self):\n \"\"\"Add one tick to progress bar\"\"\"\n self.current += 1\n if self.current == self.factor:\n sys.stdout.write('+')\n sys.stdout.flush()\n self.current = 0": 4229, "def last_item(array):\n \"\"\"Returns the last item of an array in a list or an empty list.\"\"\"\n if array.size == 0:\n # work around for https://github.com/numpy/numpy/issues/5195\n return []\n\n indexer = (slice(-1, None),) * array.ndim\n return np.ravel(array[indexer]).tolist()": 4230, "def remove_last_line(self):\n \"\"\"Removes the last line of the document.\"\"\"\n editor = self._editor\n text_cursor = editor.textCursor()\n text_cursor.movePosition(text_cursor.End, text_cursor.MoveAnchor)\n text_cursor.select(text_cursor.LineUnderCursor)\n text_cursor.removeSelectedText()\n text_cursor.deletePreviousChar()\n editor.setTextCursor(text_cursor)": 4231, "def on_mouse_motion(self, x, y, dx, dy):\n \"\"\"\n Pyglet specific mouse motion callback.\n Forwards and traslates the event to the example\n \"\"\"\n # Screen coordinates relative to the lower-left corner\n # so we have to flip the y axis to make this consistent with\n # other window libraries\n self.example.mouse_position_event(x, self.buffer_height - y)": 4232, "def ComplementEquivalence(*args, **kwargs):\n \"\"\"Change x != y to not(x == y).\"\"\"\n return ast.Complement(\n ast.Equivalence(*args, **kwargs), **kwargs)": 4233, "def fit_gaussian(samples, ddof=0):\n \"\"\"Calculates the mean and the standard deviation of the given samples.\n\n Args:\n samples (ndarray): a one or two dimensional array. If one dimensional we calculate the fit using all\n values. If two dimensional, we fit the Gaussian for every set of samples over the first dimension.\n ddof (int): the difference degrees of freedom in the std calculation. See numpy.\n \"\"\"\n if len(samples.shape) == 1:\n return np.mean(samples), np.std(samples, ddof=ddof)\n return np.mean(samples, axis=1), np.std(samples, axis=1, ddof=ddof)": 4234, "def get_dates_link(url):\n \"\"\" download the dates file from the internet and parse it as a dates file\"\"\"\n urllib.request.urlretrieve(url, \"temp.txt\")\n dates = get_dates_file(\"temp.txt\")\n os.remove(\"temp.txt\")\n return dates": 4235, "def sorted_product_set(array_a, array_b):\n \"\"\"Compute the product set of array_a and array_b and sort it.\"\"\"\n return np.sort(\n np.concatenate(\n [array_a[i] * array_b for i in xrange(len(array_a))], axis=0)\n )[::-1]": 4236, "def _tostr(self,obj):\n \"\"\" converts a object to list, if object is a list, it creates a\n comma seperated string.\n \"\"\"\n if not obj:\n return ''\n if isinstance(obj, list):\n return ', '.join(map(self._tostr, obj))\n return str(obj)": 4237, "def clear_instance(cls):\n \"\"\"unset _instance for this class and singleton parents.\n \"\"\"\n if not cls.initialized():\n return\n for subclass in cls._walk_mro():\n if isinstance(subclass._instance, cls):\n # only clear instances that are instances\n # of the calling class\n subclass._instance = None": 4238, "def iterlists(self):\n \"\"\"Like :meth:`items` but returns an iterator.\"\"\"\n for key, values in dict.iteritems(self):\n yield key, list(values)": 4239, "def delete_connection():\n \"\"\"\n Stop and destroy Bloomberg connection\n \"\"\"\n if _CON_SYM_ in globals():\n con = globals().pop(_CON_SYM_)\n if not getattr(con, '_session').start(): con.stop()": 4240, "def PopAttributeContainer(self):\n \"\"\"Pops a serialized attribute container from the list.\n\n Returns:\n bytes: serialized attribute container data.\n \"\"\"\n try:\n serialized_data = self._list.pop(0)\n self.data_size -= len(serialized_data)\n return serialized_data\n\n except IndexError:\n return None": 4241, "def _ignore_comments(lines_enum):\n \"\"\"\n Strips comments and filter empty lines.\n \"\"\"\n for line_number, line in lines_enum:\n line = COMMENT_RE.sub('', line)\n line = line.strip()\n if line:\n yield line_number, line": 4242, "def delete(self):\n \"\"\"Remove this object.\"\"\"\n self._client.remove_object(self._instance, self._bucket, self.name)": 4243, "def rpc_fix_code_with_black(self, source, directory):\n \"\"\"Formats Python code to conform to the PEP 8 style guide.\n\n \"\"\"\n source = get_source(source)\n return fix_code_with_black(source, directory)": 4244, "def cursor_up(self, count=1):\n \"\"\" (for multiline edit). Move cursor to the previous line. \"\"\"\n original_column = self.preferred_column or self.document.cursor_position_col\n self.cursor_position += self.document.get_cursor_up_position(\n count=count, preferred_column=original_column)\n\n # Remember the original column for the next up/down movement.\n self.preferred_column = original_column": 4245, "def _get_pattern(self, pys_style):\n \"\"\"Returns xlwt.pattern for pyspread style\"\"\"\n\n # Return None if there is no bgcolor\n if \"bgcolor\" not in pys_style:\n return\n\n pattern = xlwt.Pattern()\n pattern.pattern = xlwt.Pattern.SOLID_PATTERN\n\n bgcolor = wx.Colour()\n bgcolor.SetRGB(pys_style[\"bgcolor\"])\n pattern.pattern_fore_colour = self.color2idx(*bgcolor.Get())\n\n return pattern": 4246, "def impad_to_multiple(img, divisor, pad_val=0):\n \"\"\"Pad an image to ensure each edge to be multiple to some number.\n\n Args:\n img (ndarray): Image to be padded.\n divisor (int): Padded image edges will be multiple to divisor.\n pad_val (number or sequence): Same as :func:`impad`.\n\n Returns:\n ndarray: The padded image.\n \"\"\"\n pad_h = int(np.ceil(img.shape[0] / divisor)) * divisor\n pad_w = int(np.ceil(img.shape[1] / divisor)) * divisor\n return impad(img, (pad_h, pad_w), pad_val)": 4247, "def generate_nonce():\n \"\"\" Generate nonce number \"\"\"\n nonce = ''.join([str(randint(0, 9)) for i in range(8)])\n return HMAC(\n nonce.encode(),\n \"secret\".encode(),\n sha1\n ).hexdigest()": 4248, "def rfc3339_to_datetime(data):\n \"\"\"convert a rfc3339 date representation into a Python datetime\"\"\"\n try:\n ts = time.strptime(data, '%Y-%m-%d')\n return date(*ts[:3])\n except ValueError:\n pass\n\n try:\n dt, _, tz = data.partition('Z')\n if tz:\n tz = offset(tz)\n else:\n tz = offset('00:00')\n if '.' in dt and dt.rsplit('.', 1)[-1].isdigit():\n ts = time.strptime(dt, '%Y-%m-%dT%H:%M:%S.%f')\n else:\n ts = time.strptime(dt, '%Y-%m-%dT%H:%M:%S')\n return datetime(*ts[:6], tzinfo=tz)\n except ValueError:\n raise ValueError('date-time {!r} is not a valid rfc3339 date representation'.format(data))": 4249, "def get_first_lang():\n \"\"\"Get the first lang of Accept-Language Header.\n \"\"\"\n request_lang = request.headers.get('Accept-Language').split(',')\n if request_lang:\n lang = locale.normalize(request_lang[0]).split('.')[0]\n else:\n lang = False\n return lang": 4250, "def from_pystr_to_cstr(data):\n \"\"\"Convert a list of Python str to C pointer\n\n Parameters\n ----------\n data : list\n list of str\n \"\"\"\n\n if not isinstance(data, list):\n raise NotImplementedError\n pointers = (ctypes.c_char_p * len(data))()\n if PY3:\n data = [bytes(d, 'utf-8') for d in data]\n else:\n data = [d.encode('utf-8') if isinstance(d, unicode) else d # pylint: disable=undefined-variable\n for d in data]\n pointers[:] = data\n return pointers": 4251, "def document(schema):\n \"\"\"Print a documented teleport version of the schema.\"\"\"\n teleport_schema = from_val(schema)\n return json.dumps(teleport_schema, sort_keys=True, indent=2)": 4252, "def on_stop(self):\n \"\"\"\n stop publisher\n \"\"\"\n LOGGER.debug(\"zeromq.Publisher.on_stop\")\n self.zmqsocket.close()\n self.zmqcontext.destroy()": 4253, "def accuracy(self):\n \"\"\"Calculates accuracy\n\n :return: Accuracy\n \"\"\"\n true_pos = self.matrix[0][0]\n false_pos = self.matrix[1][0]\n false_neg = self.matrix[0][1]\n true_neg = self.matrix[1][1]\n\n num = 1.0 * (true_pos + true_neg)\n den = true_pos + true_neg + false_pos + false_neg\n\n return divide(num, den)": 4254, "def git_tag(tag):\n \"\"\"Tags the current version.\"\"\"\n print('Tagging \"{}\"'.format(tag))\n msg = '\"Released version {}\"'.format(tag)\n Popen(['git', 'tag', '-s', '-m', msg, tag]).wait()": 4255, "def get_from_headers(request, key):\n \"\"\"Try to read a value named ``key`` from the headers.\n \"\"\"\n value = request.headers.get(key)\n return to_native(value)": 4256, "def move_page_bottom(self):\n \"\"\"\n Move the cursor to the last item on the page.\n \"\"\"\n self.nav.page_index = self.content.range[1]\n self.nav.cursor_index = 0\n self.nav.inverted = True": 4257, "def print_runs(query):\n \"\"\" Print all rows in this result query. \"\"\"\n\n if query is None:\n return\n\n for tup in query:\n print((\"{0} @ {1} - {2} id: {3} group: {4}\".format(\n tup.end, tup.experiment_name, tup.project_name,\n tup.experiment_group, tup.run_group)))": 4258, "def wait_for_url(url, timeout=DEFAULT_TIMEOUT):\n \"\"\"\n Return True if connection to the host and port specified in url\n is successful within the timeout.\n\n @param url: str: connection url for a TCP service\n @param timeout: int: length of time in seconds to try to connect before giving up\n @raise RuntimeError: if no port is given or can't be guessed via the scheme\n @return: bool\n \"\"\"\n service = ServiceURL(url, timeout)\n return service.wait()": 4259, "def print_float(self, value, decimal_digits=2, justify_right=True):\n \"\"\"Print a numeric value to the display. If value is negative\n it will be printed with a leading minus sign. Decimal digits is the\n desired number of digits after the decimal point.\n \"\"\"\n format_string = '{{0:0.{0}F}}'.format(decimal_digits)\n self.print_number_str(format_string.format(value), justify_right)": 4260, "def _stream_docker_logs(self):\n \"\"\"Stream stdout and stderr from the task container to this\n process's stdout and stderr, respectively.\n \"\"\"\n thread = threading.Thread(target=self._stderr_stream_worker)\n thread.start()\n for line in self.docker_client.logs(self.container, stdout=True,\n stderr=False, stream=True):\n sys.stdout.write(line)\n thread.join()": 4261, "def detect(filename, include_confidence=False):\n \"\"\"\n Detect the encoding of a file.\n\n Returns only the predicted current encoding as a string.\n\n If `include_confidence` is True, \n Returns tuple containing: (str encoding, float confidence)\n \"\"\"\n f = open(filename)\n detection = chardet.detect(f.read())\n f.close()\n encoding = detection.get('encoding')\n confidence = detection.get('confidence')\n if include_confidence:\n return (encoding, confidence)\n return encoding": 4262, "def define_macro(self, name, themacro):\n \"\"\"Define a new macro\n\n Parameters\n ----------\n name : str\n The name of the macro.\n themacro : str or Macro\n The action to do upon invoking the macro. If a string, a new\n Macro object is created by passing the string to it.\n \"\"\"\n\n from IPython.core import macro\n\n if isinstance(themacro, basestring):\n themacro = macro.Macro(themacro)\n if not isinstance(themacro, macro.Macro):\n raise ValueError('A macro must be a string or a Macro instance.')\n self.user_ns[name] = themacro": 4263, "def lazy_property(function):\n \"\"\"Cache the first return value of a function for all subsequent calls.\n\n This decorator is usefull for argument-less functions that behave more\n like a global or static property that should be calculated once, but\n lazily (i.e. only if requested).\n \"\"\"\n cached_val = []\n def _wrapper(*args):\n try:\n return cached_val[0]\n except IndexError:\n ret_val = function(*args)\n cached_val.append(ret_val)\n return ret_val\n return _wrapper": 4264, "def load(filename):\n \"\"\"\n Load the state from the given file, moving to the file's directory during\n load (temporarily, moving back after loaded)\n\n Parameters\n ----------\n filename : string\n name of the file to open, should be a .pkl file\n \"\"\"\n path, name = os.path.split(filename)\n path = path or '.'\n\n with util.indir(path):\n return pickle.load(open(name, 'rb'))": 4265, "def indent(self, message):\n \"\"\"\n Sets the indent for standardized output\n :param message: (str)\n :return: (str)\n \"\"\"\n indent = self.indent_char * self.indent_size\n return indent + message": 4266, "def insert_one(self, mongo_collection, doc, mongo_db=None, **kwargs):\n \"\"\"\n Inserts a single document into a mongo collection\n https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert_one\n \"\"\"\n collection = self.get_collection(mongo_collection, mongo_db=mongo_db)\n\n return collection.insert_one(doc, **kwargs)": 4267, "def assert_called_once(_mock_self):\n \"\"\"assert that the mock was called only once.\n \"\"\"\n self = _mock_self\n if not self.call_count == 1:\n msg = (\"Expected '%s' to have been called once. Called %s times.\" %\n (self._mock_name or 'mock', self.call_count))\n raise AssertionError(msg)": 4268, "def unique_inverse(item_list):\n \"\"\"\n Like np.unique(item_list, return_inverse=True)\n \"\"\"\n import utool as ut\n unique_items = ut.unique(item_list)\n inverse = list_alignment(unique_items, item_list)\n return unique_items, inverse": 4269, "def generate_random_string(chars=7):\n \"\"\"\n\n :param chars:\n :return:\n \"\"\"\n return u\"\".join(random.sample(string.ascii_letters * 2 + string.digits, chars))": 4270, "def paginate(self, request, offset=0, limit=None):\n \"\"\"Paginate queryset.\"\"\"\n return self.collection.offset(offset).limit(limit), self.collection.count()": 4271, "def _generate_plane(normal, origin):\n \"\"\" Returns a vtk.vtkPlane \"\"\"\n plane = vtk.vtkPlane()\n plane.SetNormal(normal[0], normal[1], normal[2])\n plane.SetOrigin(origin[0], origin[1], origin[2])\n return plane": 4272, "def run(self, forever=True):\n \"\"\"start the bot\"\"\"\n loop = self.create_connection()\n self.add_signal_handlers()\n if forever:\n loop.run_forever()": 4273, "def compute_depth(self):\n \"\"\"\n Recursively computes true depth of the subtree. Should only\n be needed for debugging. Unless something is wrong, the\n depth field should reflect the correct depth of the subtree.\n \"\"\"\n left_depth = self.left_node.compute_depth() if self.left_node else 0\n right_depth = self.right_node.compute_depth() if self.right_node else 0\n return 1 + max(left_depth, right_depth)": 4274, "def convert_to_yaml(\n name, value, indentation, indexOfColon, show_multi_line_character):\n \"\"\"converts a value list into yaml syntax\n :param name: name of object (example: phone)\n :type name: str\n :param value: object contents\n :type value: str, list(str), list(list(str))\n :param indentation: indent all by number of spaces\n :type indentation: int\n :param indexOfColon: use to position : at the name string (-1 for no space)\n :type indexOfColon: int\n :param show_multi_line_character: option to hide \"|\"\n :type show_multi_line_character: boolean\n :returns: yaml formatted string array of name, value pair\n :rtype: list(str)\n \"\"\"\n strings = []\n if isinstance(value, list):\n # special case for single item lists:\n if len(value) == 1 \\\n and isinstance(value[0], str):\n # value = [\"string\"] should not be converted to\n # name:\n # - string\n # but to \"name: string\" instead\n value = value[0]\n elif len(value) == 1 \\\n and isinstance(value[0], list) \\\n and len(value[0]) == 1 \\\n and isinstance(value[0][0], str):\n # same applies to value = [[\"string\"]]\n value = value[0][0]\n if isinstance(value, str):\n strings.append(\"%s%s%s: %s\" % (\n ' ' * indentation, name, ' ' * (indexOfColon-len(name)),\n indent_multiline_string(value, indentation+4,\n show_multi_line_character)))\n elif isinstance(value, list):\n strings.append(\"%s%s%s: \" % (\n ' ' * indentation, name, ' ' * (indexOfColon-len(name))))\n for outer in value:\n # special case for single item sublists\n if isinstance(outer, list) \\\n and len(outer) == 1 \\\n and isinstance(outer[0], str):\n # outer = [\"string\"] should not be converted to\n # -\n # - string\n # but to \"- string\" instead\n outer = outer[0]\n if isinstance(outer, str):\n strings.append(\"%s- %s\" % (\n ' ' * (indentation+4), indent_multiline_string(\n outer, indentation+8, show_multi_line_character)))\n elif isinstance(outer, list):\n strings.append(\"%s- \" % (' ' * (indentation+4)))\n for inner in outer:\n if isinstance(inner, str):\n strings.append(\"%s- %s\" % (\n ' ' * (indentation+8), indent_multiline_string(\n inner, indentation+12,\n show_multi_line_character)))\n return strings": 4275, "def __exit__(self, *args):\n \"\"\"Redirect stdout back to the original stdout.\"\"\"\n sys.stdout = self._orig\n self._devnull.close()": 4276, "def _internal_kv_get(key):\n \"\"\"Fetch the value of a binary key.\"\"\"\n\n worker = ray.worker.get_global_worker()\n if worker.mode == ray.worker.LOCAL_MODE:\n return _local.get(key)\n\n return worker.redis_client.hget(key, \"value\")": 4277, "def rpop(self, key):\n \"\"\"Emulate lpop.\"\"\"\n redis_list = self._get_list(key, 'RPOP')\n\n if self._encode(key) not in self.redis:\n return None\n\n try:\n value = redis_list.pop()\n if len(redis_list) == 0:\n self.delete(key)\n return value\n except (IndexError):\n # Redis returns nil if popping from an empty list\n return None": 4278, "def exists(self):\n \"\"\"\n Returns true if the job is still running or zero-os still knows about this job ID\n\n After a job is finished, a job remains on zero-os for max of 5min where you still can read the job result\n after the 5 min is gone, the job result is no more fetchable\n :return: bool\n \"\"\"\n r = self._client._redis\n flag = '{}:flag'.format(self._queue)\n return bool(r.exists(flag))": 4279, "def disable(self):\n \"\"\"\n Disable the button, if in non-expert mode;\n unset its activity flag come-what-may.\n \"\"\"\n if not self._expert:\n self.config(state='disable')\n self._active = False": 4280, "def _cached_search_compile(pattern, re_verbose, re_version, pattern_type):\n \"\"\"Cached search compile.\"\"\"\n\n return _bregex_parse._SearchParser(pattern, re_verbose, re_version).parse()": 4281, "def parse_path(path):\n \"\"\"Parse path string.\"\"\"\n version, project = path[1:].split('/')\n return dict(version=int(version), project=project)": 4282, "def abfIDfromFname(fname):\n \"\"\"given a filename, return the ABFs ID string.\"\"\"\n fname=os.path.abspath(fname)\n basename=os.path.basename(fname)\n return os.path.splitext(basename)[0]": 4283, "def cleanwrap(func):\n \"\"\" Wrapper for Zotero._cleanup\n \"\"\"\n\n def enc(self, *args, **kwargs):\n \"\"\" Send each item to _cleanup() \"\"\"\n return (func(self, item, **kwargs) for item in args)\n\n return enc": 4284, "def remove_from_lib(self, name):\n \"\"\" Remove an object from the bin folder. \"\"\"\n self.__remove_path(os.path.join(self.root_dir, \"lib\", name))": 4285, "def _gzip(self, response):\n \"\"\"Apply gzip compression to a response.\"\"\"\n bytesio = six.BytesIO()\n with gzip.GzipFile(fileobj=bytesio, mode='w') as gz:\n gz.write(response)\n return bytesio.getvalue()": 4286, "def replace_tab_indent(s, replace=\" \"):\n \"\"\"\n :param str s: string with tabs\n :param str replace: e.g. 4 spaces\n :rtype: str\n \"\"\"\n prefix = get_indent_prefix(s)\n return prefix.replace(\"\\t\", replace) + s[len(prefix):]": 4287, "def stringToDate(fmt=\"%Y-%m-%d\"):\n \"\"\"returns a function to convert a string to a datetime.date instance\n using the formatting string fmt as in time.strftime\"\"\"\n import time\n import datetime\n def conv_func(s):\n return datetime.date(*time.strptime(s,fmt)[:3])\n return conv_func": 4288, "def set_basic_auth(self, username, password):\n \"\"\"\n Set authenatication.\n \"\"\"\n from requests.auth import HTTPBasicAuth\n self.auth = HTTPBasicAuth(username, password)\n return self": 4289, "def localeselector():\n \"\"\"Default locale selector used in abilian applications.\"\"\"\n # if a user is logged in, use the locale from the user settings\n user = getattr(g, \"user\", None)\n if user is not None:\n locale = getattr(user, \"locale\", None)\n if locale:\n return locale\n\n # Otherwise, try to guess the language from the user accept header the browser\n # transmits. By default we support en/fr. The best match wins.\n return request.accept_languages.best_match(\n current_app.config[\"BABEL_ACCEPT_LANGUAGES\"]\n )": 4290, "def xml(cls, res, *args, **kwargs):\n \"\"\"Parses XML from a response.\"\"\"\n return parse_xml(res.text, *args, **kwargs)": 4291, "def load_from_file(cls, filename_prefix):\n \"\"\"Extracts list of subwords from file.\"\"\"\n filename = cls._filename(filename_prefix)\n lines, _ = cls._read_lines_from_file(filename)\n # Strip wrapping single quotes\n vocab_list = [line[1:-1] for line in lines]\n return cls(vocab_list=vocab_list)": 4292, "def request(method, url, **kwargs):\n \"\"\"\n Wrapper for the `requests.request()` function.\n It accepts the same arguments as the original, plus an optional `retries`\n that overrides the default retry mechanism.\n \"\"\"\n retries = kwargs.pop('retries', None)\n with Session(retries=retries) as session:\n return session.request(method=method, url=url, **kwargs)": 4293, "def make_file_readable (filename):\n \"\"\"Make file user readable if it is not a link.\"\"\"\n if not os.path.islink(filename):\n util.set_mode(filename, stat.S_IRUSR)": 4294, "def handle_errors(resp):\n \"\"\"raise a descriptive exception on a \"bad request\" response\"\"\"\n if resp.status_code == 400:\n raise ApiException(json.loads(resp.content).get('message'))\n return resp": 4295, "async def handle(self, record):\n \"\"\"\n Call the handlers for the specified record.\n\n This method is used for unpickled records received from a socket, as\n well as those created locally. Logger-level filtering is applied.\n \"\"\"\n if (not self.disabled) and self.filter(record):\n await self.callHandlers(record)": 4296, "def __print_table(table):\n \"\"\"Print a list in tabular format\n Based on https://stackoverflow.com/a/8356620\"\"\"\n\n col_width = [max(len(x) for x in col) for col in zip(*table)]\n print(\"| \" + \" | \".join(\"{:{}}\".format(x, col_width[i])\n for i, x in enumerate(table[0])) + \" |\")\n print(\"| \" + \" | \".join(\"{:{}}\".format('-' * col_width[i], col_width[i])\n for i, x in enumerate(table[0])) + \" |\")\n for line in table[1:]:\n print(\"| \" + \" | \".join(\"{:{}}\".format(x, col_width[i])\n for i, x in enumerate(line)) + \" |\")": 4297, "def print_failure_message(message):\n \"\"\"Print a message indicating failure in red color to STDERR.\n\n :param message: the message to print\n :type message: :class:`str`\n \"\"\"\n try:\n import colorama\n\n print(colorama.Fore.RED + message + colorama.Fore.RESET,\n file=sys.stderr)\n except ImportError:\n print(message, file=sys.stderr)": 4298, "def generate_yaml_file(filename, contents):\n \"\"\"Creates a yaml file with the given content.\"\"\"\n with open(filename, 'w') as file:\n file.write(yaml.dump(contents, default_flow_style=False))": 4299, "def get_pull_request(project, num, auth=False):\n \"\"\"get pull request info by number\n \"\"\"\n url = \"https://api.github.com/repos/{project}/pulls/{num}\".format(project=project, num=num)\n if auth:\n header = make_auth_header()\n else:\n header = None\n response = requests.get(url, headers=header)\n response.raise_for_status()\n return json.loads(response.text, object_hook=Obj)": 4300, "def list_blobs(self, prefix=''):\n \"\"\"Lists names of all blobs by their prefix.\"\"\"\n return [b.name for b in self.bucket.list_blobs(prefix=prefix)]": 4301, "def generate_id(self, obj):\n \"\"\"Generate unique document id for ElasticSearch.\"\"\"\n object_type = type(obj).__name__.lower()\n return '{}_{}'.format(object_type, self.get_object_id(obj))": 4302, "def lengths_offsets(value):\n \"\"\"Split the given comma separated value to multiple integer values. \"\"\"\n values = []\n for item in value.split(','):\n item = int(item)\n values.append(item)\n return values": 4303, "def delete_s3_bucket(client, resource):\n \"\"\"Delete an S3 bucket\n\n This function will try to delete an S3 bucket\n\n Args:\n client (:obj:`boto3.session.Session.client`): A boto3 client object\n resource (:obj:`Resource`): The resource object to terminate\n\n Returns:\n `ActionStatus`\n \"\"\"\n\n if dbconfig.get('enable_delete_s3_buckets', NS_AUDITOR_REQUIRED_TAGS, False):\n client.delete_bucket(Bucket=resource.id)\n return ActionStatus.SUCCEED, resource.metrics()": 4304, "def escape_link(url):\n \"\"\"Remove dangerous URL schemes like javascript: and escape afterwards.\"\"\"\n lower_url = url.lower().strip('\\x00\\x1a \\n\\r\\t')\n for scheme in _scheme_blacklist:\n if lower_url.startswith(scheme):\n return ''\n return escape(url, quote=True, smart_amp=False)": 4305, "async def send_files_preconf(filepaths, config_path=CONFIG_PATH):\n \"\"\"Send files using the config.ini settings.\n\n Args:\n filepaths (list(str)): A list of filepaths.\n \"\"\"\n config = read_config(config_path)\n subject = \"PDF files from pdfebc\"\n message = \"\"\n await send_with_attachments(subject, message, filepaths, config)": 4306, "def remove_item(self, item):\n \"\"\"\n Remove (and un-index) an object\n\n :param item: object to remove\n :type item: alignak.objects.item.Item\n :return: None\n \"\"\"\n self.unindex_item(item)\n self.items.pop(item.uuid, None)": 4307, "def _replace(self, data, replacements):\n \"\"\"\n Given a list of 2-tuples (find, repl) this function performs all\n replacements on the input and returns the result.\n \"\"\"\n for find, repl in replacements:\n data = data.replace(find, repl)\n return data": 4308, "def reset(self):\n \"\"\"Reset the instance\n\n - reset rows and header\n \"\"\"\n\n self._hline_string = None\n self._row_size = None\n self._header = []\n self._rows = []": 4309, "def get_serializable_data_for_fields(model):\n \"\"\"\n Return a serialised version of the model's fields which exist as local database\n columns (i.e. excluding m2m and incoming foreign key relations)\n \"\"\"\n pk_field = model._meta.pk\n # If model is a child via multitable inheritance, use parent's pk\n while pk_field.remote_field and pk_field.remote_field.parent_link:\n pk_field = pk_field.remote_field.model._meta.pk\n\n obj = {'pk': get_field_value(pk_field, model)}\n\n for field in model._meta.fields:\n if field.serialize:\n obj[field.name] = get_field_value(field, model)\n\n return obj": 4310, "def RemoveMethod(self, function):\n \"\"\"\n Removes the specified function's MethodWrapper from the\n added_methods list, so we don't re-bind it when making a clone.\n \"\"\"\n self.added_methods = [dm for dm in self.added_methods if not dm.method is function]": 4311, "def copy_default_data_file(filename, module=None):\n \"\"\"Copies file from default data directory to local directory.\"\"\"\n if module is None:\n module = __get_filetypes_module()\n fullpath = get_default_data_path(filename, module=module)\n shutil.copy(fullpath, \".\")": 4312, "def set_logging_config(log_level, handlers):\n \"\"\"Set python logging library config.\n\n Run this ONCE at the start of your process. It formats the python logging\n module's output.\n Defaults logging level to INFO = 20)\n \"\"\"\n logging.basicConfig(\n format='%(asctime)s %(levelname)s:%(name)s:%(funcName)s: %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S',\n level=log_level,\n handlers=handlers)": 4313, "def get_local_image(self, src):\n \"\"\"\\\n returns the bytes of the image file on disk\n \"\"\"\n return ImageUtils.store_image(self.fetcher, self.article.link_hash, src, self.config)": 4314, "def round_data(filter_data):\n \"\"\" round the data\"\"\"\n for index, _ in enumerate(filter_data):\n filter_data[index][0] = round(filter_data[index][0] / 100.0) * 100.0\n return filter_data": 4315, "def image_load_time(self):\n \"\"\"\n Returns aggregate image load time for all pages.\n \"\"\"\n load_times = self.get_load_times('image')\n return round(mean(load_times), self.decimal_precision)": 4316, "def update_token_tempfile(token):\n \"\"\"\n Example of function for token update\n \"\"\"\n with open(tmp, 'w') as f:\n f.write(json.dumps(token, indent=4))": 4317, "def write_wave(path, audio, sample_rate):\n \"\"\"Writes a .wav file.\n\n Takes path, PCM audio data, and sample rate.\n \"\"\"\n with contextlib.closing(wave.open(path, 'wb')) as wf:\n wf.setnchannels(1)\n wf.setsampwidth(2)\n wf.setframerate(sample_rate)\n wf.writeframes(audio)": 4318, "def singleton_per_scope(_cls, _scope=None, _renew=False, *args, **kwargs):\n \"\"\"Instanciate a singleton per scope.\"\"\"\n\n result = None\n\n singletons = SINGLETONS_PER_SCOPES.setdefault(_scope, {})\n\n if _renew or _cls not in singletons:\n singletons[_cls] = _cls(*args, **kwargs)\n\n result = singletons[_cls]\n\n return result": 4319, "def functions(self):\n \"\"\"\n A list of functions declared or defined in this module.\n \"\"\"\n return [v for v in self.globals.values()\n if isinstance(v, values.Function)]": 4320, "def all_versions(req):\n \"\"\"Get all versions of req from PyPI.\"\"\"\n import requests\n url = \"https://pypi.python.org/pypi/\" + req + \"/json\"\n return tuple(requests.get(url).json()[\"releases\"].keys())": 4321, "def shutdown(self):\n \"\"\"close socket, immediately.\"\"\"\n if self.sock:\n self.sock.close()\n self.sock = None\n self.connected = False": 4322, "def sortlevel(self, level=None, ascending=True, sort_remaining=None):\n \"\"\"\n For internal compatibility with with the Index API.\n\n Sort the Index. This is for compat with MultiIndex\n\n Parameters\n ----------\n ascending : boolean, default True\n False to sort in descending order\n\n level, sort_remaining are compat parameters\n\n Returns\n -------\n Index\n \"\"\"\n return self.sort_values(return_indexer=True, ascending=ascending)": 4323, "def set_default(self_,param_name,value):\n \"\"\"\n Set the default value of param_name.\n\n Equivalent to setting param_name on the class.\n \"\"\"\n cls = self_.cls\n setattr(cls,param_name,value)": 4324, "def _write_separator(self):\n \"\"\"\n Inserts a horizontal (commented) line tot the generated code.\n \"\"\"\n tmp = self._page_width - ((4 * self.__indent_level) + 2)\n self._write_line('# ' + ('-' * tmp))": 4325, "def run_test(func, fobj):\n \"\"\"Run func with argument fobj and measure execution time.\n @param func: function for test\n @param fobj: data for test\n @return: execution time\n \"\"\"\n gc.disable()\n try:\n begin = time.time()\n func(fobj)\n end = time.time()\n finally:\n gc.enable()\n return end - begin": 4326, "def set_ylim(self, xlims, dx, xscale, reverse=False):\n \"\"\"Set y limits for plot.\n\n This will set the limits for the y axis\n for the specific plot.\n\n Args:\n ylims (len-2 list of floats): The limits for the axis.\n dy (float): Amount to increment by between the limits.\n yscale (str): Scale of the axis. Either `log` or `lin`.\n reverse (bool, optional): If True, reverse the axis tick marks. Default is False.\n\n \"\"\"\n self._set_axis_limits('y', xlims, dx, xscale, reverse)\n return": 4327, "def compile(expr, params=None):\n \"\"\"\n Force compilation of expression for the SQLite target\n \"\"\"\n from ibis.sql.alchemy import to_sqlalchemy\n\n return to_sqlalchemy(expr, dialect.make_context(params=params))": 4328, "def set_left_to_right(self):\n \"\"\"Set text direction left to right.\"\"\"\n self.displaymode |= LCD_ENTRYLEFT\n self.write8(LCD_ENTRYMODESET | self.displaymode)": 4329, "def print_error(msg):\n \"\"\" Print an error message \"\"\"\n if IS_POSIX:\n print(u\"%s[ERRO] %s%s\" % (ANSI_ERROR, msg, ANSI_END))\n else:\n print(u\"[ERRO] %s\" % (msg))": 4330, "def progressbar(total, pos, msg=\"\"):\n \"\"\"\n Given a total and a progress position, output a progress bar\n to stderr. It is important to not output anything else while\n using this, as it relies soley on the behavior of carriage\n return (\\\\r).\n\n Can also take an optioal message to add after the\n progressbar. It must not contain newlines.\n\n The progress bar will look something like this:\n\n [099/500][=========...............................] ETA: 13:36:59\n\n Of course, the ETA part should be supplied be the calling\n function.\n \"\"\"\n width = get_terminal_size()[0] - 40\n rel_pos = int(float(pos) / total * width)\n bar = ''.join([\"=\" * rel_pos, \".\" * (width - rel_pos)])\n\n # Determine how many digits in total (base 10)\n digits_total = len(str(total))\n fmt_width = \"%0\" + str(digits_total) + \"d\"\n fmt = \"\\r[\" + fmt_width + \"/\" + fmt_width + \"][%s] %s\"\n\n progress_stream.write(fmt % (pos, total, bar, msg))": 4331, "def info(docgraph):\n \"\"\"print node and edge statistics of a document graph\"\"\"\n print networkx.info(docgraph), '\\n'\n node_statistics(docgraph)\n print\n edge_statistics(docgraph)": 4332, "def stop_containers(self):\n \"\"\" Stops all containers used by this instance of the backend.\n \"\"\"\n while len(self._containers):\n container = self._containers.pop()\n try:\n container.kill(signal.SIGKILL)\n except docker.errors.APIError: # probably doesn't exist anymore\n pass": 4333, "def natural_sort(list, key=lambda s:s):\n \"\"\"\n Sort the list into natural alphanumeric order.\n \"\"\"\n def get_alphanum_key_func(key):\n convert = lambda text: int(text) if text.isdigit() else text\n return lambda s: [convert(c) for c in re.split('([0-9]+)', key(s))]\n sort_key = get_alphanum_key_func(key)\n list.sort(key=sort_key)": 4334, "def get_distance(F, x):\n \"\"\"Helper function for margin-based loss. Return a distance matrix given a matrix.\"\"\"\n n = x.shape[0]\n\n square = F.sum(x ** 2.0, axis=1, keepdims=True)\n distance_square = square + square.transpose() - (2.0 * F.dot(x, x.transpose()))\n\n # Adding identity to make sqrt work.\n return F.sqrt(distance_square + F.array(np.identity(n)))": 4335, "def escapePathForShell(path):\n\t\t\"\"\"\n\t\tEscapes a filesystem path for use as a command-line argument\n\t\t\"\"\"\n\t\tif platform.system() == 'Windows':\n\t\t\treturn '\"{}\"'.format(path.replace('\"', '\"\"'))\n\t\telse:\n\t\t\treturn shellescape.quote(path)": 4336, "def chunks(iterable, size=1):\n \"\"\"Splits iterator in chunks.\"\"\"\n iterator = iter(iterable)\n\n for element in iterator:\n yield chain([element], islice(iterator, size - 1))": 4337, "def normalize_array(lst):\n \"\"\"Normalizes list\n\n :param lst: Array of floats\n :return: Normalized (in [0, 1]) input array\n \"\"\"\n np_arr = np.array(lst)\n x_normalized = np_arr / np_arr.max(axis=0)\n return list(x_normalized)": 4338, "def pause(msg=\"Press Enter to Continue...\"):\n \"\"\"press to continue\"\"\"\n print('\\n' + Fore.YELLOW + msg + Fore.RESET, end='')\n input()": 4339, "def schunk(string, size):\n \"\"\"Splits string into n sized chunks.\"\"\"\n return [string[i:i+size] for i in range(0, len(string), size)]": 4340, "def terminate(self):\n \"\"\"Terminate the pool immediately.\"\"\"\n if self._pool is not None:\n self._pool.terminate()\n self._pool.join()\n self._pool = None": 4341, "def stop(self):\n \"\"\"Stop stream.\"\"\"\n if self.stream and self.stream.session.state != STATE_STOPPED:\n self.stream.stop()": 4342, "def get_memory(self, mode):\n \"\"\"Return a smt bit vector that represents a memory location.\n \"\"\"\n mem = {\n \"pre\": self._translator.get_memory_init(),\n \"post\": self._translator.get_memory_curr(),\n }\n\n return mem[mode]": 4343, "def make_slice_strings(cls, slice_key):\n \"\"\"\n Converts the given slice key to start and size query parts.\n \"\"\"\n start = slice_key.start\n size = slice_key.stop - start\n return (str(start), str(size))": 4344, "def is_callable_tag(tag):\n \"\"\" Determine whether :tag: is a valid callable string tag.\n\n String is assumed to be valid callable if it starts with '{{'\n and ends with '}}'.\n\n :param tag: String name of tag.\n \"\"\"\n return (isinstance(tag, six.string_types) and\n tag.strip().startswith('{{') and\n tag.strip().endswith('}}'))": 4345, "def get_example_features(example):\n \"\"\"Returns the non-sequence features from the provided example.\"\"\"\n return (example.features.feature if isinstance(example, tf.train.Example)\n else example.context.feature)": 4346, "def _safe_db(num, den):\n \"\"\"Properly handle the potential +Inf db SIR instead of raising a\n RuntimeWarning.\n \"\"\"\n if den == 0:\n return np.inf\n return 10 * np.log10(num / den)": 4347, "def transformer_tpu_1b():\n \"\"\"Hparams for machine translation with ~1.1B parameters.\"\"\"\n hparams = transformer_tpu()\n hparams.hidden_size = 2048\n hparams.filter_size = 8192\n hparams.num_hidden_layers = 8\n # smaller batch size to avoid OOM\n hparams.batch_size = 1024\n hparams.activation_dtype = \"bfloat16\"\n hparams.weight_dtype = \"bfloat16\"\n # maximize number of parameters relative to computation by not sharing.\n hparams.shared_embedding_and_softmax_weights = False\n return hparams": 4348, "def _float_feature(value):\n \"\"\"Wrapper for inserting float features into Example proto.\"\"\"\n if not isinstance(value, list):\n value = [value]\n return tf.train.Feature(float_list=tf.train.FloatList(value=value))": 4349, "def assert_valid_input(cls, tag):\n \"\"\"Check if valid input tag or document.\"\"\"\n\n # Fail on unexpected types.\n if not cls.is_tag(tag):\n raise TypeError(\"Expected a BeautifulSoup 'Tag', but instead recieved type {}\".format(type(tag)))": 4350, "def write_fits(data, header, file_name):\n \"\"\"\n Combine data and a fits header to write a fits file.\n\n Parameters\n ----------\n data : numpy.ndarray\n The data to be written.\n\n header : astropy.io.fits.hduheader\n The header for the fits file.\n\n file_name : string\n The file to write\n\n Returns\n -------\n None\n \"\"\"\n hdu = fits.PrimaryHDU(data)\n hdu.header = header\n hdulist = fits.HDUList([hdu])\n hdulist.writeto(file_name, overwrite=True)\n logging.info(\"Wrote {0}\".format(file_name))\n return": 4351, "def stop(self):\n \"\"\" Stops the playing thread and close \"\"\"\n with self.lock:\n self.halting = True\n self.go.clear()": 4352, "def shutdown(self):\n \"\"\"\n shutdown: to be run by atexit handler. All open connection are closed.\n \"\"\"\n self.run_clean_thread = False\n self.cleanup(True)\n if self.cleaner_thread.isAlive():\n self.cleaner_thread.join()": 4353, "def delete(self, id):\n \"\"\"\n Deletes an \"object\" (line, triangle, image, etc) from the drawing.\n\n :param int id:\n The id of the object.\n \"\"\"\n if id in self._images.keys():\n del self._images[id]\n self.tk.delete(id)": 4354, "def _format_title_string(self, title_string):\n \"\"\" format mpv's title \"\"\"\n return self._title_string_format_text_tag(title_string.replace(self.icy_tokkens[0], self.icy_title_prefix))": 4355, "def call_on_if_def(obj, attr_name, callable, default, *args, **kwargs):\n \"\"\"Calls the provided callable on the provided attribute of ``obj`` if it is defined.\n\n If not, returns default.\n \"\"\"\n try:\n attr = getattr(obj, attr_name)\n except AttributeError:\n return default\n else:\n return callable(attr, *args, **kwargs)": 4356, "def matching_line(lines, keyword):\n \"\"\" Returns the first matching line in a list of lines.\n @see match()\n \"\"\"\n for line in lines:\n matching = match(line,keyword)\n if matching != None:\n return matching\n return None": 4357, "def form_valid(self, form):\n \"\"\"Security check complete. Log the user in.\"\"\"\n auth_login(self.request, form.get_user())\n return HttpResponseRedirect(self.get_success_url())": 4358, "def str_traceback(error, tb):\n \"\"\"Returns a string representation of the traceback.\n \"\"\"\n if not isinstance(tb, types.TracebackType):\n return tb\n\n return ''.join(traceback.format_exception(error.__class__, error, tb))": 4359, "def stepBy(self, steps):\n \"\"\"steps value up/down by a single step. Single step is defined in singleStep().\n\n Args:\n steps (int): positiv int steps up, negativ steps down\n \"\"\"\n self.setValue(self.value() + steps*self.singleStep())": 4360, "def is_filelike(ob):\n \"\"\"Check for filelikeness of an object.\n\n Needed to distinguish it from file names.\n Returns true if it has a read or a write method.\n \"\"\"\n if hasattr(ob, 'read') and callable(ob.read):\n return True\n\n if hasattr(ob, 'write') and callable(ob.write):\n return True\n\n return False": 4361, "def simple_generate(cls, create, **kwargs):\n \"\"\"Generate a new instance.\n\n The instance will be either 'built' or 'created'.\n\n Args:\n create (bool): whether to 'build' or 'create' the instance.\n\n Returns:\n object: the generated instance\n \"\"\"\n strategy = enums.CREATE_STRATEGY if create else enums.BUILD_STRATEGY\n return cls.generate(strategy, **kwargs)": 4362, "def __init__(self, scope, parent):\n \"\"\"Constructor for try block structures.\n\n Args:\n scope (CodeEntity): The program scope where this object belongs.\n parent (CodeEntity): This object's parent in the program tree.\n \"\"\"\n CodeStatement.__init__(self, scope, parent)\n self.body = CodeBlock(scope, self, explicit=True)\n self.catches = []\n self.finally_body = CodeBlock(scope, self, explicit=True)": 4363, "def fval(self, instance):\n \"\"\"return the raw value that this property is holding internally for instance\"\"\"\n try:\n val = instance.__dict__[self.instance_field_name]\n except KeyError as e:\n #raise AttributeError(str(e))\n val = None\n\n return val": 4364, "def __init__(self, name, flag, **kwargs):\n \"\"\"\n Argument class constructor, should be used inside a class that inherits the BaseAction class.\n\n :param name(str): the optional argument name to be used with two slahes (--cmd)\n :param flag(str): a short flag for the argument (-c)\n :param \\*\\*kwargs: all keywords arguments supported for argparse actions.\n \"\"\"\n self.name = name\n self.flag = flag\n self.options = kwargs": 4365, "def _to_java_object_rdd(rdd):\n \"\"\" Return an JavaRDD of Object by unpickling\n\n It will convert each Python object into Java object by Pyrolite, whenever the\n RDD is serialized in batch or not.\n \"\"\"\n rdd = rdd._reserialize(AutoBatchedSerializer(PickleSerializer()))\n return rdd.ctx._jvm.org.apache.spark.ml.python.MLSerDe.pythonToJava(rdd._jrdd, True)": 4366, "def run_func(self, func_path, *func_args, **kwargs):\n \"\"\"Run a function in Matlab and return the result.\n\n Parameters\n ----------\n func_path: str\n Name of function to run or a path to an m-file.\n func_args: object, optional\n Function args to send to the function.\n nargout: int, optional\n Desired number of return arguments.\n kwargs:\n Keyword arguments are passed to Matlab in the form [key, val] so\n that matlab.plot(x, y, '--', LineWidth=2) would be translated into\n plot(x, y, '--', 'LineWidth', 2)\n\n Returns\n -------\n Result dictionary with keys: 'message', 'result', and 'success'\n \"\"\"\n if not self.started:\n raise ValueError('Session not started, use start()')\n\n nargout = kwargs.pop('nargout', 1)\n func_args += tuple(item for pair in zip(kwargs.keys(), kwargs.values())\n for item in pair)\n dname = os.path.dirname(func_path)\n fname = os.path.basename(func_path)\n func_name, ext = os.path.splitext(fname)\n if ext and not ext == '.m':\n raise TypeError('Need to give path to .m file')\n return self._json_response(cmd='eval',\n func_name=func_name,\n func_args=func_args or '',\n dname=dname,\n nargout=nargout)": 4367, "def search_script_directory(self, path):\n \"\"\"\n Recursively loop through a directory to find all python\n script files. When one is found, it is analyzed for import statements\n :param path: string\n :return: generator\n \"\"\"\n for subdir, dirs, files in os.walk(path):\n for file_name in files:\n if file_name.endswith(\".py\"):\n self.search_script_file(subdir, file_name)": 4368, "def parse_parameter(value):\n \"\"\"\n @return: The best approximation of a type of the given value.\n \"\"\"\n if any((isinstance(value, float), isinstance(value, int), isinstance(value, bool))):\n return value\n\n try:\n return int(value)\n except ValueError:\n try:\n return float(value)\n except ValueError:\n if value in string_aliases.true_boolean_aliases:\n return True\n elif value in string_aliases.false_boolean_aliases:\n return False\n else:\n return str(value)": 4369, "def wireshark(pktlist, *args):\n \"\"\"Run wireshark on a list of packets\"\"\"\n fname = get_temp_file()\n wrpcap(fname, pktlist)\n subprocess.Popen([conf.prog.wireshark, \"-r\", fname] + list(args))": 4370, "def step_impl06(context):\n \"\"\"Prepare test for singleton property.\n\n :param context: test context.\n \"\"\"\n store = context.SingleStore\n context.st_1 = store()\n context.st_2 = store()\n context.st_3 = store()": 4371, "def raises_regex(self, expected_exception, expected_regexp):\n \"\"\"\n Ensures preceding predicates (specifically, :meth:`called_with()`) result in *expected_exception* being raised,\n and the string representation of *expected_exception* must match regular expression *expected_regexp*.\n \"\"\"\n return unittest_case.assertRaisesRegexp(expected_exception, expected_regexp, self._orig_subject,\n *self._args, **self._kwargs)": 4372, "def import_path(self):\n \"\"\"The full remote import path as used in import statements in `.go` source files.\"\"\"\n return os.path.join(self.remote_root, self.pkg) if self.pkg else self.remote_root": 4373, "def sbatch_template(self):\n \"\"\":return Jinja sbatch template for the current tag\"\"\"\n template = self.sbatch_template_str\n if template.startswith('#!'):\n # script is embedded in YAML\n return jinja_environment.from_string(template)\n return jinja_environment.get_template(template)": 4374, "def timeit(method):\n \"\"\"\n A Python decorator for printing out the execution time for a function.\n\n Adapted from:\n www.andreas-jung.com/contents/a-python-decorator-for-measuring-the-execution-time-of-methods\n \"\"\"\n def timed(*args, **kw):\n time_start = time.time()\n result = method(*args, **kw)\n time_end = time.time()\n print('timeit: %r %2.2f sec (%r, %r) ' % (method.__name__, time_end-time_start, str(args)[:20], kw))\n return result\n\n return timed": 4375, "async def stop(self):\n \"\"\"Stop the current task process.\n\n Starts with SIGTERM, gives the process 1 second to terminate, then kills it\n \"\"\"\n # negate pid so that signals apply to process group\n pgid = -self.process.pid\n try:\n os.kill(pgid, signal.SIGTERM)\n await asyncio.sleep(1)\n os.kill(pgid, signal.SIGKILL)\n except (OSError, ProcessLookupError):\n return": 4376, "def escape(s):\n \"\"\"Escape a URL including any /.\"\"\"\n if not isinstance(s, bytes):\n s = s.encode('utf-8')\n return quote(s, safe='~')": 4377, "def kill_all(self, kill_signal, kill_shell=False):\n \"\"\"Kill all running processes.\"\"\"\n for key in self.processes.keys():\n self.kill_process(key, kill_signal, kill_shell)": 4378, "def _letter_map(word):\n \"\"\"Creates a map of letter use in a word.\n\n Args:\n word: a string to create a letter map from\n\n Returns:\n a dictionary of {letter: integer count of letter in word}\n \"\"\"\n\n lmap = {}\n for letter in word:\n try:\n lmap[letter] += 1\n except KeyError:\n lmap[letter] = 1\n return lmap": 4379, "def get_ip_address(ifname):\n \"\"\" Hack to get IP address from the interface \"\"\"\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n return socket.inet_ntoa(fcntl.ioctl(\n s.fileno(),\n 0x8915, # SIOCGIFADDR\n struct.pack('256s', ifname[:15])\n )[20:24])": 4380, "def is_valid(data):\n \"\"\"\n Checks if the input data is a Swagger document\n\n :param dict data: Data to be validated\n :return: True, if data is a Swagger\n \"\"\"\n return bool(data) and \\\n isinstance(data, dict) and \\\n bool(data.get(\"swagger\")) and \\\n isinstance(data.get('paths'), dict)": 4381, "def _check_list_len(row, length):\n \"\"\"\n Sanity check for csv parser\n :param row\n :param length\n :return:None\n \"\"\"\n if len(row) != length:\n raise Exception(\n \"row length does not match expected length of \" +\n str(length) + \"\\nrow: \" + str(row))": 4382, "def getprop(self, prop_name):\n \"\"\"Get a property of the device.\n\n This is a convenience wrapper for \"adb shell getprop xxx\".\n\n Args:\n prop_name: A string that is the name of the property to get.\n\n Returns:\n A string that is the value of the property, or None if the property\n doesn't exist.\n \"\"\"\n return self.shell(\n ['getprop', prop_name],\n timeout=DEFAULT_GETPROP_TIMEOUT_SEC).decode('utf-8').strip()": 4383, "def add_input_variable(self, var):\n \"\"\"Adds the argument variable as one of the input variable\"\"\"\n assert(isinstance(var, Variable))\n self.input_variable_list.append(var)": 4384, "def check_alert(self, text):\n \"\"\"\n Assert an alert is showing with the given text.\n \"\"\"\n\n try:\n alert = Alert(world.browser)\n if alert.text != text:\n raise AssertionError(\n \"Alert text expected to be {!r}, got {!r}.\".format(\n text, alert.text))\n except WebDriverException:\n # PhantomJS is kinda poor\n pass": 4385, "def size(self):\n \"\"\"Return the viewable size of the Table as @tuple (x,y)\"\"\"\n width = max(\n map(lambda x: x.size()[0], self.sections.itervalues()))\n\n height = sum(\n map(lambda x: x.size()[1], self.sections.itervalues()))\n\n return width, height": 4386, "def setAsApplication(myappid):\n \"\"\"\n Tells Windows this is an independent application with an unique icon on task bar.\n\n id is an unique string to identify this application, like: 'mycompany.myproduct.subproduct.version'\n \"\"\"\n\n if os.name == 'nt':\n import ctypes\n ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)": 4387, "def _disable_venv(self, env):\n \"\"\"\n Disable virtualenv and venv in the environment.\n \"\"\"\n venv = env.pop('VIRTUAL_ENV', None)\n if venv:\n venv_path, sep, env['PATH'] = env['PATH'].partition(os.pathsep)": 4388, "def attr_cache_clear(self):\n node = extract_node(\"\"\"def cache_clear(self): pass\"\"\")\n return BoundMethod(proxy=node, bound=self._instance.parent.scope())": 4389, "def submit_by_selector(self, selector):\n \"\"\"Submit the form matching the CSS selector.\"\"\"\n elem = find_element_by_jquery(world.browser, selector)\n elem.submit()": 4390, "def disconnect(self):\n \"\"\"\n Closes the connection.\n \"\"\"\n self.logger.debug('Close connection...')\n\n self.auto_reconnect = False\n\n if self.websocket is not None:\n self.websocket.close()": 4391, "def settimeout(self, timeout):\n \"\"\"\n Set the timeout to the websocket.\n\n timeout: timeout time(second).\n \"\"\"\n self.sock_opt.timeout = timeout\n if self.sock:\n self.sock.settimeout(timeout)": 4392, "def select_random(engine, table_or_columns, limit=5):\n \"\"\"\n Randomly select some rows from table.\n \"\"\"\n s = select(table_or_columns).order_by(func.random()).limit(limit)\n return engine.execute(s).fetchall()": 4393, "def join_field(path):\n \"\"\"\n RETURN field SEQUENCE AS STRING\n \"\"\"\n output = \".\".join([f.replace(\".\", \"\\\\.\") for f in path if f != None])\n return output if output else \".\"": 4394, "def create_widget(self):\n \"\"\" Create the toolkit widget for the proxy object.\n \"\"\"\n d = self.declaration\n button_type = UIButton.UIButtonTypeSystem if d.flat else UIButton.UIButtonTypeRoundedRect\n self.widget = UIButton(buttonWithType=button_type)": 4395, "def atom_criteria(*params):\n \"\"\"An auxiliary function to construct a dictionary of Criteria\"\"\"\n result = {}\n for index, param in enumerate(params):\n if param is None:\n continue\n elif isinstance(param, int):\n result[index] = HasAtomNumber(param)\n else:\n result[index] = param\n return result": 4396, "def normalize_path(filename):\n \"\"\"Normalize a file/dir name for comparison purposes\"\"\"\n return os.path.normcase(os.path.realpath(os.path.normpath(_cygwin_patch(filename))))": 4397, "def x_values_ref(self, series):\n \"\"\"\n The Excel worksheet reference to the X values for this chart (not\n including the column label).\n \"\"\"\n top_row = self.series_table_row_offset(series) + 2\n bottom_row = top_row + len(series) - 1\n return \"Sheet1!$A$%d:$A$%d\" % (top_row, bottom_row)": 4398, "def _wrap(text, columns=80):\n \"\"\"\n Own \"dumb\" reimplementation of textwrap.wrap().\n\n This is because calling .wrap() on bigger strings can take a LOT of\n processor power. And I mean like 8 seconds of 3GHz CPU just to wrap 20kB of\n text without spaces.\n\n Args:\n text (str): Text to wrap.\n columns (int): Wrap after `columns` characters.\n\n Returns:\n str: Wrapped text.\n \"\"\"\n out = []\n for cnt, char in enumerate(text):\n out.append(char)\n\n if (cnt + 1) % columns == 0:\n out.append(\"\\n\")\n\n return \"\".join(out)": 4399, "def sample_colormap(cmap_name, n_samples):\n \"\"\"\n Sample a colormap from matplotlib\n \"\"\"\n colors = []\n colormap = cm.cmap_d[cmap_name]\n for i in np.linspace(0, 1, n_samples):\n colors.append(colormap(i))\n\n return colors": 4400, "def write_dict_to_yaml(dictionary, path, **kwargs):\n \"\"\"\n Writes a dictionary to a yaml file\n :param dictionary: the dictionary to be written\n :param path: the absolute path of the target yaml file\n :param kwargs: optional additional parameters for dumper\n \"\"\"\n with open(path, 'w') as f:\n yaml.dump(dictionary, f, indent=4, **kwargs)": 4401, "def visit_BinOp(self, node):\n \"\"\" Return type depend from both operand of the binary operation. \"\"\"\n args = [self.visit(arg) for arg in (node.left, node.right)]\n return list({frozenset.union(*x) for x in itertools.product(*args)})": 4402, "def get_indentation(line):\n \"\"\"Return leading whitespace.\"\"\"\n if line.strip():\n non_whitespace_index = len(line) - len(line.lstrip())\n return line[:non_whitespace_index]\n else:\n return ''": 4403, "def read_bytes(fo, writer_schema=None, reader_schema=None):\n \"\"\"Bytes are encoded as a long followed by that many bytes of data.\"\"\"\n size = read_long(fo)\n return fo.read(size)": 4404, "def included_length(self):\n \"\"\"Surveyed length, not including \"excluded\" shots\"\"\"\n return sum([shot.length for shot in self.shots if shot.is_included])": 4405, "def upsert_single(db, collection, object, match_params=None):\n \"\"\"\n Wrapper for pymongo.update_one()\n :param db: db connection\n :param collection: collection to update\n :param object: the modifications to apply\n :param match_params: a query that matches the documents to update\n :return: id of updated document\n \"\"\"\n return str(db[collection].update_one(match_params, {\"$set\": object}, upsert=True).upserted_id)": 4406, "def set_slug(apps, schema_editor, class_name):\n \"\"\"\n Create a slug for each Work already in the DB.\n \"\"\"\n Cls = apps.get_model('spectator_events', class_name)\n\n for obj in Cls.objects.all():\n obj.slug = generate_slug(obj.pk)\n obj.save(update_fields=['slug'])": 4407, "def moving_average(a, n):\n \"\"\"Moving average over one-dimensional array.\n\n Parameters\n ----------\n a : np.ndarray\n One-dimensional array.\n n : int\n Number of entries to average over. n=2 means averaging over the currrent\n the previous entry.\n\n Returns\n -------\n An array view storing the moving average.\n \"\"\"\n ret = np.cumsum(a, dtype=float)\n ret[n:] = ret[n:] - ret[:-n]\n return ret[n - 1:] / n": 4408, "def count_words(file):\n \"\"\" Counts the word frequences in a list of sentences.\n\n Note:\n This is a helper function for parallel execution of `Vocabulary.from_text`\n method.\n \"\"\"\n c = Counter()\n with open(file, 'r') as f:\n for l in f:\n words = l.strip().split()\n c.update(words)\n return c": 4409, "def word_matches(s1, s2, n=3):\n \"\"\"\n Word-level n-grams that match between two strings\n\n Args:\n s1: a string\n s2: another string\n n: an int for the n in n-gram\n\n Returns:\n set: the n-grams found in both strings\n \"\"\"\n return __matches(s1, s2, word_ngrams, n=n)": 4410, "def _executemany(self, cursor, query, parameters):\n \"\"\"The function is mostly useful for commands that update the database:\n any result set returned by the query is discarded.\"\"\"\n try:\n self._log(query)\n cursor.executemany(query, parameters)\n except OperationalError as e: # pragma: no cover\n logging.error('Error connecting to PostgreSQL on %s, e', self.host, e)\n self.close()\n raise": 4411, "def iso_to_datetime(date):\n \"\"\" Convert ISO 8601 time format to datetime format\n\n This function converts a date in ISO format, e.g. ``2017-09-14`` to a `datetime` instance, e.g.\n ``datetime.datetime(2017,9,14,0,0)``\n\n :param date: date in ISO 8601 format\n :type date: str\n :return: datetime instance\n :rtype: datetime\n \"\"\"\n chunks = list(map(int, date.split('T')[0].split('-')))\n return datetime.datetime(chunks[0], chunks[1], chunks[2])": 4412, "def unique_deps(deps):\n \"\"\"Remove duplicities from deps list of the lists\"\"\"\n deps.sort()\n return list(k for k, _ in itertools.groupby(deps))": 4413, "def find_one(cls, *args, **kw):\n\t\t\"\"\"Get a single document from the collection this class is bound to.\n\t\t\n\t\tAdditional arguments are processed according to `_prepare_find` prior to passing to PyMongo, where positional\n\t\tparameters are interpreted as query fragments, parametric keyword arguments combined, and other keyword\n\t\targuments passed along with minor transformation.\n\t\t\n\t\tAutomatically calls `to_mongo` with the retrieved data.\n\t\t\n\t\thttps://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find_one\n\t\t\"\"\"\n\t\t\n\t\tif len(args) == 1 and not isinstance(args[0], Filter):\n\t\t\targs = (getattr(cls, cls.__pk__) == args[0], )\n\t\t\n\t\tDoc, collection, query, options = cls._prepare_find(*args, **kw)\n\t\tresult = Doc.from_mongo(collection.find_one(query, **options))\n\t\t\n\t\treturn result": 4414, "def _config_parse(self):\n \"\"\"Replacer oslo_config.cfg.ConfigParser.parse for in-memory cfg.\"\"\"\n res = super(cfg.ConfigParser, self).parse(Backend._config_string_io)\n return res": 4415, "def rpc_fix_code(self, source, directory):\n \"\"\"Formats Python code to conform to the PEP 8 style guide.\n\n \"\"\"\n source = get_source(source)\n return fix_code(source, directory)": 4416, "def overlap(intv1, intv2):\n \"\"\"Overlaping of two intervals\"\"\"\n return max(0, min(intv1[1], intv2[1]) - max(intv1[0], intv2[0]))": 4417, "def log(logger, level, message):\n \"\"\"Logs message to stderr if logging isn't initialized.\"\"\"\n\n if logger.parent.name != 'root':\n logger.log(level, message)\n else:\n print(message, file=sys.stderr)": 4418, "def filechunk(f, chunksize):\n \"\"\"Iterator that allow for piecemeal processing of a file.\"\"\"\n while True:\n chunk = tuple(itertools.islice(f, chunksize))\n if not chunk:\n return\n yield np.loadtxt(iter(chunk), dtype=np.float64)": 4419, "def _or(ctx, *logical):\n \"\"\"\n Returns TRUE if any argument is TRUE\n \"\"\"\n for arg in logical:\n if conversions.to_boolean(arg, ctx):\n return True\n return False": 4420, "def create_env(env_file):\n \"\"\"Create environ dictionary from current os.environ and\n variables got from given `env_file`\"\"\"\n\n environ = {}\n with open(env_file, 'r') as f:\n for line in f.readlines():\n line = line.rstrip(os.linesep)\n if '=' not in line:\n continue\n if line.startswith('#'):\n continue\n key, value = line.split('=', 1)\n environ[key] = parse_value(value)\n return environ": 4421, "def DeleteIndex(self, index):\n \"\"\"\n Remove a spent coin based on its index.\n\n Args:\n index (int):\n \"\"\"\n to_remove = None\n for i in self.Items:\n if i.index == index:\n to_remove = i\n\n if to_remove:\n self.Items.remove(to_remove)": 4422, "def StreamWrite(stream, *obj):\n \"\"\"Writes Python object to Skype application stream.\"\"\"\n stream.Write(base64.encodestring(pickle.dumps(obj)))": 4423, "def filter_lines_from_comments(lines):\n \"\"\" Filter the lines from comments and non code lines. \"\"\"\n for line_nb, raw_line in enumerate(lines):\n clean_line = remove_comments_from_line(raw_line)\n if clean_line == '':\n continue\n yield line_nb, clean_line, raw_line": 4424, "def mkhead(repo, path):\n \"\"\":return: New branch/head instance\"\"\"\n return git.Head(repo, git.Head.to_full_path(path))": 4425, "def uncomment_line(line, prefix):\n \"\"\"Remove prefix (and space) from line\"\"\"\n if not prefix:\n return line\n if line.startswith(prefix + ' '):\n return line[len(prefix) + 1:]\n if line.startswith(prefix):\n return line[len(prefix):]\n return line": 4426, "def draw_tree(t, df, size=10, ratio=0.6, precision=0):\n \"\"\" Draws a representation of a random forest in IPython.\n Parameters:\n -----------\n t: The tree you wish to draw\n df: The data used to train the tree. This is used to get the names of the features.\n \"\"\"\n s=export_graphviz(t, out_file=None, feature_names=df.columns, filled=True,\n special_characters=True, rotate=True, precision=precision)\n IPython.display.display(graphviz.Source(re.sub('Tree {',\n f'Tree {{ size={size}; ratio={ratio}', s)))": 4427, "def _breakRemNewlines(tag):\n\t\"\"\"non-recursively break spaces and remove newlines in the tag\"\"\"\n\tfor i,c in enumerate(tag.contents):\n\t\tif type(c) != bs4.element.NavigableString:\n\t\t\tcontinue\n\t\tc.replace_with(re.sub(r' {2,}', ' ', c).replace('\\n',''))": 4428, "def __repr__(self):\n \"\"\"Return string representation of object.\"\"\"\n return str(self.__class__) + '(' + ', '.join([list.__repr__(d) for d in self.data]) + ')'": 4429, "def get_subplot_at(self, row, column):\n \"\"\"Return the subplot at row, column position.\n\n :param row,column: specify the subplot.\n\n \"\"\"\n idx = row * self.columns + column\n return self.subplots[idx]": 4430, "def __add_namespaceinfo(self, ni):\n \"\"\"Internal method to directly add a _NamespaceInfo object to this\n set. No sanity checks are done (e.g. checking for prefix conflicts),\n so be sure to do it yourself before calling this.\"\"\"\n self.__ns_uri_map[ni.uri] = ni\n for prefix in ni.prefixes:\n self.__prefix_map[prefix] = ni": 4431, "def request_type(self):\n \"\"\"Retrieve the type of the request, by fetching it from\n `xenon.proto.xenon_pb2`.\"\"\"\n if self.static and not self.uses_request:\n return getattr(xenon_pb2, 'Empty')\n\n if not self.uses_request:\n return None\n\n return getattr(xenon_pb2, self.request_name)": 4432, "def add_chart(self, chart, row, col):\n \"\"\"\n Adds a chart to the worksheet at (row, col).\n\n :param xltable.Chart Chart: chart to add to the workbook.\n :param int row: Row to add the chart at.\n \"\"\"\n self.__charts.append((chart, (row, col)))": 4433, "def vec(self):\n \"\"\":obj:`numpy.ndarray` : Vector representation for this camera.\n \"\"\"\n return np.r_[self.fx, self.fy, self.cx, self.cy, self.skew, self.height, self.width]": 4434, "def kindex(matrix, k):\n \"\"\" Returns indices to select the kth nearest neighbour\"\"\"\n\n ix = (np.arange(len(matrix)), matrix.argsort(axis=0)[k])\n return ix": 4435, "def render_template(content, context):\n \"\"\" renders context aware template \"\"\"\n rendered = Template(content).render(Context(context))\n return rendered": 4436, "def _get_env(self, env_var):\n \"\"\"Helper to read an environment variable\n \"\"\"\n value = os.environ.get(env_var)\n if not value:\n raise ValueError('Missing environment variable:%s' % env_var)\n return value": 4437, "def create(parallel):\n \"\"\"Create a queue based on the provided parallel arguments.\n\n TODO Startup/tear-down. Currently using default queue for testing\n \"\"\"\n queue = {k: v for k, v in parallel.items() if k in [\"queue\", \"cores_per_job\", \"mem\"]}\n yield queue": 4438, "def safe_execute_script(driver, script):\n \"\"\" When executing a script that contains a jQuery command,\n it's important that the jQuery library has been loaded first.\n This method will load jQuery if it wasn't already loaded. \"\"\"\n try:\n driver.execute_script(script)\n except Exception:\n # The likely reason this fails is because: \"jQuery is not defined\"\n activate_jquery(driver) # It's a good thing we can define it here\n driver.execute_script(script)": 4439, "def next(self):\n \"\"\"Get the next value in the page.\"\"\"\n item = six.next(self._item_iter)\n result = self._item_to_value(self._parent, item)\n # Since we've successfully got the next value from the\n # iterator, we update the number of remaining.\n self._remaining -= 1\n return result": 4440, "def get_key(self, key, bucket_name=None):\n \"\"\"\n Returns a boto3.s3.Object\n\n :param key: the path to the key\n :type key: str\n :param bucket_name: the name of the bucket\n :type bucket_name: str\n \"\"\"\n if not bucket_name:\n (bucket_name, key) = self.parse_s3_url(key)\n\n obj = self.get_resource_type('s3').Object(bucket_name, key)\n obj.load()\n return obj": 4441, "def save_json(object, handle, indent=2):\n \"\"\"Save object as json on CNS.\"\"\"\n obj_json = json.dumps(object, indent=indent, cls=NumpyJSONEncoder)\n handle.write(obj_json)": 4442, "def extend(self, iterable):\n \"\"\"Extend the list by appending all the items in the given list.\"\"\"\n return super(Collection, self).extend(\n self._ensure_iterable_is_valid(iterable))": 4443, "def _load_mod_ui_libraries(self, path):\n \"\"\"\n :param Path path:\n \"\"\"\n path = path / Path('mod')\n sys.path.append(str(path))": 4444, "def find_model_by_table_name(name):\n \"\"\"Find a model reference by its table name\"\"\"\n\n for model in ModelBase._decl_class_registry.values():\n if hasattr(model, '__table__') and model.__table__.fullname == name:\n return model\n return None": 4445, "def calculate_bounding_box_from_image(im, curr_page):\n \"\"\"This function uses a PIL routine to get the bounding box of the rendered\n image.\"\"\"\n xMax, y_max = im.size\n bounding_box = im.getbbox() # note this uses ltrb convention\n if not bounding_box:\n #print(\"\\nWarning: could not calculate a bounding box for this page.\"\n # \"\\nAn empty page is assumed.\", file=sys.stderr)\n bounding_box = (xMax/2, y_max/2, xMax/2, y_max/2)\n\n bounding_box = list(bounding_box) # make temporarily mutable\n\n # Compensate for reversal of the image y convention versus PDF.\n bounding_box[1] = y_max - bounding_box[1]\n bounding_box[3] = y_max - bounding_box[3]\n\n full_page_box = curr_page.mediaBox # should have been set already to chosen box\n\n # Convert pixel units to PDF's bp units.\n convert_x = float(full_page_box.getUpperRight_x()\n - full_page_box.getLowerLeft_x()) / xMax\n convert_y = float(full_page_box.getUpperRight_y()\n - full_page_box.getLowerLeft_y()) / y_max\n\n # Get final box; note conversion to lower-left point, upper-right point format.\n final_box = [\n bounding_box[0] * convert_x,\n bounding_box[3] * convert_y,\n bounding_box[2] * convert_x,\n bounding_box[1] * convert_y]\n\n return final_box": 4446, "def server(request):\n \"\"\"\n Respond to requests for the server's primary web page.\n \"\"\"\n return direct_to_template(\n request,\n 'server/index.html',\n {'user_url': getViewURL(request, idPage),\n 'server_xrds_url': getViewURL(request, idpXrds),\n })": 4447, "def __add__(self, other):\n \"\"\"Merges two with identical columns.\"\"\"\n\n new_table = copy.copy(self)\n for row in other:\n new_table.Append(row)\n\n return new_table": 4448, "def content_type(self, data):\n \"\"\"The Content-Type header value for this request.\"\"\"\n self._content_type = str(data)\n self.add_header('Content-Type', str(data))": 4449, "def set_default(self, section, option,\n default):\n \"\"\"If the option did not exist, create a default value.\"\"\"\n if not self.parser.has_option(section, option):\n self.parser.set(section, option, default)": 4450, "def cli_parse(parser):\n \"\"\"Add method specific options to CLI parser.\n\n Parameters\n ----------\n parser : argparse object\n\n Returns\n ----------\n Updated argparse object\n \"\"\"\n parser.add_argument('-n', '--samples', type=int, required=True,\n help='Number of Samples')\n return parser": 4451, "def args_update(self):\n \"\"\"Update the argparser namespace with any data from configuration file.\"\"\"\n for key, value in self._config_data.items():\n setattr(self._default_args, key, value)": 4452, "def toggle_pause(self):\n \"\"\"Toggle pause mode\"\"\"\n self.controller.playing = not self.controller.playing\n self.music.toggle_pause()": 4453, "def assert_iter(**kw):\n \"\"\"\n Asserts if a given values implements a valid iterable interface.\n\n Arguments:\n **kw (mixed): value to check if it is an iterable.\n\n Raises:\n TypeError: if assertion fails.\n \"\"\"\n for name, value in kw.items():\n if not isiter(value):\n raise TypeError(\n 'paco: {} must be an iterable object'.format(name))": 4454, "def tokenize(self, s):\n \"\"\"Return a list of token strings from the given sentence.\n\n :param string s: The sentence string to tokenize.\n :rtype: iter(str)\n \"\"\"\n return [s[start:end] for start, end in self.span_tokenize(s)]": 4455, "def _resizeColumnsToContents(self, header, data, limit_ms):\n \"\"\"Resize all the colummns to its contents.\"\"\"\n max_col = data.model().columnCount()\n if limit_ms is None:\n max_col_ms = None\n else:\n max_col_ms = limit_ms / max(1, max_col)\n for col in range(max_col):\n self._resizeColumnToContents(header, data, col, max_col_ms)": 4456, "def _load_autoreload_magic(self):\n \"\"\"Load %autoreload magic.\"\"\"\n from IPython.core.getipython import get_ipython\n try:\n get_ipython().run_line_magic('reload_ext', 'autoreload')\n get_ipython().run_line_magic('autoreload', '2')\n except Exception:\n pass": 4457, "def _split_python(python):\n \"\"\"Split Python source into chunks.\n\n Chunks are separated by at least two return lines. The break must not\n be followed by a space. Also, long Python strings spanning several lines\n are not splitted.\n\n \"\"\"\n python = _preprocess(python)\n if not python:\n return []\n lexer = PythonSplitLexer()\n lexer.read(python)\n return lexer.chunks": 4458, "def stack_template_url(bucket_name, blueprint, endpoint):\n \"\"\"Produces an s3 url for a given blueprint.\n\n Args:\n bucket_name (string): The name of the S3 bucket where the resulting\n templates are stored.\n blueprint (:class:`stacker.blueprints.base.Blueprint`): The blueprint\n object to create the URL to.\n endpoint (string): The s3 endpoint used for the bucket.\n\n Returns:\n string: S3 URL.\n \"\"\"\n key_name = stack_template_key_name(blueprint)\n return \"%s/%s/%s\" % (endpoint, bucket_name, key_name)": 4459, "def get_api_url(self, lambda_name, stage_name):\n \"\"\"\n Given a lambda_name and stage_name, return a valid API URL.\n \"\"\"\n api_id = self.get_api_id(lambda_name)\n if api_id:\n return \"https://{}.execute-api.{}.amazonaws.com/{}\".format(api_id, self.boto_session.region_name, stage_name)\n else:\n return None": 4460, "def create_all(self, check_first: bool = True):\n \"\"\"Create the empty database (tables).\n\n :param bool check_first: Defaults to True, don't issue CREATEs for tables already present\n in the target database. Defers to :meth:`sqlalchemy.sql.schema.MetaData.create_all`\n \"\"\"\n self._metadata.create_all(self.engine, checkfirst=check_first)": 4461, "def _heapreplace_max(heap, item):\n \"\"\"Maxheap version of a heappop followed by a heappush.\"\"\"\n returnitem = heap[0] # raises appropriate IndexError if heap is empty\n heap[0] = item\n _siftup_max(heap, 0)\n return returnitem": 4462, "def encode_ndarray(obj):\n \"\"\"Write a numpy array and its shape to base64 buffers\"\"\"\n shape = obj.shape\n if len(shape) == 1:\n shape = (1, obj.shape[0])\n if obj.flags.c_contiguous:\n obj = obj.T\n elif not obj.flags.f_contiguous:\n obj = asfortranarray(obj.T)\n else:\n obj = obj.T\n try:\n data = obj.astype(float64).tobytes()\n except AttributeError:\n data = obj.astype(float64).tostring()\n\n data = base64.b64encode(data).decode('utf-8')\n return data, shape": 4463, "def apply_caching(response):\n \"\"\"Applies the configuration's http headers to all responses\"\"\"\n for k, v in config.get('HTTP_HEADERS').items():\n response.headers[k] = v\n return response": 4464, "def slugify_filename(filename):\n \"\"\" Slugify filename \"\"\"\n name, ext = os.path.splitext(filename)\n slugified = get_slugified_name(name)\n return slugified + ext": 4465, "def to_bytes(self):\n\t\t\"\"\"Convert the entire image to bytes.\n\t\t\n\t\t:rtype: bytes\n\t\t\"\"\"\n\t\tchunks = [PNG_SIGN]\n\t\tchunks.extend(c[1] for c in self.chunks)\n\t\treturn b\"\".join(chunks)": 4466, "def _get_bokeh_html(self, chart_obj):\n \"\"\"\n Get the html for a Bokeh chart\n \"\"\"\n global bokeh_renderer\n try:\n renderer = bokeh_renderer\n p = renderer.get_plot(chart_obj).state\n script, div = components(p)\n return script + \"\\n\" + div\n\n except Exception as e:\n self.err(e, self._get_bokeh_html,\n \"Can not get html from the Bokeh rendering engine\")": 4467, "def describe_unique_1d(series):\n \"\"\"Compute summary statistics of a unique (`S_TYPE_UNIQUE`) variable (a Series).\n\n Parameters\n ----------\n series : Series\n The variable to describe.\n\n Returns\n -------\n Series\n The description of the variable as a Series with index being stats keys.\n \"\"\"\n return pd.Series([base.S_TYPE_UNIQUE], index=['type'], name=series.name)": 4468, "def needs_update(self, cache_key):\n \"\"\"Check if the given cached item is invalid.\n\n :param cache_key: A CacheKey object (as returned by CacheKeyGenerator.key_for().\n :returns: True if the cached version of the item is out of date.\n \"\"\"\n if not self.cacheable(cache_key):\n # An uncacheable CacheKey is always out of date.\n return True\n\n return self._read_sha(cache_key) != cache_key.hash": 4469, "def delete_item(self, item):\n \"\"\"Delete an object in DynamoDB.\n\n :param item: Unpacked into kwargs for :func:`boto3.DynamoDB.Client.delete_item`.\n :raises bloop.exceptions.ConstraintViolation: if the condition (or atomic) is not met.\n \"\"\"\n try:\n self.dynamodb_client.delete_item(**item)\n except botocore.exceptions.ClientError as error:\n handle_constraint_violation(error)": 4470, "def polygon_from_points(points):\n \"\"\"\n Constructs a numpy-compatible polygon from a page representation.\n \"\"\"\n polygon = []\n for pair in points.split(\" \"):\n x_y = pair.split(\",\")\n polygon.append([float(x_y[0]), float(x_y[1])])\n return polygon": 4471, "def sync_s3(self):\n \"\"\"Walk the media/static directories and syncs files to S3\"\"\"\n bucket, key = self.open_s3()\n for directory in self.DIRECTORIES:\n for root, dirs, files in os.walk(directory):\n self.upload_s3((bucket, key, self.AWS_BUCKET_NAME, directory), root, files, dirs)": 4472, "def __call__(self, obj, *arg, **kw):\n \"\"\"\n Call the unbound method.\n \n We essentially build a bound method and call that. This ensures that\n the code for managing observers is invoked in the same was as it would\n be for a bound method.\n \"\"\"\n bound_method = self._manager.__get__(obj, obj.__class__)\n return bound_method(*arg, **kw)": 4473, "def WriteManyToPath(objs, filepath):\n \"\"\"Serializes and writes given Python objects to a multi-document YAML file.\n\n Args:\n objs: An iterable of Python objects to serialize.\n filepath: A path to the file into which the object is to be written.\n \"\"\"\n with io.open(filepath, mode=\"w\", encoding=\"utf-8\") as filedesc:\n WriteManyToFile(objs, filedesc)": 4474, "def add_swagger(app, json_route, html_route):\n \"\"\"\n a convenience method for both adding a swagger.json route,\n as well as adding a page showing the html documentation\n \"\"\"\n app.router.add_route('GET', json_route, create_swagger_json_handler(app))\n add_swagger_api_route(app, html_route, json_route)": 4475, "def get_bound(pts):\n \"\"\"Compute a minimal rectangle that covers all the points.\"\"\"\n (x0, y0, x1, y1) = (INF, INF, -INF, -INF)\n for (x, y) in pts:\n x0 = min(x0, x)\n y0 = min(y0, y)\n x1 = max(x1, x)\n y1 = max(y1, y)\n return (x0, y0, x1, y1)": 4476, "def hkm_fc(fdata, Nmax, m, s):\n \"\"\" Assume fdata has even rows\"\"\"\n\n f = fdata[:, m]\n L1 = f.size\n MM = int(L1 / 2)\n Q = s.size\n\n ff = np.zeros(Q, dtype=np.complex128)\n for n in xrange(MM, L1):\n ff[n] = f[n - MM]\n\n for n in xrange(0, MM):\n ff[n] = f[n + MM]\n\n # For larger problems, this speeds things up pretty good.\n F = np.fft.fft(ff)\n S = np.fft.fft(s)\n out = 4 * np.pi * np.fft.ifft(F * S)\n\n return out[0:Nmax + 1]": 4477, "def text(value, encoding=\"utf-8\", errors=\"strict\"):\n \"\"\"Convert a value to str on Python 3 and unicode on Python 2.\"\"\"\n if isinstance(value, text_type):\n return value\n elif isinstance(value, bytes):\n return text_type(value, encoding, errors)\n else:\n return text_type(value)": 4478, "def token_list_len(tokenlist):\n \"\"\"\n Return the amount of characters in this token list.\n\n :param tokenlist: List of (token, text) or (token, text, mouse_handler)\n tuples.\n \"\"\"\n ZeroWidthEscape = Token.ZeroWidthEscape\n return sum(len(item[1]) for item in tokenlist if item[0] != ZeroWidthEscape)": 4479, "def filter(self, func):\n \"\"\"Returns a SndRcv list filtered by a truth function\"\"\"\n return self.__class__( [ i for i in self.res if func(*i) ], name='filtered %s'%self.listname)": 4480, "def is_SYMBOL(token, *symbols):\n \"\"\" Returns True if ALL of the given argument are AST nodes\n of the given token (e.g. 'BINARY')\n \"\"\"\n from symbols.symbol_ import Symbol\n assert all(isinstance(x, Symbol) for x in symbols)\n for sym in symbols:\n if sym.token != token:\n return False\n\n return True": 4481, "def wrap(text, indent=' '):\n \"\"\"Wrap text to terminal width with default indentation\"\"\"\n wrapper = textwrap.TextWrapper(\n width=int(os.environ.get('COLUMNS', 80)),\n initial_indent=indent,\n subsequent_indent=indent\n )\n return '\\n'.join(wrapper.wrap(text))": 4482, "def _update_plot(self, _):\n \"\"\"Callback to redraw the plot to reflect the new parameter values.\"\"\"\n # Since all sliders call this same callback without saying who they are\n # I need to update the values for all parameters. This can be\n # circumvented by creating a seperate callback function for each\n # parameter.\n for param in self.model.params:\n param.value = self._sliders[param].val\n for indep_var, dep_var in self._projections:\n self._update_specific_plot(indep_var, dep_var)": 4483, "def _maybe_pandas_data(data, feature_names, feature_types):\n \"\"\" Extract internal data from pd.DataFrame for DMatrix data \"\"\"\n\n if not isinstance(data, DataFrame):\n return data, feature_names, feature_types\n\n data_dtypes = data.dtypes\n if not all(dtype.name in PANDAS_DTYPE_MAPPER for dtype in data_dtypes):\n bad_fields = [data.columns[i] for i, dtype in\n enumerate(data_dtypes) if dtype.name not in PANDAS_DTYPE_MAPPER]\n\n msg = \"\"\"DataFrame.dtypes for data must be int, float or bool.\n Did not expect the data types in fields \"\"\"\n raise ValueError(msg + ', '.join(bad_fields))\n\n if feature_names is None:\n if isinstance(data.columns, MultiIndex):\n feature_names = [\n ' '.join([str(x) for x in i])\n for i in data.columns\n ]\n else:\n feature_names = data.columns.format()\n\n if feature_types is None:\n feature_types = [PANDAS_DTYPE_MAPPER[dtype.name] for dtype in data_dtypes]\n\n data = data.values.astype('float')\n\n return data, feature_names, feature_types": 4484, "def convert_from_missing_indexer_tuple(indexer, axes):\n \"\"\"\n create a filtered indexer that doesn't have any missing indexers\n \"\"\"\n\n def get_indexer(_i, _idx):\n return (axes[_i].get_loc(_idx['key']) if isinstance(_idx, dict) else\n _idx)\n\n return tuple(get_indexer(_i, _idx) for _i, _idx in enumerate(indexer))": 4485, "def compute_centroid(points):\n \"\"\" Computes the centroid of set of points\n\n Args:\n points (:obj:`list` of :obj:`Point`)\n Returns:\n :obj:`Point`\n \"\"\"\n lats = [p[1] for p in points]\n lons = [p[0] for p in points]\n return Point(np.mean(lats), np.mean(lons), None)": 4486, "def scopes_as(self, new_scopes):\n \"\"\"Replace my :attr:`scopes` for the duration of the with block.\n\n My global scope is not replaced.\n\n Args:\n new_scopes (list of dict-likes): The new :attr:`scopes` to use.\n \"\"\"\n old_scopes, self.scopes = self.scopes, new_scopes\n yield\n self.scopes = old_scopes": 4487, "def any_of(value, *args):\n \"\"\" At least one of the items in value should match \"\"\"\n\n if len(args):\n value = (value,) + args\n\n return ExpectationAny(value)": 4488, "def round_float(f, digits, rounding=ROUND_HALF_UP):\n \"\"\"\n Accurate float rounding from http://stackoverflow.com/a/15398691.\n \"\"\"\n return Decimal(str(f)).quantize(Decimal(10) ** (-1 * digits),\n rounding=rounding)": 4489, "def contains_case_insensitive(adict, akey):\n \"\"\"Check if key is in adict. The search is case insensitive.\"\"\"\n for key in adict:\n if key.lower() == akey.lower():\n return True\n return False": 4490, "def exists(self):\n \"\"\"\n Performs an existence check on the remote database.\n\n :returns: Boolean True if the database exists, False otherwise\n \"\"\"\n resp = self.r_session.head(self.database_url)\n if resp.status_code not in [200, 404]:\n resp.raise_for_status()\n\n return resp.status_code == 200": 4491, "def readable(path):\n \"\"\"Test whether a path exists and is readable. Returns None for\n broken symbolic links or a failing stat() and False if\n the file exists but does not have read permission. True is returned\n if the file is readable.\"\"\"\n try:\n st = os.stat(path)\n return 0 != st.st_mode & READABLE_MASK\n except os.error:\n return None\n return True": 4492, "def imagemagick(color_count, img, magick_command):\n \"\"\"Call Imagemagick to generate a scheme.\"\"\"\n flags = [\"-resize\", \"25%\", \"-colors\", str(color_count),\n \"-unique-colors\", \"txt:-\"]\n img += \"[0]\"\n\n return subprocess.check_output([*magick_command, img, *flags]).splitlines()": 4493, "def delete(args):\n \"\"\"\n Delete a river by name\n \"\"\"\n m = RiverManager(args.hosts)\n m.delete(args.name)": 4494, "def exists(self):\n \"\"\" Checks if the item exists. \"\"\"\n try:\n return self.metadata is not None\n except datalab.utils.RequestException:\n return False\n except Exception as e:\n raise e": 4495, "def is_valid_file(parser,arg):\n\t\"\"\"verify the validity of the given file. Never trust the End-User\"\"\"\n\tif not os.path.exists(arg):\n \t\tparser.error(\"File %s not found\"%arg)\n\telse:\n\t \treturn arg": 4496, "def isCommaList(inputFilelist):\n \"\"\"Return True if the input is a comma separated list of names.\"\"\"\n if isinstance(inputFilelist, int) or isinstance(inputFilelist, np.int32):\n ilist = str(inputFilelist)\n else:\n ilist = inputFilelist\n if \",\" in ilist:\n return True\n return False": 4497, "def get_category(self):\n \"\"\"Get the category of the item.\n\n :return: the category of the item.\n :returntype: `unicode`\"\"\"\n var = self.xmlnode.prop(\"category\")\n if not var:\n var = \"?\"\n return var.decode(\"utf-8\")": 4498, "def watched_extension(extension):\n \"\"\"Return True if the given extension is one of the watched extensions\"\"\"\n for ext in hamlpy.VALID_EXTENSIONS:\n if extension.endswith('.' + ext):\n return True\n return False": 4499, "def binary_stdout():\n \"\"\"\n A sys.stdout that accepts bytes.\n \"\"\"\n\n # First there is a Python3 issue.\n try:\n stdout = sys.stdout.buffer\n except AttributeError:\n # Probably Python 2, where bytes are strings.\n stdout = sys.stdout\n\n # On Windows the C runtime file orientation needs changing.\n if sys.platform == \"win32\":\n import msvcrt\n import os\n msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)\n\n return stdout": 4500, "def library(func):\n \"\"\"\n A decorator for providing a unittest with a library and have it called only\n once.\n \"\"\"\n @wraps(func)\n def wrapped(*args, **kwargs):\n \"\"\"Transparent wrapper.\"\"\"\n return func(*args, **kwargs)\n SINGLES.append(wrapped)\n return wrapped": 4501, "def ExpireObject(self, key):\n \"\"\"Expire a specific object from cache.\"\"\"\n node = self._hash.pop(key, None)\n if node:\n self._age.Unlink(node)\n self.KillObject(node.data)\n\n return node.data": 4502, "def WriteToPath(obj, filepath):\n \"\"\"Serializes and writes given Python object to the specified YAML file.\n\n Args:\n obj: A Python object to serialize.\n filepath: A path to the file into which the object is to be written.\n \"\"\"\n with io.open(filepath, mode=\"w\", encoding=\"utf-8\") as filedesc:\n WriteToFile(obj, filedesc)": 4503, "def do_help(self, arg):\n \"\"\"\n Show help on all commands.\n \"\"\"\n print(self.response_prompt, file=self.stdout)\n return cmd.Cmd.do_help(self, arg)": 4504, "def linear_variogram_model(m, d):\n \"\"\"Linear model, m is [slope, nugget]\"\"\"\n slope = float(m[0])\n nugget = float(m[1])\n return slope * d + nugget": 4505, "def printcsv(csvdiffs):\n \"\"\"print the csv\"\"\"\n for row in csvdiffs:\n print(','.join([str(cell) for cell in row]))": 4506, "def from_json(cls, s):\n \"\"\"\n Restores the object from the given JSON.\n\n :param s: the JSON string to parse\n :type s: str\n :return: the\n \"\"\"\n d = json.loads(s)\n return get_dict_handler(d[\"type\"])(d)": 4507, "def point_in_multipolygon(point, multipoly):\n \"\"\"\n valid whether the point is located in a mulitpolygon (donut polygon is not supported)\n\n Keyword arguments:\n point -- point geojson object\n multipoly -- multipolygon geojson object\n\n if(point inside multipoly) return true else false\n \"\"\"\n coords_array = [multipoly['coordinates']] if multipoly[\n 'type'] == \"MultiPolygon\" else multipoly['coordinates']\n\n for coords in coords_array:\n if _point_in_polygon(point, coords):\n return True\n\n return False": 4508, "def c2s(self,p=[0,0]):\n \"\"\"Convert from canvas to screen coordinates\"\"\"\n\n return((p[0]-self.canvasx(self.cx1),p[1]-self.canvasy(self.cy1)))": 4509, "def np2str(value):\n \"\"\"Convert an `numpy.string_` to str.\n\n Args:\n value (ndarray): scalar or 1-element numpy array to convert\n\n Raises:\n ValueError: if value is array larger than 1-element or it is not of\n type `numpy.string_` or it is not a numpy array\n\n \"\"\"\n if hasattr(value, 'dtype') and \\\n issubclass(value.dtype.type, (np.string_, np.object_)) and value.size == 1:\n value = np.asscalar(value)\n if not isinstance(value, str):\n # python 3 - was scalar numpy array of bytes\n # otherwise python 2 - scalar numpy array of 'str'\n value = value.decode()\n return value\n else:\n raise ValueError(\"Array is not a string type or is larger than 1\")": 4510, "def register_blueprints(app):\n \"\"\"Register Flask blueprints.\"\"\"\n app.register_blueprint(public.public_bp)\n app.register_blueprint(genes.genes_bp)\n app.register_blueprint(cases.cases_bp)\n app.register_blueprint(login.login_bp)\n app.register_blueprint(variants.variants_bp)\n app.register_blueprint(panels.panels_bp)\n app.register_blueprint(dashboard.dashboard_bp)\n app.register_blueprint(api.api_bp)\n app.register_blueprint(alignviewers.alignviewers_bp)\n app.register_blueprint(phenotypes.hpo_bp)\n app.register_blueprint(institutes.overview)": 4511, "def _clone_properties(self):\n \"\"\"Internal helper to clone self._properties if necessary.\"\"\"\n cls = self.__class__\n if self._properties is cls._properties:\n self._properties = dict(cls._properties)": 4512, "def cross_v2(vec1, vec2):\n \"\"\"Return the crossproduct of the two vectors as a Vec2.\n Cross product doesn't really make sense in 2D, but return the Z component\n of the 3d result.\n \"\"\"\n\n return vec1.y * vec2.x - vec1.x * vec2.y": 4513, "def _get_column_by_db_name(cls, name):\n \"\"\"\n Returns the column, mapped by db_field name\n \"\"\"\n return cls._columns.get(cls._db_map.get(name, name))": 4514, "def init():\n \"\"\"\n Execute init tasks for all components (virtualenv, pip).\n \"\"\"\n print(yellow(\"# Setting up environment...\\n\", True))\n virtualenv.init()\n virtualenv.update_requirements()\n print(green(\"\\n# DONE.\", True))\n print(green(\"Type \") + green(\"activate\", True) + green(\" to enable your virtual environment.\"))": 4515, "def token(name):\n \"\"\"Marker for a token\n\n :param str name: Name of tokenizer\n \"\"\"\n\n def wrap(f):\n tokenizers.append((name, f))\n return f\n\n return wrap": 4516, "def add_column(connection, column):\n \"\"\"\n Add a column to the current table.\n \"\"\"\n stmt = alembic.ddl.base.AddColumn(_State.table.name, column)\n connection.execute(stmt)\n _State.reflect_metadata()": 4517, "def unit_ball_L_inf(shape, precondition=True):\n \"\"\"A tensorflow variable tranfomed to be constrained in a L_inf unit ball.\n\n Note that this code also preconditions the gradient to go in the L_inf\n direction of steepest descent.\n\n EXPERIMENTAL: Do not use for adverserial examples if you need to be confident\n they are strong attacks. We are not yet confident in this code.\n \"\"\"\n x = tf.Variable(tf.zeros(shape))\n if precondition:\n return constrain_L_inf_precondition(x)\n else:\n return constrain_L_inf(x)": 4518, "def save_to_16bit_wave_file(fname, sig, rate):\n \"\"\"\n Save a given signal ``sig`` to file ``fname`` as a 16-bit one-channel wave\n with the given ``rate`` sample rate.\n \"\"\"\n with closing(wave.open(fname, \"wb\")) as wave_file:\n wave_file.setnchannels(1)\n wave_file.setsampwidth(2)\n wave_file.setframerate(rate)\n for chunk in chunks((clip(sig) * 2 ** 15).map(int), dfmt=\"h\", padval=0):\n wave_file.writeframes(chunk)": 4519, "def to_bytes_or_none(value):\n \"\"\"Converts C char arrays to bytes and C NULL values to None.\"\"\"\n if value == ffi.NULL:\n return None\n elif isinstance(value, ffi.CData):\n return ffi.string(value)\n else:\n raise ValueError('Value must be char[] or NULL')": 4520, "def load(self):\n\t\t\"\"\"Load the noise texture data into the current texture unit\"\"\"\n\t\tglTexImage3D(GL_TEXTURE_3D, 0, GL_LUMINANCE16_ALPHA16, \n\t\t\tself.width, self.width, self.width, 0, GL_LUMINANCE_ALPHA, \n\t\t\tGL_UNSIGNED_SHORT, ctypes.byref(self.data))": 4521, "def timestamp_to_datetime(cls, dt, dt_format=DATETIME_FORMAT):\n \"\"\"Convert unix timestamp to human readable date/time string\"\"\"\n return cls.convert_datetime(cls.get_datetime(dt), dt_format=dt_format)": 4522, "def get_ips(self, instance_id):\n \"\"\"Retrieves all IP addresses associated to a given instance.\n\n :return: tuple (IPs)\n \"\"\"\n instance = self._load_instance(instance_id)\n IPs = sum(instance.networks.values(), [])\n return IPs": 4523, "def attribute(func):\n \"\"\"Wrap a function as an attribute.\"\"\"\n attr = abc.abstractmethod(func)\n attr.__iattribute__ = True\n attr = _property(attr)\n return attr": 4524, "def standardize():\n \"\"\"\n return variant standarize function\n \"\"\"\n\n def f(G, bim):\n G_out = standardize_snps(G)\n return G_out, bim\n\n return f": 4525, "def get_object_as_string(obj):\n \"\"\"\n Converts any object to JSON-like readable format, ready to be printed for debugging purposes\n :param obj: Any object\n :return: string\n \"\"\"\n if isinstance(obj, str):\n return obj\n if isinstance(obj, list):\n return '\\r\\n\\;'.join([get_object_as_string(item) for item in obj])\n attrs = vars(obj)\n as_string = ', '.join(\"%s: %s\" % item for item in attrs.items())\n return as_string": 4526, "def isroutine(object):\n \"\"\"Return true if the object is any kind of function or method.\"\"\"\n return (isbuiltin(object)\n or isfunction(object)\n or ismethod(object)\n or ismethoddescriptor(object))": 4527, "def inFocus(self):\n \"\"\"Set GUI on-top flag\"\"\"\n previous_flags = self.window.flags()\n self.window.setFlags(previous_flags |\n QtCore.Qt.WindowStaysOnTopHint)": 4528, "def code(self):\n \"\"\"Returns the code object for this BUILD file.\"\"\"\n return compile(self.source(), self.full_path, 'exec', flags=0, dont_inherit=True)": 4529, "def find_dist_to_centroid(cvects, idx_list, weights=None):\n \"\"\" Find the centroid for a set of vectors\n\n Parameters\n ----------\n cvects : ~numpy.ndarray(3,nsrc) with directional cosine (i.e., x,y,z component) values\n\n idx_list : [int,...]\n list of the source indices in the cluster\n\n weights : ~numpy.ndarray(nsrc) with the weights to use. None for equal weighting\n\n returns (np.ndarray(nsrc)) distances to the centroid (in degrees)\n \"\"\"\n centroid = find_centroid(cvects, idx_list, weights)\n dist_vals = np.degrees(np.arccos((centroid * cvects.T[idx_list]).sum(1)))\n return dist_vals, centroid": 4530, "async def connect(self):\n \"\"\"\n Connects to the voice channel associated with this Player.\n \"\"\"\n await self.node.join_voice_channel(self.channel.guild.id, self.channel.id)": 4531, "def dist_sq(self, other):\n \"\"\"Distance squared to some other point.\"\"\"\n dx = self.x - other.x\n dy = self.y - other.y\n return dx**2 + dy**2": 4532, "def launch_server():\n \"\"\"Launches the django server at 127.0.0.1:8000\n \"\"\"\n print(os.path.dirname(os.path.abspath(__file__)))\n cur_dir = os.getcwd()\n path = os.path.dirname(os.path.abspath(__file__))\n run = True\n os.chdir(path)\n os.system('python manage.py runserver --nostatic')\n os.chdir(cur_dir)": 4533, "def add_range(self, sequence, begin, end):\n \"\"\"Add a read_range primitive\"\"\"\n sequence.parser_tree = parsing.Range(self.value(begin).strip(\"'\"),\n self.value(end).strip(\"'\"))\n return True": 4534, "def url(viewname, *args, **kwargs):\n \"\"\"Helper for Django's ``reverse`` in templates.\"\"\"\n return reverse(viewname, args=args, kwargs=kwargs)": 4535, "def do(self):\n \"\"\"\n Set a restore point (copy the object), then call the method.\n :return: obj.do_method(*args)\n \"\"\"\n self.restore_point = self.obj.copy()\n return self.do_method(self.obj, *self.args)": 4536, "def _image_field(self):\n \"\"\"\n Try to automatically detect an image field\n \"\"\"\n for field in self.model._meta.fields:\n if isinstance(field, ImageField):\n return field.name": 4537, "def __init__(self, function):\n\t\t\"\"\"function: to be called with each stream element as its\n\t\tonly argument\n\t\t\"\"\"\n\t\tsuper(takewhile, self).__init__()\n\t\tself.function = function": 4538, "def static_urls_js():\n \"\"\"\n Add global variables to JavaScript about the location and latest version of\n transpiled files.\n Usage::\n {% static_urls_js %}\n \"\"\"\n if apps.is_installed('django.contrib.staticfiles'):\n from django.contrib.staticfiles.storage import staticfiles_storage\n static_base_url = staticfiles_storage.base_url\n else:\n static_base_url = PrefixNode.handle_simple(\"STATIC_URL\")\n transpile_base_url = urljoin(static_base_url, 'js/transpile/')\n return {\n 'static_base_url': static_base_url,\n 'transpile_base_url': transpile_base_url,\n 'version': LAST_RUN['version']\n }": 4539, "def cache(self):\n \"\"\"Memoize access to the cache backend.\"\"\"\n if self._cache is None:\n self._cache = django_cache.get_cache(self.cache_name)\n return self._cache": 4540, "def _add_line_segment(self, x, y):\n \"\"\"Add a |_LineSegment| operation to the drawing sequence.\"\"\"\n self._drawing_operations.append(_LineSegment.new(self, x, y))": 4541, "def can_elasticsearch(record):\n \"\"\"Check if a given record is indexed.\n\n :param record: A record object.\n :returns: If the record is indexed returns `True`, otherwise `False`.\n \"\"\"\n search = request._methodview.search_class()\n search = search.get_record(str(record.id))\n return search.count() == 1": 4542, "def raw(self):\n \"\"\"\n Build query and passes to `Elasticsearch`, then returns the raw\n format returned.\n \"\"\"\n es = self.get_es()\n\n params = dict(self.query_params)\n mlt_fields = self.mlt_fields or params.pop('mlt_fields', [])\n\n body = self.s.build_search() if self.s else ''\n\n hits = es.mlt(\n index=self.index, doc_type=self.doctype, id=self.id,\n mlt_fields=mlt_fields, body=body, **params)\n\n log.debug(hits)\n\n return hits": 4543, "def email_user(self, subject, message, from_email=None):\n \"\"\" Send an email to this User.\"\"\"\n send_mail(subject, message, from_email, [self.email])": 4544, "def update_scale(self, value):\n \"\"\" updates the scale of all actors in the plotter \"\"\"\n self.plotter.set_scale(self.x_slider_group.value,\n self.y_slider_group.value,\n self.z_slider_group.value)": 4545, "def selectin(table, field, value, complement=False):\n \"\"\"Select rows where the given field is a member of the given value.\"\"\"\n\n return select(table, field, lambda v: v in value,\n complement=complement)": 4546, "def create_movie(fig, update_figure, filename, title, fps=15, dpi=100):\n \"\"\"Helps us to create a movie.\"\"\"\n FFMpegWriter = manimation.writers['ffmpeg']\n metadata = dict(title=title)\n writer = FFMpegWriter(fps=fps, metadata=metadata)\n\n with writer.saving(fig, filename, dpi):\n t = 0\n while True:\n if update_figure(t):\n writer.grab_frame()\n t += 1\n else:\n break": 4547, "def is_symbol(string):\n \"\"\"\n Return true if the string is a mathematical symbol.\n \"\"\"\n return (\n is_int(string) or is_float(string) or\n is_constant(string) or is_unary(string) or\n is_binary(string) or\n (string == '(') or (string == ')')\n )": 4548, "def load(cls,filename):\n \"\"\"Load from stored files\"\"\"\n filename = cls.correct_file_extension(filename)\n with open(filename,'rb') as f:\n return pickle.load(f)": 4549, "def boxes_intersect(box1, box2):\n \"\"\"Determines if two rectangles, each input as a tuple\n (xmin, xmax, ymin, ymax), intersect.\"\"\"\n xmin1, xmax1, ymin1, ymax1 = box1\n xmin2, xmax2, ymin2, ymax2 = box2\n if interval_intersection_width(xmin1, xmax1, xmin2, xmax2) and \\\n interval_intersection_width(ymin1, ymax1, ymin2, ymax2):\n return True\n else:\n return False": 4550, "def rmfile(path):\n \"\"\"Ensure file deleted also on *Windows* where read-only files need special treatment.\"\"\"\n if osp.isfile(path):\n if is_win:\n os.chmod(path, 0o777)\n os.remove(path)": 4551, "def local_minima(img, min_distance = 4):\n r\"\"\"\n Returns all local minima from an image.\n \n Parameters\n ----------\n img : array_like\n The image.\n min_distance : integer\n The minimal distance between the minimas in voxels. If it is less, only the lower minima is returned.\n \n Returns\n -------\n indices : sequence\n List of all minima indices.\n values : sequence\n List of all minima values.\n \"\"\"\n # @TODO: Write a unittest for this.\n fits = numpy.asarray(img)\n minfits = minimum_filter(fits, size=min_distance) # default mode is reflect\n minima_mask = fits == minfits\n good_indices = numpy.transpose(minima_mask.nonzero())\n good_fits = fits[minima_mask]\n order = good_fits.argsort()\n return good_indices[order], good_fits[order]": 4552, "def _has_fr_route(self):\n \"\"\"Encapsulating the rules for whether the request was to a Flask endpoint\"\"\"\n # 404's, 405's, which might not have a url_rule\n if self._should_use_fr_error_handler():\n return True\n # for all other errors, just check if FR dispatched the route\n if not request.url_rule:\n return False\n return self.owns_endpoint(request.url_rule.endpoint)": 4553, "def _euclidean_dist(vector_a, vector_b):\n \"\"\"\n :param vector_a: A list of numbers.\n :param vector_b: A list of numbers.\n :returns: The euclidean distance between the two vectors.\n \"\"\"\n dist = 0\n for (x, y) in zip(vector_a, vector_b):\n dist += (x-y)*(x-y)\n return math.sqrt(dist)": 4554, "def enable_writes(self):\n \"\"\"Restores the state of the batched queue for writing.\"\"\"\n self.write_buffer = []\n self.flush_lock = threading.RLock()\n self.flush_thread = FlushThread(self.max_batch_time,\n self._flush_writes)": 4555, "def EvalPoissonPmf(k, lam):\n \"\"\"Computes the Poisson PMF.\n\n k: number of events\n lam: parameter lambda in events per unit time\n\n returns: float probability\n \"\"\"\n # don't use the scipy function (yet). for lam=0 it returns NaN;\n # should be 0.0\n # return scipy.stats.poisson.pmf(k, lam)\n\n return lam ** k * math.exp(-lam) / math.factorial(k)": 4556, "def _eager_tasklet(tasklet):\n \"\"\"Decorator to turn tasklet to run eagerly.\"\"\"\n\n @utils.wrapping(tasklet)\n def eager_wrapper(*args, **kwds):\n fut = tasklet(*args, **kwds)\n _run_until_rpc()\n return fut\n\n return eager_wrapper": 4557, "def close(self):\n \"\"\"Send a close message to the external process and join it.\"\"\"\n try:\n self._conn.send((self._CLOSE, None))\n self._conn.close()\n except IOError:\n # The connection was already closed.\n pass\n self._process.join()": 4558, "def GetIndentLevel(line):\n \"\"\"Return the number of leading spaces in line.\n\n Args:\n line: A string to check.\n\n Returns:\n An integer count of leading spaces, possibly zero.\n \"\"\"\n indent = Match(r'^( *)\\S', line)\n if indent:\n return len(indent.group(1))\n else:\n return 0": 4559, "def get_area(self):\n \"\"\"Calculate area of bounding box.\"\"\"\n return (self.p2.x-self.p1.x)*(self.p2.y-self.p1.y)": 4560, "def _callable_once(func):\n \"\"\" Returns a function that is only callable once; any other call will do nothing \"\"\"\n\n def once(*args, **kwargs):\n if not once.called:\n once.called = True\n return func(*args, **kwargs)\n\n once.called = False\n return once": 4561, "def _dump_spec(spec):\n \"\"\"Dump bel specification dictionary using YAML\n\n Formats this with an extra indentation for lists to make it easier to\n use cold folding on the YAML version of the spec dictionary.\n \"\"\"\n with open(\"spec.yaml\", \"w\") as f:\n yaml.dump(spec, f, Dumper=MyDumper, default_flow_style=False)": 4562, "def AddAccuracy(model, softmax, label):\n \"\"\"Adds an accuracy op to the model\"\"\"\n accuracy = brew.accuracy(model, [softmax, label], \"accuracy\")\n return accuracy": 4563, "def get_selection_owner(self, selection):\n \"\"\"Return the window that owns selection (an atom), or X.NONE if\n there is no owner for the selection. Can raise BadAtom.\"\"\"\n r = request.GetSelectionOwner(display = self.display,\n selection = selection)\n return r.owner": 4564, "def setup(self, pin, mode, pull_up_down=PUD_OFF):\n \"\"\"Set the input or output mode for a specified pin. Mode should be\n either OUTPUT or INPUT.\n \"\"\"\n self.rpi_gpio.setup(pin, self._dir_mapping[mode],\n pull_up_down=self._pud_mapping[pull_up_down])": 4565, "def ruler_line(self, widths, linetype='-'):\n \"\"\"Generates a ruler line for separating rows from each other\"\"\"\n cells = []\n for w in widths:\n cells.append(linetype * (w+2))\n return '+' + '+'.join(cells) + '+'": 4566, "def check_cv(self, y):\n \"\"\"Resolve which cross validation strategy is used.\"\"\"\n y_arr = None\n if self.stratified:\n # Try to convert y to numpy for sklearn's check_cv; if conversion\n # doesn't work, still try.\n try:\n y_arr = to_numpy(y)\n except (AttributeError, TypeError):\n y_arr = y\n\n if self._is_float(self.cv):\n return self._check_cv_float()\n return self._check_cv_non_float(y_arr)": 4567, "def cov_to_correlation(cov):\n \"\"\"Compute the correlation matrix given the covariance matrix.\n\n Parameters\n ----------\n cov : `~numpy.ndarray`\n N x N matrix of covariances among N parameters.\n\n Returns\n -------\n corr : `~numpy.ndarray`\n N x N matrix of correlations among N parameters.\n \"\"\"\n err = np.sqrt(np.diag(cov))\n errinv = np.ones_like(err) * np.nan\n m = np.isfinite(err) & (err != 0)\n errinv[m] = 1. / err[m]\n corr = np.array(cov)\n return corr * np.outer(errinv, errinv)": 4568, "def random_int(self, min=0, max=9999, step=1):\n \"\"\"\n Returns a random integer between two values.\n\n :param min: lower bound value (inclusive; default=0)\n :param max: upper bound value (inclusive; default=9999)\n :param step: range step (default=1)\n :returns: random integer between min and max\n \"\"\"\n return self.generator.random.randrange(min, max + 1, step)": 4569, "def getcoef(self):\n \"\"\"Get final coefficient map array.\"\"\"\n\n global mp_Z_Y1\n return np.swapaxes(mp_Z_Y1, 0, self.xstep.cri.axisK+1)[0]": 4570, "def find_largest_contig(contig_lengths_dict):\n \"\"\"\n Determine the largest contig for each strain\n :param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths\n :return: longest_contig_dict: dictionary of strain name: longest contig\n \"\"\"\n # Initialise the dictionary\n longest_contig_dict = dict()\n for file_name, contig_lengths in contig_lengths_dict.items():\n # As the list is sorted in descending order, the largest contig is the first entry in the list\n longest_contig_dict[file_name] = contig_lengths[0]\n return longest_contig_dict": 4571, "def get_field_by_name(self, name):\n \"\"\"\n the field member matching name, or None if no such field is found\n \"\"\"\n\n for f in self.fields:\n if f.get_name() == name:\n return f\n return None": 4572, "def test_value(self, value):\n \"\"\"Test if value is an instance of int.\"\"\"\n if not isinstance(value, int):\n raise ValueError('expected int value: ' + str(type(value)))": 4573, "def delete(self, mutagen_file):\n \"\"\"Remove all images from the file.\n \"\"\"\n for cover_tag in self.TAG_NAMES.values():\n try:\n del mutagen_file[cover_tag]\n except KeyError:\n pass": 4574, "def memory_usage(self, deep=False):\n \"\"\"\n Memory usage of my values\n\n Parameters\n ----------\n deep : bool\n Introspect the data deeply, interrogate\n `object` dtypes for system-level memory consumption\n\n Returns\n -------\n bytes used\n\n Notes\n -----\n Memory usage does not include memory consumed by elements that\n are not components of the array if deep=False\n\n See Also\n --------\n numpy.ndarray.nbytes\n \"\"\"\n return self._codes.nbytes + self.dtype.categories.memory_usage(\n deep=deep)": 4575, "def block(seed):\n \"\"\" Return block of normal random numbers\n\n Parameters\n ----------\n seed : {None, int}\n The seed to generate the noise.sd\n\n Returns\n --------\n noise : numpy.ndarray\n Array of random numbers\n \"\"\"\n num = SAMPLE_RATE * BLOCK_SIZE\n rng = RandomState(seed % 2**32)\n variance = SAMPLE_RATE / 2\n return rng.normal(size=num, scale=variance**0.5)": 4576, "def get_object_or_child_by_type(self, *types):\n \"\"\" Get object if child already been read or get child.\n\n Use this method for fast access to objects in case of static configurations.\n\n :param types: requested object types.\n :return: all children of the specified types.\n \"\"\"\n\n objects = self.get_objects_or_children_by_type(*types)\n return objects[0] if any(objects) else None": 4577, "def get_parent_var(name, global_ok=False, default=None, skip_frames=0):\n \"\"\"\n Directly gets a variable from a parent frame-scope.\n\n Returns\n --------\n Any\n The content of the variable found by the given name, or None.\n \"\"\"\n\n scope = get_parent_scope_from_var(name, global_ok=global_ok, skip_frames=skip_frames + 1)\n\n if not scope:\n return default\n\n if name in scope.locals:\n return scope.locals.get(name, default)\n\n return scope.globals.get(name, default)": 4578, "def make_coord_dict(coord):\n \"\"\"helper function to make a dict from a coordinate for logging\"\"\"\n return dict(\n z=int_if_exact(coord.zoom),\n x=int_if_exact(coord.column),\n y=int_if_exact(coord.row),\n )": 4579, "def screen_to_latlon(self, x, y):\n \"\"\"\n Return the latitude and longitude corresponding to a screen point\n :param x: screen x\n :param y: screen y\n :return: latitude and longitude at x,y\n \"\"\"\n xtile = 1. * x / TILE_SIZE + self.xtile\n ytile = 1. * y / TILE_SIZE + self.ytile\n return self.num2deg(xtile, ytile, self.zoom)": 4580, "def get_querystring(uri):\n \"\"\"Get Querystring information from uri.\n\n :param uri: uri\n :return: querystring info or {}\n \"\"\"\n parts = urlparse.urlsplit(uri)\n return urlparse.parse_qs(parts.query)": 4581, "def __get_registry_key(self, key):\n \"\"\" Read currency from windows registry \"\"\"\n import winreg\n\n root = winreg.OpenKey(\n winreg.HKEY_CURRENT_USER, r'SOFTWARE\\GSettings\\org\\gnucash\\general', 0, winreg.KEY_READ)\n [pathname, regtype] = (winreg.QueryValueEx(root, key))\n winreg.CloseKey(root)\n return pathname": 4582, "def _full_analysis_mp_alias(br_obj, analysis_set, output_directory, unique_name, verbose, quick_plots):\n \"\"\"\n Alias for instance method that allows the method to be called in a\n multiprocessing pool. Needed as multiprocessing does not otherwise work\n on object instance methods.\n \"\"\"\n return (br_obj, unique_name, br_obj.full_analysis(analysis_set, output_directory, verbose = verbose, compile_pdf = verbose, quick_plots = quick_plots))": 4583, "def get_size(self, m):\n \"\"\"\n Return the 2-D size of a Jacobian matrix in tuple\n \"\"\"\n nrow, ncol = 0, 0\n if m[0] == 'F':\n nrow = self.n\n elif m[0] == 'G':\n nrow = self.m\n\n if m[1] == 'x':\n ncol = self.n\n elif m[1] == 'y':\n ncol = self.m\n\n return nrow, ncol": 4584, "def remove_accent_string(string):\n \"\"\"\n Remove all accent from a whole string.\n \"\"\"\n return utils.join([add_accent_char(c, Accent.NONE) for c in string])": 4585, "def replace_one(self, replacement):\n \"\"\"Replace one entire document matching the selector criteria.\n\n :Parameters:\n - `replacement` (dict): the replacement document\n \"\"\"\n self.__bulk.add_replace(self.__selector, replacement, upsert=True,\n collation=self.__collation)": 4586, "def tab(self, output):\n \"\"\"Output data in excel-compatible tab-delimited format\"\"\"\n import csv\n csvwriter = csv.writer(self.outfile, dialect=csv.excel_tab)\n csvwriter.writerows(output)": 4587, "def glpk_read_cplex(path):\n \"\"\"Reads cplex file and returns glpk problem.\n\n Returns\n -------\n glp_prob\n A glpk problems (same type as returned by glp_create_prob)\n \"\"\"\n from swiglpk import glp_create_prob, glp_read_lp\n\n problem = glp_create_prob()\n glp_read_lp(problem, None, path)\n return problem": 4588, "def get_builder_toplevel(self, builder):\n \"\"\"Get the toplevel widget from a gtk.Builder file.\n\n The main view implementation first searches for the widget named as\n self.toplevel_name (which defaults to \"main\". If this is missing, or not\n a gtk.Window, the first toplevel window found in the gtk.Builder is\n used.\n \"\"\"\n toplevel = builder.get_object(self.toplevel_name)\n if not gobject.type_is_a(toplevel, gtk.Window):\n toplevel = None\n if toplevel is None:\n toplevel = get_first_builder_window(builder)\n return toplevel": 4589, "def main():\n usage=\"\"\"\nUserspace ioctl example\n\n\"\"\" + Fuse.fusage\n server = FiocFS(version=\"%prog \" + fuse.__version__,\n usage=usage,\n dash_s_do='setsingle')\n\n server.parse(errex=1)\n server.main()": 4590, "def unique(iterable):\n \"\"\"Filter out duplicate items from an iterable\"\"\"\n seen = set()\n for item in iterable:\n if item not in seen:\n seen.add(item)\n yield item": 4591, "def get_median(temp_list):\n \"\"\"Return median\n \"\"\"\n num = len(temp_list)\n temp_list.sort()\n print(temp_list)\n if num % 2 == 0:\n median = (temp_list[int(num/2)] + temp_list[int(num/2) - 1]) / 2\n else:\n median = temp_list[int(num/2)]\n return median": 4592, "def most_even(number, group):\n \"\"\"Divide a number into a list of numbers as even as possible.\"\"\"\n count, rest = divmod(number, group)\n counts = zip_longest([count] * group, [1] * rest, fillvalue=0)\n chunks = [sum(one) for one in counts]\n logging.debug('chunks: %s', chunks)\n return chunks": 4593, "def count(self):\n \"\"\"\n Returns the number of widgets currently displayed (takes child splits\n into account).\n \"\"\"\n c = self.main_tab_widget.count()\n for child in self.child_splitters:\n c += child.count()\n return c": 4594, "def _initialize_id(self):\n \"\"\"Initializes the id of the instance.\"\"\"\n self.id = str(self.db.incr(self._key['id']))": 4595, "def call_alias(self, alias, rest=''):\n \"\"\"Call an alias given its name and the rest of the line.\"\"\"\n cmd = self.transform_alias(alias, rest)\n try:\n self.shell.system(cmd)\n except:\n self.shell.showtraceback()": 4596, "def version():\n \"\"\"\n View the current version of the CLI.\n \"\"\"\n import pkg_resources\n version = pkg_resources.require(PROJECT_NAME)[0].version\n floyd_logger.info(version)": 4597, "def xor_bytes(a, b):\n \"\"\"\n Calculate the byte wise exclusive of of two :class:`bytes` objects\n of the same length.\n \"\"\"\n assert len(a) == len(b)\n return bytes(map(operator.xor, a, b))": 4598, "def get_method_from_module(module_path, method_name):\n \"\"\" from a valid python module path, get the run method name passed \"\"\"\n top_module = __import__(module_path)\n\n module = top_module\n # we tunnel down until we find the module we want\n for submodule_name in module_path.split('.')[1:]:\n module = getattr(module, submodule_name)\n\n assert hasattr(module, method_name), \\\n \"unable to find method {0} from module {1}. does the method exist?\".format(method_name, module_path)\n return getattr(module, method_name)": 4599, "def to_topojson(self):\n \"\"\"Adds points and converts to topojson string.\"\"\"\n topojson = self.topojson\n topojson[\"objects\"][\"points\"] = {\n \"type\": \"GeometryCollection\",\n \"geometries\": [point.to_topojson() for point in self.points.all()],\n }\n return json.dumps(topojson)": 4600, "def get_variables(args):\n \"\"\"\n Return a dictionary of variables specified at CLI\n :param: args: Command Line Arguments namespace\n \"\"\"\n variables_dict = {}\n if args.variables:\n for var in args.variables:\n words = var.split('=')\n variables_dict[words[0]] = words[1]\n return variables_dict": 4601, "async def create_websocket_server(sock, filter=None): # pylint: disable=W0622\n \"\"\"\n A more low-level form of open_websocket_server.\n You are responsible for closing this websocket.\n \"\"\"\n ws = Websocket()\n await ws.start_server(sock, filter=filter)\n return ws": 4602, "def _normalize(obj):\n \"\"\"\n Normalize dicts and lists\n\n :param obj:\n :return: normalized object\n \"\"\"\n if isinstance(obj, list):\n return [_normalize(item) for item in obj]\n elif isinstance(obj, dict):\n return {k: _normalize(v) for k, v in obj.items() if v is not None}\n elif hasattr(obj, 'to_python'):\n return obj.to_python()\n return obj": 4603, "def ranks(self, key, value):\n \"\"\"Populate the ``ranks`` key.\"\"\"\n return [normalize_rank(el) for el in force_list(value.get('a'))]": 4604, "def getRowCurrentIndex(self):\n \"\"\" Returns the index of column 0 of the current item in the underlying model.\n See also the notes at the top of this module on current item vs selected item(s).\n \"\"\"\n curIndex = self.currentIndex()\n col0Index = curIndex.sibling(curIndex.row(), 0)\n return col0Index": 4605, "def add_todo(request):\n cur = request.cursor\n todo = request.json[\"todo\"]\n cur.execute(\"\"\"INSERT INTO todos (todo) VALUES (?)\"\"\", (todo,))\n last_id = cur.lastrowid\n cur.connection.commit()\n\n return request.Response(json={\"id\": last_id, \"todo\": todo})": 4606, "def monkey_restore():\n \"\"\"restore real versions. Inverse of `monkey_patch`\"\"\"\n for k, v in originals.items():\n setattr(time_mod, k, v)\n \n global epoch\n epoch = None": 4607, "def _normalize_instancemethod(instance_method):\n \"\"\"\n wraps(instancemethod) returns a function, not an instancemethod so its repr() is all messed up;\n we want the original repr to show up in the logs, therefore we do this trick\n \"\"\"\n if not hasattr(instance_method, 'im_self'):\n return instance_method\n\n def _func(*args, **kwargs):\n return instance_method(*args, **kwargs)\n\n _func.__name__ = repr(instance_method)\n return _func": 4608, "def count_rows(self, table, cols='*'):\n \"\"\"Get the number of rows in a particular table.\"\"\"\n query = 'SELECT COUNT({0}) FROM {1}'.format(join_cols(cols), wrap(table))\n result = self.fetch(query)\n return result if result is not None else 0": 4609, "def log_to_json(log):\n \"\"\"Convert a log record into a list of strings\"\"\"\n return [log.timestamp.isoformat()[:22],\n log.level, log.process, log.message]": 4610, "def execute(self, cmd, *args, **kwargs):\n \"\"\" Execute the SQL command and return the data rows as tuples\n \"\"\"\n self.cursor.execute(cmd, *args, **kwargs)": 4611, "def upgrade(directory, sql, tag, x_arg, revision):\n \"\"\"Upgrade to a later version\"\"\"\n _upgrade(directory, revision, sql, tag, x_arg)": 4612, "def get_index_nested(x, i):\n \"\"\"\n Description:\n Returns the first index of the array (vector) x containing the value i.\n Parameters:\n x: one-dimensional array\n i: search value\n \"\"\"\n for ind in range(len(x)):\n if i == x[ind]:\n return ind\n return -1": 4613, "def get_table_list(dbconn):\n \"\"\"\n Get a list of tables that exist in dbconn\n :param dbconn: database connection\n :return: List of table names\n \"\"\"\n cur = dbconn.cursor()\n cur.execute(\"SELECT name FROM sqlite_master WHERE type='table';\")\n try:\n return [item[0] for item in cur.fetchall()]\n except IndexError:\n return get_table_list(dbconn)": 4614, "def inverse(self):\n \"\"\"\n Returns inverse of transformation.\n \"\"\"\n invr = np.linalg.inv(self.affine_matrix)\n return SymmOp(invr)": 4615, "def to_networkx(graph):\n \"\"\" Convert a Mapper 1-complex to a networkx graph.\n\n Parameters\n -----------\n\n graph: dictionary, graph object returned from `kmapper.map`\n\n Returns\n --------\n\n g: graph as networkx.Graph() object\n\n \"\"\"\n\n # import here so networkx is not always required.\n import networkx as nx\n\n nodes = graph[\"nodes\"].keys()\n edges = [[start, end] for start, ends in graph[\"links\"].items() for end in ends]\n\n g = nx.Graph()\n g.add_nodes_from(nodes)\n nx.set_node_attributes(g, dict(graph[\"nodes\"]), \"membership\")\n\n g.add_edges_from(edges)\n\n return g": 4616, "def _get_col_index(name):\n \"\"\"Convert column name to index.\"\"\"\n\n index = string.ascii_uppercase.index\n col = 0\n for c in name.upper():\n col = col * 26 + index(c) + 1\n return col": 4617, "def widget(self, f):\n \"\"\"\n Return an interactive function widget for the given function.\n\n The widget is only constructed, not displayed nor attached to\n the function.\n\n Returns\n -------\n An instance of ``self.cls`` (typically :class:`interactive`).\n\n Parameters\n ----------\n f : function\n The function to which the interactive widgets are tied.\n \"\"\"\n return self.cls(f, self.opts, **self.kwargs)": 4618, "def main(pargs):\n \"\"\"This should only be used for testing. The primary mode of operation is\n as an imported library.\n \"\"\"\n input_file = sys.argv[1]\n fp = ParseFileLineByLine(input_file)\n for i in fp:\n print(i)": 4619, "def _iterate_flattened_values(value):\n \"\"\"Provides an iterator over all values in a nested structure.\"\"\"\n if isinstance(value, six.string_types):\n yield value\n return\n\n if isinstance(value, collections.Mapping):\n value = collections.ValuesView(value)\n\n if isinstance(value, collections.Iterable):\n for nested_value in value:\n for nested_nested_value in _iterate_flattened_values(nested_value):\n yield nested_nested_value\n\n yield value": 4620, "def check_github(self):\n \"\"\"\n If the requirement is frozen to a github url, check for new commits.\n\n API Tokens\n ----------\n For more than 50 github api calls per hour, pipchecker requires\n authentication with the github api by settings the environemnt\n variable ``GITHUB_API_TOKEN`` or setting the command flag\n --github-api-token='mytoken'``.\n\n To create a github api token for use at the command line::\n curl -u 'rizumu' -d '{\"scopes\":[\"repo\"], \"note\":\"pipchecker\"}' https://api.github.com/authorizations\n\n For more info on github api tokens:\n https://help.github.com/articles/creating-an-oauth-token-for-command-line-use\n http://developer.github.com/v3/oauth/#oauth-authorizations-api\n\n Requirement Format\n ------------------\n Pipchecker gets the sha of frozen repo and checks if it is\n found at the head of any branches. If it is not found then\n the requirement is considered to be out of date.\n\n Therefore, freezing at the commit hash will provide the expected\n results, but if freezing at a branch or tag name, pipchecker will\n not be able to determine with certainty if the repo is out of date.\n\n Freeze at the commit hash (sha)::\n git+git://github.com/django/django.git@393c268e725f5b229ecb554f3fac02cfc250d2df#egg=Django\n https://github.com/django/django/archive/393c268e725f5b229ecb554f3fac02cfc250d2df.tar.gz#egg=Django\n https://github.com/django/django/archive/393c268e725f5b229ecb554f3fac02cfc250d2df.zip#egg=Django\n\n Freeze with a branch name::\n git+git://github.com/django/django.git@master#egg=Django\n https://github.com/django/django/archive/master.tar.gz#egg=Django\n https://github.com/django/django/archive/master.zip#egg=Django\n\n Freeze with a tag::\n git+git://github.com/django/django.git@1.5b2#egg=Django\n https://github.com/django/django/archive/1.5b2.tar.gz#egg=Django\n https://github.com/django/django/archive/1.5b2.zip#egg=Django\n\n Do not freeze::\n git+git://github.com/django/django.git#egg=Django\n\n \"\"\"\n for name, req in list(self.reqs.items()):\n req_url = req[\"url\"]\n if not req_url:\n continue\n req_url = str(req_url)\n if req_url.startswith(\"git\") and \"github.com/\" not in req_url:\n continue\n if req_url.endswith((\".tar.gz\", \".tar.bz2\", \".zip\")):\n continue\n\n headers = {\n \"content-type\": \"application/json\",\n }\n if self.github_api_token:\n headers[\"Authorization\"] = \"token {0}\".format(self.github_api_token)\n try:\n path_parts = urlparse(req_url).path.split(\"#\", 1)[0].strip(\"/\").rstrip(\"/\").split(\"/\")\n\n if len(path_parts) == 2:\n user, repo = path_parts\n\n elif 'archive' in path_parts:\n # Supports URL of format:\n # https://github.com/django/django/archive/master.tar.gz#egg=Django\n # https://github.com/django/django/archive/master.zip#egg=Django\n user, repo = path_parts[:2]\n repo += '@' + path_parts[-1].replace('.tar.gz', '').replace('.zip', '')\n\n else:\n self.style.ERROR(\"\\nFailed to parse %r\\n\" % (req_url, ))\n continue\n except (ValueError, IndexError) as e:\n self.stdout.write(self.style.ERROR(\"\\nFailed to parse %r: %s\\n\" % (req_url, e)))\n continue\n\n try:\n test_auth = requests.get(\"https://api.github.com/django/\", headers=headers).json()\n except HTTPError as e:\n self.stdout.write(\"\\n%s\\n\" % str(e))\n return\n\n if \"message\" in test_auth and test_auth[\"message\"] == \"Bad credentials\":\n self.stdout.write(self.style.ERROR(\"\\nGithub API: Bad credentials. Aborting!\\n\"))\n return\n elif \"message\" in test_auth and test_auth[\"message\"].startswith(\"API Rate Limit Exceeded\"):\n self.stdout.write(self.style.ERROR(\"\\nGithub API: Rate Limit Exceeded. Aborting!\\n\"))\n return\n\n frozen_commit_sha = None\n if \".git\" in repo:\n repo_name, frozen_commit_full = repo.split(\".git\")\n if frozen_commit_full.startswith(\"@\"):\n frozen_commit_sha = frozen_commit_full[1:]\n elif \"@\" in repo:\n repo_name, frozen_commit_sha = repo.split(\"@\")\n\n if frozen_commit_sha is None:\n msg = self.style.ERROR(\"repo is not frozen\")\n\n if frozen_commit_sha:\n branch_url = \"https://api.github.com/repos/{0}/{1}/branches\".format(user, repo_name)\n branch_data = requests.get(branch_url, headers=headers).json()\n\n frozen_commit_url = \"https://api.github.com/repos/{0}/{1}/commits/{2}\".format(\n user, repo_name, frozen_commit_sha\n )\n frozen_commit_data = requests.get(frozen_commit_url, headers=headers).json()\n\n if \"message\" in frozen_commit_data and frozen_commit_data[\"message\"] == \"Not Found\":\n msg = self.style.ERROR(\"{0} not found in {1}. Repo may be private.\".format(frozen_commit_sha[:10], name))\n elif frozen_commit_data[\"sha\"] in [branch[\"commit\"][\"sha\"] for branch in branch_data]:\n msg = self.style.BOLD(\"up to date\")\n else:\n msg = self.style.INFO(\"{0} is not the head of any branch\".format(frozen_commit_data[\"sha\"][:10]))\n\n if \"dist\" in req:\n pkg_info = \"{dist.project_name} {dist.version}\".format(dist=req[\"dist\"])\n elif frozen_commit_sha is None:\n pkg_info = name\n else:\n pkg_info = \"{0} {1}\".format(name, frozen_commit_sha[:10])\n self.stdout.write(\"{pkg_info:40} {msg}\".format(pkg_info=pkg_info, msg=msg))\n del self.reqs[name]": 4621, "def _query_for_reverse_geocoding(lat, lng):\n \"\"\"\n Given a lat & lng, what's the string search query.\n\n If the API changes, change this function. Only for internal use.\n \"\"\"\n # have to do some stupid f/Decimal/str stuff to (a) ensure we get as much\n # decimal places as the user already specified and (b) to ensure we don't\n # get e-5 stuff\n return \"{0:f},{1:f}\".format(Decimal(str(lat)), Decimal(str(lng)))": 4622, "def iterparse(source, events=('end',), remove_comments=True, **kw):\n \"\"\"Thin wrapper around ElementTree.iterparse\"\"\"\n return ElementTree.iterparse(source, events, SourceLineParser(), **kw)": 4623, "def urljoin(*urls):\n \"\"\"\n The default urlparse.urljoin behavior look strange\n Standard urlparse.urljoin('http://a.com/foo', '/bar')\n Expect: http://a.com/foo/bar\n Actually: http://a.com/bar\n\n This function fix that.\n \"\"\"\n return reduce(urlparse.urljoin, [u.strip('/')+'/' for u in urls if u.strip('/')], '').rstrip('/')": 4624, "def complex_check(*args, func=None):\n \"\"\"Check if arguments are complex numbers.\"\"\"\n func = func or inspect.stack()[2][3]\n for var in args:\n if not isinstance(var, numbers.Complex):\n name = type(var).__name__\n raise ComplexError(\n f'Function {func} expected complex number, {name} got instead.')": 4625, "def magic(self, alias):\n \"\"\"Returns the appropriate IPython code magic when\n called with an alias for a language.\n \"\"\"\n if alias in self.aliases:\n return self.aliases[alias]\n else:\n return \"%%{}\\n\".format(alias)": 4626, "def pprint(j, no_pretty):\n \"\"\"\n Prints as formatted JSON\n \"\"\"\n if not no_pretty:\n click.echo(\n json.dumps(j, cls=PotionJSONEncoder, sort_keys=True, indent=4, separators=(\",\", \": \"))\n )\n else:\n click.echo(j)": 4627, "def append_query_parameter(url, parameters, ignore_if_exists=True):\n \"\"\" quick and dirty appending of query parameters to a url \"\"\"\n if ignore_if_exists:\n for key in parameters.keys():\n if key + \"=\" in url:\n del parameters[key]\n parameters_str = \"&\".join(k + \"=\" + v for k, v in parameters.items())\n append_token = \"&\" if \"?\" in url else \"?\"\n return url + append_token + parameters_str": 4628, "def _increment(arr, indices):\n \"\"\"Increment some indices in a 1D vector of non-negative integers.\n Repeated indices are taken into account.\"\"\"\n arr = _as_array(arr)\n indices = _as_array(indices)\n bbins = np.bincount(indices)\n arr[:len(bbins)] += bbins\n return arr": 4629, "def plot_kde(data, ax, title=None, color='r', fill_bt=True):\n \"\"\"\n Plot a smoothed (by kernel density estimate) histogram.\n :type data: numpy array\n :param data: An array containing the data to be plotted\n\n :type ax: matplotlib.Axes\n :param ax: The Axes object to draw to\n\n :type title: str\n :param title: The plot title\n\n :type color: str\n :param color: The color of the histogram line and fill. Note that the fill\n will be plotted with an alpha of 0.35.\n\n :type fill_bt: bool\n :param fill_bt: Specify whether to fill the area beneath the histogram line\n \"\"\"\n if isinstance(data, list):\n data = np.asarray(data)\n e = kde.KDEUnivariate(data.astype(np.float))\n e.fit()\n ax.plot(e.support, e.density, color=color, alpha=0.9, linewidth=2.25)\n if fill_bt:\n ax.fill_between(e.support, e.density, alpha=.35, zorder=1,\n antialiased=True, color=color)\n if title is not None:\n t = ax.set_title(title)\n t.set_y(1.05)": 4630, "def get_long_description():\n \"\"\" Read the long description. \"\"\"\n here = path.abspath(path.dirname(__file__))\n with open(path.join(here, 'README.rst')) as readme:\n return readme.read()\n return None": 4631, "def calculate_size(name, replace_existing_values):\n \"\"\" Calculates the request payload size\"\"\"\n data_size = 0\n data_size += calculate_size_str(name)\n data_size += BOOLEAN_SIZE_IN_BYTES\n return data_size": 4632, "def _mid(string, start, end=None):\n \"\"\"\n Returns a substring delimited by start and end position.\n \"\"\"\n if end is None:\n end = len(string)\n return string[start:start + end]": 4633, "def confirm(question, default=True):\n \"\"\"Ask a yes/no question interactively.\n\n :param question: The text of the question to ask.\n :returns: True if the answer was \"yes\", False otherwise.\n \"\"\"\n valid = {\"\": default, \"yes\": True, \"y\": True, \"no\": False, \"n\": False}\n while 1:\n choice = input(question + (\" [Y/n] \" if default else \" [y/N] \")).lower()\n if choice in valid:\n return valid[choice]\n print(\"Please respond with 'y' or 'n' \")": 4634, "def ylim(self, low, high):\n \"\"\"Set yaxis limits\n\n Parameters\n ----------\n low : number\n high : number\n index : int, optional\n\n Returns\n -------\n Chart\n\n \"\"\"\n self.chart['yAxis'][0]['min'] = low\n self.chart['yAxis'][0]['max'] = high\n return self": 4635, "def get_tail(self):\n \"\"\"Gets tail\n\n :return: Tail of linked list\n \"\"\"\n node = self.head\n last_node = self.head\n\n while node is not None:\n last_node = node\n node = node.next_node\n\n return last_node": 4636, "def empirical(X):\n \"\"\"Compute empirical covariance as baseline estimator.\n \"\"\"\n print(\"Empirical\")\n cov = np.dot(X.T, X) / n_samples\n return cov, np.linalg.inv(cov)": 4637, "def dedup(seq):\n \"\"\"Remove duplicates from a list while keeping order.\"\"\"\n seen = set()\n for item in seq:\n if item not in seen:\n seen.add(item)\n yield item": 4638, "def stddev(values, meanval=None): #from AI: A Modern Appproach\n \"\"\"The standard deviation of a set of values.\n Pass in the mean if you already know it.\"\"\"\n if meanval == None: meanval = mean(values)\n return math.sqrt( sum([(x - meanval)**2 for x in values]) / (len(values)-1) )": 4639, "def __enter__(self):\n \"\"\"Acquire a lock on the output file, prevents collisions between multiple runs.\"\"\"\n self.fd = open(self.filename, 'a')\n fcntl.lockf(self.fd, fcntl.LOCK_EX)\n return self.fd": 4640, "def log_stop(logger):\n \"\"\"log stop\"\"\"\n\n handlers = logger.handlers[:]\n for handler in handlers:\n handler.close()\n logger.removeHandler(handler)": 4641, "def parse(self):\n \"\"\"\n Parses format string looking for substitutions\n\n This method is responsible for returning a list of fields (as strings)\n to include in all log messages.\n \"\"\"\n standard_formatters = re.compile(r'\\((.+?)\\)', re.IGNORECASE)\n return standard_formatters.findall(self._fmt)": 4642, "def _is_retryable_exception(e):\n \"\"\"Returns True if the exception is always safe to retry.\n\n This is True if the client was never able to establish a connection\n to the server (for example, name resolution failed or the connection\n could otherwise not be initialized).\n\n Conservatively, if we can't tell whether a network connection could\n have been established, we return False.\n\n \"\"\"\n if isinstance(e, urllib3.exceptions.ProtocolError):\n e = e.args[1]\n if isinstance(e, (socket.gaierror, socket.herror)):\n return True\n if isinstance(e, socket.error) and e.errno in _RETRYABLE_SOCKET_ERRORS:\n return True\n if isinstance(e, urllib3.exceptions.NewConnectionError):\n return True\n return False": 4643, "def enableEditing(self, enabled):\n \"\"\"Enable the editing buttons to add/remove rows/columns and to edit the data.\n\n This method is also a slot.\n In addition, the data of model will be made editable,\n if the `enabled` parameter is true.\n\n Args:\n enabled (bool): This flag indicates, if the buttons\n shall be activated.\n\n \"\"\"\n for button in self.buttons[1:]:\n button.setEnabled(enabled)\n if button.isChecked():\n button.setChecked(False)\n\n model = self.tableView.model()\n\n if model is not None:\n model.enableEditing(enabled)": 4644, "def apply_color_map(name: str, mat: np.ndarray = None):\n \"\"\"returns an RGB matrix scaled by a matplotlib color map\"\"\"\n def apply_map(mat):\n return (cm.get_cmap(name)(_normalize(mat))[:, :, :3] * 255).astype(np.uint8)\n \n return apply_map if mat is None else apply_map(mat)": 4645, "def check_player_collision(self):\n \"\"\"Check to see if we are colliding with the player.\"\"\"\n player_tiles = r.TileMapManager.active_map.grab_collisions(self.char.coords)\n enemy_tiles = r.TileMapManager.active_map.grab_collisions(self.coords)\n\n #Check to see if any of the tiles are the same. If so, there is a collision.\n for ptile in player_tiles:\n for etile in enemy_tiles:\n if r.TileMapManager.active_map.pixels_to_tiles(ptile.coords) == r.TileMapManager.active_map.pixels_to_tiles(etile.coords):\n return True\n\n return False": 4646, "def read_image(filepath):\n \"\"\"Returns an image tensor.\"\"\"\n im_bytes = tf.io.read_file(filepath)\n im = tf.image.decode_image(im_bytes, channels=CHANNELS)\n im = tf.image.convert_image_dtype(im, tf.float32)\n return im": 4647, "def calculate_size(name, max_size):\n \"\"\" Calculates the request payload size\"\"\"\n data_size = 0\n data_size += calculate_size_str(name)\n data_size += INT_SIZE_IN_BYTES\n return data_size": 4648, "def clear_all(self):\n \"\"\" clear all files that were to be injected \"\"\"\n self.injections.clear_all()\n for config_file in CONFIG_FILES:\n self.injections.clear(os.path.join(\"~\", config_file))": 4649, "def clear_worker_output(self):\n \"\"\"Drops all of the worker output collections\n Args:\n None\n Returns:\n Nothing\n \"\"\"\n self.data_store.clear_worker_output()\n\n # Have the plugin manager reload all the plugins\n self.plugin_manager.load_all_plugins()\n\n # Store information about commands and workbench\n self._store_information()": 4650, "def tinsel(to_patch, module_name, decorator=mock_decorator):\n \"\"\"\n Decorator for simple in-place decorator mocking for tests\n\n Args:\n to_patch: the string path of the function to patch\n module_name: complete string path of the module to reload\n decorator (optional): replacement decorator. By default a pass-through\n will be used.\n\n Returns:\n A wrapped test function, during the context of execution the specified\n path is patched.\n\n \"\"\"\n def fn_decorator(function):\n def wrapper(*args, **kwargs):\n with patch(to_patch, decorator):\n m = importlib.import_module(module_name)\n reload(m)\n function(*args, **kwargs)\n\n reload(m)\n return wrapper\n return fn_decorator": 4651, "def step_table_made(self):\n \"\"\"check if the step table exists\"\"\"\n try:\n empty = self.step_table.empty\n except AttributeError:\n empty = True\n return not empty": 4652, "def on_modified(self, event):\n \"\"\"Function called everytime a new file is modified.\n\n Args:\n event: Event to process.\n \"\"\"\n self._logger.debug('Detected modify event on watched path: %s', event.src_path)\n\n self._process_event(event)": 4653, "def _modify(item, func):\n \"\"\"\n Modifies each item.keys() string based on the func passed in.\n Often used with inflection's camelize or underscore methods.\n\n :param item: dictionary representing item to be modified\n :param func: function to run on each key string\n :return: dictionary where each key has been modified by func.\n \"\"\"\n result = dict()\n for key in item:\n result[func(key)] = item[key]\n return result": 4654, "def find_one_by_id(self, _id):\n \"\"\"\n Find a single document by id\n\n :param str _id: BSON string repreentation of the Id\n :return: a signle object\n :rtype: dict\n\n \"\"\"\n document = (yield self.collection.find_one({\"_id\": ObjectId(_id)}))\n raise Return(self._obj_cursor_to_dictionary(document))": 4655, "def _records_commit(record_ids):\n \"\"\"Commit all records.\"\"\"\n for record_id in record_ids:\n record = Record.get_record(record_id)\n record.commit()": 4656, "def select_up(self):\n \"\"\"move cursor up\"\"\"\n r, c = self._index\n self._select_index(r-1, c)": 4657, "def _cast_to_type(self, value):\n \"\"\" Convert the value to its string representation\"\"\"\n if isinstance(value, str) or value is None:\n return value\n return str(value)": 4658, "def stop(self, timeout=None):\n \"\"\" Initiates a graceful stop of the processes \"\"\"\n\n self.stopping = True\n\n for process in list(self.processes):\n self.stop_process(process, timeout=timeout)": 4659, "def _intermediary_to_dot(tables, relationships):\n \"\"\" Returns the dot source representing the database in a string. \"\"\"\n t = '\\n'.join(t.to_dot() for t in tables)\n r = '\\n'.join(r.to_dot() for r in relationships)\n return '{}\\n{}\\n{}\\n}}'.format(GRAPH_BEGINNING, t, r)": 4660, "def getCursor(self):\n\t\t\"\"\"\n\t\tGet a Dictionary Cursor for executing queries\n\t\t\"\"\"\n\t\tif self.connection is None:\n\t\t\tself.Connect()\n\t\t\t\n\t\treturn self.connection.cursor(MySQLdb.cursors.DictCursor)": 4661, "def gaussian_distribution(mean, stdev, num_pts=50):\n \"\"\" get an x and y numpy.ndarray that spans the +/- 4\n standard deviation range of a gaussian distribution with\n a given mean and standard deviation. useful for plotting\n\n Parameters\n ----------\n mean : float\n the mean of the distribution\n stdev : float\n the standard deviation of the distribution\n num_pts : int\n the number of points in the returned ndarrays.\n Default is 50\n\n Returns\n -------\n x : numpy.ndarray\n the x-values of the distribution\n y : numpy.ndarray\n the y-values of the distribution\n\n \"\"\"\n xstart = mean - (4.0 * stdev)\n xend = mean + (4.0 * stdev)\n x = np.linspace(xstart,xend,num_pts)\n y = (1.0/np.sqrt(2.0*np.pi*stdev*stdev)) * np.exp(-1.0 * ((x - mean)**2)/(2.0*stdev*stdev))\n return x,y": 4662, "def new(self, size, fill):\n \"\"\"Return a new Image instance filled with a color.\"\"\"\n return Image(PIL.Image.new(\"RGB\", size, fill))": 4663, "def wheel(delta=1):\n \"\"\" Sends a wheel event for the provided number of clicks. May be negative to reverse\n direction. \"\"\"\n location = get_position()\n e = Quartz.CGEventCreateMouseEvent(\n None,\n Quartz.kCGEventScrollWheel,\n location,\n Quartz.kCGMouseButtonLeft)\n e2 = Quartz.CGEventCreateScrollWheelEvent(\n None,\n Quartz.kCGScrollEventUnitLine,\n 1,\n delta)\n Quartz.CGEventPost(Quartz.kCGHIDEventTap, e)\n Quartz.CGEventPost(Quartz.kCGHIDEventTap, e2)": 4664, "def header_length(bytearray):\n \"\"\"Return the length of s when it is encoded with base64.\"\"\"\n groups_of_3, leftover = divmod(len(bytearray), 3)\n # 4 bytes out for each 3 bytes (or nonzero fraction thereof) in.\n n = groups_of_3 * 4\n if leftover:\n n += 4\n return n": 4665, "def setdict(self, D):\n \"\"\"Set dictionary array.\"\"\"\n\n self.D = np.asarray(D, dtype=self.dtype)": 4666, "def zoomed_scaled_array_around_mask(self, mask, buffer=1):\n \"\"\"Extract the 2D region of an array corresponding to the rectangle encompassing all unmasked values.\n\n This is used to extract and visualize only the region of an image that is used in an analysis.\n\n Parameters\n ----------\n mask : mask.Mask\n The mask around which the scaled array is extracted.\n buffer : int\n The buffer of pixels around the extraction.\n \"\"\"\n return self.new_with_array(array=array_util.extracted_array_2d_from_array_2d_and_coordinates(\n array_2d=self, y0=mask.zoom_region[0]-buffer, y1=mask.zoom_region[1]+buffer,\n x0=mask.zoom_region[2]-buffer, x1=mask.zoom_region[3]+buffer))": 4667, "def _download(url):\n \"\"\"Downloads an URL and returns a file-like object open for reading,\n compatible with zipping.ZipFile (it has a seek() method).\n \"\"\"\n fh = StringIO()\n\n for line in get(url):\n fh.write(line)\n\n fh.seek(0)\n return fh": 4668, "def new_random_state(seed=None, fully_random=False):\n \"\"\"\n Returns a new random state.\n\n Parameters\n ----------\n seed : None or int, optional\n Optional seed value to use.\n The same datatypes are allowed as for ``numpy.random.RandomState(seed)``.\n\n fully_random : bool, optional\n Whether to use numpy's random initialization for the\n RandomState (used if set to True). If False, a seed is sampled from\n the global random state, which is a bit faster and hence the default.\n\n Returns\n -------\n numpy.random.RandomState\n The new random state.\n\n \"\"\"\n if seed is None:\n if not fully_random:\n # sample manually a seed instead of just RandomState(),\n # because the latter one\n # is way slower.\n seed = CURRENT_RANDOM_STATE.randint(SEED_MIN_VALUE, SEED_MAX_VALUE, 1)[0]\n return np.random.RandomState(seed)": 4669, "def _strip_empty_keys(self, params):\n \"\"\"Added because the Dropbox OAuth2 flow doesn't\n work when scope is passed in, which is empty.\n \"\"\"\n keys = [k for k, v in params.items() if v == '']\n for key in keys:\n del params[key]": 4670, "def click_by_selector(self, selector):\n \"\"\"Click the element matching the CSS selector.\"\"\"\n # No need for separate button press step with selector style.\n elem = find_element_by_jquery(world.browser, selector)\n elem.click()": 4671, "def set_attrs(self):\n \"\"\" set our object attributes \"\"\"\n self.attrs.encoding = self.encoding\n self.attrs.errors = self.errors": 4672, "def update(self, **kwargs):\n \"\"\"Customize the lazy field\"\"\"\n assert not self.called\n self.kw.update(kwargs)\n return self": 4673, "def stylize(text, styles, reset=True):\n \"\"\"conveniently styles your text as and resets ANSI codes at its end.\"\"\"\n terminator = attr(\"reset\") if reset else \"\"\n return \"{}{}{}\".format(\"\".join(styles), text, terminator)": 4674, "def _covariance_matrix(self, type='noise'):\n \"\"\"\n Constructs the covariance matrix from PCA\n residuals\n \"\"\"\n if type == 'sampling':\n return self.sigma**2/(self.n-1)\n elif type == 'noise':\n return 4*self.sigma*N.var(self.rotated(), axis=0)": 4675, "def get_all_names(self):\n \"\"\"Return the list of all cached global names\"\"\"\n result = set()\n for module in self.names:\n result.update(set(self.names[module]))\n return result": 4676, "def camelcase2list(s, lower=False):\n \"\"\"Converts a camelcase string to a list.\"\"\"\n s = re.findall(r'([A-Z][a-z0-9]+)', s)\n return [w.lower() for w in s] if lower else s": 4677, "def get_active_window(self):\n \"\"\"\n The current active :class:`.Window`.\n \"\"\"\n app = get_app()\n\n try:\n return self._active_window_for_cli[app]\n except KeyError:\n self._active_window_for_cli[app] = self._last_active_window or self.windows[0]\n return self.windows[0]": 4678, "def trivial_partition(set_):\n \"\"\"Returns a parition of given set into 1-element subsets.\n\n :return: Trivial partition of given set, i.e. iterable containing disjoint\n 1-element sets, each consisting of a single element\n from given set\n \"\"\"\n ensure_countable(set_)\n\n result = ((x,) for x in set_)\n return _harmonize_subset_types(set_, result)": 4679, "def inventory(self, source_id, fetch=False, fmt='table'):\n \"\"\"\n Prints a summary of all objects in the database. Input string or list of strings in **ID** or **unum**\n for specific objects.\n\n Parameters\n ----------\n source_id: int\n The id from the SOURCES table whose data across all tables is to be printed.\n fetch: bool\n Return the results.\n fmt: str\n Returns the data as a dictionary, array, or astropy.table given 'dict', 'array', or 'table'\n\n Returns\n -------\n data_tables: dict\n Returns a dictionary of astropy tables with the table name as the keys.\n\n \"\"\"\n data_tables = {}\n\n t = self.query(\"SELECT * FROM sqlite_master WHERE type='table'\", fmt='table')\n all_tables = t['name'].tolist()\n for table in ['sources'] + [t for t in all_tables if\n t not in ['sources', 'sqlite_sequence']]:\n\n try:\n\n # Get the columns, pull out redundant ones, and query the table for this source's data\n t = self.query(\"PRAGMA table_info({})\".format(table), fmt='table')\n columns = np.array(t['name'])\n types = np.array(t['type'])\n\n if table == 'sources' or 'source_id' in columns:\n\n # If printing, only get simple data types and exclude redundant 'source_id' for nicer printing\n if not fetch:\n columns = columns[\n ((types == 'REAL') | (types == 'INTEGER') | (types == 'TEXT')) & (columns != 'source_id')]\n\n # Query the table\n try:\n id = 'id' if table.lower() == 'sources' else 'source_id'\n data = self.query(\n \"SELECT {} FROM {} WHERE {}={}\".format(','.join(columns), table, id, source_id),\n fmt='table')\n\n if not data and table.lower() == 'sources':\n print(\n 'No source with id {}. Try db.search() to search the database for a source_id.'.format(\n source_id))\n\n except:\n data = None\n\n # If there's data for this table, save it\n if data:\n if fetch:\n data_tables[table] = self.query(\n \"SELECT {} FROM {} WHERE {}={}\".format(','.join(columns), table, id, source_id), \\\n fetch=True, fmt=fmt)\n else:\n data = data[[c.lower() for c in columns]]\n pprint(data, title=table.upper())\n\n else:\n pass\n\n except:\n print('Could not retrieve data from {} table.'.format(table.upper()))\n\n if fetch: return data_tables": 4680, "def parse(self, data, lexer=None, *args, **kwargs):\n \"\"\"Parse the input JSON data string into a python data structure.\n Args:\n data: An input data string\n lexer: An optional ply.lex instance that overrides the default lexer.\n Returns:\n A python dict or list representing the input JSON data.\n \"\"\"\n if lexer is None:\n lexer = self.lexer\n return self.parser.parse(data, lexer=lexer, *args, **kwargs)": 4681, "def coords_from_query(query):\n \"\"\"Transform a query line into a (lng, lat) pair of coordinates.\"\"\"\n try:\n coords = json.loads(query)\n except ValueError:\n vals = re.split(r'[,\\s]+', query.strip())\n coords = [float(v) for v in vals]\n return tuple(coords[:2])": 4682, "def _parse_boolean(value, default=False):\n \"\"\"\n Attempt to cast *value* into a bool, returning *default* if it fails.\n \"\"\"\n if value is None:\n return default\n try:\n return bool(value)\n except ValueError:\n return default": 4683, "def ColumnToIndex (col):\n \"\"\"convert column to index. Eg: ConvertInIndex(\"AB\") = 28\"\"\"\n ndx = 0\n for c in col:\n ndx = ndx * 26 + ord(c.upper()) - 64\n return ndx": 4684, "def smartread(path):\n \"\"\"Read text from file, automatically detect encoding. ``chardet`` required.\n \"\"\"\n with open(path, \"rb\") as f:\n content = f.read()\n result = chardet.detect(content)\n return content.decode(result[\"encoding\"])": 4685, "def get_data():\n \"\"\"\n Currently pretends to talk to an instrument and get back the magnitud\n and phase of the measurement.\n \"\"\"\n\n # pretend we're measuring a noisy resonance at zero\n y = 1.0 / (1.0 + 1j*(n_x.get_value()-0.002)*1000) + _n.random.rand()*0.1\n\n # and that it takes time to do so\n _t.sleep(0.1)\n\n # return mag phase\n return abs(y), _n.angle(y, True)": 4686, "def _restore_seq_field_pickle(checked_class, item_type, data):\n \"\"\"Unpickling function for auto-generated PVec/PSet field types.\"\"\"\n type_ = _seq_field_types[checked_class, item_type]\n return _restore_pickle(type_, data)": 4687, "def save(self, f):\n \"\"\"Save pickled model to file.\"\"\"\n return pickle.dump((self.perceptron.weights, self.tagdict, self.classes, self.clusters), f, protocol=pickle.HIGHEST_PROTOCOL)": 4688, "def puts_err(s='', newline=True, stream=STDERR):\n \"\"\"Prints given string to stderr.\"\"\"\n puts(s, newline, stream)": 4689, "def image_to_texture(image):\n \"\"\"Converts ``vtkImageData`` to a ``vtkTexture``\"\"\"\n vtex = vtk.vtkTexture()\n vtex.SetInputDataObject(image)\n vtex.Update()\n return vtex": 4690, "def write_to_file(file_path, contents, encoding=\"utf-8\"):\n \"\"\"\n Write helper method\n\n :type file_path: str|unicode\n :type contents: str|unicode\n :type encoding: str|unicode\n \"\"\"\n with codecs.open(file_path, \"w\", encoding) as f:\n f.write(contents)": 4691, "def as_dict(self):\n \"\"\"\n Json-serializable dict representation of PhononDos.\n \"\"\"\n return {\"@module\": self.__class__.__module__,\n \"@class\": self.__class__.__name__,\n \"frequencies\": list(self.frequencies),\n \"densities\": list(self.densities)}": 4692, "def is_floating(self):\n \"\"\"Returns whether this is a (non-quantized, real) floating point type.\"\"\"\n return (\n self.is_numpy_compatible and np.issubdtype(self.as_numpy_dtype, np.floating)\n ) or self.base_dtype == bfloat16": 4693, "def hidden_cursor():\n \"\"\"Temporarily hide the terminal cursor.\"\"\"\n if sys.stdout.isatty():\n _LOGGER.debug('Hiding cursor.')\n print('\\x1B[?25l', end='')\n sys.stdout.flush()\n try:\n yield\n finally:\n if sys.stdout.isatty():\n _LOGGER.debug('Showing cursor.')\n print('\\n\\x1B[?25h', end='')\n sys.stdout.flush()": 4694, "def _join_masks_from_masked_array(data):\n \"\"\"Union of masks.\"\"\"\n if not isinstance(data.mask, np.ndarray):\n # workaround to handle mask compressed to single value\n mask = np.empty(data.data.shape, dtype=np.bool)\n mask.fill(data.mask)\n return mask\n mask = data.mask[0].copy()\n for i in range(1, len(data.mask)):\n mask = np.logical_or(mask, data.mask[i])\n return mask[np.newaxis, :, :]": 4695, "def on_property_change(self, name, old_value, new_value):\n \"\"\"\n Called by the instance manager when a component property is modified\n\n :param name: The changed property name\n :param old_value: The previous property value\n :param new_value: The new property value\n \"\"\"\n if self._registration is not None:\n # use the registration to trigger the service event\n self._registration.set_properties({name: new_value})": 4696, "def get_property(self):\n \"\"\"Establishes access of GettableProperty values\"\"\"\n\n scope = self\n\n def fget(self):\n \"\"\"Call the HasProperties _get method\"\"\"\n return self._get(scope.name)\n\n return property(fget=fget, doc=scope.sphinx())": 4697, "def fopen(name, mode='r', buffering=-1):\n \"\"\"Similar to Python's built-in `open()` function.\"\"\"\n f = _fopen(name, mode, buffering)\n return _FileObjectThreadWithContext(f, mode, buffering)": 4698, "def win32_refresh_window(cls):\n \"\"\"\n Call win32 API to refresh the whole Window.\n\n This is sometimes necessary when the application paints background\n for completion menus. When the menu disappears, it leaves traces due\n to a bug in the Windows Console. Sending a repaint request solves it.\n \"\"\"\n # Get console handle\n handle = windll.kernel32.GetConsoleWindow()\n\n RDW_INVALIDATE = 0x0001\n windll.user32.RedrawWindow(handle, None, None, c_uint(RDW_INVALIDATE))": 4699, "def represented_args(args, separator=\" \"):\n \"\"\"\n Args:\n args (list | tuple | None): Arguments to represent\n separator (str | unicode): Separator to use\n\n Returns:\n (str): Quoted as needed textual representation\n \"\"\"\n result = []\n if args:\n for text in args:\n result.append(quoted(short(text)))\n return separator.join(result)": 4700, "def err(msg):\n \"\"\"Pretty-print an error.\"\"\"\n click.echo(click.style(msg, fg=\"red\", bold=True))": 4701, "async def power(source, exponent):\n \"\"\"Raise the elements of an asynchronous sequence to the given power.\"\"\"\n async with streamcontext(source) as streamer:\n async for item in streamer:\n yield item ** exponent": 4702, "def startEdit( self ):\n \"\"\"\n Rebuilds the pathing based on the parts.\n \"\"\"\n self._originalText = self.text()\n self.scrollWidget().hide()\n self.setFocus()\n self.selectAll()": 4703, "def _clean_workers(self):\n \"\"\"Delete periodically workers in workers bag.\"\"\"\n while self._bag_collector:\n self._bag_collector.popleft()\n self._timer_worker_delete.stop()": 4704, "def attach_to_container(self, container_id):\n \"\"\" A socket attached to the stdin/stdout of a container. The object returned contains a get_socket() function to get a socket.socket\n object and close_socket() to close the connection \"\"\"\n sock = self._docker.containers.get(container_id).attach_socket(params={\n 'stdin': 1,\n 'stdout': 1,\n 'stderr': 0,\n 'stream': 1,\n })\n # fix a problem with docker-py; we must keep a reference of sock at every time\n return FixDockerSocket(sock)": 4705, "def save_list(key, *values):\n \"\"\"Convert the given list of parameters to a JSON object.\n\n JSON object is of the form:\n { key: [values[0], values[1], ... ] },\n where values represent the given list of parameters.\n\n \"\"\"\n return json.dumps({key: [_get_json(value) for value in values]})": 4706, "def validate(schema, data, owner=None):\n \"\"\"Validate input data with input schema.\n\n :param Schema schema: schema able to validate input data.\n :param data: data to validate.\n :param Schema owner: input schema parent schema.\n :raises: Exception if the data is not validated.\n \"\"\"\n schema._validate(data=data, owner=owner)": 4707, "def make_key(self, key, version=None):\n \"\"\"RedisCache will set prefix+version as prefix for each key.\"\"\"\n return '{}:{}:{}'.format(\n self.prefix,\n version or self.version,\n key,\n )": 4708, "def confusion_matrix(links_true, links_pred, total=None):\n \"\"\"Compute the confusion matrix.\n\n The confusion matrix is of the following form:\n\n +----------------------+-----------------------+----------------------+\n | | Predicted Positives | Predicted Negatives |\n +======================+=======================+======================+\n | **True Positives** | True Positives (TP) | False Negatives (FN) |\n +----------------------+-----------------------+----------------------+\n | **True Negatives** | False Positives (FP) | True Negatives (TN) |\n +----------------------+-----------------------+----------------------+\n\n The confusion matrix is an informative way to analyse a prediction. The\n matrix can used to compute measures like precision and recall. The count\n of true prositives is [0,0], false negatives is [0,1], true negatives\n is [1,1] and false positives is [1,0].\n\n Parameters\n ----------\n links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series\n The true (or actual) links.\n links_pred: pandas.MultiIndex, pandas.DataFrame, pandas.Series\n The predicted links.\n total: int, pandas.MultiIndex\n The count of all record pairs (both links and non-links). When the\n argument is a pandas.MultiIndex, the length of the index is used. If\n the total is None, the number of True Negatives is not computed.\n Default None.\n\n Returns\n -------\n numpy.array\n The confusion matrix with TP, TN, FN, FP values.\n\n Note\n ----\n The number of True Negatives is computed based on the total argument.\n This argument is the number of record pairs of the entire matrix.\n\n \"\"\"\n\n links_true = _get_multiindex(links_true)\n links_pred = _get_multiindex(links_pred)\n\n tp = true_positives(links_true, links_pred)\n fp = false_positives(links_true, links_pred)\n fn = false_negatives(links_true, links_pred)\n\n if total is None:\n tn = numpy.nan\n else:\n tn = true_negatives(links_true, links_pred, total)\n\n return numpy.array([[tp, fn], [fp, tn]])": 4709, "def lpush(self, key, *args):\n \"\"\"Emulate lpush.\"\"\"\n redis_list = self._get_list(key, 'LPUSH', create=True)\n\n # Creates the list at this key if it doesn't exist, and appends args to its beginning\n args_reversed = [self._encode(arg) for arg in args]\n args_reversed.reverse()\n updated_list = args_reversed + redis_list\n self.redis[self._encode(key)] = updated_list\n\n # Return the length of the list after the push operation\n return len(updated_list)": 4710, "def connect(self):\n \"\"\"\n Connects to publisher\n \"\"\"\n self.client = redis.Redis(\n host=self.host, port=self.port, password=self.password)": 4711, "def __init__(self, node_def, op, message):\n \"\"\"Creates an `InvalidArgumentError`.\"\"\"\n super(InvalidArgumentError, self).__init__(\n node_def, op, message, INVALID_ARGUMENT\n )": 4712, "def substitute(dict_, source):\n \"\"\" Perform re.sub with the patterns in the given dict\n Args:\n dict_: {pattern: repl}\n source: str\n \"\"\"\n d_esc = (re.escape(k) for k in dict_.keys())\n pattern = re.compile('|'.join(d_esc))\n return pattern.sub(lambda x: dict_[x.group()], source)": 4713, "def parse_scale(x):\n \"\"\"Splits a \"%s:%d\" string and returns the string and number.\n\n :return: A ``(string, int)`` pair extracted from ``x``.\n\n :raise ValueError: the string ``x`` does not respect the input format.\n \"\"\"\n match = re.match(r'^(.+?):(\\d+)$', x)\n if not match:\n raise ValueError('Invalid scale \"%s\".' % x)\n return match.group(1), int(match.group(2))": 4714, "def read_raw(data_path):\n \"\"\"\n Parameters\n ----------\n data_path : str\n \"\"\"\n with open(data_path, 'rb') as f:\n data = pickle.load(f)\n return data": 4715, "def _series_col_letter(self, series):\n \"\"\"\n The letter of the Excel worksheet column in which the data for a\n series appears.\n \"\"\"\n column_number = 1 + series.categories.depth + series.index\n return self._column_reference(column_number)": 4716, "def __del__(self):\n \"\"\"Cleans up the file entry.\"\"\"\n # __del__ can be invoked before __init__ has completed.\n if hasattr(self, '_encoded_stream'):\n self._encoded_stream.close()\n self._encoded_stream = None\n\n super(EncodedStreamFileEntry, self).__del__()": 4717, "def slugify(s, delimiter='-'):\n \"\"\"\n Normalize `s` into ASCII and replace non-word characters with `delimiter`.\n \"\"\"\n s = unicodedata.normalize('NFKD', to_unicode(s)).encode('ascii', 'ignore').decode('ascii')\n return RE_SLUG.sub(delimiter, s).strip(delimiter).lower()": 4718, "def dict_keys_without_hyphens(a_dict):\n \"\"\"Return the a new dict with underscores instead of hyphens in keys.\"\"\"\n return dict(\n (key.replace('-', '_'), val) for key, val in a_dict.items())": 4719, "def _preprocess(df):\n \"\"\"\n given a DataFrame where records are stored row-wise, rearrange it\n such that records are stored column-wise.\n \"\"\"\n\n df = df.stack()\n\n df.index.rename([\"id\", \"time\"], inplace=True) # .reset_index()\n df.name = \"value\"\n df = df.reset_index()\n\n return df": 4720, "def template_substitute(text, **kwargs):\n \"\"\"\n Replace placeholders in text by using the data mapping.\n Other placeholders that is not represented by data is left untouched.\n\n :param text: Text to search and replace placeholders.\n :param data: Data mapping/dict for placeholder key and values.\n :return: Potentially modified text with replaced placeholders.\n \"\"\"\n for name, value in kwargs.items():\n placeholder_pattern = \"{%s}\" % name\n if placeholder_pattern in text:\n text = text.replace(placeholder_pattern, value)\n return text": 4721, "def fillna(series_or_arr, missing_value=0.0):\n \"\"\"Fill missing values in pandas objects and numpy arrays.\n\n Arguments\n ---------\n series_or_arr : pandas.Series, numpy.ndarray\n The numpy array or pandas series for which the missing values\n need to be replaced.\n missing_value : float, int, str\n The value to replace the missing value with. Default 0.0.\n\n Returns\n -------\n pandas.Series, numpy.ndarray\n The numpy array or pandas series with the missing values\n filled.\n \"\"\"\n\n if pandas.notnull(missing_value):\n if isinstance(series_or_arr, (numpy.ndarray)):\n series_or_arr[numpy.isnan(series_or_arr)] = missing_value\n else:\n series_or_arr.fillna(missing_value, inplace=True)\n\n return series_or_arr": 4722, "def reset_namespace(self):\n \"\"\"Resets the namespace by removing all names defined by the user\"\"\"\n self.shellwidget.reset_namespace(warning=self.reset_warning,\n message=True)": 4723, "def input_yn(conf_mess):\n \"\"\"Print Confirmation Message and Get Y/N response from user.\"\"\"\n ui_erase_ln()\n ui_print(conf_mess)\n with term.cbreak():\n input_flush()\n val = input_by_key()\n return bool(val.lower() == 'y')": 4724, "def _send_cmd(self, cmd):\n \"\"\"Write command to remote process\n \"\"\"\n self._process.stdin.write(\"{}\\n\".format(cmd).encode(\"utf-8\"))\n self._process.stdin.flush()": 4725, "def from_rotation_vector(rot):\n \"\"\"Convert input 3-vector in axis-angle representation to unit quaternion\n\n Parameters\n ----------\n rot: (Nx3) float array\n Each vector represents the axis of the rotation, with norm\n proportional to the angle of the rotation in radians.\n\n Returns\n -------\n q: array of quaternions\n Unit quaternions resulting in rotations corresponding to input\n rotations. Output shape is rot.shape[:-1].\n\n \"\"\"\n rot = np.array(rot, copy=False)\n quats = np.zeros(rot.shape[:-1]+(4,))\n quats[..., 1:] = rot[...]/2\n quats = as_quat_array(quats)\n return np.exp(quats)": 4726, "def rq_job(self):\n \"\"\"The last RQ Job this ran on\"\"\"\n if not self.rq_id or not self.rq_origin:\n return\n try:\n return RQJob.fetch(self.rq_id, connection=get_connection(self.rq_origin))\n except NoSuchJobError:\n return": 4727, "def set_sig_figs(n=4):\n \"\"\"Set the number of significant figures used to print Pint, Pandas, and\n NumPy quantities.\n\n Args:\n n (int): Number of significant figures to display.\n \"\"\"\n u.default_format = '.' + str(n) + 'g'\n pd.options.display.float_format = ('{:,.' + str(n) + '}').format": 4728, "def _chunks(l, n):\n \"\"\" Yield successive n-sized chunks from l.\n\n http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python\n \"\"\"\n for i in xrange(0, len(l), n):\n yield l[i:i+n]": 4729, "def run_hive_script(script):\n \"\"\"\n Runs the contents of the given script in hive and returns stdout.\n \"\"\"\n if not os.path.isfile(script):\n raise RuntimeError(\"Hive script: {0} does not exist.\".format(script))\n return run_hive(['-f', script])": 4730, "def dump_to_log(self, logger):\n \"\"\"Send the cmd info and collected stdout to logger.\"\"\"\n logger.error(\"Execution ended in %s for cmd %s\", self._retcode, self._cmd)\n for line in self._collected_stdout:\n logger.error(STDOUT_LOG_PREFIX + line)": 4731, "def set_file_mtime(path, mtime, atime=None):\n \"\"\"Set access and modification times on a file.\"\"\"\n if not atime:\n atime = mtime\n f = open(path, 'a')\n try:\n os.utime(path, (atime, mtime))\n finally:\n f.close()": 4732, "def print_verbose(*args, **kwargs):\n \"\"\"Utility to print something only if verbose=True is given\n \"\"\"\n if kwargs.pop('verbose', False) is True:\n gprint(*args, **kwargs)": 4733, "def clean_colnames(df):\n \"\"\" Cleans the column names on a DataFrame\n Parameters:\n df - DataFrame\n The DataFrame to clean\n \"\"\"\n col_list = []\n for index in range(_dutils.cols(df)):\n col_list.append(df.columns[index].strip().lower().replace(' ','_'))\n df.columns = col_list": 4734, "def trapz2(f, x=None, y=None, dx=1.0, dy=1.0):\n \"\"\"Double integrate.\"\"\"\n return numpy.trapz(numpy.trapz(f, x=y, dx=dy), x=x, dx=dx)": 4735, "def set_attr(self, name, value):\n \"\"\" Sets the value of an attribute. \"\"\"\n self.exec_script(\"node.setAttribute(%s, %s)\" % (repr(name), repr(value)))": 4736, "def _set_tab_width(self, tab_width):\n \"\"\" Sets the width (in terms of space characters) for tab characters.\n \"\"\"\n font_metrics = QtGui.QFontMetrics(self.font)\n self._control.setTabStopWidth(tab_width * font_metrics.width(' '))\n\n self._tab_width = tab_width": 4737, "def get_shape_mask(self, shape_obj):\n \"\"\"\n Return full mask where True marks pixels within the given shape.\n \"\"\"\n wd, ht = self.get_size()\n yi = np.mgrid[:ht].reshape(-1, 1)\n xi = np.mgrid[:wd].reshape(1, -1)\n pts = np.asarray((xi, yi)).T\n contains = shape_obj.contains_pts(pts)\n return contains": 4738, "def move(self, x, y):\n \"\"\"Move the virtual cursor.\n\n Args:\n x (int): x-coordinate to place the cursor.\n y (int): y-coordinate to place the cursor.\n\n .. seealso:: :any:`get_cursor`, :any:`print_str`, :any:`write`\n \"\"\"\n self._cursor = self._normalizePoint(x, y)": 4739, "def ignore_comments(iterator):\n \"\"\"\n Strips and filters empty or commented lines.\n \"\"\"\n for line in iterator:\n line = COMMENT_RE.sub('', line)\n line = line.strip()\n if line:\n yield line": 4740, "def include_raw_constructor(self, loader, node):\n \"\"\"\n Called when PyYaml encounters '!include-raw'\n \"\"\"\n\n path = convert_path(node.value)\n\n with open(path, 'r') as f:\n config = f.read()\n\n config = self.inject_include_info(path, config, include_type='include-raw')\n\n self.add_file(path, config)\n\n return config": 4741, "def send(self, *args, **kwargs):\n \"\"\"Writes the passed chunk and flushes it to the client.\"\"\"\n self.write(*args, **kwargs)\n self.flush()": 4742, "def parsePoint(line):\n \"\"\"\n Parse a line of text into an MLlib LabeledPoint object.\n \"\"\"\n values = [float(s) for s in line.split(' ')]\n if values[0] == -1: # Convert -1 labels to 0 for MLlib\n values[0] = 0\n return LabeledPoint(values[0], values[1:])": 4743, "def _file_chunks(self, data, chunk_size):\n \"\"\" Yield compressed chunks from a data array\"\"\"\n for i in xrange(0, len(data), chunk_size):\n yield self.compressor(data[i:i+chunk_size])": 4744, "def update(table, values, where=(), **kwargs):\n \"\"\"Convenience wrapper for database UPDATE.\"\"\"\n where = dict(where, **kwargs).items()\n sql, args = makeSQL(\"UPDATE\", table, values=values, where=where)\n return execute(sql, args).rowcount": 4745, "def get_least_distinct_words(vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n=None):\n \"\"\"\n Order the words from `vocab` by \"distinctiveness score\" (Chuang et al. 2012) from least to most distinctive.\n Optionally only return the `n` least distinctive words.\n\n J. Chuang, C. Manning, J. Heer 2012: \"Termite: Visualization Techniques for Assessing Textual Topic Models\"\n \"\"\"\n return _words_by_distinctiveness_score(vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n,\n least_to_most=True)": 4746, "def delete(self, key_name):\n \"\"\"Delete the key and return true if the key was deleted, else false\n \"\"\"\n self.db.remove(Query().name == key_name)\n return self.get(key_name) == {}": 4747, "def teardown(self):\n \"\"\"Cleanup cache tables.\"\"\"\n for table_spec in reversed(self._table_specs):\n with self._conn:\n table_spec.teardown(self._conn)": 4748, "def show_intro(self):\n \"\"\"Show intro to IPython help\"\"\"\n from IPython.core.usage import interactive_usage\n self.main.help.show_rich_text(interactive_usage)": 4749, "def is_array(self, key):\n \"\"\"Return True if variable is a numpy array\"\"\"\n data = self.model.get_data()\n return isinstance(data[key], (ndarray, MaskedArray))": 4750, "def stop(self):\n \"\"\"Stop the resolver threads.\n \"\"\"\n with self.lock:\n for dummy in self.threads:\n self.queue.put(None)": 4751, "def _date_to_json(value):\n \"\"\"Coerce 'value' to an JSON-compatible representation.\"\"\"\n if isinstance(value, datetime.date):\n value = value.isoformat()\n return value": 4752, "def _insert_row(self, i, index):\n \"\"\"\n Insert a new row in the Series.\n\n :param i: index location to insert\n :param index: index value to insert into the index list\n :return: nothing\n \"\"\"\n if i == len(self._index):\n self._add_row(index)\n else:\n self._index.insert(i, index)\n self._data.insert(i, None)": 4753, "def unpack_from(self, data, offset=0):\n \"\"\"See :func:`~bitstruct.unpack_from()`.\n\n \"\"\"\n\n return tuple([v[1] for v in self.unpack_from_any(data, offset)])": 4754, "def super_lm_tpu_memtest():\n \"\"\"Crazy set of hyperparameters to test memory optimizations.\n\n Quality will be very poor due to lack of attention layers.\n 853M parameters\n This seems to run on TPU for languagemodel_lm1b8k_packed as of 2018-01-19.\n\n Returns:\n An hparams object.\n \"\"\"\n hparams = super_lm_base()\n hparams.num_model_shards = 1\n hparams.layers = \"ffn,\" * 8\n hparams.hidden_size = 4096\n hparams.filter_size = 12000\n hparams.batch_size = 512\n return hparams": 4755, "def mod(value, arg):\n \"\"\"Return the modulo value.\"\"\"\n try:\n return valid_numeric(value) % valid_numeric(arg)\n except (ValueError, TypeError):\n try:\n return value % arg\n except Exception:\n return ''": 4756, "def excepthook(self, etype, value, tb):\n \"\"\"One more defense for GUI apps that call sys.excepthook.\n\n GUI frameworks like wxPython trap exceptions and call\n sys.excepthook themselves. I guess this is a feature that\n enables them to keep running after exceptions that would\n otherwise kill their mainloop. This is a bother for IPython\n which excepts to catch all of the program exceptions with a try:\n except: statement.\n\n Normally, IPython sets sys.excepthook to a CrashHandler instance, so if\n any app directly invokes sys.excepthook, it will look to the user like\n IPython crashed. In order to work around this, we can disable the\n CrashHandler and replace it with this excepthook instead, which prints a\n regular traceback using our InteractiveTB. In this fashion, apps which\n call sys.excepthook will generate a regular-looking exception from\n IPython, and the CrashHandler will only be triggered by real IPython\n crashes.\n\n This hook should be used sparingly, only in places which are not likely\n to be true IPython errors.\n \"\"\"\n self.showtraceback((etype,value,tb),tb_offset=0)": 4757, "def if_(*args):\n \"\"\"Implements the 'if' operator with support for multiple elseif-s.\"\"\"\n for i in range(0, len(args) - 1, 2):\n if args[i]:\n return args[i + 1]\n if len(args) % 2:\n return args[-1]\n else:\n return None": 4758, "def compute_jaccard_index(x_set, y_set):\n \"\"\"Return the Jaccard similarity coefficient of 2 given sets.\n\n Args:\n x_set (set): first set.\n y_set (set): second set.\n\n Returns:\n float: Jaccard similarity coefficient.\n\n \"\"\"\n if not x_set or not y_set:\n return 0.0\n\n intersection_cardinal = len(x_set & y_set)\n union_cardinal = len(x_set | y_set)\n\n return intersection_cardinal / float(union_cardinal)": 4759, "def inverse_jacobian(self, maps):\n \"\"\"Returns the Jacobian for transforming mass1 and mass2 to\n mchirp and eta.\n \"\"\"\n m1 = maps[parameters.mass1]\n m2 = maps[parameters.mass2]\n mchirp = conversions.mchirp_from_mass1_mass2(m1, m2)\n eta = conversions.eta_from_mass1_mass2(m1, m2)\n return -1. * mchirp / eta**(6./5)": 4760, "def dimension_size(x, axis):\n \"\"\"Returns the size of a specific dimension.\"\"\"\n # Since tf.gather isn't \"constant-in, constant-out\", we must first check the\n # static shape or fallback to dynamic shape.\n s = tf.compat.dimension_value(\n tensorshape_util.with_rank_at_least(x.shape, np.abs(axis))[axis])\n if s is not None:\n return s\n return tf.shape(input=x)[axis]": 4761, "def encode_to_shape(inputs, shape, scope):\n \"\"\"Encode the given tensor to given image shape.\"\"\"\n with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n w, h = shape[1], shape[2]\n x = inputs\n x = tfl.flatten(x)\n x = tfl.dense(x, w * h, activation=None, name=\"enc_dense\")\n x = tf.reshape(x, (-1, w, h, 1))\n return x": 4762, "def load_parameters(self, source):\n \"\"\"For JSON, the source it the file path\"\"\"\n with open(source) as parameters_source:\n return json.loads(parameters_source.read())": 4763, "def list(self,table, **kparams):\n \"\"\"\n get a collection of records by table name.\n returns a dict (the json map) for python 3.4\n \"\"\"\n result = self.table_api_get(table, **kparams)\n return self.to_records(result, table)": 4764, "def join(self):\n \"\"\"Joins the coordinator thread and all worker threads.\"\"\"\n for thread in self.worker_threads:\n thread.join()\n WorkerThread.join(self)": 4765, "def timedelta_seconds(timedelta):\n \"\"\"Returns the total timedelta duration in seconds.\"\"\"\n return (timedelta.total_seconds() if hasattr(timedelta, \"total_seconds\")\n else timedelta.days * 24 * 3600 + timedelta.seconds +\n timedelta.microseconds / 1000000.)": 4766, "def clean(self):\n \"\"\"Return a copy of this Text instance with invalid characters removed.\"\"\"\n return Text(self.__text_cleaner.clean(self[TEXT]), **self.__kwargs)": 4767, "def load_object_at_path(path):\n \"\"\"Load an object from disk at explicit path\"\"\"\n with open(path, 'r') as f:\n data = _deserialize(f.read())\n return aadict(data)": 4768, "def update_menu(self):\n \"\"\"Update context menu\"\"\"\n self.menu.clear()\n add_actions(self.menu, self.create_context_menu_actions())": 4769, "def show_tip(self, tip=\"\"):\n \"\"\"Show tip\"\"\"\n QToolTip.showText(self.mapToGlobal(self.pos()), tip, self)": 4770, "def setup_environment():\n \"\"\"Set up neccessary environment variables\n\n This appends all path of sys.path to the python path\n so mayapy will find all installed modules.\n We have to make sure, that we use maya libs instead of\n libs of the virtual env. So we insert all the libs for mayapy\n first.\n\n :returns: None\n :rtype: None\n :raises: None\n \"\"\"\n osinter = ostool.get_interface()\n pypath = osinter.get_maya_envpath()\n for p in sys.path:\n pypath = os.pathsep.join((pypath, p))\n os.environ['PYTHONPATH'] = pypath": 4771, "def focusInEvent(self, event):\n \"\"\"Reimplement Qt method to send focus change notification\"\"\"\n self.focus_changed.emit()\n return super(ShellWidget, self).focusInEvent(event)": 4772, "def get_focused_window_sane(self):\n \"\"\"\n Like xdo_get_focused_window, but return the first ancestor-or-self\n window * having a property of WM_CLASS. This allows you to get\n the \"real\" or top-level-ish window having focus rather than something\n you may not expect to be the window having focused.\n\n :param window_ret:\n Pointer to a window where the currently-focused window\n will be stored.\n \"\"\"\n window_ret = window_t(0)\n _libxdo.xdo_get_focused_window_sane(\n self._xdo, ctypes.byref(window_ret))\n return window_ret.value": 4773, "def flush_on_close(self, stream):\n \"\"\"Flush tornado iostream write buffer and prevent further writes.\n\n Returns a future that resolves when the stream is flushed.\n\n \"\"\"\n assert get_thread_ident() == self.ioloop_thread_id\n # Prevent futher writes\n stream.KATCPServer_closing = True\n # Write empty message to get future that resolves when buffer is flushed\n return stream.write('\\n')": 4774, "def write_json_response(self, response):\n \"\"\" write back json response \"\"\"\n self.write(tornado.escape.json_encode(response))\n self.set_header(\"Content-Type\", \"application/json\")": 4775, "def _ndarray_representer(dumper, data):\n \"\"\"\n\n :param dumper:\n :param data:\n :type data: :class:`numpy.ndarray`\n :return:\n \"\"\"\n mapping = [('object', data.tolist()), ('dtype', data.dtype.name)]\n return dumper.represent_mapping(_NUMPY_ARRAY_TAG, mapping)": 4776, "def tuple(self, var, cast=None, default=NOTSET):\n \"\"\"\n :rtype: tuple\n \"\"\"\n return self.get_value(var, cast=tuple if not cast else (cast,), default=default)": 4777, "def coverage(ctx, opts=\"\"):\n \"\"\"\n Execute all tests (normal and slow) with coverage enabled.\n \"\"\"\n return test(ctx, coverage=True, include_slow=True, opts=opts)": 4778, "def minify(path):\n \"\"\"\n Load a javascript file and minify.\n\n Parameters\n ------------\n path: str, path of resource\n \"\"\"\n\n if 'http' in path:\n data = requests.get(path).content.decode(\n 'ascii', errors='ignore')\n else:\n with open(path, 'rb') as f:\n # some of these assholes use unicode spaces -_-\n data = f.read().decode('ascii',\n errors='ignore')\n # don't re- minify\n if '.min.' in path:\n return data\n\n try:\n return jsmin.jsmin(data)\n except BaseException:\n return data": 4779, "def _upper(val_list):\n \"\"\"\n :param val_list: a list of strings\n :return: a list of upper-cased strings\n \"\"\"\n res = []\n for ele in val_list:\n res.append(ele.upper())\n return res": 4780, "async def write_register(self, address, value, skip_encode=False):\n \"\"\"Write a modbus register.\"\"\"\n await self._request('write_registers', address, value, skip_encode=skip_encode)": 4781, "def with_args(self, *args, **kwargs):\n \"\"\"Declares that the double can only be called with the provided arguments.\n\n :param args: Any positional arguments required for invocation.\n :param kwargs: Any keyword arguments required for invocation.\n \"\"\"\n\n self.args = args\n self.kwargs = kwargs\n self.verify_arguments()\n return self": 4782, "def minify_js(input_files, output_file):\n \"\"\"\n Minifies the input javascript files to the output file.\n\n Output file may be same as input to minify in place.\n\n In debug mode this function just concatenates the files\n without minifying.\n \"\"\"\n from .modules import minify, utils\n\n if not isinstance(input_files, (list, tuple)):\n raise RuntimeError('JS minifier takes a list of input files.')\n\n return {\n 'dependencies_fn': utils.no_dependencies,\n 'compiler_fn': minify.minify_js,\n 'input': input_files,\n 'output': output_file,\n 'kwargs': {},\n }": 4783, "def get_img_data(f, maxsize = (1200, 850), first = False):\n \"\"\"Generate image data using PIL\n \"\"\"\n img = Image.open(f)\n img.thumbnail(maxsize)\n if first: # tkinter is inactive the first time\n bio = io.BytesIO()\n img.save(bio, format = \"PNG\")\n del img\n return bio.getvalue()\n return ImageTk.PhotoImage(img)": 4784, "def serve(application, host='127.0.0.1', port=8080, threads=4, **kw):\n\t\"\"\"The recommended development HTTP server.\n\t\n\tNote that this server performs additional buffering and will not honour chunked encoding breaks.\n\t\"\"\"\n\t\n\t# Bind and start the server; this is a blocking process.\n\tserve_(application, host=host, port=int(port), threads=int(threads), **kw)": 4785, "def run_migration(connection, queries, engine):\n \"\"\" Apply a migration to the SQL server \"\"\"\n\n # Execute query\n with connection.cursor() as cursorMig:\n # Parse statements\n queries = parse_statements(queries, engine)\n\n for query in queries:\n cursorMig.execute(query)\n connection.commit()\n\n return True": 4786, "def LogBinomialCoef(n, k):\n \"\"\"Computes the log of the binomial coefficient.\n\n http://math.stackexchange.com/questions/64716/\n approximating-the-logarithm-of-the-binomial-coefficient\n\n n: number of trials\n k: number of successes\n\n Returns: float\n \"\"\"\n return n * log(n) - k * log(k) - (n - k) * log(n - k)": 4787, "def clean_text_by_sentences(text, language=\"english\", additional_stopwords=None):\n \"\"\" Tokenizes a given text into sentences, applying filters and lemmatizing them.\n Returns a SyntacticUnit list. \"\"\"\n init_textcleanner(language, additional_stopwords)\n original_sentences = split_sentences(text)\n filtered_sentences = filter_words(original_sentences)\n\n return merge_syntactic_units(original_sentences, filtered_sentences)": 4788, "def return_future(fn):\n \"\"\"Decorator that turns a synchronous function into one returning a future.\n\n This should only be applied to non-blocking functions. Will do set_result()\n with the return value, or set_exc_info() if an exception is raised.\n\n \"\"\"\n @wraps(fn)\n def decorated(*args, **kwargs):\n return gen.maybe_future(fn(*args, **kwargs))\n\n return decorated": 4789, "def neo(graph: BELGraph, connection: str, password: str):\n \"\"\"Upload to neo4j.\"\"\"\n import py2neo\n neo_graph = py2neo.Graph(connection, password=password)\n to_neo4j(graph, neo_graph)": 4790, "def has_next_async(self):\n \"\"\"Return a Future whose result will say whether a next item is available.\n\n See the module docstring for the usage pattern.\n \"\"\"\n if self._fut is None:\n self._fut = self._iter.getq()\n flag = True\n try:\n yield self._fut\n except EOFError:\n flag = False\n raise tasklets.Return(flag)": 4791, "def WritePythonFile(file_descriptor, package, version, printer):\n \"\"\"Write the given extended file descriptor to out.\"\"\"\n _WriteFile(file_descriptor, package, version,\n _ProtoRpcPrinter(printer))": 4792, "def dumps(obj, indent=None, default=None, sort_keys=False, **kw):\n \"\"\"Dump string.\"\"\"\n return YAMLEncoder(indent=indent, default=default, sort_keys=sort_keys, **kw).encode(obj)": 4793, "def close_session(self):\n \"\"\" Close tensorflow session. Exposes for memory management. \"\"\"\n with self._graph.as_default():\n self._sess.close()\n self._sess = None": 4794, "def scale_min(im, targ, interpolation=cv2.INTER_AREA):\n \"\"\" Scale the image so that the smallest axis is of size targ.\n\n Arguments:\n im (array): image\n targ (int): target size\n \"\"\"\n r,c,*_ = im.shape\n ratio = targ/min(r,c)\n sz = (scale_to(c, ratio, targ), scale_to(r, ratio, targ))\n return cv2.resize(im, sz, interpolation=interpolation)": 4795, "def json_pretty_dump(obj, filename):\n \"\"\"\n Serialize obj as a JSON formatted stream to the given filename (\n pretty printing version)\n \"\"\"\n with open(filename, \"wt\") as fh:\n json.dump(obj, fh, indent=4, sort_keys=4)": 4796, "def dump(self, *args, **kwargs):\n \"\"\"Dumps a representation of the Model on standard output.\"\"\"\n lxml.etree.dump(self._obj, *args, **kwargs)": 4797, "def parse(text, showToc=True):\n\t\"\"\"Returns HTML from MediaWiki markup\"\"\"\n\tp = Parser(show_toc=showToc)\n\treturn p.parse(text)": 4798, "def clearImg(self):\n \"\"\"Clears the current image\"\"\"\n self.img.setImage(np.array([[0]]))\n self.img.image = None": 4799, "def sql(self, sql: str, *qmark_params, **named_params):\n \"\"\"\n :deprecated: use self.statement to execute properly-formatted sql statements\n \"\"\"\n statement = SingleSqlStatement(sql)\n return self.statement(statement).execute(*qmark_params, **named_params)": 4800, "def trigger_installed(connection: connection, table: str, schema: str='public'):\n \"\"\"Test whether or not a psycopg2-pgevents trigger is installed for a table.\n\n Parameters\n ----------\n connection: psycopg2.extensions.connection\n Active connection to a PostGreSQL database.\n table: str\n Table whose trigger-existence will be checked.\n schema: str\n Schema to which the table belongs.\n\n Returns\n -------\n bool\n True if the trigger is installed, otherwise False.\n\n \"\"\"\n installed = False\n\n log('Checking if {}.{} trigger installed...'.format(schema, table), logger_name=_LOGGER_NAME)\n\n statement = SELECT_TRIGGER_STATEMENT.format(\n table=table,\n schema=schema\n )\n\n result = execute(connection, statement)\n if result:\n installed = True\n\n log('...{}installed'.format('' if installed else 'NOT '), logger_name=_LOGGER_NAME)\n\n return installed": 4801, "def stack_as_string():\n \"\"\"\n stack_as_string\n \"\"\"\n if sys.version_info.major == 3:\n stack = io.StringIO()\n else:\n stack = io.BytesIO()\n\n traceback.print_stack(file=stack)\n stack.seek(0)\n stack = stack.read()\n return stack": 4802, "def is_standalone(self):\n \"\"\"Return True if Glances is running in standalone mode.\"\"\"\n return (not self.args.client and\n not self.args.browser and\n not self.args.server and\n not self.args.webserver)": 4803, "def reload(self, save_config=True):\n \"\"\"Reload the device.\n\n !!!WARNING! there is unsaved configuration!!!\n This command will reboot the system. (y/n)? [n]\n \"\"\"\n if save_config:\n self.device.send(\"copy running-config startup-config\")\n self.device(\"reload\", wait_for_string=\"This command will reboot the system\")\n self.device.ctrl.sendline(\"y\")": 4804, "def addfield(self, pkt, buf, val):\n \"\"\"add the field with endianness to the buffer\"\"\"\n self.set_endianess(pkt)\n return self.fld.addfield(pkt, buf, val)": 4805, "def MessageToDict(message,\n including_default_value_fields=False,\n preserving_proto_field_name=False):\n \"\"\"Converts protobuf message to a JSON dictionary.\n\n Args:\n message: The protocol buffers message instance to serialize.\n including_default_value_fields: If True, singular primitive fields,\n repeated fields, and map fields will always be serialized. If\n False, only serialize non-empty fields. Singular message fields\n and oneof fields are not affected by this option.\n preserving_proto_field_name: If True, use the original proto field\n names as defined in the .proto file. If False, convert the field\n names to lowerCamelCase.\n\n Returns:\n A dict representation of the JSON formatted protocol buffer message.\n \"\"\"\n printer = _Printer(including_default_value_fields,\n preserving_proto_field_name)\n # pylint: disable=protected-access\n return printer._MessageToJsonObject(message)": 4806, "def have_pyrex():\n \"\"\"\n Return True if Cython or Pyrex can be imported.\n \"\"\"\n pyrex_impls = 'Cython.Distutils.build_ext', 'Pyrex.Distutils.build_ext'\n for pyrex_impl in pyrex_impls:\n try:\n # from (pyrex_impl) import build_ext\n __import__(pyrex_impl, fromlist=['build_ext']).build_ext\n return True\n except Exception:\n pass\n return False": 4807, "def reverse_transform(self, col):\n \"\"\"Converts data back into original format.\n\n Args:\n col(pandas.DataFrame): Data to transform.\n\n Returns:\n pandas.DataFrame\n \"\"\"\n\n output = pd.DataFrame()\n output[self.col_name] = self.get_category(col[self.col_name])\n\n return output": 4808, "def columnclean(column):\n \"\"\"\n Modifies column header format to be importable into a database\n :param column: raw column header\n :return: cleanedcolumn: reformatted column header\n \"\"\"\n cleanedcolumn = str(column) \\\n .replace('%', 'percent') \\\n .replace('(', '_') \\\n .replace(')', '') \\\n .replace('As', 'Adenosines') \\\n .replace('Cs', 'Cytosines') \\\n .replace('Gs', 'Guanines') \\\n .replace('Ts', 'Thymines') \\\n .replace('Ns', 'Unknowns') \\\n .replace('index', 'adapterIndex')\n return cleanedcolumn": 4809, "def strip_tweet(text, remove_url=True):\n \"\"\"Strip tweet message.\n\n This method removes mentions strings and urls(optional).\n\n :param text: tweet message\n :type text: :class:`str`\n\n :param remove_url: Remove urls. default :const:`True`.\n :type remove_url: :class:`boolean`\n\n :returns: Striped tweet message\n :rtype: :class:`str`\n\n \"\"\"\n if remove_url:\n text = url_pattern.sub('', text)\n else:\n text = expand_url(text)\n text = mention_pattern.sub('', text)\n text = html_parser.unescape(text)\n text = text.strip()\n return text": 4810, "def makeBiDirectional(d):\n \"\"\"\n Helper for generating tagNameConverter\n Makes dict that maps from key to value and back\n \"\"\"\n dTmp = d.copy()\n for k in d:\n dTmp[d[k]] = k\n return dTmp": 4811, "def fillScreen(self, color=None):\n \"\"\"Fill the matrix with the given RGB color\"\"\"\n md.fill_rect(self.set, 0, 0, self.width, self.height, color)": 4812, "def __unroll(self, rolled):\n \"\"\"Converts parameter matrices into an array.\"\"\"\n return np.array(np.concatenate([matrix.flatten() for matrix in rolled], axis=1)).reshape(-1)": 4813, "def downgrade():\n \"\"\"Downgrade database.\"\"\"\n op.drop_table('transaction')\n if op._proxy.migration_context.dialect.supports_sequences:\n op.execute(DropSequence(Sequence('transaction_id_seq')))": 4814, "def iparallel_progbar(mapper, iterable, nprocs=None, starmap=False, flatmap=False, shuffle=False,\n verbose=True, verbose_flatmap=None, max_cache=-1, **kwargs):\n \"\"\"Performs a parallel mapping of the given iterable, reporting a progress bar as values get returned. Yields\n objects as soon as they're computed, but does not guarantee that they'll be in the correct order.\n\n :param mapper: The mapping function to apply to elements of the iterable\n :param iterable: The iterable to map\n :param nprocs: The number of processes (defaults to the number of cpu's)\n :param starmap: If true, the iterable is expected to contain tuples and the mapper function gets each element of a\n tuple as an argument\n :param flatmap: If true, flatten out the returned values if the mapper function returns a list of objects\n :param shuffle: If true, randomly sort the elements before processing them. This might help provide more uniform\n runtimes if processing different objects takes different amounts of time.\n :param verbose: Whether or not to print the progress bar\n :param verbose_flatmap: If performing a flatmap, whether or not to report each object as it's returned\n :param max_cache: Maximum number of mapped objects to permit in the queue at once\n :param kwargs: Any other keyword arguments to pass to the progress bar (see ``progbar``)\n :return: A list of the returned objects, in whatever order they're done being computed\n \"\"\"\n\n results = _parallel_progbar_launch(mapper, iterable, nprocs, starmap, flatmap, shuffle, verbose,\n verbose_flatmap, max_cache, **kwargs)\n return (x for i, x in results)": 4815, "def resource_property(klass, name, **kwargs):\n \"\"\"Builds a resource object property.\"\"\"\n klass.PROPERTIES[name] = kwargs\n\n def getter(self):\n return getattr(self, '_%s' % name, kwargs.get('default', None))\n\n if kwargs.get('readonly', False):\n setattr(klass, name, property(getter))\n else:\n def setter(self, value):\n setattr(self, '_%s' % name, value)\n setattr(klass, name, property(getter, setter))": 4816, "def get_single_file_info(self, rel_path):\n \"\"\" Gets last change time for a single file \"\"\"\n\n f_path = self.get_full_file_path(rel_path)\n return get_single_file_info(f_path, rel_path)": 4817, "def __len__(self):\n\t\t\"\"\"Get a list of the public data attributes.\"\"\"\n\t\treturn len([i for i in (set(dir(self)) - self._STANDARD_ATTRS) if i[0] != '_'])": 4818, "def str2bool(value):\n \"\"\"Parse Yes/No/Default string\n https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse\"\"\"\n if value.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n if value.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n if value.lower() in ('d', 'default', ''):\n return None\n raise argparse.ArgumentTypeError('Expected: (Y)es/(T)rue/(N)o/(F)alse/(D)efault')": 4819, "def add_option(self, *args, **kwargs):\n \"\"\"Add optparse or argparse option depending on CmdHelper initialization.\"\"\"\n if self.parseTool == 'argparse':\n if args and args[0] == '': # no short option\n args = args[1:]\n return self.parser.add_argument(*args, **kwargs)\n else:\n return self.parser.add_option(*args, **kwargs)": 4820, "async def unignore_all(self, ctx):\n \"\"\"Unignores all channels in this server from being processed.\n\n To use this command you must have the Manage Channels permission or have the\n Bot Admin role.\n \"\"\"\n channels = [c for c in ctx.message.server.channels if c.type is discord.ChannelType.text]\n await ctx.invoke(self.unignore, *channels)": 4821, "def async_update(self, event):\n \"\"\"New event for light.\n\n Check that state is part of event.\n Signal that light has updated state.\n \"\"\"\n self.update_attr(event.get('state', {}))\n super().async_update(event)": 4822, "def resize(self):\n \"\"\"\n Get target size for a cropped image and do the resizing if we got\n anything usable.\n \"\"\"\n resized_size = self.get_resized_size()\n if not resized_size:\n return\n\n self.image = self.image.resize(resized_size, Image.ANTIALIAS)": 4823, "def read_full(stream):\n \"\"\"Read the full contents of the given stream into memory.\n\n :return:\n A future containing the complete stream contents.\n \"\"\"\n assert stream, \"stream is required\"\n\n chunks = []\n chunk = yield stream.read()\n\n while chunk:\n chunks.append(chunk)\n chunk = yield stream.read()\n\n raise tornado.gen.Return(b''.join(chunks))": 4824, "def list_to_csv(my_list, csv_file):\n \"\"\"\n Save a matrix (list of lists) to a file as a CSV\n\n .. code:: python\n\n my_list = [[\"Name\", \"Location\"],\n [\"Chris\", \"South Pole\"],\n [\"Harry\", \"Depth of Winter\"],\n [\"Bob\", \"Skull\"]]\n\n reusables.list_to_csv(my_list, \"example.csv\")\n\n example.csv\n\n .. code:: csv\n\n \"Name\",\"Location\"\n \"Chris\",\"South Pole\"\n \"Harry\",\"Depth of Winter\"\n \"Bob\",\"Skull\"\n\n :param my_list: list of lists to save to CSV\n :param csv_file: File to save data to\n \"\"\"\n if PY3:\n csv_handler = open(csv_file, 'w', newline='')\n else:\n csv_handler = open(csv_file, 'wb')\n\n try:\n writer = csv.writer(csv_handler, delimiter=',', quoting=csv.QUOTE_ALL)\n writer.writerows(my_list)\n finally:\n csv_handler.close()": 4825, "def set_xticks_for_all(self, row_column_list=None, ticks=None):\n \"\"\"Manually specify the x-axis tick values.\n\n :param row_column_list: a list containing (row, column) tuples to\n specify the subplots, or None to indicate *all* subplots.\n :type row_column_list: list or None\n :param ticks: list of tick values.\n\n \"\"\"\n if row_column_list is None:\n self.ticks['x'] = ticks\n else:\n for row, column in row_column_list:\n self.set_xticks(row, column, ticks)": 4826, "def optional(self, value = None):\n\t\t\"\"\"Optional\n\n\t\tGetter/Setter method for optional flag\n\n\t\tArgs:\n\t\t\tvalue (bool): If set, the method is a setter\n\n\t\tReturns:\n\t\t\tbool | None\n\t\t\"\"\"\n\n\t\t# If there's no value, this is a getter\n\t\tif value is None:\n\t\t\treturn this._optional\n\n\t\t# Else, set the flag\n\t\telse:\n\t\t\tthis._optional = value and True or False": 4827, "def into2dBlocks(arr, n0, n1):\n \"\"\"\n similar to blockshaped\n but splits an array into n0*n1 blocks\n \"\"\"\n s0, s1 = arr.shape\n b = blockshaped(arr, s0// n0, s1// n1)\n return b.reshape(n0, n1, *b.shape[1:])": 4828, "def libpath(self):\n \"\"\"Returns the full path to the shared *wrapper* library created for the\n module.\n \"\"\"\n from os import path\n return path.join(self.dirpath, self.libname)": 4829, "def RandomShuffle(a, seed):\n \"\"\"\n Random uniform op.\n \"\"\"\n if seed:\n np.random.seed(seed)\n r = a.copy()\n np.random.shuffle(r)\n return r,": 4830, "def day_to_month(timeperiod):\n \"\"\":param timeperiod: as string in YYYYMMDD00 format\n :return string in YYYYMM0000 format\"\"\"\n t = datetime.strptime(timeperiod, SYNERGY_DAILY_PATTERN)\n return t.strftime(SYNERGY_MONTHLY_PATTERN)": 4831, "def get_cached_data(datatable, **kwargs):\n \"\"\" Returns the cached object list under the appropriate key, or None if not set. \"\"\"\n cache_key = '%s%s' % (CACHE_PREFIX, datatable.get_cache_key(**kwargs))\n data = cache.get(cache_key)\n log.debug(\"Reading data from cache at %r: %r\", cache_key, data)\n return data": 4832, "def _process_and_sort(s, force_ascii, full_process=True):\n \"\"\"Return a cleaned string with token sorted.\"\"\"\n # pull tokens\n ts = utils.full_process(s, force_ascii=force_ascii) if full_process else s\n tokens = ts.split()\n\n # sort tokens and join\n sorted_string = u\" \".join(sorted(tokens))\n return sorted_string.strip()": 4833, "def set_primary_key(self, table, column):\n \"\"\"Create a Primary Key constraint on a specific column when the table is already created.\"\"\"\n self.execute('ALTER TABLE {0} ADD PRIMARY KEY ({1})'.format(wrap(table), column))\n self._printer('\\tAdded primary key to {0} on column {1}'.format(wrap(table), column))": 4834, "def is_primary(self):\n \"\"\"``True`` if this is a primary key; ``False`` if this is a subkey\"\"\"\n return isinstance(self._key, Primary) and not isinstance(self._key, Sub)": 4835, "def getCenter(self):\n \"\"\" Return the ``Location`` of the center of this region \"\"\"\n return Location(self.x+(self.w/2), self.y+(self.h/2))": 4836, "def styles(self, dictobj):\n\t\t\"\"\"\n\t\tAdd or update styles\n\t\t\"\"\"\n\t\tfor k in dictobj:\n\t\t\tself.chart_style[k] = dictobj[k]": 4837, "def flipwritable(fn, mode=None):\n \"\"\"\n Flip the writability of a file and return the old mode. Returns None\n if the file is already writable.\n \"\"\"\n if os.access(fn, os.W_OK):\n return None\n old_mode = os.stat(fn).st_mode\n os.chmod(fn, stat.S_IWRITE | old_mode)\n return old_mode": 4838, "def synth_hangul(string):\n \"\"\"Convert jamo characters in a string into hcj as much as possible.\"\"\"\n raise NotImplementedError\n return ''.join([''.join(''.join(jamo_to_hcj(_)) for _ in string)])": 4839, "def equal(x, y):\n \"\"\"\n Return True if x == y and False otherwise.\n\n This function returns False whenever x and/or y is a NaN.\n\n \"\"\"\n x = BigFloat._implicit_convert(x)\n y = BigFloat._implicit_convert(y)\n return mpfr.mpfr_equal_p(x, y)": 4840, "def load_from_file(module_path):\n \"\"\"\n Load a python module from its absolute filesystem path\n\n Borrowed from django-cms\n \"\"\"\n from imp import load_module, PY_SOURCE\n\n imported = None\n if module_path:\n with open(module_path, 'r') as openfile:\n imported = load_module('mod', openfile, module_path, ('imported', 'r', PY_SOURCE))\n return imported": 4841, "def qth_pw(self, q):\n \"\"\"\n returns the qth most probable element in the dawg.\n \"\"\"\n return heapq.nlargest(q + 2, self._T.iteritems(),\n key=operator.itemgetter(1))[-1]": 4842, "def remote_file_exists(self, url):\n \"\"\" Checks whether the remote file exists.\n\n :param url:\n The url that has to be checked.\n :type url:\n String\n\n :returns:\n **True** if remote file exists and **False** if it doesn't exist.\n \"\"\"\n status = requests.head(url).status_code\n\n if status != 200:\n raise RemoteFileDoesntExist": 4843, "def do_last(environment, seq):\n \"\"\"Return the last item of a sequence.\"\"\"\n try:\n return next(iter(reversed(seq)))\n except StopIteration:\n return environment.undefined('No last item, sequence was empty.')": 4844, "def toarray(self):\n \"\"\"Returns the data as numpy.array from each partition.\"\"\"\n rdd = self._rdd.map(lambda x: x.toarray())\n return np.concatenate(rdd.collect())": 4845, "def ishex(obj):\n \"\"\"\n Test if the argument is a string representing a valid hexadecimal digit.\n\n :param obj: Object\n :type obj: any\n\n :rtype: boolean\n \"\"\"\n return isinstance(obj, str) and (len(obj) == 1) and (obj in string.hexdigits)": 4846, "def post_tweet(user_id, message, additional_params={}):\n \"\"\"\n Helper function to post a tweet \n \"\"\"\n url = \"https://api.twitter.com/1.1/statuses/update.json\" \n params = { \"status\" : message }\n params.update(additional_params)\n r = make_twitter_request(url, user_id, params, request_type='POST')\n print (r.text)\n return \"Successfully posted a tweet {}\".format(message)": 4847, "def _config_section(config, section):\n \"\"\"Read the configuration file and return a section.\"\"\"\n path = os.path.join(config.get('config_path'), config.get('config_file'))\n conf = _config_ini(path)\n return conf.get(section)": 4848, "def setConfigKey(key, value):\n\t\t\"\"\"\n\t\tSets the config data value for the specified dictionary key\n\t\t\"\"\"\n\t\tconfigFile = ConfigurationManager._configFile()\n\t\treturn JsonDataManager(configFile).setKey(key, value)": 4849, "def getBitmap(self):\n \"\"\" Captures screen area of this region, at least the part that is on the screen\n\n Returns image as numpy array\n \"\"\"\n return PlatformManager.getBitmapFromRect(self.x, self.y, self.w, self.h)": 4850, "def _removeLru(self):\n \"\"\"\n Remove the least recently used file handle from the cache.\n The pop method removes an element from the right of the deque.\n Returns the name of the file that has been removed.\n \"\"\"\n (dataFile, handle) = self._cache.pop()\n handle.close()\n return dataFile": 4851, "def eval(e, amplitude, e_0, alpha, beta):\n \"\"\"One dimenional log parabola model function\"\"\"\n\n ee = e / e_0\n eeponent = -alpha - beta * np.log(ee)\n return amplitude * ee ** eeponent": 4852, "def visit_ellipsis(self, node, parent):\n \"\"\"visit an Ellipsis node by returning a fresh instance of it\"\"\"\n return nodes.Ellipsis(\n getattr(node, \"lineno\", None), getattr(node, \"col_offset\", None), parent\n )": 4853, "def track_update(self):\n \"\"\"Update the lastest updated date in the database.\"\"\"\n metadata = self.info()\n metadata.updated_at = dt.datetime.now()\n self.commit()": 4854, "def strip_comment_marker(text):\n \"\"\" Strip # markers at the front of a block of comment text.\n \"\"\"\n lines = []\n for line in text.splitlines():\n lines.append(line.lstrip('#'))\n text = textwrap.dedent('\\n'.join(lines))\n return text": 4855, "def is_cyclic(graph):\n \"\"\"\n Return True if the directed graph g has a cycle. The directed graph\n should be represented as a dictionary mapping of edges for each node.\n \"\"\"\n path = set()\n\n def visit(vertex):\n path.add(vertex)\n for neighbour in graph.get(vertex, ()):\n if neighbour in path or visit(neighbour):\n return True\n path.remove(vertex)\n return False\n\n return any(visit(v) for v in graph)": 4856, "def scale_v2(vec, amount):\n \"\"\"Return a new Vec2 with x and y from vec and multiplied by amount.\"\"\"\n\n return Vec2(vec.x * amount, vec.y * amount)": 4857, "def is_adb_detectable(self):\n \"\"\"Checks if USB is on and device is ready by verifying adb devices.\"\"\"\n serials = list_adb_devices()\n if self.serial in serials:\n self.log.debug('Is now adb detectable.')\n return True\n return False": 4858, "def subsystem(s):\n \"\"\"Validate a |Subsystem|.\n\n Checks its state and cut.\n \"\"\"\n node_states(s.state)\n cut(s.cut, s.cut_indices)\n if config.VALIDATE_SUBSYSTEM_STATES:\n state_reachable(s)\n return True": 4859, "def _truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):\n \"\"\"\n Truncates a colormap to use.\n Code originall from http://stackoverflow.com/questions/18926031/how-to-extract-a-subset-of-a-colormap-as-a-new-colormap-in-matplotlib\n \"\"\"\n new_cmap = LinearSegmentedColormap.from_list(\n 'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval),\n cmap(numpy.linspace(minval, maxval, n))\n )\n return new_cmap": 4860, "def _tool_to_dict(tool):\n \"\"\"Parse a tool definition into a cwl2wdl style dictionary.\n \"\"\"\n out = {\"name\": _id_to_name(tool.tool[\"id\"]),\n \"baseCommand\": \" \".join(tool.tool[\"baseCommand\"]),\n \"arguments\": [],\n \"inputs\": [_input_to_dict(i) for i in tool.tool[\"inputs\"]],\n \"outputs\": [_output_to_dict(o) for o in tool.tool[\"outputs\"]],\n \"requirements\": _requirements_to_dict(tool.requirements + tool.hints),\n \"stdin\": None, \"stdout\": None}\n return out": 4861, "def is_instance_or_subclass(val, class_):\n \"\"\"Return True if ``val`` is either a subclass or instance of ``class_``.\"\"\"\n try:\n return issubclass(val, class_)\n except TypeError:\n return isinstance(val, class_)": 4862, "def _compile(pattern, flags):\n \"\"\"Compile the pattern to regex.\"\"\"\n\n return re.compile(WcParse(pattern, flags & FLAG_MASK).parse())": 4863, "def atlasdb_format_query( query, values ):\n \"\"\"\n Turn a query into a string for printing.\n Useful for debugging.\n \"\"\"\n return \"\".join( [\"%s %s\" % (frag, \"'%s'\" % val if type(val) in [str, unicode] else val) for (frag, val) in zip(query.split(\"?\"), values + (\"\",))] )": 4864, "def _compress_obj(obj, level):\n \"\"\"Compress object to bytes.\n \"\"\"\n return zlib.compress(pickle.dumps(obj, protocol=2), level)": 4865, "def loads(string):\n \"\"\"\n Deserializes Java objects and primitive data serialized by ObjectOutputStream\n from a string.\n \"\"\"\n f = StringIO.StringIO(string)\n marshaller = JavaObjectUnmarshaller(f)\n marshaller.add_transformer(DefaultObjectTransformer())\n return marshaller.readObject()": 4866, "def mtf_unitransformer_all_layers_tiny():\n \"\"\"Test out all the layers on local CPU.\"\"\"\n hparams = mtf_unitransformer_tiny()\n hparams.moe_num_experts = 4\n hparams.moe_expert_x = 4\n hparams.moe_expert_y = 4\n hparams.moe_hidden_size = 512\n hparams.layers = [\"self_att\", \"local_self_att\", \"moe_1d\", \"moe_2d\", \"drd\"]\n return hparams": 4867, "def each_img(img_dir):\n \"\"\"\n Reads and iterates through each image file in the given directory\n \"\"\"\n for fname in utils.each_img(img_dir):\n fname = os.path.join(img_dir, fname)\n yield cv.imread(fname), fname": 4868, "def clean(ctx, dry_run=False):\n \"\"\"Cleanup generated document artifacts.\"\"\"\n basedir = ctx.sphinx.destdir or \"build/docs\"\n cleanup_dirs([basedir], dry_run=dry_run)": 4869, "def convert_date(date):\n \"\"\"Convert string to datetime object.\"\"\"\n date = convert_month(date, shorten=False)\n clean_string = convert_string(date)\n return datetime.strptime(clean_string, DATE_FMT.replace('-',''))": 4870, "def __init__(self, xmin=0, ymin=0, xmax=1, ymax=1):\n \"\"\"\n Create the chart bounds with min max horizontal\n and vertical values\n \"\"\"\n self._xmin = xmin\n self._ymin = ymin\n self._xmax = xmax\n self._ymax = ymax": 4871, "def set_attached_console_visible(state):\n \"\"\"Show/hide system console window attached to current process.\n Return it's previous state.\n\n Availability: Windows\"\"\"\n flag = {True: SW_SHOW, False: SW_HIDE}\n return bool(ShowWindow(console_window_handle, flag[state]))": 4872, "def delete_environment(self, environment_name):\n \"\"\"\n Deletes an environment\n \"\"\"\n self.ebs.terminate_environment(environment_name=environment_name, terminate_resources=True)": 4873, "def __delitem__ (self, key):\n \"\"\"Remove key from dict.\"\"\"\n self._keys.remove(key)\n super(ListDict, self).__delitem__(key)": 4874, "def _get_node_path(self, node):\n \"\"\"Return the path from the root to ``node`` as a list of node names.\"\"\"\n path = []\n while node.up:\n path.append(node.name)\n node = node.up\n return list(reversed(path))": 4875, "def map_tree(visitor, tree):\n \"\"\"Apply function to nodes\"\"\"\n newn = [map_tree(visitor, node) for node in tree.nodes]\n return visitor(tree, newn)": 4876, "def scroll_up(self, locator):\n \"\"\"Scrolls up to element\"\"\"\n driver = self._current_application()\n element = self._element_find(locator, True, True)\n driver.execute_script(\"mobile: scroll\", {\"direction\": 'up', 'element': element.id})": 4877, "def _name_exists(self, name):\n \"\"\"\n Checks if we already have an opened tab with the same name.\n \"\"\"\n for i in range(self.count()):\n if self.tabText(i) == name:\n return True\n return False": 4878, "def mask_and_flatten(self):\n \"\"\"Return a vector of the masked data.\n\n Returns\n -------\n np.ndarray, tuple of indices (np.ndarray), tuple of the mask shape\n \"\"\"\n self._check_for_mask()\n\n return self.get_data(smoothed=True, masked=True, safe_copy=False)[self.get_mask_indices()],\\\n self.get_mask_indices(), self.mask.shape": 4879, "def _convert_dict_to_json(array):\n \"\"\" Converts array to a json string \"\"\"\n return json.dumps(\n array,\n skipkeys=False,\n allow_nan=False,\n indent=None,\n separators=(\",\", \":\"),\n sort_keys=True,\n default=lambda o: o.__dict__,\n )": 4880, "async def acquire_async(self):\n \"\"\"Acquire the :attr:`lock` asynchronously\n\n \"\"\"\n r = self.acquire(blocking=False)\n while not r:\n await asyncio.sleep(.01)\n r = self.acquire(blocking=False)": 4881, "def dict_pop_or(d, key, default=None):\n \"\"\" Try popping a key from a dict.\n Instead of raising KeyError, just return the default value.\n \"\"\"\n val = default\n with suppress(KeyError):\n val = d.pop(key)\n return val": 4882, "def update(dct, dct_merge):\n \"\"\"Recursively merge dicts.\"\"\"\n for key, value in dct_merge.items():\n if key in dct and isinstance(dct[key], dict):\n dct[key] = update(dct[key], value)\n else:\n dct[key] = value\n return dct": 4883, "def show(self):\n \"\"\" Ensure the widget is shown.\n Calling this method will also set the widget visibility to True.\n \"\"\"\n self.visible = True\n if self.proxy_is_active:\n self.proxy.ensure_visible()": 4884, "def total_seconds(td):\n \"\"\"convert a timedelta to seconds.\n\n This is patterned after timedelta.total_seconds, which is only\n available in python 27.\n\n Args:\n td: a timedelta object.\n\n Returns:\n total seconds within a timedelta. Rounded up to seconds.\n \"\"\"\n secs = td.seconds + td.days * 24 * 3600\n if td.microseconds:\n secs += 1\n return secs": 4885, "def calculate_delay(original, delay):\n \"\"\"\n Calculate the delay\n \"\"\"\n original = datetime.strptime(original, '%H:%M')\n delayed = datetime.strptime(delay, '%H:%M')\n diff = delayed - original\n return diff.total_seconds() // 60": 4886, "def angle(vec1, vec2):\n \"\"\"Returns the angle between two vectors\"\"\"\n dot_vec = dot(vec1, vec2)\n mag1 = vec1.length()\n mag2 = vec2.length()\n result = dot_vec / (mag1 * mag2)\n return math.acos(result)": 4887, "def convert_ajax_data(self, field_data):\n \"\"\"\n Due to the way Angular organizes it model, when this Form data is sent using Ajax,\n then for this kind of widget, the sent data has to be converted into a format suitable\n for Django's Form validation.\n \"\"\"\n data = [key for key, val in field_data.items() if val]\n return data": 4888, "def get_future_days(self):\n \"\"\"Return only future Day objects.\"\"\"\n today = timezone.now().date()\n\n return Day.objects.filter(date__gte=today)": 4889, "def get_enum_documentation(class_name, module_name, enum_class_object):\n documentation = \"\"\".. _{module_name}.{class_name}:\n\n``enum {class_name}``\n+++++++{plus}++\n\n**module:** ``{module_name}``\"\"\".format(\n module_name=module_name,\n class_name=class_name,\n plus='+' * len(class_name),\n )\n\n if enum_class_object.__doc__ and enum_class_object.__doc__.strip():\n documentation += '\\n\\n{}'.format(_clean_literals(inspect.cleandoc(enum_class_object.__doc__)))\n\n documentation += '\\n\\nConstant Values:\\n'\n for e in enum_class_object:\n documentation += '\\n- ``{}`` (``{}``)'.format(e.name, repr(e.value).lstrip('u'))\n\n return documentation": 4890, "def uncamel(name):\n \"\"\"Transform CamelCase naming convention into C-ish convention.\"\"\"\n s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', name)\n return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()": 4891, "def flat_list(input_list):\n r\"\"\"\n Given a list of nested lists of arbitrary depth, returns a single level or\n 'flat' list.\n\n \"\"\"\n x = input_list\n if isinstance(x, list):\n return [a for i in x for a in flat_list(i)]\n else:\n return [x]": 4892, "def compress(obj):\n \"\"\"Outputs json without whitespace.\"\"\"\n return json.dumps(obj, sort_keys=True, separators=(',', ':'),\n cls=CustomEncoder)": 4893, "def cell(self, rowName, columnName):\n \"\"\"\n Returns the value of the cell on the given row and column.\n \"\"\"\n return self.matrix[self.rowIndices[rowName], self.columnIndices[columnName]]": 4894, "def convert(self, value, _type):\n \"\"\"\n Convert instances of textx types and match rules to python types.\n \"\"\"\n return self.type_convertors.get(_type, lambda x: x)(value)": 4895, "def get_index(self, bucket, index, startkey, endkey=None,\n return_terms=None, max_results=None, continuation=None,\n timeout=None, term_regex=None):\n \"\"\"\n Performs a secondary index query.\n \"\"\"\n raise NotImplementedError": 4896, "def class_check(vector):\n \"\"\"\n Check different items in matrix classes.\n\n :param vector: input vector\n :type vector : list\n :return: bool\n \"\"\"\n for i in vector:\n if not isinstance(i, type(vector[0])):\n return False\n return True": 4897, "def cpp_checker(code, working_directory):\n \"\"\"Return checker.\"\"\"\n return gcc_checker(code, '.cpp',\n [os.getenv('CXX', 'g++'), '-std=c++0x'] + INCLUDE_FLAGS,\n working_directory=working_directory)": 4898, "def open(name=None, fileobj=None, closefd=True):\n \"\"\"\n Use all decompressor possible to make the stream\n \"\"\"\n return Guesser().open(name=name, fileobj=fileobj, closefd=closefd)": 4899, "def label_saves(name):\n \"\"\"Labels plots and saves file\"\"\"\n plt.legend(loc=0)\n plt.ylim([0, 1.025])\n plt.xlabel('$U/D$', fontsize=20)\n plt.ylabel('$Z$', fontsize=20)\n plt.savefig(name, dpi=300, format='png',\n transparent=False, bbox_inches='tight', pad_inches=0.05)": 4900, "def is_client(self):\n \"\"\"Return True if Glances is running in client mode.\"\"\"\n return (self.args.client or self.args.browser) and not self.args.server": 4901, "def update_hash(cls, filelike, digest):\n \"\"\"Update the digest of a single file in a memory-efficient manner.\"\"\"\n block_size = digest.block_size * 1024\n for chunk in iter(lambda: filelike.read(block_size), b''):\n digest.update(chunk)": 4902, "def _check_surrounded_by_space(self, tokens, i):\n \"\"\"Check that a binary operator is surrounded by exactly one space.\"\"\"\n self._check_space(tokens, i, (_MUST, _MUST))": 4903, "def remove_unsafe_chars(text):\n \"\"\"Remove unsafe unicode characters from a piece of text.\"\"\"\n if isinstance(text, six.string_types):\n text = UNSAFE_RE.sub('', text)\n return text": 4904, "def resize(self, width, height):\n \"\"\"\n @summary: override resize function\n @param width: {int} width of widget\n @param height: {int} height of widget\n \"\"\"\n self._buffer = QtGui.QImage(width, height, QtGui.QImage.Format_RGB32)\n QtGui.QWidget.resize(self, width, height)": 4905, "def _convert(self, image, output=None):\n \"\"\"Private method for converting a single PNG image to a PDF.\"\"\"\n with Image.open(image) as im:\n width, height = im.size\n\n co = CanvasObjects()\n co.add(CanvasImg(image, 1.0, w=width, h=height))\n\n return WatermarkDraw(co, tempdir=self.tempdir, pagesize=(width, height)).write(output)": 4906, "def _read_indexlist(self, name):\n \"\"\"Read a list of indexes.\"\"\"\n setattr(self, '_' + name, [self._timeline[int(i)] for i in\n self.db.lrange('site:{0}'.format(name), 0,\n -1)])": 4907, "def __add__(self, other):\n \"\"\"Concatenate two InferenceData objects.\"\"\"\n return concat(self, other, copy=True, inplace=False)": 4908, "def median(ls):\n \"\"\"\n Takes a list and returns the median.\n \"\"\"\n ls = sorted(ls)\n return ls[int(floor(len(ls)/2.0))]": 4909, "def RMS_energy(frames):\n \"\"\"Computes the RMS energy of frames\"\"\"\n f = frames.flatten()\n return N.sqrt(N.mean(f * f))": 4910, "def identifierify(name):\n \"\"\" Clean up name so it works for a Python identifier. \"\"\"\n name = name.lower()\n name = re.sub('[^a-z0-9]', '_', name)\n return name": 4911, "def reduce_freqs(freqlist):\n \"\"\"\n Add up a list of freq counts to get the total counts.\n \"\"\"\n allfreqs = np.zeros_like(freqlist[0])\n for f in freqlist:\n allfreqs += f\n return allfreqs": 4912, "def create(self, ami, count, config=None):\n \"\"\"Create an instance using the launcher.\"\"\"\n return self.Launcher(config=config).launch(ami, count)": 4913, "def load(cls, tree_path):\n \"\"\"Create a new instance from a file.\"\"\"\n with open(tree_path) as f:\n tree_dict = json.load(f)\n\n return cls.from_dict(tree_dict)": 4914, "def dmap(fn, record):\n \"\"\"map for a directory\"\"\"\n values = (fn(v) for k, v in record.items())\n return dict(itertools.izip(record, values))": 4915, "def create_dir_rec(path: Path):\n \"\"\"\n Create a folder recursive.\n\n :param path: path\n :type path: ~pathlib.Path\n \"\"\"\n if not path.exists():\n Path.mkdir(path, parents=True, exist_ok=True)": 4916, "def get_the_node_dict(G, name):\n \"\"\"\n Helper function that returns the node data\n of the node with the name supplied\n \"\"\"\n for node in G.nodes(data=True):\n if node[0] == name:\n return node[1]": 4917, "def js_classnameify(s):\n \"\"\"\n Makes a classname.\n \"\"\"\n if not '_' in s:\n return s\n return ''.join(w[0].upper() + w[1:].lower() for w in s.split('_'))": 4918, "def to_json(value, **kwargs):\n \"\"\"Return a copy of the tuple as a list\n\n If the tuple contains HasProperties instances, they are serialized.\n \"\"\"\n serial_list = [\n val.serialize(**kwargs) if isinstance(val, HasProperties)\n else val for val in value\n ]\n return serial_list": 4919, "def validate(self, value, model_instance, **kwargs):\n \"\"\"This follows the validate rules for choices_form_class field used.\n \"\"\"\n self.get_choices_form_class().validate(value, model_instance, **kwargs)": 4920, "def snap_to_beginning_of_week(day, weekday_start=\"Sunday\"):\n \"\"\" Get the first day of the current week.\n\n :param day: The input date to snap.\n :param weekday_start: Either \"Monday\" or \"Sunday\", indicating the first day of the week.\n :returns: A date representing the first day of the current week.\n \"\"\"\n delta_days = ((day.weekday() + 1) % 7) if weekday_start is \"Sunday\" else day.weekday()\n return day - timedelta(days=delta_days)": 4921, "def get_current_desktop(self):\n \"\"\"\n Get the current desktop.\n Uses ``_NET_CURRENT_DESKTOP`` of the EWMH spec.\n \"\"\"\n desktop = ctypes.c_long(0)\n _libxdo.xdo_get_current_desktop(self._xdo, ctypes.byref(desktop))\n return desktop.value": 4922, "def empty(self, name, **kwargs):\n \"\"\"Create an array. Keyword arguments as per\n :func:`zarr.creation.empty`.\"\"\"\n return self._write_op(self._empty_nosync, name, **kwargs)": 4923, "def get_filetype_icon(fname):\n \"\"\"Return file type icon\"\"\"\n ext = osp.splitext(fname)[1]\n if ext.startswith('.'):\n ext = ext[1:]\n return get_icon( \"%s.png\" % ext, ima.icon('FileIcon') )": 4924, "def guess_media_type(filepath):\n \"\"\"Returns the media-type of the file at the given ``filepath``\"\"\"\n o = subprocess.check_output(['file', '--mime-type', '-Lb', filepath])\n o = o.strip()\n return o": 4925, "def get_hash(self, handle):\n \"\"\"Return the hash.\"\"\"\n fpath = self._fpath_from_handle(handle)\n return DiskStorageBroker.hasher(fpath)": 4926, "def on_press_key(key, callback, suppress=False):\n \"\"\"\n Invokes `callback` for KEY_DOWN event related to the given key. For details see `hook`.\n \"\"\"\n return hook_key(key, lambda e: e.event_type == KEY_UP or callback(e), suppress=suppress)": 4927, "def get_mtime(fname):\n \"\"\"\n Find the time this file was last modified.\n\n :param fname: File name\n :return: The last time the file was modified.\n \"\"\"\n try:\n mtime = os.stat(fname).st_mtime_ns\n except OSError:\n # The file might be right in the middle of being written\n # so sleep\n time.sleep(1)\n mtime = os.stat(fname).st_mtime_ns\n\n return mtime": 4928, "def _get_current_label(self):\n \"\"\"Get the label from the last line read\"\"\"\n if len(self._last) == 0:\n raise StopIteration\n return self._last[:self._last.find(\":\")]": 4929, "def splitBy(data, num):\n \"\"\" Turn a list to list of list \"\"\"\n return [data[i:i + num] for i in range(0, len(data), num)]": 4930, "def get_entity_kind(self, model_obj):\n \"\"\"\n Returns a tuple for a kind name and kind display name of an entity.\n By default, uses the app_label and model of the model object's content\n type as the kind.\n \"\"\"\n model_obj_ctype = ContentType.objects.get_for_model(self.queryset.model)\n return (u'{0}.{1}'.format(model_obj_ctype.app_label, model_obj_ctype.model), u'{0}'.format(model_obj_ctype))": 4931, "def get_known_read_position(fp, buffered=True):\n \"\"\" \n Return a position in a file which is known to be read & handled.\n It assumes a buffered file and streaming processing. \n \"\"\"\n buffer_size = io.DEFAULT_BUFFER_SIZE if buffered else 0\n return max(fp.tell() - buffer_size, 0)": 4932, "def _longest_val_in_column(self, col):\n \"\"\"\n get size of longest value in specific column\n\n :param col: str, column name\n :return int\n \"\"\"\n try:\n # +2 is for implicit separator\n return max([len(x[col]) for x in self.table if x[col]]) + 2\n except KeyError:\n logger.error(\"there is no column %r\", col)\n raise": 4933, "def _take_ownership(self):\n \"\"\"Make the Python instance take ownership of the GIBaseInfo. i.e.\n unref if the python instance gets gc'ed.\n \"\"\"\n\n if self:\n ptr = cast(self.value, GIBaseInfo)\n _UnrefFinalizer.track(self, ptr)\n self.__owns = True": 4934, "def get_month_namedays(self, month=None):\n \"\"\"Return names as a tuple based on given month.\n If no month given, use current one\"\"\"\n if month is None:\n month = datetime.now().month\n return self.NAMEDAYS[month-1]": 4935, "def get_system_root_directory():\n \"\"\"\n Get system root directory (application installed root directory)\n\n Returns\n -------\n string\n A full path\n\n \"\"\"\n root = os.path.dirname(__file__)\n root = os.path.dirname(root)\n root = os.path.abspath(root)\n return root": 4936, "def _jit_pairwise_distances(pos1, pos2):\n \"\"\"Optimized function for calculating the distance between each pair\n of points in positions1 and positions2.\n\n Does use python mode as fallback, if a scalar and not an array is\n given.\n \"\"\"\n n1 = pos1.shape[0]\n n2 = pos2.shape[0]\n D = np.empty((n1, n2))\n\n for i in range(n1):\n for j in range(n2):\n D[i, j] = np.sqrt(((pos1[i] - pos2[j])**2).sum())\n return D": 4937, "def _update_globals():\n \"\"\"\n Patch the globals to remove the objects not available on some platforms.\n\n XXX it'd be better to test assertions about bytecode instead.\n \"\"\"\n\n if not sys.platform.startswith('java') and sys.platform != 'cli':\n return\n incompatible = 'extract_constant', 'get_module_constant'\n for name in incompatible:\n del globals()[name]\n __all__.remove(name)": 4938, "def get_content_type (headers):\n \"\"\"\n Get the MIME type from the Content-Type header value, or\n 'application/octet-stream' if not found.\n\n @return: MIME type\n @rtype: string\n \"\"\"\n ptype = headers.get('Content-Type', 'application/octet-stream')\n if \";\" in ptype:\n # split off not needed extension info\n ptype = ptype.split(';')[0]\n return ptype.strip().lower()": 4939, "def call_with_context(func, context, *args):\n \"\"\"\n Check if given function has more arguments than given. Call it with context\n as last argument or without it.\n \"\"\"\n return make_context_aware(func, len(args))(*args + (context,))": 4940, "def _extract_traceback(start):\n \"\"\"\n SNAGGED FROM traceback.py\n\n RETURN list OF dicts DESCRIBING THE STACK TRACE\n \"\"\"\n tb = sys.exc_info()[2]\n for i in range(start):\n tb = tb.tb_next\n return _parse_traceback(tb)": 4941, "def __call__(self, *args, **kwargs):\n \"\"\" Instanciates a new *Document* from this collection \"\"\"\n kwargs[\"mongokat_collection\"] = self\n return self.document_class(*args, **kwargs)": 4942, "def restore_image_options(cli, image, options):\n \"\"\" Restores CMD and ENTRYPOINT values of the image\n\n This is needed because we force the overwrite of ENTRYPOINT and CMD in the\n `run_code_in_container` function, to be able to run the code in the\n container, through /bin/bash.\n \"\"\"\n dockerfile = io.StringIO()\n\n dockerfile.write(u'FROM {image}\\nCMD {cmd}'.format(\n image=image, cmd=json.dumps(options['cmd'])))\n\n if options['entrypoint']:\n dockerfile.write(\n '\\nENTRYPOINT {}'.format(json.dumps(options['entrypoint'])))\n\n cli.build(tag=image, fileobj=dockerfile)": 4943, "def get_sparse_matrix_keys(session, key_table):\n \"\"\"Return a list of keys for the sparse matrix.\"\"\"\n return session.query(key_table).order_by(key_table.name).all()": 4944, "def rdist(x, y):\n \"\"\"Reduced Euclidean distance.\n\n Parameters\n ----------\n x: array of shape (embedding_dim,)\n y: array of shape (embedding_dim,)\n\n Returns\n -------\n The squared euclidean distance between x and y\n \"\"\"\n result = 0.0\n for i in range(x.shape[0]):\n result += (x[i] - y[i]) ** 2\n\n return result": 4945, "def _to_hours_mins_secs(time_taken):\n \"\"\"Convert seconds to hours, mins, and seconds.\"\"\"\n mins, secs = divmod(time_taken, 60)\n hours, mins = divmod(mins, 60)\n return hours, mins, secs": 4946, "def correlation_2D(image):\n \"\"\"\n\n :param image: 2d image\n :return: psd1D, psd2D\n \"\"\"\n # Take the fourier transform of the image.\n F1 = fftpack.fft2(image)\n\n # Now shift the quadrants around so that low spatial frequencies are in\n # the center of the 2D fourier transformed image.\n F2 = fftpack.fftshift(F1)\n\n # Calculate a 2D power spectrum\n psd2D = np.abs(F2)\n\n # Calculate the azimuthally averaged 1D power spectrum\n psd1D = analysis_util.azimuthalAverage(psd2D)\n return psd1D, psd2D": 4947, "def open_hdf5(filename, mode='r'):\n \"\"\"Wrapper to open a :class:`h5py.File` from disk, gracefully\n handling a few corner cases\n \"\"\"\n if isinstance(filename, (h5py.Group, h5py.Dataset)):\n return filename\n if isinstance(filename, FILE_LIKE):\n return h5py.File(filename.name, mode)\n return h5py.File(filename, mode)": 4948, "def load_fasta_file(filename):\n \"\"\"Load a FASTA file and return the sequences as a list of SeqRecords\n\n Args:\n filename (str): Path to the FASTA file to load\n\n Returns:\n list: list of all sequences in the FASTA file as Biopython SeqRecord objects\n\n \"\"\"\n\n with open(filename, \"r\") as handle:\n records = list(SeqIO.parse(handle, \"fasta\"))\n return records": 4949, "def scaled_fft(fft, scale=1.0):\n \"\"\"\n Produces a nicer graph, I'm not sure if this is correct\n \"\"\"\n data = np.zeros(len(fft))\n for i, v in enumerate(fft):\n data[i] = scale * (i * v) / NUM_SAMPLES\n\n return data": 4950, "def _get_file_sha1(file):\n \"\"\"Return the SHA1 hash of the given a file-like object as ``file``.\n This will seek the file back to 0 when it's finished.\n\n \"\"\"\n bits = file.read()\n file.seek(0)\n h = hashlib.new('sha1', bits).hexdigest()\n return h": 4951, "def normalize_field(self, value):\n \"\"\"\n Method that must transform the value from string\n Ex: if the expected type is int, it should return int(self._attr)\n\n \"\"\"\n if self.default is not None:\n if value is None or value == '':\n value = self.default\n return value": 4952, "def exists(self, path):\n \"\"\"\n Returns true if the path exists and false otherwise.\n \"\"\"\n import hdfs\n try:\n self.client.status(path)\n return True\n except hdfs.util.HdfsError as e:\n if str(e).startswith('File does not exist: '):\n return False\n else:\n raise e": 4953, "def getSize(self):\n \"\"\"\n Returns the size of the layer, with the border size already subtracted.\n \"\"\"\n return self.widget.size[0]-self.border[0]*2,self.widget.size[1]-self.border[1]*2": 4954, "def chunks(dictionary, chunk_size):\n \"\"\"\n Yield successive n-sized chunks from dictionary.\n \"\"\"\n iterable = iter(dictionary)\n for __ in range(0, len(dictionary), chunk_size):\n yield {key: dictionary[key] for key in islice(iterable, chunk_size)}": 4955, "def extend_with(func):\n \"\"\"Extends with class or function\"\"\"\n if not func.__name__ in ArgParseInator._plugins:\n ArgParseInator._plugins[func.__name__] = func": 4956, "def _transform_col(self, x, i):\n \"\"\"Encode one categorical column into labels.\n\n Args:\n x (pandas.Series): a categorical column to encode\n i (int): column index\n\n Returns:\n x (pandas.Series): a column with labels.\n \"\"\"\n return x.fillna(NAN_INT).map(self.label_encoders[i]).fillna(0)": 4957, "def _bind_parameter(self, parameter, value):\n \"\"\"Assigns a parameter value to matching instructions in-place.\"\"\"\n for (instr, param_index) in self._parameter_table[parameter]:\n instr.params[param_index] = value": 4958, "def check_if_numbers_are_consecutive(list_):\n \"\"\"\n Returns True if numbers in the list are consecutive\n\n :param list_: list of integers\n :return: Boolean\n \"\"\"\n return all((True if second - first == 1 else False\n for first, second in zip(list_[:-1], list_[1:])))": 4959, "def chi_square_calc(classes, table, TOP, P, POP):\n \"\"\"\n Calculate chi-squared.\n\n :param classes: confusion matrix classes\n :type classes : list\n :param table: confusion matrix table\n :type table : dict\n :param TOP: test outcome positive\n :type TOP : dict\n :param P: condition positive\n :type P : dict\n :param POP: population\n :type POP : dict\n :return: chi-squared as float\n \"\"\"\n try:\n result = 0\n for i in classes:\n for index, j in enumerate(classes):\n expected = (TOP[j] * P[i]) / (POP[i])\n result += ((table[i][j] - expected)**2) / expected\n return result\n except Exception:\n return \"None\"": 4960, "def auto_update(cls, function):\n \"\"\"\n This class method could be used as decorator on subclasses, it ensures\n update method is called after function execution.\n \"\"\"\n\n def wrapper(self, *args, **kwargs):\n f = function(self, *args, **kwargs)\n self.update()\n return f\n return wrapper": 4961, "def parse_float(float_str):\n \"\"\"Parse a string of the form 305.48b into a Python float.\n The terminal letter, if present, indicates e.g. billions.\"\"\"\n factor = __get_factor(float_str)\n if factor != 1:\n float_str = float_str[:-1]\n\n try:\n return float(float_str.replace(',', '')) * factor\n except ValueError:\n return None": 4962, "def cli(ctx, project_dir):\n \"\"\"Clean the previous generated files.\"\"\"\n exit_code = SCons(project_dir).clean()\n ctx.exit(exit_code)": 4963, "def apply(self, func, args=(), kwds=dict()):\n \"\"\"Equivalent of the apply() builtin function. It blocks till\n the result is ready.\"\"\"\n return self.apply_async(func, args, kwds).get()": 4964, "def _check_task_id(self, context):\n \"\"\"\n Gets the returned Celery result from the Airflow task\n ID provided to the sensor, and returns True if the\n celery result has been finished execution.\n\n :param context: Airflow's execution context\n :type context: dict\n :return: True if task has been executed, otherwise False\n :rtype: bool\n \"\"\"\n ti = context['ti']\n celery_result = ti.xcom_pull(task_ids=self.target_task_id)\n return celery_result.ready()": 4965, "def to_tree(self):\n \"\"\" returns a TreeLib tree \"\"\"\n tree = TreeLibTree()\n for node in self:\n tree.create_node(node, node.node_id, parent=node.parent)\n return tree": 4966, "def gaussian_kernel(sigma, truncate=4.0):\n \"\"\"Return Gaussian that truncates at the given number of std deviations.\n\n Adapted from https://github.com/nicjhan/gaussian-filter\n \"\"\"\n\n sigma = float(sigma)\n radius = int(truncate * sigma + 0.5)\n\n x, y = np.mgrid[-radius:radius + 1, -radius:radius + 1]\n sigma = sigma ** 2\n\n k = 2 * np.exp(-0.5 * (x ** 2 + y ** 2) / sigma)\n k = k / np.sum(k)\n\n return k": 4967, "def mongoqs_to_json(qs, fields=None):\n \"\"\"\n transform mongoengine.QuerySet to json\n \"\"\"\n\n l = list(qs.as_pymongo())\n\n for element in l:\n element.pop('_cls')\n\n # use DjangoJSONEncoder for transform date data type to datetime\n json_qs = json.dumps(l, indent=2, ensure_ascii=False, cls=DjangoJSONEncoder)\n return json_qs": 4968, "def _uniform_phi(M):\n \"\"\"\n Generate M random numbers in [-pi, pi).\n\n \"\"\"\n return np.random.uniform(-np.pi, np.pi, M)": 4969, "def set_context(self, data):\n \"\"\"Load Context with data\"\"\"\n for key in data:\n setattr(self.local_context, key, data[key])": 4970, "def shape(self):\n \"\"\"\n Return a tuple of axis dimensions\n \"\"\"\n return tuple(len(self._get_axis(a)) for a in self._AXIS_ORDERS)": 4971, "def reopen(self):\n \"\"\"Reopen the tough connection.\n\n It will not complain if the connection cannot be reopened.\n\n \"\"\"\n try:\n self._con.reopen()\n except Exception:\n if self._transcation:\n self._transaction = False\n try:\n self._con.query('rollback')\n except Exception:\n pass\n else:\n self._transaction = False\n self._closed = False\n self._setsession()\n self._usage = 0": 4972, "def native_conn(self):\n \"\"\"Native connection object.\"\"\"\n if self.__native is None:\n self.__native = self._get_connection()\n\n return self.__native": 4973, "def eval_Rf(self, Vf):\n \"\"\"Evaluate smooth term in Vf.\"\"\"\n\n return sl.inner(self.Df, Vf, axis=self.cri.axisM) - self.Sf": 4974, "def is_integer(dtype):\n \"\"\"Returns whether this is a (non-quantized) integer type.\"\"\"\n dtype = tf.as_dtype(dtype)\n if hasattr(dtype, 'is_integer'):\n return dtype.is_integer\n return np.issubdtype(np.dtype(dtype), np.integer)": 4975, "def matches_glob_list(path, glob_list):\n \"\"\"\n Given a list of glob patterns, returns a boolean\n indicating if a path matches any glob in the list\n \"\"\"\n for glob in glob_list:\n try:\n if PurePath(path).match(glob):\n return True\n except TypeError:\n pass\n return False": 4976, "def _find_value(key, *args):\n \"\"\"Find a value for 'key' in any of the objects given as 'args'\"\"\"\n for arg in args:\n v = _get_value(arg, key)\n if v is not None:\n return v": 4977, "def _latest_date(self, query, datetime_field_name):\n \"\"\"Given a QuerySet and the name of field containing datetimes, return the\n latest (most recent) date.\n\n Return None if QuerySet is empty.\n\n \"\"\"\n return list(\n query.aggregate(django.db.models.Max(datetime_field_name)).values()\n )[0]": 4978, "def _random_x(self):\n \"\"\"If the database is empty, generate a random vector.\"\"\"\n return (tuple(random.random() for _ in range(self.fmodel.dim_x)),)": 4979, "def model_field_attr(model, model_field, attr):\n \"\"\"\n Returns the specified attribute for the specified field on the model class.\n \"\"\"\n fields = dict([(field.name, field) for field in model._meta.fields])\n return getattr(fields[model_field], attr)": 4980, "def get_next_weekday(self, including_today=False):\n \"\"\"Gets next week day\n\n :param including_today: If today is sunday and requesting next sunday\n :return: Date of next monday, tuesday ..\n \"\"\"\n weekday = self.date_time.weekday()\n return Weekday.get_next(weekday, including_today=including_today)": 4981, "def Unlock(fd, path):\n \"\"\"Release the lock on the file.\n\n Args:\n fd: int, the file descriptor of the file to unlock.\n path: string, the name of the file to lock.\n\n Raises:\n IOError, raised from flock while attempting to release a file lock.\n \"\"\"\n try:\n fcntl.flock(fd, fcntl.LOCK_UN | fcntl.LOCK_NB)\n except IOError as e:\n if e.errno == errno.EWOULDBLOCK:\n raise IOError('Exception unlocking %s. Locked by another process.' % path)\n else:\n raise IOError('Exception unlocking %s. %s.' % (path, str(e)))": 4982, "def display_iframe_url(target, **kwargs):\n \"\"\"Display the contents of a URL in an IPython notebook.\n \n :param target: the target url.\n :type target: string\n\n .. seealso:: `iframe_url()` for additional arguments.\"\"\"\n\n txt = iframe_url(target, **kwargs)\n display(HTML(txt))": 4983, "def get_points(self):\n \"\"\"Returns a ketama compatible list of (position, nodename) tuples.\n \"\"\"\n return [(k, self.runtime._ring[k]) for k in self.runtime._keys]": 4984, "def getheader(self, name, default=None):\n \"\"\"Returns a given response header.\"\"\"\n return self.aiohttp_response.headers.get(name, default)": 4985, "def legend_title_header_element(feature, parent):\n \"\"\"Retrieve legend title header string from definitions.\"\"\"\n _ = feature, parent # NOQA\n header = legend_title_header['string_format']\n return header.capitalize()": 4986, "def calculate_size(name, count):\n \"\"\" Calculates the request payload size\"\"\"\n data_size = 0\n data_size += calculate_size_str(name)\n data_size += INT_SIZE_IN_BYTES\n return data_size": 4987, "def layout(self, indent=' '):\n\t\t\"\"\"This will indent each new tag in the body by given number of spaces.\"\"\"\n\n\n\t\tself.__indent(self.head, indent)\n\t\tself.__indent(self.meta, indent)\n\t\tself.__indent(self.stylesheet, indent)\n\t\tself.__indent(self.header, indent)\n\t\tself.__indent(self.body, indent, initial=3)\n\t\tself.__indent(self.footer, indent)\n\t\tself.__indent(self.body_pre_docinfo, indent, initial=3)\n\t\tself.__indent(self.docinfo, indent)": 4988, "def pagerank_limit_push(s, r, w_i, a_i, push_node, rho):\n \"\"\"\n Performs a random step without a self-loop.\n \"\"\"\n # Calculate the A and B quantities to infinity\n A_inf = rho*r[push_node]\n B_inf = (1-rho)*r[push_node]\n\n # Update approximate Pagerank and residual vectors\n s[push_node] += A_inf\n r[push_node] = 0.0\n\n # Update residual vector at push node's adjacent nodes\n r[a_i] += B_inf * w_i": 4989, "def set_clear_color(self, color='black', alpha=None):\n \"\"\"Set the screen clear color\n\n This is a wrapper for gl.glClearColor.\n\n Parameters\n ----------\n color : str | tuple | instance of Color\n Color to use. See vispy.color.Color for options.\n alpha : float | None\n Alpha to use.\n \"\"\"\n self.glir.command('FUNC', 'glClearColor', *Color(color, alpha).rgba)": 4990, "def _get_binary_from_ipv4(self, ip_addr):\n \"\"\"Converts IPv4 address to binary form.\"\"\"\n\n return struct.unpack(\"!L\", socket.inet_pton(socket.AF_INET,\n ip_addr))[0]": 4991, "def _hess_two_param(self, funct, p0, p1, dl=2e-5, rts=False, **kwargs):\n \"\"\"\n Hessian of `func` wrt two parameters `p0` and `p1`. (see _graddoc)\n \"\"\"\n vals0 = self.get_values(p0)\n vals1 = self.get_values(p1)\n\n f00 = funct(**kwargs)\n\n self.update(p0, vals0+dl)\n f10 = funct(**kwargs)\n\n self.update(p1, vals1+dl)\n f11 = funct(**kwargs)\n\n self.update(p0, vals0)\n f01 = funct(**kwargs)\n\n if rts:\n self.update(p0, vals0)\n self.update(p1, vals1)\n return (f11 - f10 - f01 + f00) / (dl**2)": 4992, "def unique_iter(seq):\n \"\"\"\n See http://www.peterbe.com/plog/uniqifiers-benchmark\n Originally f8 written by Dave Kirby\n \"\"\"\n seen = set()\n return [x for x in seq if x not in seen and not seen.add(x)]": 4993, "def set_mlimits(self, row, column, min=None, max=None):\n \"\"\"Set limits for the point meta (colormap).\n\n Point meta values outside this range will be clipped.\n\n :param min: value for start of the colormap.\n :param max: value for end of the colormap.\n\n \"\"\"\n subplot = self.get_subplot_at(row, column)\n subplot.set_mlimits(min, max)": 4994, "def _validate_input_data(self, data, request):\n \"\"\" Validate input data.\n\n :param request: the HTTP request\n :param data: the parsed data\n :return: if validation is performed and succeeds the data is converted\n into whatever format the validation uses (by default Django's\n Forms) If not, the data is returned unchanged.\n :raises: HttpStatusCodeError if data is not valid\n \"\"\"\n\n validator = self._get_input_validator(request)\n if isinstance(data, (list, tuple)):\n return map(validator.validate, data)\n else:\n return validator.validate(data)": 4995, "def finditer(self, string, pos=0, endpos=sys.maxint):\n \"\"\"Return a list of all non-overlapping matches of pattern in string.\"\"\"\n scanner = self.scanner(string, pos, endpos)\n return iter(scanner.search, None)": 4996, "def set(cls, color):\n \"\"\"\n Sets the terminal to the passed color.\n :param color: one of the availabe colors.\n \"\"\"\n sys.stdout.write(cls.colors.get(color, cls.colors['RESET']))": 4997, "def refresh_core(self):\n \"\"\"Query device for all attributes that exist regardless of power state.\n\n This will force a refresh for all device queries that are valid to\n request at any time. It's the only safe suite of queries that we can\n make if we do not know the current state (on or off+standby).\n\n This does not return any data, it just issues the queries.\n \"\"\"\n self.log.info('Sending out mass query for all attributes')\n for key in ATTR_CORE:\n self.query(key)": 4998, "def next(self):\n \"\"\"Provides hook for Python2 iterator functionality.\"\"\"\n _LOGGER.debug(\"reading next\")\n if self.closed:\n _LOGGER.debug(\"stream is closed\")\n raise StopIteration()\n\n line = self.readline()\n if not line:\n _LOGGER.debug(\"nothing more to read\")\n raise StopIteration()\n\n return line": 4999, "def __iter__(self):\n \"\"\"Overloads iter(condition), and also, for bit in condition. The\n values yielded by the iterator are True (1), False (0), or\n None (#).\"\"\"\n for bit, mask in zip(self._bits, self._mask):\n yield bit if mask else None": 5000, "def purge_cache(self, object_type):\n \"\"\" Purge the named cache of all values. If no cache exists for object_type, nothing is done \"\"\"\n if object_type in self.mapping:\n cache = self.mapping[object_type]\n log.debug(\"Purging [{}] cache of {} values.\".format(object_type, len(cache)))\n cache.purge()": 5001, "def eval(self, expression, use_compilation_plan=False):\n \"\"\"evaluates expression in current context and returns its value\"\"\"\n code = 'PyJsEvalResult = eval(%s)' % json.dumps(expression)\n self.execute(code, use_compilation_plan=use_compilation_plan)\n return self['PyJsEvalResult']": 5002, "def test_security(self):\n \"\"\" Run security.py -- demonstrate the SECURITY extension \"\"\"\n self.assertEqual(run_example(examples_folder + \"security.py --generate\"), 0)\n self.assertEqual(run_example(examples_folder + \"security.py --revoke\"), 0)": 5003, "def _validate(data, schema, ac_schema_safe=True, **options):\n \"\"\"\n See the descritpion of :func:`validate` for more details of parameters and\n return value.\n\n Validate target object 'data' with given schema object.\n \"\"\"\n try:\n jsonschema.validate(data, schema, **options)\n\n except (jsonschema.ValidationError, jsonschema.SchemaError,\n Exception) as exc:\n if ac_schema_safe:\n return (False, str(exc)) # Validation was failed.\n raise\n\n return (True, '')": 5004, "def wait(self, timeout=None):\n \"\"\"\n Block until all jobs in the ThreadPool are finished. Beware that this can\n make the program run into a deadlock if another thread adds new jobs to the\n pool!\n\n # Raises\n Timeout: If the timeout is exceeded.\n \"\"\"\n\n if not self.__running:\n raise RuntimeError(\"ThreadPool ain't running\")\n self.__queue.wait(timeout)": 5005, "def vadd(v1, v2):\n \"\"\" Add two 3 dimensional vectors.\n http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vadd_c.html\n\n :param v1: First vector to be added. \n :type v1: 3-Element Array of floats\n :param v2: Second vector to be added. \n :type v2: 3-Element Array of floats\n :return: v1+v2\n :rtype: 3-Element Array of floats\n \"\"\"\n v1 = stypes.toDoubleVector(v1)\n v2 = stypes.toDoubleVector(v2)\n vout = stypes.emptyDoubleVector(3)\n libspice.vadd_c(v1, v2, vout)\n return stypes.cVectorToPython(vout)": 5006, "def query(self, base, filterstr, attrlist=None):\n\t\t\"\"\" wrapper to search_s \"\"\"\n\t\treturn self.conn.search_s(base, ldap.SCOPE_SUBTREE, filterstr, attrlist)": 5007, "def cols_strip(df,col_list, dest = False):\n \"\"\" Performs str.strip() a column of a DataFrame\n Parameters:\n df - DataFrame\n DataFrame to operate on\n col_list - list of strings\n names of columns to strip\n dest - bool, default False\n Whether to apply the result to the DataFrame or return it.\n True is apply, False is return.\n \"\"\"\n if not dest:\n return _pd.DataFrame({col_name:col_strip(df,col_name) for col_name in col_list})\n for col_name in col_list:\n col_strip(df,col_name,dest)": 5008, "def get_groups(self, username):\n \"\"\"Get all groups of a user\"\"\"\n username = ldap.filter.escape_filter_chars(self._byte_p2(username))\n userdn = self._get_user(username, NO_ATTR)\n\n searchfilter = self.group_filter_tmpl % {\n 'userdn': userdn,\n 'username': username\n }\n\n groups = self._search(searchfilter, NO_ATTR, self.groupdn)\n ret = []\n for entry in groups:\n ret.append(self._uni(entry[0]))\n return ret": 5009, "def _get_xy_scaling_parameters(self):\n \"\"\"Get the X/Y coordinate limits for the full resulting image\"\"\"\n return self.mx, self.bx, self.my, self.by": 5010, "def _set_request_cache_if_django_cache_hit(key, django_cached_response):\n \"\"\"\n Sets the value in the request cache if the django cached response was a hit.\n\n Args:\n key (string)\n django_cached_response (CachedResponse)\n\n \"\"\"\n if django_cached_response.is_found:\n DEFAULT_REQUEST_CACHE.set(key, django_cached_response.value)": 5011, "def fgrad_y(self, y, return_precalc=False):\n \"\"\"\n gradient of f w.r.t to y ([N x 1])\n\n :returns: Nx1 vector of derivatives, unless return_precalc is true, \n then it also returns the precomputed stuff\n \"\"\"\n d = self.d\n mpsi = self.psi\n\n # vectorized version\n S = (mpsi[:,1] * (y[:,:,None] + mpsi[:,2])).T\n R = np.tanh(S)\n D = 1 - (R ** 2)\n\n GRAD = (d + (mpsi[:,0:1][:,:,None] * mpsi[:,1:2][:,:,None] * D).sum(axis=0)).T\n\n if return_precalc:\n return GRAD, S, R, D\n\n return GRAD": 5012, "def zs(inlist):\n \"\"\"\nReturns a list of z-scores, one for each score in the passed list.\n\nUsage: lzs(inlist)\n\"\"\"\n zscores = []\n for item in inlist:\n zscores.append(z(inlist, item))\n return zscores": 5013, "def update(self, **kwargs):\n \"\"\" Explicitly reload context with DB usage to get access\n to complete DB object.\n \"\"\"\n self.reload_context(es_based=False, **kwargs)\n return super(ESCollectionView, self).update(**kwargs)": 5014, "def handle_test(self, command, **options):\n \"\"\"Send a test error to APM Server\"\"\"\n # can't be async for testing\n config = {\"async_mode\": False}\n for key in (\"service_name\", \"secret_token\"):\n if options.get(key):\n config[key] = options[key]\n client = DjangoClient(**config)\n client.error_logger = ColoredLogger(self.stderr)\n client.logger = ColoredLogger(self.stderr)\n self.write(\n \"Trying to send a test error to APM Server using these settings:\\n\\n\"\n \"SERVICE_NAME:\\t%s\\n\"\n \"SECRET_TOKEN:\\t%s\\n\"\n \"SERVER:\\t\\t%s\\n\\n\" % (client.config.service_name, client.config.secret_token, client.config.server_url)\n )\n\n try:\n raise TestException(\"Hi there!\")\n except TestException:\n client.capture_exception()\n if not client.error_logger.errors:\n self.write(\n \"Success! We tracked the error successfully! You should be\"\n \" able to see it in a few seconds at the above URL\"\n )\n finally:\n client.close()": 5015, "def load(cls, fp, **kwargs):\n \"\"\"wrapper for :py:func:`json.load`\"\"\"\n json_obj = json.load(fp, **kwargs)\n return parse(cls, json_obj)": 5016, "def assert_lock(fname):\n \"\"\"\n If file is locked then terminate program else lock file.\n \"\"\"\n\n if not set_lock(fname):\n logger.error('File {} is already locked. Terminating.'.format(fname))\n sys.exit()": 5017, "def execute_cast_simple_literal_to_timestamp(op, data, type, **kwargs):\n \"\"\"Cast integer and strings to timestamps\"\"\"\n return pd.Timestamp(data, tz=type.timezone)": 5018, "def _debug_log(self, msg):\n \"\"\"Debug log messages if debug=True\"\"\"\n if not self.debug:\n return\n sys.stderr.write('{}\\n'.format(msg))": 5019, "def set_verbosity(verbosity):\n \"\"\"Banana banana\n \"\"\"\n Logger._verbosity = min(max(0, WARNING - verbosity), 2)\n debug(\"Verbosity set to %d\" % (WARNING - Logger._verbosity), 'logging')": 5020, "def count_nulls(self, field):\n \"\"\"\n Count the number of null values in a column\n \"\"\"\n try:\n n = self.df[field].isnull().sum()\n except KeyError:\n self.warning(\"Can not find column\", field)\n return\n except Exception as e:\n self.err(e, \"Can not count nulls\")\n return\n self.ok(\"Found\", n, \"nulls in column\", field)": 5021, "def package_in_pypi(package):\n \"\"\"Check whether the package is registered on pypi\"\"\"\n url = 'http://pypi.python.org/simple/%s' % package\n try:\n urllib.request.urlopen(url)\n return True\n except urllib.error.HTTPError as e:\n logger.debug(\"Package not found on pypi: %s\", e)\n return False": 5022, "def instance_name(string):\n \"\"\"Check for valid instance name\n \"\"\"\n invalid = ':/@'\n if set(string).intersection(invalid):\n msg = 'Invalid instance name {}'.format(string)\n raise argparse.ArgumentTypeError(msg)\n return string": 5023, "def check_update():\n \"\"\"\n Check for app updates and print/log them.\n \"\"\"\n logging.info('Check for app updates.')\n try:\n update = updater.check_for_app_updates()\n except Exception:\n logging.exception('Check for updates failed.')\n return\n if update:\n print(\"!!! UPDATE AVAILABLE !!!\\n\"\n \"\" + static_data.PROJECT_URL + \"\\n\\n\")\n logging.info(\"Update available: \" + static_data.PROJECT_URL)\n else:\n logging.info(\"No update available.\")": 5024, "def get_matrix(self):\n \"\"\" Use numpy to create a real matrix object from the data\n\n :return: the matrix representation of the fvm\n \"\"\"\n return np.array([ self.get_row_list(i) for i in range(self.row_count()) ])": 5025, "def db_exists():\n \"\"\"Test if DATABASES['default'] exists\"\"\"\n logger.info(\"Checking to see if %s already exists\", repr(DB[\"NAME\"]))\n try:\n # Hide stderr since it is confusing here\n psql(\"\", stderr=subprocess.STDOUT)\n except subprocess.CalledProcessError:\n return False\n return True": 5026, "def hmean_int(a, a_min=5778, a_max=1149851):\n \"\"\" Harmonic mean of an array, returns the closest int\n \"\"\"\n from scipy.stats import hmean\n return int(round(hmean(np.clip(a, a_min, a_max))))": 5027, "def contextMenuEvent(self, event):\n \"\"\"Override Qt method\"\"\"\n self.update_menu()\n self.menu.popup(event.globalPos())": 5028, "def compare(self, first, second):\n \"\"\"\n Case in-sensitive comparison of two strings.\n Required arguments:\n * first - The first string to compare.\n * second - The second string to compare.\n \"\"\"\n if first.lower() == second.lower():\n return True\n else:\n return False": 5029, "def comments(self):\n \"\"\"The AST comments.\"\"\"\n if self._comments is None:\n self._comments = [c for c in self.grammar.children if c.is_type(TokenType.comment)]\n return self._comments": 5030, "def tag_to_dict(html):\n \"\"\"Extract tag's attributes into a `dict`.\"\"\"\n\n element = document_fromstring(html).xpath(\"//html/body/child::*\")[0]\n attributes = dict(element.attrib)\n attributes[\"text\"] = element.text_content()\n return attributes": 5031, "def _config_session():\n \"\"\"\n Configure session for particular device\n\n Returns:\n tensorflow.Session\n \"\"\"\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n config.gpu_options.visible_device_list = '0'\n return tf.Session(config=config)": 5032, "def get_object_or_none(model, *args, **kwargs):\n \"\"\"\n Like get_object_or_404, but doesn't throw an exception.\n\n Allows querying for an object that might not exist without triggering\n an exception.\n \"\"\"\n try:\n return model._default_manager.get(*args, **kwargs)\n except model.DoesNotExist:\n return None": 5033, "def write(self, value):\n \"\"\"\n Write value to the target\n \"\"\"\n self.get_collection().update_one(\n {'_id': self._document_id},\n {'$set': {self._path: value}},\n upsert=True\n )": 5034, "def _calc_dir_size(path):\n \"\"\"\n Calculate size of all files in `path`.\n\n Args:\n path (str): Path to the directory.\n\n Returns:\n int: Size of the directory in bytes.\n \"\"\"\n dir_size = 0\n for (root, dirs, files) in os.walk(path):\n for fn in files:\n full_fn = os.path.join(root, fn)\n dir_size += os.path.getsize(full_fn)\n\n return dir_size": 5035, "def create_node(self, network, participant):\n \"\"\"Create a node for a participant.\"\"\"\n return self.models.MCMCPAgent(network=network, participant=participant)": 5036, "def index_nearest(array, value):\n \"\"\"\n Finds index of nearest value in array.\n\n Args:\n array: numpy array\n value:\n\n Returns:\n int\n\n http://stackoverflow.com/questions/2566412/find-nearest-value-in-numpy-array\n \"\"\"\n idx = (np.abs(array-value)).argmin()\n return idx": 5037, "def doc_parser():\n \"\"\"Utility function to allow getting the arguments for a single command, for Sphinx documentation\"\"\"\n\n parser = argparse.ArgumentParser(\n prog='ambry',\n description='Ambry {}. Management interface for ambry, libraries '\n 'and repositories. '.format(ambry._meta.__version__))\n\n return parser": 5038, "def has_edge(self, edge):\n \"\"\"\n Return whether an edge exists.\n\n @type edge: tuple\n @param edge: Edge.\n\n @rtype: boolean\n @return: Truth-value for edge existence.\n \"\"\"\n u, v = edge\n return (u, v) in self.edge_properties": 5039, "def earth_orientation(date):\n \"\"\"Earth orientation as a rotating matrix\n \"\"\"\n\n x_p, y_p, s_prime = np.deg2rad(_earth_orientation(date))\n return rot3(-s_prime) @ rot2(x_p) @ rot1(y_p)": 5040, "def __del__(self):\n \"\"\"Deletes the database file.\"\"\"\n if self._delete_file:\n try:\n os.remove(self.name)\n except (OSError, IOError):\n pass": 5041, "def request(self, method, url, body=None, headers={}):\n \"\"\"Send a complete request to the server.\"\"\"\n self._send_request(method, url, body, headers)": 5042, "def gtype(n):\n \"\"\"\n Return the a string with the data type of a value, for Graph data\n \"\"\"\n t = type(n).__name__\n return str(t) if t != 'Literal' else 'Literal, {}'.format(n.language)": 5043, "def __str__(self):\n \"\"\"Return human readable string.\"\"\"\n return \", \".join(\"{:02x}{:02x}={:02x}{:02x}\".format(c[0][0], c[0][1], c[1][0], c[1][1]) for c in self.alias_array_)": 5044, "def rgamma(alpha, beta, size=None):\n \"\"\"\n Random gamma variates.\n \"\"\"\n\n return np.random.gamma(shape=alpha, scale=1. / beta, size=size)": 5045, "def __iter__(self):\n \"\"\"\n Returns the list of modes.\n\n :return:\n \"\"\"\n return iter([v for k, v in sorted(self._modes.items())])": 5046, "def top_class(self):\n \"\"\"reference to a parent class, which contains this class and defined\n within a namespace\n\n if this class is defined under a namespace, self will be returned\"\"\"\n curr = self\n parent = self.parent\n while isinstance(parent, class_t):\n curr = parent\n parent = parent.parent\n return curr": 5047, "def load_results(result_files, options, run_set_id=None, columns=None,\n columns_relevant_for_diff=set()):\n \"\"\"Version of load_result for multiple input files that will be loaded concurrently.\"\"\"\n return parallel.map(\n load_result,\n result_files,\n itertools.repeat(options),\n itertools.repeat(run_set_id),\n itertools.repeat(columns),\n itertools.repeat(columns_relevant_for_diff))": 5048, "def screen_to_client(self, x, y):\n \"\"\"\n Translates window screen coordinates to client coordinates.\n\n @note: This is a simplified interface to some of the functionality of\n the L{win32.Point} class.\n\n @see: {win32.Point.screen_to_client}\n\n @type x: int\n @param x: Horizontal coordinate.\n @type y: int\n @param y: Vertical coordinate.\n\n @rtype: tuple( int, int )\n @return: Translated coordinates in a tuple (x, y).\n\n @raise WindowsError: An error occured while processing this request.\n \"\"\"\n return tuple( win32.ScreenToClient( self.get_handle(), (x, y) ) )": 5049, "def expand_path(path):\n \"\"\"Returns ``path`` as an absolute path with ~user and env var expansion applied.\n\n :API: public\n \"\"\"\n return os.path.abspath(os.path.expandvars(os.path.expanduser(path)))": 5050, "def parent(self, index):\n \"\"\"Return the index of the parent for a given index of the\n child. Unfortunately, the name of the method has to be parent,\n even though a more verbose name like parentIndex, would avoid\n confusion about what parent actually is - an index or an item.\n \"\"\"\n childItem = self.item(index)\n parentItem = childItem.parent\n\n if parentItem == self.rootItem:\n parentIndex = QModelIndex()\n else:\n parentIndex = self.createIndex(parentItem.row(), 0, parentItem)\n\n return parentIndex": 5051, "def standardize(table, with_std=True):\n \"\"\"\n Perform Z-Normalization on each numeric column of the given table.\n\n Parameters\n ----------\n table : pandas.DataFrame or numpy.ndarray\n Data to standardize.\n\n with_std : bool, optional, default: True\n If ``False`` data is only centered and not converted to unit variance.\n\n Returns\n -------\n normalized : pandas.DataFrame\n Table with numeric columns normalized.\n Categorical columns in the input table remain unchanged.\n \"\"\"\n if isinstance(table, pandas.DataFrame):\n cat_columns = table.select_dtypes(include=['category']).columns\n else:\n cat_columns = []\n\n new_frame = _apply_along_column(table, standardize_column, with_std=with_std)\n\n # work around for apply converting category dtype to object\n # https://github.com/pydata/pandas/issues/9573\n for col in cat_columns:\n new_frame[col] = table[col].copy()\n\n return new_frame": 5052, "def PythonPercentFormat(format_str):\n \"\"\"Use Python % format strings as template format specifiers.\"\"\"\n\n if format_str.startswith('printf '):\n fmt = format_str[len('printf '):]\n return lambda value: fmt % value\n else:\n return None": 5053, "def _last_index(x, default_dim):\n \"\"\"Returns the last dimension's index or default_dim if x has no shape.\"\"\"\n if x.get_shape().ndims is not None:\n return len(x.get_shape()) - 1\n else:\n return default_dim": 5054, "def _async_requests(urls):\n \"\"\"\n Sends multiple non-blocking requests. Returns\n a list of responses.\n\n :param urls:\n List of urls\n \"\"\"\n session = FuturesSession(max_workers=30)\n futures = [\n session.get(url)\n for url in urls\n ]\n return [ future.result() for future in futures ]": 5055, "def prompt(*args, **kwargs):\n \"\"\"Prompt the user for input and handle any abort exceptions.\"\"\"\n try:\n return click.prompt(*args, **kwargs)\n except click.Abort:\n return False": 5056, "def value_for_key(membersuite_object_data, key):\n \"\"\"Return the value for `key` of membersuite_object_data.\n \"\"\"\n key_value_dicts = {\n d['Key']: d['Value'] for d\n in membersuite_object_data[\"Fields\"][\"KeyValueOfstringanyType\"]}\n return key_value_dicts[key]": 5057, "def _baseattrs(self):\n \"\"\"A dict of members expressed in literals\"\"\"\n\n result = super()._baseattrs\n result[\"params\"] = \", \".join(self.parameters)\n return result": 5058, "def _parse_ranges(ranges):\n \"\"\" Converts a list of string ranges to a list of [low, high] tuples. \"\"\"\n for txt in ranges:\n if '-' in txt:\n low, high = txt.split('-')\n else:\n low, high = txt, txt\n yield int(low), int(high)": 5059, "def plot_pauli_transfer_matrix(self, ax):\n \"\"\"\n Plot the elements of the Pauli transfer matrix.\n\n :param matplotlib.Axes ax: A matplotlib Axes object to plot into.\n \"\"\"\n title = \"Estimated process\"\n ut.plot_pauli_transfer_matrix(self.r_est, ax, self.pauli_basis.labels, title)": 5060, "def replace(self, text):\n \"\"\"Do j/v replacement\"\"\"\n for (pattern, repl) in self.patterns:\n text = re.subn(pattern, repl, text)[0]\n return text": 5061, "def utcfromtimestamp(cls, timestamp):\n \"\"\"Returns a datetime object of a given timestamp (in UTC).\"\"\"\n obj = datetime.datetime.utcfromtimestamp(timestamp)\n obj = pytz.utc.localize(obj)\n return cls(obj)": 5062, "def _read_preference_for(self, session):\n \"\"\"Read only access to the read preference of this instance or session.\n \"\"\"\n # Override this operation's read preference with the transaction's.\n if session:\n return session._txn_read_preference() or self.__read_preference\n return self.__read_preference": 5063, "def tuplize(nested):\n \"\"\"Recursively converts iterables into tuples.\n\n Args:\n nested: A nested structure of items and iterables.\n\n Returns:\n A nested structure of items and tuples.\n \"\"\"\n if isinstance(nested, str):\n return nested\n try:\n return tuple(map(tuplize, nested))\n except TypeError:\n return nested": 5064, "def _GetProxies(self):\n \"\"\"Gather a list of proxies to use.\"\"\"\n # Detect proxies from the OS environment.\n result = client_utils.FindProxies()\n\n # Also try to connect directly if all proxies fail.\n result.append(\"\")\n\n # Also try all proxies configured in the config system.\n result.extend(config.CONFIG[\"Client.proxy_servers\"])\n\n return result": 5065, "def _load_ngram(name):\n \"\"\"Dynamically import the python module with the ngram defined as a dictionary.\n Since bigger ngrams are large files its wasteful to always statically import them if they're not used.\n \"\"\"\n module = importlib.import_module('lantern.analysis.english_ngrams.{}'.format(name))\n return getattr(module, name)": 5066, "def find_number(regex, s):\n \"\"\"Find a number using a given regular expression.\n If the string cannot be found, returns None.\n The regex should contain one matching group, \n as only the result of the first group is returned.\n The group should only contain numeric characters ([0-9]+).\n \n s - The string to search.\n regex - A string containing the regular expression.\n \n Returns an integer or None.\n \"\"\"\n result = find_string(regex, s)\n if result is None:\n return None\n return int(result)": 5067, "def detach_index(self, name):\n \"\"\"\n\n :param name:\n :return:\n \"\"\"\n assert type(name) == str\n\n if name in self._indexes:\n del self._indexes[name]": 5068, "def gaussian_kernel(gstd):\n \"\"\"Generate odd sized truncated Gaussian\n\n The generated filter kernel has a cutoff at $3\\sigma$\n and is normalized to sum to 1\n\n Parameters\n -------------\n gstd : float\n Standard deviation of filter\n\n Returns\n -------------\n g : ndarray\n Array with kernel coefficients\n \"\"\"\n Nc = np.ceil(gstd*3)*2+1\n x = np.linspace(-(Nc-1)/2,(Nc-1)/2,Nc,endpoint=True)\n g = np.exp(-.5*((x/gstd)**2))\n g = g/np.sum(g)\n\n return g": 5069, "def plot_dot_graph(graph, filename=None):\n \"\"\"\n Plots a graph in graphviz dot notation.\n\n :param graph: the dot notation graph\n :type graph: str\n :param filename: the (optional) file to save the generated plot to. The extension determines the file format.\n :type filename: str\n \"\"\"\n if not plot.pygraphviz_available:\n logger.error(\"Pygraphviz is not installed, cannot generate graph plot!\")\n return\n if not plot.PIL_available:\n logger.error(\"PIL is not installed, cannot display graph plot!\")\n return\n\n agraph = AGraph(graph)\n agraph.layout(prog='dot')\n if filename is None:\n filename = tempfile.mktemp(suffix=\".png\")\n agraph.draw(filename)\n image = Image.open(filename)\n image.show()": 5070, "def get_plugin_icon(self):\n \"\"\"Return widget icon\"\"\"\n path = osp.join(self.PLUGIN_PATH, self.IMG_PATH)\n return ima.icon('pylint', icon_path=path)": 5071, "def generate_header(headerfields, oldheader, group_by_field):\n \"\"\"Returns a header as a list, ready to write to TSV file\"\"\"\n fieldtypes = ['peptidefdr', 'peptidepep', 'nopsms', 'proteindata',\n 'precursorquant', 'isoquant']\n return generate_general_header(headerfields, fieldtypes,\n peptabledata.HEADER_PEPTIDE, oldheader,\n group_by_field)": 5072, "def to_linspace(self):\n \"\"\"\n convert from arange to linspace\n \"\"\"\n num = int((self.stop-self.start)/(self.step))\n return Linspace(self.start, self.stop-self.step, num)": 5073, "def paragraph(separator='\\n\\n', wrap_start='', wrap_end='',\n html=False, sentences_quantity=3):\n \"\"\"Return a random paragraph.\"\"\"\n return paragraphs(quantity=1, separator=separator, wrap_start=wrap_start,\n wrap_end=wrap_end, html=html,\n sentences_quantity=sentences_quantity)": 5074, "def trim_trailing_silence(self):\n \"\"\"Trim the trailing silence of the pianoroll.\"\"\"\n length = self.get_active_length()\n self.pianoroll = self.pianoroll[:length]": 5075, "def list_replace(subject_list, replacement, string):\n \"\"\"\n To replace a list of items by a single replacement\n :param subject_list: list\n :param replacement: string\n :param string: string\n :return: string\n \"\"\"\n for s in subject_list:\n string = string.replace(s, replacement)\n return string": 5076, "def do_restart(self, line):\n \"\"\"\n Attempt to restart the bot.\n \"\"\"\n self.bot._frame = 0\n self.bot._namespace.clear()\n self.bot._namespace.update(self.bot._initial_namespace)": 5077, "def new_figure_manager_given_figure(num, figure):\n \"\"\"\n Create a new figure manager instance for the given figure.\n \"\"\"\n fig = figure\n frame = FigureFrameWx(num, fig)\n figmgr = frame.get_figure_manager()\n if matplotlib.is_interactive():\n figmgr.frame.Show()\n\n return figmgr": 5078, "def _prt_line_detail(self, prt, line, lnum=\"\"):\n \"\"\"Print each field and its value.\"\"\"\n data = zip(self.flds, line.split('\\t'))\n txt = [\"{:2}) {:13} {}\".format(i, hdr, val) for i, (hdr, val) in enumerate(data)]\n prt.write(\"{LNUM}\\n{TXT}\\n\".format(LNUM=lnum, TXT='\\n'.join(txt)))": 5079, "def show_partitioning(rdd, show=True):\n \"\"\"Seems to be significantly more expensive on cluster than locally\"\"\"\n if show:\n partitionCount = rdd.getNumPartitions()\n try:\n valueCount = rdd.countApprox(1000, confidence=0.50)\n except:\n valueCount = -1\n try:\n name = rdd.name() or None\n except:\n pass\n name = name or \"anonymous\"\n logging.info(\"For RDD %s, there are %d partitions with on average %s values\" % \n (name, partitionCount, int(valueCount/float(partitionCount))))": 5080, "def replacing_symlink(source, link_name):\n \"\"\"Create symlink that overwrites any existing target.\n \"\"\"\n with make_tmp_name(link_name) as tmp_link_name:\n os.symlink(source, tmp_link_name)\n replace_file_or_dir(link_name, tmp_link_name)": 5081, "def home_lib(home):\n \"\"\"Return the lib dir under the 'home' installation scheme\"\"\"\n if hasattr(sys, 'pypy_version_info'):\n lib = 'site-packages'\n else:\n lib = os.path.join('lib', 'python')\n return os.path.join(home, lib)": 5082, "def selectnotin(table, field, value, complement=False):\n \"\"\"Select rows where the given field is not a member of the given value.\"\"\"\n\n return select(table, field, lambda v: v not in value,\n complement=complement)": 5083, "def _send(self, data):\n \"\"\"Send data to statsd.\"\"\"\n if not self._sock:\n self.connect()\n self._do_send(data)": 5084, "def send(self, data):\n \"\"\"\n Send data to the child process through.\n \"\"\"\n self.stdin.write(data)\n self.stdin.flush()": 5085, "def serialize_me(self, account, bucket_details):\n \"\"\"Serializes the JSON for the Polling Event Model.\n\n :param account:\n :param bucket_details:\n :return:\n \"\"\"\n return self.dumps({\n \"account\": account,\n \"detail\": {\n \"request_parameters\": {\n \"bucket_name\": bucket_details[\"Name\"],\n \"creation_date\": bucket_details[\"CreationDate\"].replace(\n tzinfo=None, microsecond=0).isoformat() + \"Z\"\n }\n }\n }).data": 5086, "def _updateTabStopWidth(self):\n \"\"\"Update tabstop width after font or indentation changed\n \"\"\"\n self.setTabStopWidth(self.fontMetrics().width(' ' * self._indenter.width))": 5087, "def print_fatal_results(results, level=0):\n \"\"\"Print fatal errors that occurred during validation runs.\n \"\"\"\n print_level(logger.critical, _RED + \"[X] Fatal Error: %s\", level, results.error)": 5088, "def set_limits(self, min_=None, max_=None):\n \"\"\"\n Sets limits for this config value\n\n If the resulting integer is outside those limits, an exception will be raised\n\n :param min_: minima\n :param max_: maxima\n \"\"\"\n self._min, self._max = min_, max_": 5089, "def close(self):\n \"\"\"Flush the buffer and finalize the file.\n\n When this returns the new file is available for reading.\n \"\"\"\n if not self.closed:\n self.closed = True\n self._flush(finish=True)\n self._buffer = None": 5090, "def __init__(self, iterable):\n \"\"\"Initialize the cycle with some iterable.\"\"\"\n self._values = []\n self._iterable = iterable\n self._initialized = False\n self._depleted = False\n self._offset = 0": 5091, "def print_message(message=None):\n \"\"\"Print message via ``subprocess.call`` function.\n\n This helps to ensure consistent output and avoid situations where print\n messages actually shown after messages from all inner threads.\n\n :param message: Text message to print.\n \"\"\"\n kwargs = {'stdout': sys.stdout,\n 'stderr': sys.stderr,\n 'shell': True}\n return subprocess.call('echo \"{0}\"'.format(message or ''), **kwargs)": 5092, "def segments_to_numpy(segments):\n \"\"\"given a list of 4-element tuples, transforms it into a numpy array\"\"\"\n segments = numpy.array(segments, dtype=SEGMENT_DATATYPE, ndmin=2) # each segment in a row\n segments = segments if SEGMENTS_DIRECTION == 0 else numpy.transpose(segments)\n return segments": 5093, "def search_index_file():\n \"\"\"Return the default local index file, from the download cache\"\"\"\n from metapack import Downloader\n from os import environ\n\n return environ.get('METAPACK_SEARCH_INDEX',\n Downloader.get_instance().cache.getsyspath('index.json'))": 5094, "def _connect(self, servers):\n \"\"\" connect to the given server, e.g.: \\\\connect localhost:4200 \"\"\"\n self._do_connect(servers.split(' '))\n self._verify_connection(verbose=True)": 5095, "def offsets(self):\n \"\"\" Returns the offsets values of x, y, z as a numpy array\n \"\"\"\n return np.array([self.x_offset, self.y_offset, self.z_offset])": 5096, "def cluster_kmeans(data, n_clusters, **kwargs):\n \"\"\"\n Identify clusters using K - Means algorithm.\n\n Parameters\n ----------\n data : array_like\n array of size [n_samples, n_features].\n n_clusters : int\n The number of clusters expected in the data.\n\n Returns\n -------\n dict\n boolean array for each identified cluster.\n \"\"\"\n km = cl.KMeans(n_clusters, **kwargs)\n kmf = km.fit(data)\n\n labels = kmf.labels_\n\n return labels, [np.nan]": 5097, "def ReverseV2(a, axes):\n \"\"\"\n Reverse op.\n \"\"\"\n idxs = tuple(slice(None, None, 2 * int(i not in axes) - 1) for i in range(len(a.shape)))\n return np.copy(a[idxs]),": 5098, "def set_slug(apps, schema_editor):\n \"\"\"\n Create a slug for each Event already in the DB.\n \"\"\"\n Event = apps.get_model('spectator_events', 'Event')\n\n for e in Event.objects.all():\n e.slug = generate_slug(e.pk)\n e.save(update_fields=['slug'])": 5099, "def wait_send(self, timeout = None):\n\t\t\"\"\"Wait until all queued messages are sent.\"\"\"\n\t\tself._send_queue_cleared.clear()\n\t\tself._send_queue_cleared.wait(timeout = timeout)": 5100, "def _rows_sort(self, rows):\n \"\"\"\n Returns a list of rows sorted by start and end date.\n\n :param list[dict[str,T]] rows: The list of rows.\n\n :rtype: list[dict[str,T]]\n \"\"\"\n return sorted(rows, key=lambda row: (row[self._key_start_date], row[self._key_end_date]))": 5101, "def to_html(self, write_to):\n \"\"\"Method to convert the repository list to a search results page and\n write it to a HTML file.\n\n :param write_to: File/Path to write the html file to.\n \"\"\"\n page_html = self.get_html()\n\n with open(write_to, \"wb\") as writefile:\n writefile.write(page_html.encode(\"utf-8\"))": 5102, "def build_columns(self, X, verbose=False):\n \"\"\"construct the model matrix columns for the term\n\n Parameters\n ----------\n X : array-like\n Input dataset with n rows\n\n verbose : bool\n whether to show warnings\n\n Returns\n -------\n scipy sparse array with n rows\n \"\"\"\n return sp.sparse.csc_matrix(X[:, self.feature][:, np.newaxis])": 5103, "def feature_subset(self, indices):\n \"\"\" Returns some subset of the features.\n \n Parameters\n ----------\n indices : :obj:`list` of :obj:`int`\n indices of the features in the list\n\n Returns\n -------\n :obj:`list` of :obj:`Feature`\n \"\"\"\n if isinstance(indices, np.ndarray):\n indices = indices.tolist()\n if not isinstance(indices, list):\n raise ValueError('Can only index with lists')\n return [self.features_[i] for i in indices]": 5104, "def _request_modify_dns_record(self, record):\n \"\"\"Sends Modify_DNS_Record request\"\"\"\n return self._request_internal(\"Modify_DNS_Record\",\n domain=self.domain,\n record=record)": 5105, "def table_exists(cursor, tablename, schema='public'):\n query = \"\"\"\n SELECT EXISTS (\n SELECT 1\n FROM information_schema.tables\n WHERE table_schema = %s\n AND table_name = %s\n )\"\"\"\n cursor.execute(query, (schema, tablename))\n res = cursor.fetchone()[0]\n return res": 5106, "def truncate_table(self, tablename):\n \"\"\"\n SQLite3 doesn't support direct truncate, so we just use delete here\n \"\"\"\n self.get(tablename).remove()\n self.db.commit()": 5107, "def fix_line_breaks(s):\n \"\"\"\n Convert \\r\\n and \\r to \\n chars. Strip any leading or trailing whitespace\n on each line. Remove blank lines.\n \"\"\"\n l = s.splitlines()\n x = [i.strip() for i in l]\n x = [i for i in x if i] # remove blank lines\n return \"\\n\".join(x)": 5108, "def do_quit(self, arg):\n \"\"\"\n quit || exit || q\n Stop and quit the current debugging session\n \"\"\"\n for name, fh in self._backup:\n setattr(sys, name, fh)\n self.console.writeline('*** Aborting program ***\\n')\n self.console.flush()\n self.console.close()\n WebPdb.active_instance = None\n return Pdb.do_quit(self, arg)": 5109, "def itemlist(item, sep, suppress_trailing=True):\n \"\"\"Create a list of items seperated by seps.\"\"\"\n return condense(item + ZeroOrMore(addspace(sep + item)) + Optional(sep.suppress() if suppress_trailing else sep))": 5110, "def subat(orig, index, replace):\n \"\"\"Substitutes the replacement string/character at the given index in the\n given string, returns the modified string.\n\n **Examples**:\n ::\n auxly.stringy.subat(\"bit\", 2, \"n\")\n \"\"\"\n return \"\".join([(orig[x] if x != index else replace) for x in range(len(orig))])": 5111, "def bytes_to_bits(bytes_):\n \"\"\"Convert bytes to a list of bits\n \"\"\"\n res = []\n for x in bytes_:\n if not isinstance(x, int):\n x = ord(x)\n res += byte_to_bits(x)\n return res": 5112, "def get_last_filled_cell(self, table=None):\n \"\"\"Returns key for the bottommost rightmost cell with content\n\n Parameters\n ----------\n table: Integer, defaults to None\n \\tLimit search to this table\n\n \"\"\"\n\n maxrow = 0\n maxcol = 0\n\n for row, col, tab in self.dict_grid:\n if table is None or tab == table:\n maxrow = max(row, maxrow)\n maxcol = max(col, maxcol)\n\n return maxrow, maxcol, table": 5113, "def run_std_server(self):\n \"\"\"Starts a TensorFlow server and joins the serving thread.\n\n Typically used for parameter servers.\n\n Raises:\n ValueError: if not enough information is available in the estimator's\n config to create a server.\n \"\"\"\n config = tf.estimator.RunConfig()\n server = tf.train.Server(\n config.cluster_spec,\n job_name=config.task_type,\n task_index=config.task_id,\n protocol=config.protocol)\n server.join()": 5114, "def filesavebox(msg=None, title=None, argInitialFile=None):\n \"\"\"Original doc: A file to get the name of a file to save.\n Returns the name of a file, or None if user chose to cancel.\n\n if argInitialFile contains a valid filename, the dialog will\n be positioned at that file when it appears.\n \"\"\"\n return psidialogs.ask_file(message=msg, title=title, default=argInitialFile, save=True)": 5115, "def is_array(type_):\n \"\"\"returns True, if type represents C++ array type, False otherwise\"\"\"\n nake_type = remove_alias(type_)\n nake_type = remove_reference(nake_type)\n nake_type = remove_cv(nake_type)\n return isinstance(nake_type, cpptypes.array_t)": 5116, "def colorize(txt, fg=None, bg=None):\n \"\"\"\n Print escape codes to set the terminal color.\n\n fg and bg are indices into the color palette for the foreground and\n background colors.\n \"\"\"\n\n setting = ''\n setting += _SET_FG.format(fg) if fg else ''\n setting += _SET_BG.format(bg) if bg else ''\n return setting + str(txt) + _STYLE_RESET": 5117, "def import_public_rsa_key_from_file(filename):\n \"\"\"\n Read a public RSA key from a PEM file.\n\n :param filename: The name of the file\n :param passphrase: A pass phrase to use to unpack the PEM file.\n :return: A\n cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey instance\n \"\"\"\n with open(filename, \"rb\") as key_file:\n public_key = serialization.load_pem_public_key(\n key_file.read(),\n backend=default_backend())\n return public_key": 5118, "def Join(self):\n \"\"\"Waits until all outstanding tasks are completed.\"\"\"\n\n for _ in range(self.JOIN_TIMEOUT_DECISECONDS):\n if self._queue.empty() and not self.busy_threads:\n return\n time.sleep(0.1)\n\n raise ValueError(\"Timeout during Join() for threadpool %s.\" % self.name)": 5119, "def seconds_to_time(x):\n \"\"\"Convert a number of second into a time\"\"\"\n t = int(x * 10**6)\n ms = t % 10**6\n t = t // 10**6\n s = t % 60\n t = t // 60\n m = t % 60\n t = t // 60\n h = t\n return time(h, m, s, ms)": 5120, "def _make_sql_params(self,kw):\n \"\"\"Make a list of strings to pass to an SQL statement\n from the dictionary kw with Python types\"\"\"\n return ['%s=?' %k for k in kw.keys() ]\n for k,v in kw.iteritems():\n vals.append('%s=?' %k)\n return vals": 5121, "def GetRootKey(self):\n \"\"\"Retrieves the root key.\n\n Returns:\n WinRegistryKey: Windows Registry root key or None if not available.\n \"\"\"\n regf_key = self._regf_file.get_root_key()\n if not regf_key:\n return None\n\n return REGFWinRegistryKey(regf_key, key_path=self._key_path_prefix)": 5122, "def _grid_widgets(self):\n \"\"\"Puts the two whole widgets in the correct position depending on compound.\"\"\"\n scrollbar_column = 0 if self.__compound is tk.LEFT else 2\n self.listbox.grid(row=0, column=1, sticky=\"nswe\")\n self.scrollbar.grid(row=0, column=scrollbar_column, sticky=\"ns\")": 5123, "def value_left(self, other):\n \"\"\"\n Returns the value of the other type instance to use in an\n operator method, namely when the method's instance is on the\n left side of the expression.\n \"\"\"\n return other.value if isinstance(other, self.__class__) else other": 5124, "def detach(self, *items):\n \"\"\"\n Unlinks all of the specified items from the tree.\n\n The items and all of their descendants are still present, and may be\n reinserted at another point in the tree, but will not be displayed.\n The root item may not be detached.\n\n :param items: list of item identifiers\n :type items: sequence[str]\n \"\"\"\n self._visual_drag.detach(*items)\n ttk.Treeview.detach(self, *items)": 5125, "def make_prefixed_stack_name(prefix, template_path):\n \"\"\"\n\n :param prefix:\n :param template_path:\n \"\"\"\n parts = os.path.basename(template_path).split('-')\n parts = parts if len(parts) == 1 else parts[:-1]\n return ('%s-%s' % (prefix, '-'.join(parts))).split('.')[0]": 5126, "def append_position_to_token_list(token_list):\n \"\"\"Converts a list of Token into a list of Token, asuming size == 1\"\"\"\n return [PositionToken(value.content, value.gd, index, index+1) for (index, value) in enumerate(token_list)]": 5127, "def on_success(self, fn, *args, **kwargs):\n \"\"\"\n Call the given callback if or when the connected deferred succeeds.\n\n \"\"\"\n\n self._callbacks.append((fn, args, kwargs))\n\n result = self._resulted_in\n if result is not _NOTHING_YET:\n self._succeed(result=result)": 5128, "def log(self, level, msg=None, *args, **kwargs):\n \"\"\"Writes log out at any arbitray level.\"\"\"\n\n return self._log(level, msg, args, kwargs)": 5129, "def timestamping_validate(data, schema):\n \"\"\"\n Custom validation function which inserts a timestamp for when the\n validation occurred\n \"\"\"\n jsonschema.validate(data, schema)\n data['timestamp'] = str(time.time())": 5130, "def assert_error(text, check, n=1):\n \"\"\"Assert that text has n errors of type check.\"\"\"\n assert_error.description = \"No {} error for '{}'\".format(check, text)\n assert(check in [error[0] for error in lint(text)])": 5131, "def send(self, topic, *args, **kwargs):\n \"\"\"\n Appends the prefix to the topic before sendingf\n \"\"\"\n prefix_topic = self.heroku_kafka.prefix_topic(topic)\n return super(HerokuKafkaProducer, self).send(prefix_topic, *args, **kwargs)": 5132, "def kubectl(*args, input=None, **flags):\n \"\"\"Simple wrapper to kubectl.\"\"\"\n # Build command line call.\n line = ['kubectl'] + list(args)\n line = line + get_flag_args(**flags)\n if input is not None:\n line = line + ['-f', '-']\n # Run subprocess\n output = subprocess.run(\n line,\n input=input,\n capture_output=True,\n text=True\n )\n return output": 5133, "def _get_context(argspec, kwargs):\n \"\"\"Prepare a context for the serialization.\n\n :param argspec: The argspec of the serialization function.\n :param kwargs: Dict with context\n :return: Keywords arguments that function can accept.\n \"\"\"\n if argspec.keywords is not None:\n return kwargs\n return dict((arg, kwargs[arg]) for arg in argspec.args if arg in kwargs)": 5134, "def retry_until_not_none_or_limit_reached(method, limit, sleep_s=1,\n catch_exceptions=()):\n \"\"\"Executes a method until the retry limit is hit or not None is returned.\"\"\"\n return retry_until_valid_or_limit_reached(\n method, limit, lambda x: x is not None, sleep_s, catch_exceptions)": 5135, "def increment(self, amount=1):\n \"\"\"\n Increments the main progress bar by amount.\n \"\"\"\n self._primaryProgressBar.setValue(self.value() + amount)\n QApplication.instance().processEvents()": 5136, "def safe_url(url):\n \"\"\"Remove password from printed connection URLs.\"\"\"\n parsed = urlparse(url)\n if parsed.password is not None:\n pwd = ':%s@' % parsed.password\n url = url.replace(pwd, ':*****@')\n return url": 5137, "def get_services():\n \"\"\"\n Retrieve a list of all system services.\n\n @see: L{get_active_services},\n L{start_service}, L{stop_service},\n L{pause_service}, L{resume_service}\n\n @rtype: list( L{win32.ServiceStatusProcessEntry} )\n @return: List of service status descriptors.\n \"\"\"\n with win32.OpenSCManager(\n dwDesiredAccess = win32.SC_MANAGER_ENUMERATE_SERVICE\n ) as hSCManager:\n try:\n return win32.EnumServicesStatusEx(hSCManager)\n except AttributeError:\n return win32.EnumServicesStatus(hSCManager)": 5138, "def addClassKey(self, klass, key, obj):\n \"\"\"\n Adds an object to the collection, based on klass and key.\n\n @param klass: The class of the object.\n @param key: The datastore key of the object.\n @param obj: The loaded instance from the datastore.\n \"\"\"\n d = self._getClass(klass)\n\n d[key] = obj": 5139, "def c2u(name):\n \"\"\"Convert camelCase (used in PHP) to Python-standard snake_case.\n\n Src:\n https://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-snake-case\n\n Parameters\n ----------\n name: A function or variable name in camelCase\n\n Returns\n -------\n str: The name in snake_case\n\n \"\"\"\n s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', name)\n s1 = re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()\n return s1": 5140, "def clear_caches():\n \"\"\"Jinja2 keeps internal caches for environments and lexers. These are\n used so that Jinja2 doesn't have to recreate environments and lexers all\n the time. Normally you don't have to care about that but if you are\n measuring memory consumption you may want to clean the caches.\n \"\"\"\n from jinja2.environment import _spontaneous_environments\n from jinja2.lexer import _lexer_cache\n _spontaneous_environments.clear()\n _lexer_cache.clear()": 5141, "def __init__(self, response):\n \"\"\"Initialize a ResponseException instance.\n\n :param response: A requests.response instance.\n\n \"\"\"\n self.response = response\n super(ResponseException, self).__init__(\n \"received {} HTTP response\".format(response.status_code)\n )": 5142, "def _group_dict_set(iterator):\n \"\"\"Make a dict that accumulates the values for each key in an iterator of doubles.\n\n :param iter[tuple[A,B]] iterator: An iterator\n :rtype: dict[A,set[B]]\n \"\"\"\n d = defaultdict(set)\n for key, value in iterator:\n d[key].add(value)\n return dict(d)": 5143, "def acquire_nix(lock_file): # pragma: no cover\n \"\"\"Acquire a lock file on linux or osx.\"\"\"\n fd = os.open(lock_file, OPEN_MODE)\n\n try:\n fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)\n except (IOError, OSError):\n os.close(fd)\n else:\n return fd": 5144, "def __Logout(si):\n \"\"\"\n Disconnect (logout) service instance\n @param si: Service instance (returned from Connect)\n \"\"\"\n try:\n if si:\n content = si.RetrieveContent()\n content.sessionManager.Logout()\n except Exception as e:\n pass": 5145, "def write_string(value, buff, byteorder='big'):\n \"\"\"Write a string to a file-like object.\"\"\"\n data = value.encode('utf-8')\n write_numeric(USHORT, len(data), buff, byteorder)\n buff.write(data)": 5146, "def start_task(self, task):\n \"\"\"Begin logging of a task\n\n Stores the time this task was started in order to return\n time lapsed when `complete_task` is called.\n\n Parameters\n ----------\n task : str\n Name of the task to be started\n \"\"\"\n self.info(\"Calculating {}...\".format(task))\n self.tasks[task] = self.timer()": 5147, "def merge(self, obj):\n \"\"\"This function merge another object's values with this instance\n\n :param obj: An object to be merged with into this layer\n :type obj: object\n \"\"\"\n for attribute in dir(obj):\n if '__' in attribute:\n continue\n setattr(self, attribute, getattr(obj, attribute))": 5148, "def elXpath(self, xpath, dom=None):\n \"\"\"check if element is present by css\"\"\"\n if dom is None:\n dom = self.browser\n return expect(dom.is_element_present_by_xpath, args=[xpath])": 5149, "def astype(array, y):\n \"\"\"A functional form of the `astype` method.\n\n Args:\n array: The array or number to cast.\n y: An array or number, as the input, whose type should be that of array.\n\n Returns:\n An array or number with the same dtype as `y`.\n \"\"\"\n if isinstance(y, autograd.core.Node):\n return array.astype(numpy.array(y.value).dtype)\n return array.astype(numpy.array(y).dtype)": 5150, "def save(self):\n \"\"\"save the current session\n override, if session was saved earlier\"\"\"\n if self.path:\n self._saveState(self.path)\n else:\n self.saveAs()": 5151, "def _parse_array(self, tensor_proto):\n \"\"\"Grab data in TensorProto and convert to numpy array.\"\"\"\n try:\n from onnx.numpy_helper import to_array\n except ImportError as e:\n raise ImportError(\"Unable to import onnx which is required {}\".format(e))\n np_array = to_array(tensor_proto).reshape(tuple(tensor_proto.dims))\n return mx.nd.array(np_array)": 5152, "def filehash(path):\n \"\"\"Make an MD5 hash of a file, ignoring any differences in line\n ending characters.\"\"\"\n with open(path, \"rU\") as f:\n return md5(py3compat.str_to_bytes(f.read())).hexdigest()": 5153, "def _is_target_a_directory(link, rel_target):\n\t\"\"\"\n\tIf creating a symlink from link to a target, determine if target\n\tis a directory (relative to dirname(link)).\n\t\"\"\"\n\ttarget = os.path.join(os.path.dirname(link), rel_target)\n\treturn os.path.isdir(target)": 5154, "def fetch(self):\n \"\"\"\n Fetch & return a new `Domain` object representing the domain's current\n state\n\n :rtype: Domain\n :raises DOAPIError: if the API endpoint replies with an error (e.g., if\n the domain no longer exists)\n \"\"\"\n api = self.doapi_manager\n return api._domain(api.request(self.url)[\"domain\"])": 5155, "def _fetch_all_as_dict(self, cursor):\n \"\"\"\n Iterates over the result set and converts each row to a dictionary\n\n :return: A list of dictionaries where each row is a dictionary\n :rtype: list of dict\n \"\"\"\n desc = cursor.description\n return [\n dict(zip([col[0] for col in desc], row))\n for row in cursor.fetchall()\n ]": 5156, "def add_widgets(self, *widgets_or_spacings):\n \"\"\"Add widgets/spacing to dialog vertical layout\"\"\"\n layout = self.layout()\n for widget_or_spacing in widgets_or_spacings:\n if isinstance(widget_or_spacing, int):\n layout.addSpacing(widget_or_spacing)\n else:\n layout.addWidget(widget_or_spacing)": 5157, "def _sort_r(sorted, processed, key, deps, dependency_tree):\n \"\"\"Recursive topological sort implementation.\"\"\"\n if key in processed:\n return\n processed.add(key)\n for dep_key in deps:\n dep_deps = dependency_tree.get(dep_key)\n if dep_deps is None:\n log.debug('\"%s\" not found, skipped', Repr(dep_key))\n continue\n _sort_r(sorted, processed, dep_key, dep_deps, dependency_tree)\n sorted.append((key, deps))": 5158, "def sinwave(n=4,inc=.25):\n\t\"\"\"\n\tReturns a DataFrame with the required format for \n\ta surface (sine wave) plot\n\n\tParameters:\n\t-----------\n\t\tn : int\n\t\t\tRanges for X and Y axis (-n,n)\n\t\tn_y : int\n\t\t\tSize of increment along the axis\n\t\"\"\"\t\n\tx=np.arange(-n,n,inc)\n\ty=np.arange(-n,n,inc)\n\tX,Y=np.meshgrid(x,y)\n\tR = np.sqrt(X**2 + Y**2)\n\tZ = np.sin(R)/(.5*R)\n\treturn pd.DataFrame(Z,index=x,columns=y)": 5159, "def get_serial_number_string(self):\n \"\"\" Get the Serial Number String from the HID device.\n\n :return: The Serial Number String\n :rtype: unicode\n\n \"\"\"\n self._check_device_status()\n str_p = ffi.new(\"wchar_t[]\", 255)\n rv = hidapi.hid_get_serial_number_string(self._device, str_p, 255)\n if rv == -1:\n raise IOError(\"Failed to read serial number string from HID \"\n \"device: {0}\".format(self._get_last_error_string()))\n return ffi.string(str_p)": 5160, "def __PrintEnumDocstringLines(self, enum_type):\n description = enum_type.description or '%s enum type.' % enum_type.name\n for line in textwrap.wrap('r\"\"\"%s' % description,\n self.__printer.CalculateWidth()):\n self.__printer(line)\n PrintIndentedDescriptions(self.__printer, enum_type.values, 'Values')\n self.__printer('\"\"\"')": 5161, "def property_as_list(self, property_name):\n \"\"\" property() but encapsulates it in a list, if it's a\n single-element property.\n \"\"\"\n try:\n res = self._a_tags[property_name]\n except KeyError:\n return []\n\n if type(res) == list:\n return res\n else:\n return [res]": 5162, "def reindex_axis(self, labels, axis=0, **kwargs):\n \"\"\"\n Conform Series to new index with optional filling logic.\n\n .. deprecated:: 0.21.0\n Use ``Series.reindex`` instead.\n \"\"\"\n # for compatibility with higher dims\n if axis != 0:\n raise ValueError(\"cannot reindex series on non-zero axis!\")\n msg = (\"'.reindex_axis' is deprecated and will be removed in a future \"\n \"version. Use '.reindex' instead.\")\n warnings.warn(msg, FutureWarning, stacklevel=2)\n\n return self.reindex(index=labels, **kwargs)": 5163, "def listen_for_updates(self):\n \"\"\"Attach a callback on the group pubsub\"\"\"\n self.toredis.subscribe(self.group_pubsub, callback=self.callback)": 5164, "def remove_element(self, e):\n \"\"\"Remove element `e` from model\n \"\"\"\n \n if e.label is not None: self.elementdict.pop(e.label)\n self.elementlist.remove(e)": 5165, "def block_view(arr, block=(3, 3)):\n \"\"\"Provide a 2D block view to 2D array.\n\n No error checking made. Therefore meaningful (as implemented) only for\n blocks strictly compatible with the shape of A.\n\n \"\"\"\n\n # simple shape and strides computations may seem at first strange\n # unless one is able to recognize the 'tuple additions' involved ;-)\n shape = (arr.shape[0] // block[0], arr.shape[1] // block[1]) + block\n strides = (block[0] * arr.strides[0], block[1] * arr.strides[1]) + arr.strides\n return ast(arr, shape=shape, strides=strides)": 5166, "def delete_index(self):\n \"\"\"\n Delete the index, if it exists.\n \"\"\"\n es = self._init_connection()\n if es.indices.exists(index=self.index):\n es.indices.delete(index=self.index)": 5167, "def preprocess_french(trans, fr_nlp, remove_brackets_content=True):\n \"\"\" Takes a list of sentences in french and preprocesses them.\"\"\"\n\n if remove_brackets_content:\n trans = pangloss.remove_content_in_brackets(trans, \"[]\")\n # Not sure why I have to split and rejoin, but that fixes a Spacy token\n # error.\n trans = fr_nlp(\" \".join(trans.split()[:]))\n #trans = fr_nlp(trans)\n trans = \" \".join([token.lower_ for token in trans if not token.is_punct])\n\n return trans": 5168, "def __init__(self, filename, mode, encoding=None):\n \"\"\"Use the specified filename for streamed logging.\"\"\"\n FileHandler.__init__(self, filename, mode, encoding)\n self.mode = mode\n self.encoding = encoding": 5169, "def _create_statusicon(self):\n \"\"\"Return a new Gtk.StatusIcon.\"\"\"\n statusicon = Gtk.StatusIcon()\n statusicon.set_from_gicon(self._icons.get_gicon('media'))\n statusicon.set_tooltip_text(_(\"udiskie\"))\n return statusicon": 5170, "def sort_matrix(a,n=0):\n \"\"\"\n This will rearrange the array a[n] from lowest to highest, and\n rearrange the rest of a[i]'s in the same way. It is dumb and slow.\n\n Returns a numpy array.\n \"\"\"\n a = _n.array(a)\n return a[:,a[n,:].argsort()]": 5171, "def add_params_to_url(url, params):\n \"\"\"Adds params to url\n\n :param url: Url\n :param params: Params to add\n :return: original url with new params\n \"\"\"\n url_parts = list(urlparse.urlparse(url)) # get url parts\n query = dict(urlparse.parse_qsl(url_parts[4])) # get url query\n query.update(params) # add new params\n url_parts[4] = urlencode(query)\n return urlparse.urlunparse(url_parts)": 5172, "def make_aware(value, timezone):\n \"\"\"\n Makes a naive datetime.datetime in a given time zone aware.\n \"\"\"\n if hasattr(timezone, 'localize') and value not in (datetime.datetime.min, datetime.datetime.max):\n # available for pytz time zones\n return timezone.localize(value, is_dst=None)\n else:\n # may be wrong around DST changes\n return value.replace(tzinfo=timezone)": 5173, "def reset_password(app, appbuilder, username, password):\n \"\"\"\n Resets a user's password\n \"\"\"\n _appbuilder = import_application(app, appbuilder)\n user = _appbuilder.sm.find_user(username=username)\n if not user:\n click.echo(\"User {0} not found.\".format(username))\n else:\n _appbuilder.sm.reset_password(user.id, password)\n click.echo(click.style(\"User {0} reseted.\".format(username), fg=\"green\"))": 5174, "def check(text):\n \"\"\"Check the text.\"\"\"\n err = \"malapropisms.misc\"\n msg = u\"'{}' is a malapropism.\"\n\n illogics = [\n \"the infinitesimal universe\",\n \"a serial experience\",\n \"attack my voracity\",\n ]\n\n return existence_check(text, illogics, err, msg, offset=1)": 5175, "def apply(filter):\n \"\"\"Manufacture decorator that filters return value with given function.\n\n ``filter``:\n Callable that takes a single parameter.\n \"\"\"\n def decorator(callable):\n return lambda *args, **kwargs: filter(callable(*args, **kwargs))\n return decorator": 5176, "def create_response(self, request, content, content_type):\n \"\"\"Returns a response object for the request. Can be overridden to return different responses.\"\"\"\n\n return HttpResponse(content=content, content_type=content_type)": 5177, "def latlng(arg):\n \"\"\"Converts a lat/lon pair to a comma-separated string.\n\n For example:\n\n sydney = {\n \"lat\" : -33.8674869,\n \"lng\" : 151.2069902\n }\n\n convert.latlng(sydney)\n # '-33.8674869,151.2069902'\n\n For convenience, also accepts lat/lon pair as a string, in\n which case it's returned unchanged.\n\n :param arg: The lat/lon pair.\n :type arg: string or dict or list or tuple\n \"\"\"\n if is_string(arg):\n return arg\n\n normalized = normalize_lat_lng(arg)\n return \"%s,%s\" % (format_float(normalized[0]), format_float(normalized[1]))": 5178, "def delete(filething):\n \"\"\" delete(filething)\n\n Arguments:\n filething (filething)\n Raises:\n mutagen.MutagenError\n\n Remove tags from a file.\n \"\"\"\n\n t = MP4(filething)\n filething.fileobj.seek(0)\n t.delete(filething)": 5179, "def access_ok(self, access):\n \"\"\" Check if there is enough permissions for access \"\"\"\n for c in access:\n if c not in self.perms:\n return False\n return True": 5180, "def creation_time(self):\n \"\"\"dfdatetime.Filetime: creation time or None if not set.\"\"\"\n timestamp = self._fsntfs_attribute.get_creation_time_as_integer()\n return dfdatetime_filetime.Filetime(timestamp=timestamp)": 5181, "def nmse(a, b):\n \"\"\"Returns the normalized mean square error of a and b\n \"\"\"\n return np.square(a - b).mean() / (a.mean() * b.mean())": 5182, "def _rescale_array(self, array, scale, zero):\n \"\"\"\n Scale the input array\n \"\"\"\n if scale != 1.0:\n sval = numpy.array(scale, dtype=array.dtype)\n array *= sval\n if zero != 0.0:\n zval = numpy.array(zero, dtype=array.dtype)\n array += zval": 5183, "def extract_vars_above(*names):\n \"\"\"Extract a set of variables by name from another frame.\n\n Similar to extractVars(), but with a specified depth of 1, so that names\n are exctracted exactly from above the caller.\n\n This is simply a convenience function so that the very common case (for us)\n of skipping exactly 1 frame doesn't have to construct a special dict for\n keyword passing.\"\"\"\n\n callerNS = sys._getframe(2).f_locals\n return dict((k,callerNS[k]) for k in names)": 5184, "def __init__(self, name, contained_key):\n \"\"\"Instantiate an anonymous file-based Bucket around a single key.\n \"\"\"\n self.name = name\n self.contained_key = contained_key": 5185, "def Any(a, axis, keep_dims):\n \"\"\"\n Any reduction op.\n \"\"\"\n return np.any(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),\n keepdims=keep_dims),": 5186, "def uncheck(self, locator=None, allow_label_click=None, **kwargs):\n \"\"\"\n Find a check box and uncheck it. The check box can be found via name, id, or label text. ::\n\n page.uncheck(\"German\")\n\n Args:\n locator (str, optional): Which check box to uncheck.\n allow_label_click (bool, optional): Attempt to click the label to toggle state if\n element is non-visible. Defaults to :data:`capybara.automatic_label_click`.\n **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.\n \"\"\"\n\n self._check_with_label(\n \"checkbox\", False, locator=locator, allow_label_click=allow_label_click, **kwargs)": 5187, "def upload_as_json(name, mylist):\n \"\"\"\n Upload the IPList as json payload. \n\n :param str name: name of IPList\n :param list: list of IPList entries\n :return: None\n \"\"\"\n location = list(IPList.objects.filter(name))\n if location:\n iplist = location[0]\n return iplist.upload(json=mylist, as_type='json')": 5188, "def __getattr__(self, *args, **kwargs):\n \"\"\"\n Magic method dispatcher\n \"\"\"\n\n return xmlrpc.client._Method(self.__request, *args, **kwargs)": 5189, "def setRect(self, rect):\n\t\t\"\"\"\n\t\tSets the window bounds from a tuple of (x,y,w,h)\n\t\t\"\"\"\n\t\tself.x, self.y, self.w, self.h = rect": 5190, "def calc_base64(s):\n \"\"\"Return base64 encoded binarystring.\"\"\"\n s = compat.to_bytes(s)\n s = compat.base64_encodebytes(s).strip() # return bytestring\n return compat.to_native(s)": 5191, "def prsint(string):\n \"\"\"\n Parse a string as an integer, encapsulating error handling.\n\n http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/prsint_c.html\n\n :param string: String representing an integer.\n :type string: str\n :return: Integer value obtained by parsing string.\n :rtype: int\n \"\"\"\n string = stypes.stringToCharP(string)\n intval = ctypes.c_int()\n libspice.prsint_c(string, ctypes.byref(intval))\n return intval.value": 5192, "def testable_memoized_property(func=None, key_factory=per_instance, **kwargs):\n \"\"\"A variant of `memoized_property` that allows for setting of properties (for tests, etc).\"\"\"\n getter = memoized_method(func=func, key_factory=key_factory, **kwargs)\n\n def setter(self, val):\n with getter.put(self) as putter:\n putter(val)\n\n return property(fget=getter,\n fset=setter,\n fdel=lambda self: getter.forget(self))": 5193, "def is_cached(self, url):\n \"\"\"Checks if specified URL is cached.\"\"\"\n try:\n return True if url in self.cache else False\n except TypeError:\n return False": 5194, "def add_xlabel(self, text=None):\n \"\"\"\n Add a label to the x-axis.\n \"\"\"\n x = self.fit.meta['independent']\n if not text:\n text = '$' + x['tex_symbol'] + r'$ $(\\si{' + x['siunitx'] + r'})$'\n self.plt.set_xlabel(text)": 5195, "def stft(func=None, **kwparams):\n \"\"\"\n Short Time Fourier Transform for complex data.\n\n Same to the default STFT strategy, but with new defaults. This is the same\n to:\n\n .. code-block:: python\n\n stft.base(transform=numpy.fft.fft, inverse_transform=numpy.fft.ifft)\n\n See ``stft.base`` docs for more.\n \"\"\"\n from numpy.fft import fft, ifft\n return stft.base(transform=fft, inverse_transform=ifft)(func, **kwparams)": 5196, "def sdmethod(meth):\n \"\"\"\n This is a hack to monkey patch sdproperty to work as expected with instance methods.\n \"\"\"\n sd = singledispatch(meth)\n\n def wrapper(obj, *args, **kwargs):\n return sd.dispatch(args[0].__class__)(obj, *args, **kwargs)\n\n wrapper.register = sd.register\n wrapper.dispatch = sd.dispatch\n wrapper.registry = sd.registry\n wrapper._clear_cache = sd._clear_cache\n functools.update_wrapper(wrapper, meth)\n return wrapper": 5197, "def str_to_boolean(input_str):\n \"\"\" a conversion function for boolean\n \"\"\"\n if not isinstance(input_str, six.string_types):\n raise ValueError(input_str)\n input_str = str_quote_stripper(input_str)\n return input_str.lower() in (\"true\", \"t\", \"1\", \"y\", \"yes\")": 5198, "def schedule_task(self):\n \"\"\"\n Schedules this publish action as a Celery task.\n \"\"\"\n from .tasks import publish_task\n\n publish_task.apply_async(kwargs={'pk': self.pk}, eta=self.scheduled_time)": 5199, "def force_stop(self):\n \"\"\"\n Forcibly terminates all Celery processes.\n \"\"\"\n r = self.local_renderer\n with self.settings(warn_only=True):\n r.sudo('pkill -9 -f celery')\n r.sudo('rm -f /tmp/celery*.pid')": 5200, "def has_add_permission(self, request):\n \"\"\" Can add this object \"\"\"\n return request.user.is_authenticated and request.user.is_active and request.user.is_staff": 5201, "def do_forceescape(value):\n \"\"\"Enforce HTML escaping. This will probably double escape variables.\"\"\"\n if hasattr(value, '__html__'):\n value = value.__html__()\n return escape(unicode(value))": 5202, "def fieldstorage(self):\n \"\"\" `cgi.FieldStorage` from `wsgi.input`.\n \"\"\"\n if self._fieldstorage is None:\n if self._body is not None:\n raise ReadBodyTwiceError()\n\n self._fieldstorage = cgi.FieldStorage(\n environ=self._environ,\n fp=self._environ['wsgi.input']\n )\n\n return self._fieldstorage": 5203, "def napoleon_to_sphinx(docstring, **config_params):\n \"\"\"\n Convert napoleon docstring to plain sphinx string.\n\n Args:\n docstring (str): Docstring in napoleon format.\n **config_params (dict): Whatever napoleon doc configuration you want.\n\n Returns:\n str: Sphinx string.\n \"\"\"\n if \"napoleon_use_param\" not in config_params:\n config_params[\"napoleon_use_param\"] = False\n\n if \"napoleon_use_rtype\" not in config_params:\n config_params[\"napoleon_use_rtype\"] = False\n\n config = Config(**config_params)\n\n return str(GoogleDocstring(docstring, config))": 5204, "def split_string(text, chars_per_string):\n \"\"\"\n Splits one string into multiple strings, with a maximum amount of `chars_per_string` characters per string.\n This is very useful for splitting one giant message into multiples.\n\n :param text: The text to split\n :param chars_per_string: The number of characters per line the text is split into.\n :return: The splitted text as a list of strings.\n \"\"\"\n return [text[i:i + chars_per_string] for i in range(0, len(text), chars_per_string)]": 5205, "def get_checkerboard_matrix(kernel_width):\n\n \"\"\"\n example matrix for width = 2\n\n -1 -1 1 1\n -1 -1 1 1\n 1 1 -1 -1\n 1 1 -1 -1\n\n :param kernel_width:\n :return:\n \"\"\"\n\n return np.vstack((\n np.hstack((\n -1 * np.ones((kernel_width, kernel_width)), np.ones((kernel_width, kernel_width))\n )),\n np.hstack((\n np.ones((kernel_width, kernel_width)), -1 * np.ones((kernel_width, kernel_width))\n ))\n ))": 5206, "def cric__lasso():\n \"\"\" Lasso Regression\n \"\"\"\n model = sklearn.linear_model.LogisticRegression(penalty=\"l1\", C=0.002)\n\n # we want to explain the raw probability outputs of the trees\n model.predict = lambda X: model.predict_proba(X)[:,1]\n \n return model": 5207, "def from_file_url(url):\n \"\"\" Convert from file:// url to file path\n \"\"\"\n if url.startswith('file://'):\n url = url[len('file://'):].replace('/', os.path.sep)\n\n return url": 5208, "def to_array(self):\n \"\"\"Convert the table to a structured NumPy array.\"\"\"\n dt = np.dtype(list(zip(self.labels, (c.dtype for c in self.columns))))\n arr = np.empty_like(self.columns[0], dt)\n for label in self.labels:\n arr[label] = self[label]\n return arr": 5209, "def _check_valid(key, val, valid):\n \"\"\"Helper to check valid options\"\"\"\n if val not in valid:\n raise ValueError('%s must be one of %s, not \"%s\"'\n % (key, valid, val))": 5210, "def blueprint_name_to_url(name):\n \"\"\" remove the last . in the string it it ends with a .\n for the url structure must follow the flask routing format\n it should be /model/method instead of /model/method/\n \"\"\"\n if name[-1:] == \".\":\n name = name[:-1]\n name = str(name).replace(\".\", \"/\")\n return name": 5211, "def is_bytes(string):\n \"\"\"Check if a string is a bytes instance\n\n :param Union[str, bytes] string: A string that may be string or bytes like\n :return: Whether the provided string is a bytes type or not\n :rtype: bool\n \"\"\"\n if six.PY3 and isinstance(string, (bytes, memoryview, bytearray)): # noqa\n return True\n elif six.PY2 and isinstance(string, (buffer, bytearray)): # noqa\n return True\n return False": 5212, "def closeEvent(self, e):\n \"\"\"Qt slot when the window is closed.\"\"\"\n if self._closed:\n return\n res = self.emit('close')\n # Discard the close event if False is returned by one of the callback\n # functions.\n if False in res: # pragma: no cover\n e.ignore()\n return\n super(GUI, self).closeEvent(e)\n self._closed = True": 5213, "def byteswap(data, word_size=4):\n \"\"\" Swap the byte-ordering in a packet with N=4 bytes per word\n \"\"\"\n return reduce(lambda x,y: x+''.join(reversed(y)), chunks(data, word_size), '')": 5214, "def point8_to_box(points):\n \"\"\"\n Args:\n points: (nx4)x2\n Returns:\n nx4 boxes (x1y1x2y2)\n \"\"\"\n p = points.reshape((-1, 4, 2))\n minxy = p.min(axis=1) # nx2\n maxxy = p.max(axis=1) # nx2\n return np.concatenate((minxy, maxxy), axis=1)": 5215, "def wrap(s, width=80):\n \"\"\"\n Formats the text input with newlines given the user specified width for\n each line.\n\n Parameters\n ----------\n\n s : str\n width : int\n\n Returns\n -------\n\n text : str\n\n Notes\n -----\n\n .. versionadded:: 1.1\n\n \"\"\"\n return '\\n'.join(textwrap.wrap(str(s), width=width))": 5216, "def mul(a, b):\n \"\"\"\n A wrapper around tf multiplication that does more automatic casting of\n the input.\n \"\"\"\n def multiply(a, b):\n \"\"\"Multiplication\"\"\"\n return a * b\n return op_with_scalar_cast(a, b, multiply)": 5217, "def is_edge_consistent(graph, u, v):\n \"\"\"Check if all edges between two nodes have the same relation.\n\n :param pybel.BELGraph graph: A BEL Graph\n :param tuple u: The source BEL node\n :param tuple v: The target BEL node\n :return: If all edges from the source to target node have the same relation\n :rtype: bool\n \"\"\"\n if not graph.has_edge(u, v):\n raise ValueError('{} does not contain an edge ({}, {})'.format(graph, u, v))\n\n return 0 == len(set(d[RELATION] for d in graph.edge[u][v].values()))": 5218, "def isreal(obj):\n \"\"\"\n Test if the argument is a real number (float or integer).\n\n :param obj: Object\n :type obj: any\n\n :rtype: boolean\n \"\"\"\n return (\n (obj is not None)\n and (not isinstance(obj, bool))\n and isinstance(obj, (int, float))\n )": 5219, "def irecarray_to_py(a):\n \"\"\"Slow conversion of a recarray into a list of records with python types.\n\n Get the field names from :attr:`a.dtype.names`.\n\n :Returns: iterator so that one can handle big input arrays\n \"\"\"\n pytypes = [pyify(typestr) for name,typestr in a.dtype.descr]\n def convert_record(r):\n return tuple([converter(value) for converter, value in zip(pytypes,r)])\n return (convert_record(r) for r in a)": 5220, "def close(self):\n \"\"\"Flush the file and close it.\n\n A closed file cannot be written any more. Calling\n :meth:`close` more than once is allowed.\n \"\"\"\n if not self._closed:\n self.__flush()\n object.__setattr__(self, \"_closed\", True)": 5221, "def __call__(self, actual_value, expect):\n \"\"\"Main entry point for assertions (called by the wrapper).\n expect is a function the wrapper class uses to assert a given match.\n \"\"\"\n self._expect = expect\n if self.expected_value is NO_ARG:\n return self.asserts(actual_value)\n return self.asserts(actual_value, self.expected_value)": 5222, "def matchfieldnames(field_a, field_b):\n \"\"\"Check match between two strings, ignoring case and spaces/underscores.\n \n Parameters\n ----------\n a : str\n b : str\n \n Returns\n -------\n bool\n \n \"\"\"\n normalised_a = field_a.replace(' ', '_').lower()\n normalised_b = field_b.replace(' ', '_').lower()\n \n return normalised_a == normalised_b": 5223, "def assert_looks_like(first, second, msg=None):\n \"\"\" Compare two strings if all contiguous whitespace is coalesced. \"\"\"\n first = _re.sub(\"\\s+\", \" \", first.strip())\n second = _re.sub(\"\\s+\", \" \", second.strip())\n if first != second:\n raise AssertionError(msg or \"%r does not look like %r\" % (first, second))": 5224, "def constraint_range_dict(self,*args,**kwargs):\n \"\"\" \n Creates a list of dictionaries which each give a constraint for a certain\n section of the dimension.\n\n bins arguments overwrites resolution\n \"\"\"\n bins = self.bins(*args,**kwargs)\n return [{self.name+'__gte': a,self.name+'__lt': b} for a,b in zip(bins[:-1],bins[1:])]\n space = self.space(*args,**kwargs)\n resolution = space[1] - space[0]\n return [{self.name+'__gte': s,self.name+'__lt': s+resolution} for s in space]": 5225, "def __similarity(s1, s2, ngrams_fn, n=3):\n \"\"\"\n The fraction of n-grams matching between two sequences\n\n Args:\n s1: a string\n s2: another string\n n: an int for the n in n-gram\n\n Returns:\n float: the fraction of n-grams matching\n \"\"\"\n ngrams1, ngrams2 = set(ngrams_fn(s1, n=n)), set(ngrams_fn(s2, n=n))\n matches = ngrams1.intersection(ngrams2)\n return 2 * len(matches) / (len(ngrams1) + len(ngrams2))": 5226, "def __complex__(self):\n \"\"\"Called to implement the built-in function complex().\"\"\"\n if self._t != 99 or self.key != ['re', 'im']:\n return complex(float(self))\n return complex(float(self.re), float(self.im))": 5227, "def extract_pdfminer(self, filename, **kwargs):\n \"\"\"Extract text from pdfs using pdfminer.\"\"\"\n stdout, _ = self.run(['pdf2txt.py', filename])\n return stdout": 5228, "def connect_rds(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):\n \"\"\"\n :type aws_access_key_id: string\n :param aws_access_key_id: Your AWS Access Key ID\n\n :type aws_secret_access_key: string\n :param aws_secret_access_key: Your AWS Secret Access Key\n\n :rtype: :class:`boto.rds.RDSConnection`\n :return: A connection to RDS\n \"\"\"\n from boto.rds import RDSConnection\n return RDSConnection(aws_access_key_id, aws_secret_access_key, **kwargs)": 5229, "def read(self):\n \"\"\"Iterate over all JSON input (Generator)\"\"\"\n\n for line in self.io.read():\n with self.parse_line(line) as j:\n yield j": 5230, "def _parse_canonical_int64(doc):\n \"\"\"Decode a JSON int64 to bson.int64.Int64.\"\"\"\n l_str = doc['$numberLong']\n if len(doc) != 1:\n raise TypeError('Bad $numberLong, extra field(s): %s' % (doc,))\n return Int64(l_str)": 5231, "def find_commons(lists):\n \"\"\"Finds common values\n\n :param lists: List of lists\n :return: List of values that are in common between inner lists\n \"\"\"\n others = lists[1:]\n return [\n val\n for val in lists[0]\n if is_in_all(val, others)\n ]": 5232, "def not0(a):\n \"\"\"Return u if u!= 0, return 1 if u == 0\"\"\"\n return matrix(list(map(lambda x: 1 if x == 0 else x, a)), a.size)": 5233, "def link(self, mu, dist):\n \"\"\"\n glm link function\n this is useful for going from mu to the linear prediction\n\n Parameters\n ----------\n mu : array-like of legth n\n dist : Distribution instance\n\n Returns\n -------\n lp : np.array of length n\n \"\"\"\n return np.log(mu) - np.log(dist.levels - mu)": 5234, "def lines(self):\n \"\"\"\n\n :return:\n \"\"\"\n if self._lines is None:\n self._lines = self.obj.content.splitlines()\n return self._lines": 5235, "def vectorsToMatrix(aa, bb):\n \"\"\"\n Performs the vector multiplication of the elements of two vectors, constructing the 3x3 matrix.\n :param aa: One vector of size 3\n :param bb: Another vector of size 3\n :return: A 3x3 matrix M composed of the products of the elements of aa and bb :\n M_ij = aa_i * bb_j\n \"\"\"\n MM = np.zeros([3, 3], np.float)\n for ii in range(3):\n for jj in range(3):\n MM[ii, jj] = aa[ii] * bb[jj]\n return MM": 5236, "def build_service_class(metadata):\n \"\"\"Generate a service class for the service contained in the specified metadata class.\"\"\"\n i = importlib.import_module(metadata)\n service = i.service\n env = get_jinja_env()\n service_template = env.get_template('service.py.jinja2')\n with open(api_path(service.name.lower()), 'w') as t:\n t.write(service_template.render(service_md=service))": 5237, "def validate(self, obj):\n \"\"\" Raises django.core.exceptions.ValidationError if any validation error exists \"\"\"\n\n if not isinstance(obj, self.model_class):\n raise ValidationError('Invalid object(%s) for service %s' % (type(obj), type(self)))\n LOG.debug(u'Object %s state: %s', self.model_class, obj.__dict__)\n obj.full_clean()": 5238, "def is_port_open(port, host=\"127.0.0.1\"):\n \"\"\"\n Check if a port is open\n :param port:\n :param host:\n :return bool:\n \"\"\"\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n s.connect((host, int(port)))\n s.shutdown(2)\n return True\n except Exception as e:\n return False": 5239, "def _is_utf_8(txt):\n \"\"\"\n Check a string is utf-8 encoded\n\n :param bytes txt: utf-8 string\n :return: Whether the string\\\n is utf-8 encoded or not\n :rtype: bool\n \"\"\"\n assert isinstance(txt, six.binary_type)\n\n try:\n _ = six.text_type(txt, 'utf-8')\n except (TypeError, UnicodeEncodeError):\n return False\n else:\n return True": 5240, "def validate(self, val):\n \"\"\"\n Validates that the val is in the list of values for this Enum.\n\n Returns two element tuple: (bool, string)\n\n - `bool` - True if valid, False if not\n - `string` - Description of validation error, or None if valid\n\n :Parameters:\n val\n Value to validate. Should be a string.\n \"\"\"\n if val in self.values:\n return True, None\n else:\n return False, \"'%s' is not in enum: %s\" % (val, str(self.values))": 5241, "def token_accuracy(labels, outputs):\n \"\"\"Compute tokenwise (elementwise) accuracy.\n\n Args:\n labels: ground-truth labels, shape=(batch, seq_length)\n outputs: predicted tokens, shape=(batch, seq_length)\n Returns:\n Two ops, one for getting the current average accuracy and another for\n updating the running average estimate.\n \"\"\"\n weights = tf.to_float(tf.not_equal(labels, 0))\n return tf.metrics.accuracy(labels, outputs, weights=weights)": 5242, "def add_bg(img, padding, color=COL_WHITE):\n \"\"\"\n Adds a padding to the given image as background of specified color\n\n :param img: Input image.\n :param padding: constant padding around the image.\n :param color: background color that needs to filled for the newly padded region.\n :return: New image with background.\n \"\"\"\n img = gray3(img)\n h, w, d = img.shape\n new_img = np.ones((h + 2*padding, w + 2*padding, d)) * color[:d]\n new_img = new_img.astype(np.uint8)\n set_img_box(new_img, (padding, padding, w, h), img)\n return new_img": 5243, "def clone(src, **kwargs):\n \"\"\"Clones object with optionally overridden fields\"\"\"\n obj = object.__new__(type(src))\n obj.__dict__.update(src.__dict__)\n obj.__dict__.update(kwargs)\n return obj": 5244, "def activate():\n \"\"\"\n Usage:\n containment activate\n \"\"\"\n # This is derived from the clone\n cli = CommandLineInterface()\n cli.ensure_config()\n cli.write_dockerfile()\n cli.build()\n cli.run()": 5245, "def mimetype(self):\n \"\"\"MIME type of the asset.\"\"\"\n return (self.environment.mimetypes.get(self.format_extension) or\n self.compiler_mimetype or 'application/octet-stream')": 5246, "def ts_func(f):\n \"\"\"\n This wraps a function that would normally only accept an array\n and allows it to operate on a DataFrame. Useful for applying\n numpy functions to DataFrames.\n \"\"\"\n def wrap_func(df, *args):\n # TODO: should vectorize to apply over all columns?\n return Chromatogram(f(df.values, *args), df.index, df.columns)\n return wrap_func": 5247, "def apply_conditional_styles(self, cbfct):\n \"\"\"\n Ability to provide dynamic styling of the cell based on its value.\n :param cbfct: function(cell_value) should return a dict of format commands to apply to that cell\n :return: self\n \"\"\"\n for ridx in range(self.nrows):\n for cidx in range(self.ncols):\n fmts = cbfct(self.actual_values.iloc[ridx, cidx])\n fmts and self.iloc[ridx, cidx].apply_styles(fmts)\n return self": 5248, "def create_alias(self):\n \"\"\"Create lambda alias with env name and points it to $LATEST.\"\"\"\n LOG.info('Creating alias %s', self.env)\n\n try:\n self.lambda_client.create_alias(\n FunctionName=self.app_name,\n Name=self.env,\n FunctionVersion='$LATEST',\n Description='Alias for {}'.format(self.env))\n except boto3.exceptions.botocore.exceptions.ClientError as error:\n LOG.debug('Create alias error: %s', error)\n LOG.info(\"Alias creation failed. Retrying...\")\n raise": 5249, "def cmyk(c, m, y, k):\n \"\"\"\n Create a spectra.Color object in the CMYK color space.\n\n :param float c: c coordinate.\n :param float m: m coordinate.\n :param float y: y coordinate.\n :param float k: k coordinate.\n\n :rtype: Color\n :returns: A spectra.Color object in the CMYK color space.\n \"\"\"\n return Color(\"cmyk\", c, m, y, k)": 5250, "def _merge_meta(model1, model2):\n \"\"\"Simple merge of samplesets.\"\"\"\n w1 = _get_meta(model1)\n w2 = _get_meta(model2)\n return metadata.merge(w1, w2, metadata_conflicts='silent')": 5251, "def fromiterable(cls, itr):\n \"\"\"Initialize from iterable\"\"\"\n x, y, z = itr\n return cls(x, y, z)": 5252, "def normalize(self, dt, is_dst=False):\n \"\"\"Correct the timezone information on the given datetime\"\"\"\n if dt.tzinfo is self:\n return dt\n if dt.tzinfo is None:\n raise ValueError('Naive time - no tzinfo set')\n return dt.astimezone(self)": 5253, "def covariance(self,pt0,pt1):\n \"\"\" get the covarince between two points implied by Vario2d\n\n Parameters\n ----------\n pt0 : (iterable of len 2)\n first point x and y\n pt1 : (iterable of len 2)\n second point x and y\n\n Returns\n -------\n cov : float\n covariance between pt0 and pt1\n\n \"\"\"\n\n x = np.array([pt0[0],pt1[0]])\n y = np.array([pt0[1],pt1[1]])\n names = [\"n1\",\"n2\"]\n return self.covariance_matrix(x,y,names=names).x[0,1]": 5254, "def build_parser():\n \"\"\"Build the script's argument parser.\"\"\"\n\n parser = argparse.ArgumentParser(description=\"The IOTile task supervisor\")\n parser.add_argument('-c', '--config', help=\"config json with options\")\n parser.add_argument('-v', '--verbose', action=\"count\", default=0, help=\"Increase logging verbosity\")\n\n return parser": 5255, "def get_mod_time(self, path):\n \"\"\"\n Returns a datetime object representing the last time the file was modified\n\n :param path: remote file path\n :type path: string\n \"\"\"\n conn = self.get_conn()\n ftp_mdtm = conn.sendcmd('MDTM ' + path)\n time_val = ftp_mdtm[4:]\n # time_val optionally has microseconds\n try:\n return datetime.datetime.strptime(time_val, \"%Y%m%d%H%M%S.%f\")\n except ValueError:\n return datetime.datetime.strptime(time_val, '%Y%m%d%H%M%S')": 5256, "def _update_font_style(self, font_style):\n \"\"\"Updates font style widget\n\n Parameters\n ----------\n\n font_style: Integer\n \\tButton down iif font_style == wx.FONTSTYLE_ITALIC\n\n \"\"\"\n\n toggle_state = font_style & wx.FONTSTYLE_ITALIC == wx.FONTSTYLE_ITALIC\n\n self.ToggleTool(wx.FONTFLAG_ITALIC, toggle_state)": 5257, "def expect_comment_end(self):\n \"\"\"Expect a comment end and return the match object.\n \"\"\"\n match = self._expect_match('#}', COMMENT_END_PATTERN)\n self.advance(match.end())": 5258, "def round_corner(radius, fill):\n \"\"\"Draw a round corner\"\"\"\n corner = Image.new('L', (radius, radius), 0) # (0, 0, 0, 0))\n draw = ImageDraw.Draw(corner)\n draw.pieslice((0, 0, radius * 2, radius * 2), 180, 270, fill=fill)\n return corner": 5259, "def this_week():\n \"\"\" Return start and end date of the current week. \"\"\"\n since = TODAY + delta(weekday=MONDAY(-1))\n until = since + delta(weeks=1)\n return Date(since), Date(until)": 5260, "def setHSV(self, pixel, hsv):\n \"\"\"Set single pixel to HSV tuple\"\"\"\n color = conversions.hsv2rgb(hsv)\n self._set_base(pixel, color)": 5261, "def activate_subplot(numPlot):\n \"\"\"Make subplot *numPlot* active on the canvas.\n\n Use this if a simple ``subplot(numRows, numCols, numPlot)``\n overwrites the subplot instead of activating it.\n \"\"\"\n # see http://www.mail-archive.com/matplotlib-users@lists.sourceforge.net/msg07156.html\n from pylab import gcf, axes\n numPlot -= 1 # index is 0-based, plots are 1-based\n return axes(gcf().get_axes()[numPlot])": 5262, "def last_month():\n \"\"\" Return start and end date of this month. \"\"\"\n since = TODAY + delta(day=1, months=-1)\n until = since + delta(months=1)\n return Date(since), Date(until)": 5263, "def select_down(self):\n \"\"\"move cursor down\"\"\"\n r, c = self._index\n self._select_index(r+1, c)": 5264, "def _get_mtime():\n \"\"\"\n Get the modified time of the RPM Database.\n\n Returns:\n Unix ticks\n \"\"\"\n return os.path.exists(RPM_PATH) and int(os.path.getmtime(RPM_PATH)) or 0": 5265, "def del_object_from_parent(self):\n \"\"\" Delete object from parent object. \"\"\"\n if self.parent:\n self.parent.objects.pop(self.ref)": 5266, "def up(self):\n \"\"\"Go up in stack and return True if top frame\"\"\"\n if self.frame:\n self.frame = self.frame.f_back\n return self.frame is None": 5267, "def dispose_orm():\n \"\"\" Properly close pooled database connections \"\"\"\n log.debug(\"Disposing DB connection pool (PID %s)\", os.getpid())\n global engine\n global Session\n\n if Session:\n Session.remove()\n Session = None\n if engine:\n engine.dispose()\n engine = None": 5268, "def _valid_table_name(name):\n \"\"\"Verify if a given table name is valid for `rows`\n\n Rules:\n - Should start with a letter or '_'\n - Letters can be capitalized or not\n - Accepts letters, numbers and _\n \"\"\"\n\n if name[0] not in \"_\" + string.ascii_letters or not set(name).issubset(\n \"_\" + string.ascii_letters + string.digits\n ):\n return False\n\n else:\n return True": 5269, "def has_common(self, other):\n \"\"\"Return set of common words between two word sets.\"\"\"\n if not isinstance(other, WordSet):\n raise ValueError('Can compare only WordSets')\n return self.term_set & other.term_set": 5270, "def timeit(self, metric, func, *args, **kwargs):\n \"\"\"Time execution of callable and emit metric then return result.\"\"\"\n return metrics.timeit(metric, func, *args, **kwargs)": 5271, "def _call_retry(self, force_retry):\n \"\"\"Call request and retry up to max_attempts times (or none if self.max_attempts=1)\"\"\"\n last_exception = None\n for i in range(self.max_attempts):\n try:\n log.info(\"Calling %s %s\" % (self.method, self.url))\n response = self.requests_method(\n self.url,\n data=self.data,\n params=self.params,\n headers=self.headers,\n timeout=(self.connect_timeout, self.read_timeout),\n verify=self.verify_ssl,\n )\n\n if response is None:\n log.warn(\"Got response None\")\n if self._method_is_safe_to_retry():\n delay = 0.5 + i * 0.5\n log.info(\"Waiting %s sec and Retrying since call is a %s\" % (delay, self.method))\n time.sleep(delay)\n continue\n else:\n raise PyMacaronCoreException(\"Call %s %s returned empty response\" % (self.method, self.url))\n\n return response\n\n except Exception as e:\n\n last_exception = e\n\n retry = force_retry\n\n if isinstance(e, ReadTimeout):\n # Log enough to help debugging...\n log.warn(\"Got a ReadTimeout calling %s %s\" % (self.method, self.url))\n log.warn(\"Exception was: %s\" % str(e))\n resp = e.response\n if not resp:\n log.info(\"Requests error has no response.\")\n # TODO: retry=True? Is it really safe?\n else:\n b = resp.content\n log.info(\"Requests has a response with content: \" + pprint.pformat(b))\n if self._method_is_safe_to_retry():\n # It is safe to retry\n log.info(\"Retrying since call is a %s\" % self.method)\n retry = True\n\n elif isinstance(e, ConnectTimeout):\n log.warn(\"Got a ConnectTimeout calling %s %s\" % (self.method, self.url))\n log.warn(\"Exception was: %s\" % str(e))\n # ConnectTimeouts are safe to retry whatever the call...\n retry = True\n\n if retry:\n continue\n else:\n raise e\n\n # max_attempts has been reached: propagate the last received Exception\n if not last_exception:\n last_exception = Exception(\"Reached max-attempts (%s). Giving up calling %s %s\" % (self.max_attempts, self.method, self.url))\n raise last_exception": 5272, "def _check_valid_key(self, key):\n \"\"\"Checks if a key is valid and raises a ValueError if its not.\n\n When in need of checking a key for validity, always use this\n method if possible.\n\n :param key: The key to be checked\n \"\"\"\n if not isinstance(key, key_type):\n raise ValueError('%r is not a valid key type' % key)\n if not VALID_KEY_RE.match(key):\n raise ValueError('%r contains illegal characters' % key)": 5273, "def convert_string(string):\n \"\"\"Convert string to int, float or bool.\n \"\"\"\n if is_int(string):\n return int(string)\n elif is_float(string):\n return float(string)\n elif convert_bool(string)[0]:\n return convert_bool(string)[1]\n elif string == 'None':\n return None\n else:\n return string": 5274, "def get_serialize_format(self, mimetype):\n\t\t\"\"\" Get the serialization format for the given mimetype \"\"\"\n\t\tformat = self.formats.get(mimetype, None)\n\t\tif format is None:\n\t\t\tformat = formats.get(mimetype, None)\n\t\treturn format": 5275, "def tree_render(request, upy_context, vars_dictionary):\n \"\"\"\n It renders template defined in upy_context's page passed in arguments\n \"\"\"\n page = upy_context['PAGE']\n return render_to_response(page.template.file_name, vars_dictionary, context_instance=RequestContext(request))": 5276, "def smartSum(x,key,value):\n \"\"\" create a new page in x if key is not a page of x\n otherwise add value to x[key] \"\"\"\n if key not in list(x.keys()):\n x[key] = value\n else: x[key]+=value": 5277, "def add(self, entity):\n\t\t\"\"\"\n\t\tAdds the supplied dict as a new entity\n\t\t\"\"\"\n\t\tresult = self._http_req('connections', method='POST', payload=entity)\n\t\tstatus = result['status']\n\t\tif not status==201:\n\t\t\traise ServiceRegistryError(status,\"Couldn't add entity\")\n\n\t\tself.debug(0x01,result)\n\t\treturn result['decoded']": 5278, "def load_member(fqn):\n \"\"\"Loads and returns a class for a given fully qualified name.\"\"\"\n modulename, member_name = split_fqn(fqn)\n module = __import__(modulename, globals(), locals(), member_name)\n return getattr(module, member_name)": 5279, "def encode_list(dynamizer, value):\n \"\"\" Encode a list for the DynamoDB format \"\"\"\n encoded_list = []\n dict(map(dynamizer.raw_encode, value))\n for v in value:\n encoded_type, encoded_value = dynamizer.raw_encode(v)\n encoded_list.append({\n encoded_type: encoded_value,\n })\n return 'L', encoded_list": 5280, "def compute_ssim(image1, image2, gaussian_kernel_sigma=1.5,\n gaussian_kernel_width=11):\n \"\"\"Computes SSIM.\n\n Args:\n im1: First PIL Image object to compare.\n im2: Second PIL Image object to compare.\n\n Returns:\n SSIM float value.\n \"\"\"\n gaussian_kernel_1d = get_gaussian_kernel(\n gaussian_kernel_width, gaussian_kernel_sigma)\n return SSIM(image1, gaussian_kernel_1d).ssim_value(image2)": 5281, "def set_strict(self, value):\n \"\"\"\n Set the strict mode active/disable\n\n :param value:\n :type value: bool\n \"\"\"\n assert isinstance(value, bool)\n self.__settings.set_strict(value)": 5282, "def copy(self):\n\t\t\"\"\"Return a shallow copy.\"\"\"\n\t\treturn self.__class__(self.operations.copy(), self.collection, self.document)": 5283, "def cli(yamlfile, directory, out, classname, format):\n \"\"\" Generate graphviz representations of the biolink model \"\"\"\n DotGenerator(yamlfile, format).serialize(classname=classname, dirname=directory, filename=out)": 5284, "def tanimoto_coefficient(a, b):\n \"\"\"Measured similarity between two points in a multi-dimensional space.\n\n Returns:\n 1.0 if the two points completely overlap,\n 0.0 if the two points are infinitely far apart.\n \"\"\"\n return sum(map(lambda (x,y): float(x)*float(y), zip(a,b))) / sum([\n -sum(map(lambda (x,y): float(x)*float(y), zip(a,b))),\n sum(map(lambda x: float(x)**2, a)),\n sum(map(lambda x: float(x)**2, b))])": 5285, "def prt_nts(data_nts, prtfmt=None, prt=sys.stdout, nt_fields=None, **kws):\n \"\"\"Print list of namedtuples into a table using prtfmt.\"\"\"\n prt_txt(prt, data_nts, prtfmt, nt_fields, **kws)": 5286, "def add_column(filename,column,formula,force=False):\n \"\"\" Add a column to a FITS file.\n\n ADW: Could this be replaced by a ftool?\n \"\"\"\n columns = parse_formula(formula)\n logger.info(\"Running file: %s\"%filename)\n logger.debug(\" Reading columns: %s\"%columns)\n data = fitsio.read(filename,columns=columns)\n\n logger.debug(' Evaluating formula: %s'%formula)\n col = eval(formula)\n\n col = np.asarray(col,dtype=[(column,col.dtype)])\n insert_columns(filename,col,force=force)\n return True": 5287, "def from_json(cls, json_doc):\n \"\"\"Parse a JSON string and build an entity.\"\"\"\n try:\n d = json.load(json_doc)\n except AttributeError: # catch the read() error\n d = json.loads(json_doc)\n\n return cls.from_dict(d)": 5288, "def lambda_failure_response(*args):\n \"\"\"\n Helper function to create a Lambda Failure Response\n\n :return: A Flask Response\n \"\"\"\n response_data = jsonify(ServiceErrorResponses._LAMBDA_FAILURE)\n return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_502)": 5289, "def get_handler(self, *args, **options):\n \"\"\"\n Returns the default WSGI handler for the runner.\n \"\"\"\n handler = get_internal_wsgi_application()\n from django.contrib.staticfiles.handlers import StaticFilesHandler\n return StaticFilesHandler(handler)": 5290, "def _enter_plotting(self, fontsize=9):\n \"\"\"assumes that a figure is open \"\"\"\n # interactive_status = matplotlib.is_interactive()\n self.original_fontsize = pyplot.rcParams['font.size']\n pyplot.rcParams['font.size'] = fontsize\n pyplot.hold(False) # opens a figure window, if non exists\n pyplot.ioff()": 5291, "def count_levels(value):\n \"\"\"\n Count how many levels are in a dict:\n scalar, list etc = 0\n {} = 0\n {'a':1} = 1\n {'a' : {'b' : 1}} = 2\n etc...\n \"\"\"\n if not isinstance(value, dict) or len(value) == 0:\n return 0\n elif len(value) == 0:\n return 0 #An emptu dict has 0\n else:\n nextval = list(value.values())[0]\n return 1 + count_levels(nextval)": 5292, "def list_of(cls):\n \"\"\"\n Returns a function that checks that each element in a\n list is of a specific type.\n \"\"\"\n return lambda l: isinstance(l, list) and all(isinstance(x, cls) for x in l)": 5293, "def delete(self, name):\n \"\"\"\n Deletes the named entry in the cache.\n :param name: the name.\n :return: true if it is deleted.\n \"\"\"\n if name in self._cache:\n del self._cache[name]\n self.writeCache()\n # TODO clean files\n return True\n return False": 5294, "def rotation_from_quaternion(q_wxyz):\n \"\"\"Convert quaternion array to rotation matrix.\n\n Parameters\n ----------\n q_wxyz : :obj:`numpy.ndarray` of float\n A quaternion in wxyz order.\n\n Returns\n -------\n :obj:`numpy.ndarray` of float\n A 3x3 rotation matrix made from the quaternion.\n \"\"\"\n q_xyzw = np.array([q_wxyz[1], q_wxyz[2], q_wxyz[3], q_wxyz[0]])\n R = transformations.quaternion_matrix(q_xyzw)[:3,:3]\n return R": 5295, "def delete_object_from_file(file_name, save_key, file_location):\n \"\"\"\n Function to delete objects from a shelve\n Args:\n file_name: Shelve storage file name\n save_key: The name of the key the item is stored in\n file_location: The location of the file, derive from the os module\n\n Returns:\n\n \"\"\"\n file = __os.path.join(file_location, file_name)\n shelve_store = __shelve.open(file)\n del shelve_store[save_key]\n shelve_store.close()": 5296, "def getHeaders(self):\n \"\"\"\n Get the headers of this DataFrame.\n\n Returns:\n The headers of this DataFrame.\n \"\"\"\n headers = self._impl.getHeaders()\n return tuple(\n headers.getIndex(i) for i in range(self._impl.getNumCols())\n )": 5297, "def get_chat_member(self, user_id):\n \"\"\"\n Get information about a member of a chat.\n\n :param int user_id: Unique identifier of the target user\n \"\"\"\n return self.bot.api_call(\n \"getChatMember\", chat_id=str(self.id), user_id=str(user_id)\n )": 5298, "def confirm_credential_display(force=False):\n if force:\n return True\n\n msg = \"\"\"\n [WARNING] Your credential is about to be displayed on screen.\n If this is really what you want, type 'y' and press enter.\"\"\"\n\n result = click.confirm(text=msg)\n return result": 5299, "def _is_start(event, node, tagName): # pylint: disable=invalid-name\n \"\"\"Return true if (event, node) is a start event for tagname.\"\"\"\n\n return event == pulldom.START_ELEMENT and node.tagName == tagName": 5300, "def _index2n(self, index):\n \"\"\"\n\n :param index: index convention\n :return: n\n \"\"\"\n n_float = np.sqrt(index + 1) - 1\n n_int = int(n_float)\n if n_int == n_float:\n n = n_int\n else:\n n = n_int + 1\n return n": 5301, "def to_basestring(value):\n \"\"\"Converts a string argument to a subclass of basestring.\n\n In python2, byte and unicode strings are mostly interchangeable,\n so functions that deal with a user-supplied argument in combination\n with ascii string constants can use either and should return the type\n the user supplied. In python3, the two types are not interchangeable,\n so this method is needed to convert byte strings to unicode.\n \"\"\"\n if isinstance(value, _BASESTRING_TYPES):\n return value\n assert isinstance(value, bytes)\n return value.decode(\"utf-8\")": 5302, "def draw(self, mode=\"triangles\"):\n \"\"\" Draw collection \"\"\"\n\n gl.glDepthMask(0)\n Collection.draw(self, mode)\n gl.glDepthMask(1)": 5303, "def fetch(table, cols=\"*\", where=(), group=\"\", order=(), limit=(), **kwargs):\n \"\"\"Convenience wrapper for database SELECT and fetch all.\"\"\"\n return select(table, cols, where, group, order, limit, **kwargs).fetchall()": 5304, "def deleteAll(self):\n \"\"\"\n Deletes whole Solr index. Use with care.\n \"\"\"\n for core in self.endpoints:\n self._send_solr_command(self.endpoints[core], \"{\\\"delete\\\": { \\\"query\\\" : \\\"*:*\\\"}}\")": 5305, "def current_timestamp():\n \"\"\"Returns current time as ISO8601 formatted string in the Zulu TZ\"\"\"\n now = datetime.utcnow()\n timestamp = now.isoformat()[0:19] + 'Z'\n\n debug(\"generated timestamp: {now}\".format(now=timestamp))\n\n return timestamp": 5306, "def hex_to_rgb(h):\n \"\"\" Returns 0 to 1 rgb from a hex list or tuple \"\"\"\n h = h.lstrip('#')\n return tuple(int(h[i:i+2], 16)/255. for i in (0, 2 ,4))": 5307, "def string_to_genomic_range(rstring):\n \"\"\" Convert a string to a genomic range\n\n :param rstring: string representing a genomic range chr1:801-900\n :type rstring:\n :returns: object representing the string\n :rtype: GenomicRange\n \"\"\"\n m = re.match('([^:]+):(\\d+)-(\\d+)',rstring)\n if not m: \n sys.stderr.write(\"ERROR: problem with range string \"+rstring+\"\\n\")\n return GenomicRange(m.group(1),int(m.group(2)),int(m.group(3)))": 5308, "def code_from_ipynb(nb, markdown=False):\n \"\"\"\n Get the code for a given notebook\n\n nb is passed in as a dictionary that's a parsed ipynb file\n \"\"\"\n code = PREAMBLE\n for cell in nb['cells']:\n if cell['cell_type'] == 'code':\n # transform the input to executable Python\n code += ''.join(cell['source'])\n if cell['cell_type'] == 'markdown':\n code += '\\n# ' + '# '.join(cell['source'])\n # We want a blank newline after each cell's output.\n # And the last line of source doesn't have a newline usually.\n code += '\\n\\n'\n return code": 5309, "def gcall(func, *args, **kwargs):\n \"\"\"\n Calls a function, with the given arguments inside Gtk's main loop.\n Example::\n gcall(lbl.set_text, \"foo\")\n\n If this call would be made in a thread there could be problems, using\n it inside Gtk's main loop makes it thread safe.\n \"\"\"\n def idle():\n with gdk.lock:\n return bool(func(*args, **kwargs))\n return gobject.idle_add(idle)": 5310, "def readline(self):\n \"\"\"Get the next line including the newline or '' on EOF.\"\"\"\n self.lineno += 1\n if self._buffer:\n return self._buffer.pop()\n else:\n return self.input.readline()": 5311, "def ratelimit_remaining(self):\n \"\"\"Number of requests before GitHub imposes a ratelimit.\n\n :returns: int\n \"\"\"\n json = self._json(self._get(self._github_url + '/rate_limit'), 200)\n core = json.get('resources', {}).get('core', {})\n self._remaining = core.get('remaining', 0)\n return self._remaining": 5312, "def rewrap(s, width=COLS):\n \"\"\" Join all lines from input string and wrap it at specified width \"\"\"\n s = ' '.join([l.strip() for l in s.strip().split('\\n')])\n return '\\n'.join(textwrap.wrap(s, width))": 5313, "def has_overlaps(self):\n \"\"\"\n :returns: True if one or more range in the list overlaps with another\n :rtype: bool\n \"\"\"\n sorted_list = sorted(self)\n for i in range(0, len(sorted_list) - 1):\n if sorted_list[i].overlaps(sorted_list[i + 1]):\n return True\n return False": 5314, "def login(self, username, password=None, token=None):\n \"\"\"Login user for protected API calls.\"\"\"\n self.session.basic_auth(username, password)": 5315, "def get_year_start(day=None):\n \"\"\"Returns January 1 of the given year.\"\"\"\n day = add_timezone(day or datetime.date.today())\n return day.replace(month=1).replace(day=1)": 5316, "def feature_union_concat(Xs, nsamples, weights):\n \"\"\"Apply weights and concatenate outputs from a FeatureUnion\"\"\"\n if any(x is FIT_FAILURE for x in Xs):\n return FIT_FAILURE\n Xs = [X if w is None else X * w for X, w in zip(Xs, weights) if X is not None]\n if not Xs:\n return np.zeros((nsamples, 0))\n if any(sparse.issparse(f) for f in Xs):\n return sparse.hstack(Xs).tocsr()\n return np.hstack(Xs)": 5317, "def _get_wow64():\n \"\"\"\n Determines if the current process is running in Windows-On-Windows 64 bits.\n\n @rtype: bool\n @return: C{True} of the current process is a 32 bit program running in a\n 64 bit version of Windows, C{False} if it's either a 32 bit program\n in a 32 bit Windows or a 64 bit program in a 64 bit Windows.\n \"\"\"\n # Try to determine if the debugger itself is running on WOW64.\n # On error assume False.\n if bits == 64:\n wow64 = False\n else:\n try:\n wow64 = IsWow64Process( GetCurrentProcess() )\n except Exception:\n wow64 = False\n return wow64": 5318, "def _weighted_selection(l, n):\n \"\"\"\n Selects n random elements from a list of (weight, item) tuples.\n Based on code snippet by Nick Johnson\n \"\"\"\n cuml = []\n items = []\n total_weight = 0.0\n for weight, item in l:\n total_weight += weight\n cuml.append(total_weight)\n items.append(item)\n\n return [items[bisect.bisect(cuml, random.random()*total_weight)] for _ in range(n)]": 5319, "def move_to_start(self, column_label):\n \"\"\"Move a column to the first in order.\"\"\"\n self._columns.move_to_end(column_label, last=False)\n return self": 5320, "def files_changed():\n \"\"\"\n Return the list of file changed in the current branch compared to `master`\n \"\"\"\n with chdir(get_root()):\n result = run_command('git diff --name-only master...', capture='out')\n changed_files = result.stdout.splitlines()\n\n # Remove empty lines\n return [f for f in changed_files if f]": 5321, "def _get_name(column_like):\n \"\"\"\n Get the name from a column-like SQLAlchemy expression.\n\n Works for Columns and Cast expressions.\n \"\"\"\n if isinstance(column_like, Column):\n return column_like.name\n elif isinstance(column_like, Cast):\n return column_like.clause.name": 5322, "def _reload(self, force=False):\n \"\"\"Reloads the configuration from the file and environment variables. Useful if using\n `os.environ` instead of this class' `set_env` method, or if the underlying configuration\n file is changed externally.\n \"\"\"\n self._config_map = dict()\n self._registered_env_keys = set()\n self.__reload_sources(force)\n self.__load_environment_keys()\n self.verify()\n self._clear_memoization()": 5323, "def commits_with_message(message):\n \"\"\"All commits with that message (in current branch)\"\"\"\n output = log(\"--grep '%s'\" % message, oneline=True, quiet=True)\n lines = output.splitlines()\n return [l.split(' ', 1)[0] for l in lines]": 5324, "def get_winfunc(libname, funcname, restype=None, argtypes=(), _libcache={}):\n \"\"\"Retrieve a function from a library/DLL, and set the data types.\"\"\"\n if libname not in _libcache:\n _libcache[libname] = windll.LoadLibrary(libname)\n func = getattr(_libcache[libname], funcname)\n func.argtypes = argtypes\n func.restype = restype\n return func": 5325, "def terminate(self):\n \"\"\"Override of PantsService.terminate() that cleans up when the Pailgun server is terminated.\"\"\"\n # Tear down the Pailgun TCPServer.\n if self.pailgun:\n self.pailgun.server_close()\n\n super(PailgunService, self).terminate()": 5326, "def _find_first_of(line, substrings):\n \"\"\"Find earliest occurrence of one of substrings in line.\n\n Returns pair of index and found substring, or (-1, None)\n if no occurrences of any of substrings were found in line.\n \"\"\"\n starts = ((line.find(i), i) for i in substrings)\n found = [(i, sub) for i, sub in starts if i != -1]\n if found:\n return min(found)\n else:\n return -1, None": 5327, "def open_as_pillow(filename):\n \"\"\" This way can delete file immediately \"\"\"\n with __sys_open(filename, 'rb') as f:\n data = BytesIO(f.read())\n return Image.open(data)": 5328, "async def i2c_write_request(self, command):\n \"\"\"\n This method performs an I2C write at a given I2C address,\n :param command: {\"method\": \"i2c_write_request\", \"params\": [I2C_DEVICE_ADDRESS, [DATA_TO_WRITE]]}\n :returns:No return message.\n \"\"\"\n device_address = int(command[0])\n params = command[1]\n params = [int(i) for i in params]\n await self.core.i2c_write_request(device_address, params)": 5329, "def ismatch(text, pattern):\n \"\"\"Test whether text contains string or matches regex.\"\"\"\n\n if hasattr(pattern, 'search'):\n return pattern.search(text) is not None\n else:\n return pattern in text if Config.options.case_sensitive \\\n else pattern.lower() in text.lower()": 5330, "def static_get_type_attr(t, name):\n \"\"\"\n Get a type attribute statically, circumventing the descriptor protocol.\n \"\"\"\n for type_ in t.mro():\n try:\n return vars(type_)[name]\n except KeyError:\n pass\n raise AttributeError(name)": 5331, "def _get_device_id(self, bus):\n \"\"\"\n Find the device id\n \"\"\"\n _dbus = bus.get(SERVICE_BUS, PATH)\n devices = _dbus.devices()\n\n if self.device is None and self.device_id is None and len(devices) == 1:\n return devices[0]\n\n for id in devices:\n self._dev = bus.get(SERVICE_BUS, DEVICE_PATH + \"/%s\" % id)\n if self.device == self._dev.name:\n return id\n\n return None": 5332, "def props(cls):\n \"\"\"\n Class method that returns all defined arguments within the class.\n \n Returns:\n A dictionary containing all action defined arguments (if any).\n \"\"\"\n return {k:v for (k, v) in inspect.getmembers(cls) if type(v) is Argument}": 5333, "def gettext(self, string, domain=None, **variables):\n \"\"\"Translate a string with the current locale.\"\"\"\n t = self.get_translations(domain)\n return t.ugettext(string) % variables": 5334, "def connect(self, A, B, distance=1):\n \"\"\"Add a link from A and B of given distance, and also add the inverse\n link if the graph is undirected.\"\"\"\n self.connect1(A, B, distance)\n if not self.directed: self.connect1(B, A, distance)": 5335, "def draw_graph(G: nx.DiGraph, filename: str):\n \"\"\" Draw a networkx graph with Pygraphviz. \"\"\"\n A = to_agraph(G)\n A.graph_attr[\"rankdir\"] = \"LR\"\n A.draw(filename, prog=\"dot\")": 5336, "def on_windows ():\n \"\"\" Returns true if running on windows, whether in cygwin or not.\n \"\"\"\n if bjam.variable(\"NT\"):\n return True\n\n elif bjam.variable(\"UNIX\"):\n\n uname = bjam.variable(\"JAMUNAME\")\n if uname and uname[0].startswith(\"CYGWIN\"):\n return True\n\n return False": 5337, "def generate_chunks(string, num_chars):\n \"\"\"Yield num_chars-character chunks from string.\"\"\"\n for start in range(0, len(string), num_chars):\n yield string[start:start+num_chars]": 5338, "def __iter__(self):\n \"\"\"\n Iterate through tree, leaves first\n\n following http://stackoverflow.com/questions/6914803/python-iterator-through-tree-with-list-of-children\n \"\"\"\n for node in chain(*imap(iter, self.children)):\n yield node\n yield self": 5339, "def _clean_up_name(self, name):\n \"\"\"\n Cleans up the name according to the rules specified in this exact\n function. Uses self.naughty, a list of naughty characters.\n \"\"\"\n for n in self.naughty: name = name.replace(n, '_')\n return name": 5340, "def assert_single_element(iterable):\n \"\"\"Get the single element of `iterable`, or raise an error.\n\n :raise: :class:`StopIteration` if there is no element.\n :raise: :class:`ValueError` if there is more than one element.\n \"\"\"\n it = iter(iterable)\n first_item = next(it)\n\n try:\n next(it)\n except StopIteration:\n return first_item\n\n raise ValueError(\"iterable {!r} has more than one element.\".format(iterable))": 5341, "def _grammatical_join_filter(l, arg=None):\n \"\"\"\n :param l: List of strings to join\n :param arg: A pipe-separated list of final_join (\" and \") and\n initial_join (\", \") strings. For example\n :return: A string that grammatically concatenates the items in the list.\n \"\"\"\n if not arg:\n arg = \" and |, \"\n try:\n final_join, initial_joins = arg.split(\"|\")\n except ValueError:\n final_join = arg\n initial_joins = \", \"\n return grammatical_join(l, initial_joins, final_join)": 5342, "def setup():\n \"\"\"Setup pins\"\"\"\n print(\"Simple drive\")\n board.set_pin_mode(L_CTRL_1, Constants.OUTPUT)\n board.set_pin_mode(L_CTRL_2, Constants.OUTPUT)\n board.set_pin_mode(PWM_L, Constants.PWM)\n board.set_pin_mode(R_CTRL_1, Constants.OUTPUT)\n board.set_pin_mode(R_CTRL_2, Constants.OUTPUT)\n board.set_pin_mode(PWM_R, Constants.PWM)": 5343, "def validate(payload, schema):\n \"\"\"Validate `payload` against `schema`, returning an error list.\n\n jsonschema provides lots of information in it's errors, but it can be a bit\n of work to extract all the information.\n \"\"\"\n v = jsonschema.Draft4Validator(\n schema, format_checker=jsonschema.FormatChecker())\n error_list = []\n for error in v.iter_errors(payload):\n message = error.message\n location = '/' + '/'.join([str(c) for c in error.absolute_path])\n error_list.append(message + ' at ' + location)\n return error_list": 5344, "def kill_process(process):\n \"\"\"Kill the process group associated with the given process. (posix)\"\"\"\n logger = logging.getLogger('xenon')\n logger.info('Terminating Xenon-GRPC server.')\n os.kill(process.pid, signal.SIGINT)\n process.wait()": 5345, "def register_plugin(self):\n \"\"\"Register plugin in Spyder's main window\"\"\"\n self.main.restore_scrollbar_position.connect(\n self.restore_scrollbar_position)\n self.main.add_dockwidget(self)": 5346, "def append_text(self, txt):\n \"\"\" adds a line of text to a file \"\"\"\n with open(self.fullname, \"a\") as myfile:\n myfile.write(txt)": 5347, "def tree_predict(x, root, proba=False, regression=False):\n \"\"\"Predicts a probabilities/value/label for the sample x.\n \"\"\"\n\n if isinstance(root, Leaf):\n if proba:\n return root.probabilities\n elif regression:\n return root.mean\n else:\n return root.most_frequent\n\n if root.question.match(x):\n return tree_predict(x, root.true_branch, proba=proba, regression=regression)\n else:\n return tree_predict(x, root.false_branch, proba=proba, regression=regression)": 5348, "def minimise_xyz(xyz):\n \"\"\"Minimise an (x, y, z) coordinate.\"\"\"\n x, y, z = xyz\n m = max(min(x, y), min(max(x, y), z))\n return (x-m, y-m, z-m)": 5349, "def should_be_hidden_as_cause(exc):\n \"\"\" Used everywhere to decide if some exception type should be displayed or hidden as the casue of an error \"\"\"\n # reduced traceback in case of HasWrongType (instance_of checks)\n from valid8.validation_lib.types import HasWrongType, IsWrongType\n return isinstance(exc, (HasWrongType, IsWrongType))": 5350, "def getAllTriples(self):\n \"\"\"Returns:\n\n list of tuples : Each tuple holds a subject, predicate, object triple\n\n \"\"\"\n return [(str(s), str(p), str(o)) for s, p, o in self]": 5351, "def _call(callable_obj, arg_names, namespace):\n \"\"\"Actually calls the callable with the namespace parsed from the command\n line.\n\n Args:\n callable_obj: a callable object\n arg_names: name of the function arguments\n namespace: the namespace object parsed from the command line\n \"\"\"\n arguments = {arg_name: getattr(namespace, arg_name)\n for arg_name in arg_names}\n return callable_obj(**arguments)": 5352, "def load(obj, cls, default_factory):\n \"\"\"Create or load an object if necessary.\n\n Parameters\n ----------\n obj : `object` or `dict` or `None`\n cls : `type`\n default_factory : `function`\n\n Returns\n -------\n `object`\n \"\"\"\n if obj is None:\n return default_factory()\n if isinstance(obj, dict):\n return cls.load(obj)\n return obj": 5353, "def datetime_from_str(string):\n \"\"\"\n\n Args:\n string: string of the form YYMMDD-HH_MM_SS, e.g 160930-18_43_01\n\n Returns: a datetime object\n\n \"\"\"\n\n\n return datetime.datetime(year=2000+int(string[0:2]), month=int(string[2:4]), day=int(string[4:6]), hour=int(string[7:9]), minute=int(string[10:12]),second=int(string[13:15]))": 5354, "def _normalize_numpy_indices(i):\n \"\"\"Normalize the index in case it is a numpy integer or boolean\n array.\"\"\"\n if isinstance(i, np.ndarray):\n if i.dtype == bool:\n i = tuple(j.tolist() for j in i.nonzero())\n elif i.dtype == int:\n i = i.tolist()\n return i": 5355, "def convert_types(cls, value):\n \"\"\"\n Takes a value from MSSQL, and converts it to a value that's safe for\n JSON/Google Cloud Storage/BigQuery.\n \"\"\"\n if isinstance(value, decimal.Decimal):\n return float(value)\n else:\n return value": 5356, "def set_index(self, index):\n \"\"\" Sets the pd dataframe index of all dataframes in the system to index\n \"\"\"\n for df in self.get_DataFrame(data=True, with_population=False):\n df.index = index": 5357, "def screen(self, width, height, colorDepth):\n \"\"\"\n @summary: record resize event of screen (maybe first event)\n @param width: {int} width of screen\n @param height: {int} height of screen\n @param colorDepth: {int} colorDepth\n \"\"\"\n screenEvent = ScreenEvent()\n screenEvent.width.value = width\n screenEvent.height.value = height\n screenEvent.colorDepth.value = colorDepth\n self.rec(screenEvent)": 5358, "def iflatten(L):\n \"\"\"Iterative flatten.\"\"\"\n for sublist in L:\n if hasattr(sublist, '__iter__'):\n for item in iflatten(sublist): yield item\n else: yield sublist": 5359, "def wait_run_in_executor(func, *args, **kwargs):\n \"\"\"\n Run blocking code in a different thread and wait\n for the result.\n\n :param func: Run this function in a different thread\n :param args: Parameters of the function\n :param kwargs: Keyword parameters of the function\n :returns: Return the result of the function\n \"\"\"\n\n loop = asyncio.get_event_loop()\n future = loop.run_in_executor(None, functools.partial(func, *args, **kwargs))\n yield from asyncio.wait([future])\n return future.result()": 5360, "def is_builtin_css_function(name):\n \"\"\"Returns whether the given `name` looks like the name of a builtin CSS\n function.\n\n Unrecognized functions not in this list produce warnings.\n \"\"\"\n name = name.replace('_', '-')\n\n if name in BUILTIN_FUNCTIONS:\n return True\n\n # Vendor-specific functions (-foo-bar) are always okay\n if name[0] == '-' and '-' in name[1:]:\n return True\n\n return False": 5361, "def roots(self):\n \"\"\"\n Returns a list with all roots. Needs Numpy.\n \"\"\"\n import numpy as np\n return np.roots(list(self.values())[::-1]).tolist()": 5362, "def with_defaults(method, nparams, defaults=None):\n \"\"\"Call method with nparams positional parameters, all non-specified defaults are passed None.\n\n :method: the method to call\n :nparams: the number of parameters the function expects\n :defaults: the default values to pass in for the last len(defaults) params\n \"\"\"\n args = [None] * nparams if not defaults else defaults + max(nparams - len(defaults), 0) * [None]\n return method(*args)": 5363, "def is_same_nick(self, left, right):\n \"\"\" Check if given nicknames are equal in the server's case mapping. \"\"\"\n return self.normalize(left) == self.normalize(right)": 5364, "def stop_refresh(self):\n \"\"\"Stop redrawing the canvas at the previously set timed interval.\n \"\"\"\n self.logger.debug(\"stopping timed refresh\")\n self.rf_flags['done'] = True\n self.rf_timer.clear()": 5365, "def _close(self):\n \"\"\"\n Closes the client connection to the database.\n \"\"\"\n if self.connection:\n with self.wrap_database_errors:\n self.connection.client.close()": 5366, "def pascal_row(n):\n \"\"\" Returns n-th row of Pascal's triangle\n \"\"\"\n result = [1]\n x, numerator = 1, n\n for denominator in range(1, n // 2 + 1):\n x *= numerator\n x /= denominator\n result.append(x)\n numerator -= 1\n if n & 1 == 0:\n result.extend(reversed(result[:-1]))\n else:\n result.extend(reversed(result))\n return result": 5367, "def place(self):\n \"\"\"Place this container's canvas onto the parent container's canvas.\"\"\"\n self.place_children()\n self.canvas.append(self.parent.canvas,\n float(self.left), float(self.top))": 5368, "def compute_number_edges(function):\n \"\"\"\n Compute the number of edges of the CFG\n Args:\n function (core.declarations.function.Function)\n Returns:\n int\n \"\"\"\n n = 0\n for node in function.nodes:\n n += len(node.sons)\n return n": 5369, "def solr_to_date(d):\n \"\"\" converts YYYY-MM-DDT00:00:00Z to DD-MM-YYYY \"\"\"\n return \"{day}:{m}:{y}\".format(y=d[:4], m=d[5:7], day=d[8:10]) if d else d": 5370, "def total_regular_pixels_from_mask(mask):\n \"\"\"Compute the total number of unmasked regular pixels in a masks.\"\"\"\n\n total_regular_pixels = 0\n\n for y in range(mask.shape[0]):\n for x in range(mask.shape[1]):\n if not mask[y, x]:\n total_regular_pixels += 1\n\n return total_regular_pixels": 5371, "def make_temp(text):\n \"\"\"\n Creates a temprorary file and writes the `text` into it\n \"\"\"\n import tempfile\n (handle, path) = tempfile.mkstemp(text=True)\n os.close(handle)\n afile = File(path)\n afile.write(text)\n return afile": 5372, "def shader_string(body, glsl_version='450 core'):\n \"\"\"\n Call this method from a function that defines a literal shader string as the \"body\" argument.\n Dresses up a shader string in three ways:\n 1) Insert #version at the top\n 2) Insert #line number declaration\n 3) un-indents\n The line number information can help debug glsl compile errors.\n The version string needs to be the very first characters in the shader,\n which can be distracting, requiring backslashes or other tricks.\n The unindenting allows you to type the shader code at a pleasing indent level\n in your python method, while still creating an unindented GLSL string at the end.\n \"\"\"\n line_count = len(body.split('\\n'))\n line_number = inspect.currentframe().f_back.f_lineno + 1 - line_count\n return \"\"\"\\\n#version %s\n%s\n\"\"\" % (glsl_version, shader_substring(body, stack_frame=2))": 5373, "def perl_cmd():\n \"\"\"Retrieve path to locally installed conda Perl or first in PATH.\n \"\"\"\n perl = which(os.path.join(get_bcbio_bin(), \"perl\"))\n if perl:\n return perl\n else:\n return which(\"perl\")": 5374, "def interface_direct_class(data_class):\n \"\"\"help to direct to the correct interface interacting with DB by class name only\"\"\"\n if data_class in ASSET:\n interface = AssetsInterface()\n elif data_class in PARTY:\n interface = PartiesInterface()\n elif data_class in BOOK:\n interface = BooksInterface()\n elif data_class in CORPORATE_ACTION:\n interface = CorporateActionsInterface()\n elif data_class in MARKET_DATA:\n interface = MarketDataInterface()\n elif data_class in TRANSACTION:\n interface = TransactionsInterface()\n else:\n interface = AssetManagersInterface()\n return interface": 5375, "def dcounts(self):\n \"\"\"\n :return: a data frame with names and distinct counts and fractions for all columns in the database\n \"\"\"\n print(\"WARNING: Distinct value count for all tables can take a long time...\", file=sys.stderr)\n sys.stderr.flush()\n\n data = []\n for t in self.tables():\n for c in t.columns():\n data.append([t.name(), c.name(), c.dcount(), t.size(), c.dcount() / float(t.size())])\n df = pd.DataFrame(data, columns=[\"table\", \"column\", \"distinct\", \"size\", \"fraction\"])\n return df": 5376, "def ms_panset(self, viewer, event, data_x, data_y,\n msg=True):\n \"\"\"An interactive way to set the pan position. The location\n (data_x, data_y) will be centered in the window.\n \"\"\"\n if self.canpan and (event.state == 'down'):\n self._panset(viewer, data_x, data_y, msg=msg)\n return True": 5377, "def _parse_single_response(cls, response_data):\n \"\"\"de-serialize a JSON-RPC Response/error\n\n :Returns: | [result, id] for Responses\n :Raises: | RPCFault+derivates for error-packages/faults, RPCParseError, RPCInvalidRPC\n \"\"\"\n\n if not isinstance(response_data, dict):\n raise errors.RPCInvalidRequest(\"No valid RPC-package.\")\n\n if \"id\" not in response_data:\n raise errors.RPCInvalidRequest(\"\"\"Invalid Response, \"id\" missing.\"\"\")\n\n request_id = response_data['id']\n\n if \"jsonrpc\" not in response_data:\n raise errors.RPCInvalidRequest(\"\"\"Invalid Response, \"jsonrpc\" missing.\"\"\", request_id)\n if not isinstance(response_data[\"jsonrpc\"], (str, unicode)):\n raise errors.RPCInvalidRequest(\"\"\"Invalid Response, \"jsonrpc\" must be a string.\"\"\")\n if response_data[\"jsonrpc\"] != \"2.0\":\n raise errors.RPCInvalidRequest(\"\"\"Invalid jsonrpc version.\"\"\", request_id)\n\n error = response_data.get('error', None)\n result = response_data.get('result', None)\n\n if error and result:\n raise errors.RPCInvalidRequest(\"\"\"Invalid Response, only \"result\" OR \"error\" allowed.\"\"\", request_id)\n\n if error:\n if not isinstance(error, dict):\n raise errors.RPCInvalidRequest(\"Invalid Response, invalid error-object.\", request_id)\n\n if not (\"code\" in error and \"message\" in error):\n raise errors.RPCInvalidRequest(\"Invalid Response, invalid error-object.\", request_id)\n\n error_data = error.get(\"data\", None)\n\n if error['code'] in errors.ERROR_CODE_CLASS_MAP:\n raise errors.ERROR_CODE_CLASS_MAP[error['code']](error_data, request_id)\n else:\n error_object = errors.RPCFault(error_data, request_id)\n error_object.error_code = error['code']\n error_object.message = error['message']\n raise error_object\n\n return result, request_id": 5378, "def _calculate_similarity(c):\n \"\"\"Get a similarity matrix of % of shared sequence\n\n :param c: cluster object\n\n :return ma: similarity matrix\n \"\"\"\n ma = {}\n for idc in c:\n set1 = _get_seqs(c[idc])\n [ma.update({(idc, idc2): _common(set1, _get_seqs(c[idc2]), idc, idc2)}) for idc2 in c if idc != idc2 and (idc2, idc) not in ma]\n # logger.debug(\"_calculate_similarity_ %s\" % ma)\n return ma": 5379, "def bundle_dir():\n \"\"\"Handle resource management within an executable file.\"\"\"\n if frozen():\n directory = sys._MEIPASS\n else:\n directory = os.path.dirname(os.path.abspath(stack()[1][1]))\n if os.path.exists(directory):\n return directory": 5380, "def plotfft(s, fmax, doplot=False):\n \"\"\"\n -----\n Brief\n -----\n This functions computes the Fast Fourier Transform of a signal, returning the frequency and magnitude values.\n\n -----------\n Description\n -----------\n Fast Fourier Transform (FFT) is a method to computationally calculate the Fourier Transform of discrete finite\n signals. This transform converts the time domain signal into a frequency domain signal by abdicating the temporal\n dimension.\n\n This function computes the FFT of the input signal and returns the frequency and respective amplitude values.\n\n ----------\n Parameters\n ----------\n s: array-like\n the input signal.\n fmax: int\n the sampling frequency.\n doplot: boolean\n a variable to indicate whether the plot is done or not.\n\n Returns\n -------\n f: array-like\n the frequency values (xx axis)\n fs: array-like\n the amplitude of the frequency values (yy axis)\n \"\"\"\n\n fs = abs(numpy.fft.fft(s))\n f = numpy.linspace(0, fmax / 2, len(s) / 2)\n if doplot:\n plot(list(f[1:int(len(s) / 2)]), list(fs[1:int(len(s) / 2)]))\n return f[1:int(len(s) / 2)].copy(), fs[1:int(len(s) / 2)].copy()": 5381, "def psql(sql, show=True):\n \"\"\"\n Runs SQL against the project's database.\n \"\"\"\n out = postgres('psql -c \"%s\"' % sql)\n if show:\n print_command(sql)\n return out": 5382, "def download_url(url, filename, headers):\n \"\"\"Download a file from `url` to `filename`.\"\"\"\n ensure_dirs(filename)\n response = requests.get(url, headers=headers, stream=True)\n if response.status_code == 200:\n with open(filename, 'wb') as f:\n for chunk in response.iter_content(16 * 1024):\n f.write(chunk)": 5383, "def destroy(self):\n \"\"\" Destroy the SQLStepQueue tables in the database \"\"\"\n with self._db_conn() as conn:\n for table_name in self._tables:\n conn.execute('DROP TABLE IF EXISTS %s' % table_name)\n return self": 5384, "def do_forceescape(value):\n \"\"\"Enforce HTML escaping. This will probably double escape variables.\"\"\"\n if hasattr(value, '__html__'):\n value = value.__html__()\n return escape(text_type(value))": 5385, "def format_time(timestamp):\n \"\"\"Formats timestamp to human readable format\"\"\"\n format_string = '%Y_%m_%d_%Hh%Mm%Ss'\n formatted_time = datetime.datetime.fromtimestamp(timestamp).strftime(format_string)\n return formatted_time": 5386, "def _chunk_write(chunk, local_file, progress):\n \"\"\"Write a chunk to file and update the progress bar\"\"\"\n local_file.write(chunk)\n progress.update_with_increment_value(len(chunk))": 5387, "def write_only_property(f):\n \"\"\"\n @write_only_property decorator. Creates a property (descriptor attribute)\n that accepts assignment, but not getattr (use in an expression).\n \"\"\"\n docstring = f.__doc__\n\n return property(fset=f, doc=docstring)": 5388, "def getEdges(npArr):\n \"\"\"get np array of bin edges\"\"\"\n edges = np.concatenate(([0], npArr[:,0] + npArr[:,2]))\n return np.array([Decimal(str(i)) for i in edges])": 5389, "def get_callable_documentation(the_callable):\n \"\"\"Return a string with the callable signature and its docstring.\n\n :param the_callable: the callable to be analyzed.\n :type the_callable: function/callable.\n :return: the signature.\n \"\"\"\n return wrap_text_in_a_box(\n title=get_callable_signature_as_string(the_callable),\n body=(getattr(the_callable, '__doc__') or 'No documentation').replace(\n '\\n', '\\n\\n'),\n style='ascii_double')": 5390, "def main(output=None, error=None, verbose=False):\n \"\"\" The main (cli) interface for the pylint runner. \"\"\"\n runner = Runner(args=[\"--verbose\"] if verbose is not False else None)\n runner.run(output, error)": 5391, "def compose(*parameter_functions):\n \"\"\"Composes multiple modification functions in order.\n\n Args:\n *parameter_functions: The functions to compose.\n\n Returns:\n A parameter modification function that consists of applying all the provided\n functions.\n \"\"\"\n def composed_fn(var_name, variable, phase):\n for fn in parameter_functions:\n variable = fn(var_name, variable, phase)\n return variable\n return composed_fn": 5392, "def contextMenuEvent(self, event):\n \"\"\"Reimplement Qt method\"\"\"\n self.menu.popup(event.globalPos())\n event.accept()": 5393, "def remove_parameter(self, name):\n\t\t\"\"\" Remove the specified parameter from this query\n\n\t\t:param name: name of a parameter to remove\n\t\t:return: None\n\t\t\"\"\"\n\t\tif name in self.__query:\n\t\t\tself.__query.pop(name)": 5394, "def bbox(self):\n \"\"\"BBox\"\"\"\n return self.left, self.top, self.right, self.bottom": 5395, "def get_offset_topic_partition_count(kafka_config):\n \"\"\"Given a kafka cluster configuration, return the number of partitions\n in the offset topic. It will raise an UnknownTopic exception if the topic\n cannot be found.\"\"\"\n metadata = get_topic_partition_metadata(kafka_config.broker_list)\n if CONSUMER_OFFSET_TOPIC not in metadata:\n raise UnknownTopic(\"Consumer offset topic is missing.\")\n return len(metadata[CONSUMER_OFFSET_TOPIC])": 5396, "def _regex_span(_regex, _str, case_insensitive=True):\n \"\"\"Return all matches in an input string.\n :rtype : regex.match.span\n :param _regex: A regular expression pattern.\n :param _str: Text on which to run the pattern.\n \"\"\"\n if case_insensitive:\n flags = regex.IGNORECASE | regex.FULLCASE | regex.VERSION1\n else:\n flags = regex.VERSION1\n comp = regex.compile(_regex, flags=flags)\n matches = comp.finditer(_str)\n for match in matches:\n yield match": 5397, "def GetValueByName(self, name):\n \"\"\"Retrieves a value by name.\n\n Value names are not unique and pyregf provides first match for the value.\n\n Args:\n name (str): name of the value or an empty string for the default value.\n\n Returns:\n WinRegistryValue: Windows Registry value if a corresponding value was\n found or None if not.\n \"\"\"\n pyregf_value = self._pyregf_key.get_value_by_name(name)\n if not pyregf_value:\n return None\n\n return REGFWinRegistryValue(pyregf_value)": 5398, "def table_nan_locs(table):\n \"\"\"\n from http://stackoverflow.com/a/14033137/623735\n # gets the indices of the rows with nan values in a dataframe\n pd.isnull(df).any(1).nonzero()[0]\n \"\"\"\n ans = []\n for rownum, row in enumerate(table):\n try:\n if pd.isnull(row).any():\n colnums = pd.isnull(row).nonzero()[0]\n ans += [(rownum, colnum) for colnum in colnums]\n except AttributeError: # table is really just a sequence of scalars\n if pd.isnull(row):\n ans += [(rownum, 0)]\n return ans": 5399, "def strip_sdist_extras(filelist):\n \"\"\"Strip generated files that are only present in source distributions.\n\n We also strip files that are ignored for other reasons, like\n command line arguments, setup.cfg rules or MANIFEST.in rules.\n \"\"\"\n return [name for name in filelist\n if not file_matches(name, IGNORE)\n and not file_matches_regexps(name, IGNORE_REGEXPS)]": 5400, "def get_param_names(cls):\n \"\"\"Returns a list of plottable CBC parameter variables\"\"\"\n return [m[0] for m in inspect.getmembers(cls) \\\n if type(m[1]) == property]": 5401, "def PyplotHistogram():\n \"\"\"\n =============================================================\n Demo of the histogram (hist) function with multiple data sets\n =============================================================\n\n Plot histogram with multiple sample sets and demonstrate:\n\n * Use of legend with multiple sample sets\n * Stacked bars\n * Step curve with no fill\n * Data sets of different sample sizes\n\n Selecting different bin counts and sizes can significantly affect the\n shape of a histogram. The Astropy docs have a great section on how to\n select these parameters:\n http://docs.astropy.org/en/stable/visualization/histogram.html\n \"\"\"\n\n import numpy as np\n import matplotlib.pyplot as plt\n\n np.random.seed(0)\n\n n_bins = 10\n x = np.random.randn(1000, 3)\n\n fig, axes = plt.subplots(nrows=2, ncols=2)\n ax0, ax1, ax2, ax3 = axes.flatten()\n\n colors = ['red', 'tan', 'lime']\n ax0.hist(x, n_bins, normed=1, histtype='bar', color=colors, label=colors)\n ax0.legend(prop={'size': 10})\n ax0.set_title('bars with legend')\n\n ax1.hist(x, n_bins, normed=1, histtype='bar', stacked=True)\n ax1.set_title('stacked bar')\n\n ax2.hist(x, n_bins, histtype='step', stacked=True, fill=False)\n ax2.set_title('stack step (unfilled)')\n\n # Make a multiple-histogram of data-sets with different length.\n x_multi = [np.random.randn(n) for n in [10000, 5000, 2000]]\n ax3.hist(x_multi, n_bins, histtype='bar')\n ax3.set_title('different sample sizes')\n\n fig.tight_layout()\n return fig": 5402, "def dir_exists(self):\n \"\"\"\n Makes a ``HEAD`` requests to the URI.\n\n :returns: ``True`` if status code is 2xx.\n \"\"\"\n\n r = requests.request(self.method if self.method else 'HEAD', self.url, **self.storage_args)\n try: r.raise_for_status()\n except Exception: return False\n\n return True": 5403, "def print_result_from_timeit(stmt='pass', setup='pass', number=1000000):\n \"\"\"\n Clean function to know how much time took the execution of one statement\n \"\"\"\n units = [\"s\", \"ms\", \"us\", \"ns\"]\n duration = timeit(stmt, setup, number=int(number))\n avg_duration = duration / float(number)\n thousands = int(math.floor(math.log(avg_duration, 1000)))\n\n print(\"Total time: %fs. Average run: %.3f%s.\" % (\n duration, avg_duration * (1000 ** -thousands), units[-thousands]))": 5404, "def rotation_matrix(sigma):\n \"\"\"\n\n https://en.wikipedia.org/wiki/Rotation_matrix\n\n \"\"\"\n\n radians = sigma * np.pi / 180.0\n\n r11 = np.cos(radians)\n r12 = -np.sin(radians)\n r21 = np.sin(radians)\n r22 = np.cos(radians)\n\n R = np.array([[r11, r12], [r21, r22]])\n\n return R": 5405, "def readme(filename, encoding='utf8'):\n \"\"\"\n Read the contents of a file\n \"\"\"\n\n with io.open(filename, encoding=encoding) as source:\n return source.read()": 5406, "def bin_open(fname: str):\n \"\"\"\n Returns a file descriptor for a plain text or gzipped file, binary read mode\n for subprocess interaction.\n\n :param fname: The filename to open.\n :return: File descriptor in binary read mode.\n \"\"\"\n if fname.endswith(\".gz\"):\n return gzip.open(fname, \"rb\")\n return open(fname, \"rb\")": 5407, "def pstd(self, *args, **kwargs):\n \"\"\" Console to STDOUT \"\"\"\n kwargs['file'] = self.out\n self.print(*args, **kwargs)\n sys.stdout.flush()": 5408, "def _sslobj(sock):\n \"\"\"Returns the underlying PySLLSocket object with which the C extension\n functions interface.\n\n \"\"\"\n pass\n if isinstance(sock._sslobj, _ssl._SSLSocket):\n return sock._sslobj\n else:\n return sock._sslobj._sslobj": 5409, "def _cho_factor(A, lower=True, check_finite=True):\n \"\"\"Implementaton of :func:`scipy.linalg.cho_factor` using\n a function supported in cupy.\"\"\"\n\n return cp.linalg.cholesky(A), True": 5410, "def handle_logging(self):\n \"\"\"\n To allow devs to log as early as possible, logging will already be\n handled here\n \"\"\"\n\n configure_logging(self.get_scrapy_options())\n\n # Disable duplicates\n self.__scrapy_options[\"LOG_ENABLED\"] = False\n\n # Now, after log-level is correctly set, lets log them.\n for msg in self.log_output:\n if msg[\"level\"] is \"error\":\n self.log.error(msg[\"msg\"])\n elif msg[\"level\"] is \"info\":\n self.log.info(msg[\"msg\"])\n elif msg[\"level\"] is \"debug\":\n self.log.debug(msg[\"msg\"])": 5411, "def __isub__(self, other):\n \"\"\"Remove all elements of another set from this RangeSet.\"\"\"\n self._binary_sanity_check(other)\n set.difference_update(self, other)\n return self": 5412, "def partial_fit(self, X, y=None, classes=None, **fit_params):\n \"\"\"Fit the module.\n\n If the module is initialized, it is not re-initialized, which\n means that this method should be used if you want to continue\n training a model (warm start).\n\n Parameters\n ----------\n X : input data, compatible with skorch.dataset.Dataset\n By default, you should be able to pass:\n\n * numpy arrays\n * torch tensors\n * pandas DataFrame or Series\n * scipy sparse CSR matrices\n * a dictionary of the former three\n * a list/tuple of the former three\n * a Dataset\n\n If this doesn't work with your data, you have to pass a\n ``Dataset`` that can deal with the data.\n\n y : target data, compatible with skorch.dataset.Dataset\n The same data types as for ``X`` are supported. If your X is\n a Dataset that contains the target, ``y`` may be set to\n None.\n\n classes : array, sahpe (n_classes,)\n Solely for sklearn compatibility, currently unused.\n\n **fit_params : dict\n Additional parameters passed to the ``forward`` method of\n the module and to the ``self.train_split`` call.\n\n \"\"\"\n if not self.initialized_:\n self.initialize()\n\n self.notify('on_train_begin', X=X, y=y)\n try:\n self.fit_loop(X, y, **fit_params)\n except KeyboardInterrupt:\n pass\n self.notify('on_train_end', X=X, y=y)\n return self": 5413, "def returns(self):\n \"\"\"The return type for this method in a JSON-compatible format.\n\n This handles the special case of ``None`` which allows ``type(None)`` also.\n\n :rtype: str | None\n \"\"\"\n return_type = self.signature.return_type\n none_type = type(None)\n if return_type is not None and return_type is not none_type:\n return return_type.__name__": 5414, "def process_docstring(app, what, name, obj, options, lines):\n \"\"\"Process the docstring for a given python object.\n\n Called when autodoc has read and processed a docstring. `lines` is a list\n of docstring lines that `_process_docstring` modifies in place to change\n what Sphinx outputs.\n\n The following settings in conf.py control what styles of docstrings will\n be parsed:\n\n * ``napoleon_google_docstring`` -- parse Google style docstrings\n * ``napoleon_numpy_docstring`` -- parse NumPy style docstrings\n\n Parameters\n ----------\n app : sphinx.application.Sphinx\n Application object representing the Sphinx process.\n what : str\n A string specifying the type of the object to which the docstring\n belongs. Valid values: \"module\", \"class\", \"exception\", \"function\",\n \"method\", \"attribute\".\n name : str\n The fully qualified name of the object.\n obj : module, class, exception, function, method, or attribute\n The object to which the docstring belongs.\n options : sphinx.ext.autodoc.Options\n The options given to the directive: an object with attributes\n inherited_members, undoc_members, show_inheritance and noindex that\n are True if the flag option of same name was given to the auto\n directive.\n lines : list of str\n The lines of the docstring, see above.\n\n .. note:: `lines` is modified *in place*\n\n Notes\n -----\n This function is (to most parts) taken from the :mod:`sphinx.ext.napoleon`\n module, sphinx version 1.3.1, and adapted to the classes defined here\"\"\"\n result_lines = lines\n if app.config.napoleon_numpy_docstring:\n docstring = ExtendedNumpyDocstring(\n result_lines, app.config, app, what, name, obj, options)\n result_lines = docstring.lines()\n if app.config.napoleon_google_docstring:\n docstring = ExtendedGoogleDocstring(\n result_lines, app.config, app, what, name, obj, options)\n result_lines = docstring.lines()\n\n lines[:] = result_lines[:]": 5415, "def prompt_yes_or_no(message):\n \"\"\" prompt_yes_or_no: Prompt user to reply with a y/n response\n Args: None\n Returns: None\n \"\"\"\n user_input = input(\"{} [y/n]:\".format(message)).lower()\n if user_input.startswith(\"y\"):\n return True\n elif user_input.startswith(\"n\"):\n return False\n else:\n return prompt_yes_or_no(message)": 5416, "def get_sql(query):\n \"\"\" Returns the sql query \"\"\"\n sql = str(query.statement.compile(dialect=sqlite.dialect(),\n compile_kwargs={\"literal_binds\": True}))\n return sql": 5417, "def rotate_point(xorigin, yorigin, x, y, angle):\n \"\"\"Rotate the given point by angle\n \"\"\"\n rotx = (x - xorigin) * np.cos(angle) - (y - yorigin) * np.sin(angle)\n roty = (x - yorigin) * np.sin(angle) + (y - yorigin) * np.cos(angle)\n return rotx, roty": 5418, "def write_json_corpus(documents, fnm):\n \"\"\"Write a lisst of Text instances as JSON corpus on disk.\n A JSON corpus contains one document per line, encoded in JSON.\n\n Parameters\n ----------\n documents: iterable of estnltk.text.Text\n The documents of the corpus\n fnm: str\n The path to save the corpus.\n \"\"\"\n with codecs.open(fnm, 'wb', 'ascii') as f:\n for document in documents:\n f.write(json.dumps(document) + '\\n')\n return documents": 5419, "def get_connection(self, host, port, db):\n \"\"\"\n Returns a ``StrictRedis`` connection instance.\n \"\"\"\n return redis.StrictRedis(\n host=host,\n port=port,\n db=db,\n decode_responses=True\n )": 5420, "def file_to_png(fp):\n\t\"\"\"Convert an image to PNG format with Pillow.\n\t\n\t:arg file-like fp: The image file.\n\t:rtype: bytes\n\t\"\"\"\n\timport PIL.Image # pylint: disable=import-error\n\twith io.BytesIO() as dest:\n\t\tPIL.Image.open(fp).save(dest, \"PNG\", optimize=True)\n\t\treturn dest.getvalue()": 5421, "def parse_case_snake_to_camel(snake, upper_first=True):\n\t\"\"\"\n\tConvert a string from snake_case to CamelCase.\n\n\t:param str snake: The snake_case string to convert.\n\t:param bool upper_first: Whether or not to capitalize the first\n\t\tcharacter of the string.\n\t:return: The CamelCase version of string.\n\t:rtype: str\n\t\"\"\"\n\tsnake = snake.split('_')\n\tfirst_part = snake[0]\n\tif upper_first:\n\t\tfirst_part = first_part.title()\n\treturn first_part + ''.join(word.title() for word in snake[1:])": 5422, "def set_gradclip_const(self, min_value, max_value):\n \"\"\"\n Configure constant clipping settings.\n\n\n :param min_value: the minimum value to clip by\n :param max_value: the maxmimum value to clip by\n \"\"\"\n callBigDlFunc(self.bigdl_type, \"setConstantClip\", self.value, min_value, max_value)": 5423, "def connect(self):\n \"\"\"Connects to the given host\"\"\"\n self.socket = socket.create_connection(self.address, self.timeout)": 5424, "def dump_parent(self, obj):\n \"\"\"Dump the parent of a PID.\"\"\"\n if not self._is_parent(obj):\n return self._dump_relative(obj.pid)\n return None": 5425, "def test_SVD(pca):\n \"\"\"\n Function to test the validity of singular\n value decomposition by reconstructing original\n data.\n \"\"\"\n _ = pca\n rec = N.dot(_.U,N.dot(_.sigma,_.V))\n assert N.allclose(_.arr,rec)": 5426, "def set_float(self, option, value):\n \"\"\"Set a float option.\n\n Args:\n option (str): name of option.\n value (float): value of the option.\n\n Raises:\n TypeError: Value must be a float.\n \"\"\"\n if not isinstance(value, float):\n raise TypeError(\"Value must be a float\")\n self.options[option] = value": 5427, "def symbols():\n \"\"\"Return a list of symbols.\"\"\"\n symbols = []\n for line in symbols_stream():\n symbols.append(line.decode('utf-8').strip())\n return symbols": 5428, "def fn_abs(self, value):\n \"\"\"\n Return the absolute value of a number.\n\n :param value: The number.\n :return: The absolute value of the number.\n \"\"\"\n\n if is_ndarray(value):\n return numpy.absolute(value)\n else:\n return abs(value)": 5429, "def remove_stopped_threads (self):\n \"\"\"Remove the stopped threads from the internal thread list.\"\"\"\n self.threads = [t for t in self.threads if t.is_alive()]": 5430, "def open_store_variable(self, name, var):\n \"\"\"Turn CDMRemote variable into something like a numpy.ndarray.\"\"\"\n data = indexing.LazilyOuterIndexedArray(CDMArrayWrapper(name, self))\n return Variable(var.dimensions, data, {a: getattr(var, a) for a in var.ncattrs()})": 5431, "def _shutdown_proc(p, timeout):\n \"\"\"Wait for a proc to shut down, then terminate or kill it after `timeout`.\"\"\"\n freq = 10 # how often to check per second\n for _ in range(1 + timeout * freq):\n ret = p.poll()\n if ret is not None:\n logging.info(\"Shutdown gracefully.\")\n return ret\n time.sleep(1 / freq)\n logging.warning(\"Killing the process.\")\n p.kill()\n return p.wait()": 5432, "def to_unix(cls, timestamp):\n \"\"\" Wrapper over time module to produce Unix epoch time as a float \"\"\"\n if not isinstance(timestamp, datetime.datetime):\n raise TypeError('Time.milliseconds expects a datetime object')\n base = time.mktime(timestamp.timetuple())\n return base": 5433, "def keyReleaseEvent(self, event):\n \"\"\"\n Pyqt specific key release callback function.\n Translates and forwards events to :py:func:`keyboard_event`.\n \"\"\"\n self.keyboard_event(event.key(), self.keys.ACTION_RELEASE, 0)": 5434, "def empty(self):\n \"\"\"remove all children from the widget\"\"\"\n for k in list(self.children.keys()):\n self.remove_child(self.children[k])": 5435, "def select_default(self):\n \"\"\"\n Resets the combo box to the original \"selected\" value from the\n constructor (or the first value if no selected value was specified).\n \"\"\"\n if self._default is None:\n if not self._set_option_by_index(0):\n utils.error_format(self.description + \"\\n\" +\n \"Unable to select default option as the Combo is empty\")\n\n else:\n if not self._set_option(self._default):\n utils.error_format( self.description + \"\\n\" +\n \"Unable to select default option as it doesnt exist in the Combo\")": 5436, "def get_host_power_status(self):\n \"\"\"Request the power state of the server.\n\n :returns: Power State of the server, 'ON' or 'OFF'\n :raises: IloError, on an error from iLO.\n \"\"\"\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n return GET_POWER_STATE_MAP.get(sushy_system.power_state)": 5437, "def eglInitialize(display):\n \"\"\" Initialize EGL and return EGL version tuple.\n \"\"\"\n majorVersion = (_c_int*1)()\n minorVersion = (_c_int*1)()\n res = _lib.eglInitialize(display, majorVersion, minorVersion)\n if res == EGL_FALSE:\n raise RuntimeError('Could not initialize')\n return majorVersion[0], minorVersion[0]": 5438, "def stdout_to_results(s):\n \"\"\"Turns the multi-line output of a benchmark process into\n a sequence of BenchmarkResult instances.\"\"\"\n results = s.strip().split('\\n')\n return [BenchmarkResult(*r.split()) for r in results]": 5439, "def union(self, other):\n \"\"\"Return a new set which is the union of I{self} and I{other}.\n\n @param other: the other set\n @type other: Set object\n @rtype: the same type as I{self}\n \"\"\"\n\n obj = self._clone()\n obj.union_update(other)\n return obj": 5440, "def tuple_check(*args, func=None):\n \"\"\"Check if arguments are tuple type.\"\"\"\n func = func or inspect.stack()[2][3]\n for var in args:\n if not isinstance(var, (tuple, collections.abc.Sequence)):\n name = type(var).__name__\n raise TupleError(\n f'Function {func} expected tuple, {name} got instead.')": 5441, "def list_of_dict(self):\n \"\"\"\n This will convert the data from a list of list to a list of dictionary\n :return: list of dict\n \"\"\"\n ret = []\n for row in self:\n ret.append(dict([(self._col_names[i], row[i]) for i in\n range(len(self._col_names))]))\n return ReprListDict(ret, col_names=self._col_names,\n col_types=self._col_types,\n width_limit=self._width_limit,\n digits=self._digits,\n convert_unicode=self._convert_unicode)": 5442, "def uri_to_iri_parts(path, query, fragment):\n r\"\"\"\n Converts a URI parts to corresponding IRI parts in a given charset.\n\n Examples for URI versus IRI:\n\n :param path: The path of URI to convert.\n :param query: The query string of URI to convert.\n :param fragment: The fragment of URI to convert.\n \"\"\"\n path = url_unquote(path, '%/;?')\n query = url_unquote(query, '%;/?:@&=+,$#')\n fragment = url_unquote(fragment, '%;/?:@&=+,$#')\n return path, query, fragment": 5443, "def subscribe(self, handler):\n \"\"\"Adds a new event handler.\"\"\"\n assert callable(handler), \"Invalid handler %s\" % handler\n self.handlers.append(handler)": 5444, "def get_form_bound_field(form, field_name):\n \"\"\"\n Intends to get the bound field from the form regarding the field name\n\n :param form: Django Form: django form instance\n :param field_name: str: name of the field in form instance\n :return: Django Form bound field\n \"\"\"\n field = form.fields[field_name]\n field = field.get_bound_field(form, field_name)\n return field": 5445, "def flatten_union(table):\n \"\"\"Extract all union queries from `table`.\n\n Parameters\n ----------\n table : TableExpr\n\n Returns\n -------\n Iterable[Union[TableExpr, bool]]\n \"\"\"\n op = table.op()\n if isinstance(op, ops.Union):\n return toolz.concatv(\n flatten_union(op.left), [op.distinct], flatten_union(op.right)\n )\n return [table]": 5446, "def script_repr(val,imports,prefix,settings):\n \"\"\"\n Variant of repr() designed for generating a runnable script.\n\n Instances of types that require special handling can use the\n script_repr_reg dictionary. Using the type as a key, add a\n function that returns a suitable representation of instances of\n that type, and adds the required import statement.\n\n The repr of a parameter can be suppressed by returning None from\n the appropriate hook in script_repr_reg.\n \"\"\"\n return pprint(val,imports,prefix,settings,unknown_value=None,\n qualify=True,separator=\"\\n\")": 5447, "def assert_redirect(self, response, expected_url=None):\n \"\"\"\n assertRedirects from Django TestCase follows the redirects chains,\n this assertion does not - which is more like real unit testing\n \"\"\"\n self.assertIn(\n response.status_code,\n self.redirect_codes,\n self._get_redirect_assertion_message(response),\n )\n if expected_url:\n location_header = response._headers.get('location', None)\n self.assertEqual(\n location_header,\n ('Location', str(expected_url)),\n 'Response should redirect to {0}, but it redirects to {1} instead'.format(\n expected_url,\n location_header[1],\n )\n )": 5448, "def _keys_to_camel_case(self, obj):\n \"\"\"\n Make a copy of a dictionary with all keys converted to camel case. This is just calls to_camel_case on each of the keys in the dictionary and returns a new dictionary.\n\n :param obj: Dictionary to convert keys to camel case.\n :return: Dictionary with the input values and all keys in camel case\n \"\"\"\n return dict((to_camel_case(key), value) for (key, value) in obj.items())": 5449, "def update_context(self, ctx):\n \"\"\" updates the query context with this clauses values \"\"\"\n assert isinstance(ctx, dict)\n ctx[str(self.context_id)] = self.value": 5450, "def generate_user_token(self, user, salt=None):\n \"\"\"Generates a unique token associated to the user\n \"\"\"\n return self.token_serializer.dumps(str(user.id), salt=salt)": 5451, "def random_string(string_length=10):\n \"\"\"Returns a random string of length string_length.\"\"\"\n random = str(uuid.uuid4()) # Convert UUID format to a Python string.\n random = random.upper() # Make all characters uppercase.\n random = random.replace(\"-\", \"\") # Remove the UUID '-'.\n return random[0:string_length]": 5452, "def bool_str(string):\n \"\"\"Returns a boolean from a string imput of 'true' or 'false'\"\"\"\n if string not in BOOL_STRS:\n raise ValueError('Invalid boolean string: \"{}\"'.format(string))\n return True if string == 'true' else False": 5453, "def _set_lastpage(self):\n \"\"\"Calculate value of class attribute ``last_page``.\"\"\"\n self.last_page = (len(self._page_data) - 1) // self.screen.page_size": 5454, "def put_text(self, key, text):\n \"\"\"Put the text into the storage associated with the key.\"\"\"\n with open(key, \"w\") as fh:\n fh.write(text)": 5455, "def destroy_webdriver(driver):\n \"\"\"\n Destroy a driver\n \"\"\"\n\n # This is some very flaky code in selenium. Hence the retries\n # and catch-all exceptions\n try:\n retry_call(driver.close, tries=2)\n except Exception:\n pass\n try:\n driver.quit()\n except Exception:\n pass": 5456, "def _checkSize(self):\n \"\"\"Automatically resizes widget to display at most max_height_items items\"\"\"\n if self._item_height is not None:\n sz = min(self._max_height_items, self.count()) * self._item_height + 5\n sz = max(sz, 20)\n self.setMinimumSize(0, sz)\n self.setMaximumSize(1000000, sz)\n self.resize(self.width(), sz)": 5457, "def path_distance(points):\n \"\"\"\n Compute the path distance from given set of points\n \"\"\"\n vecs = np.diff(points, axis=0)[:, :3]\n d2 = [np.dot(p, p) for p in vecs]\n return np.sum(np.sqrt(d2))": 5458, "def element_to_string(element, include_declaration=True, encoding=DEFAULT_ENCODING, method='xml'):\n \"\"\" :return: the string value of the element or element tree \"\"\"\n\n if isinstance(element, ElementTree):\n element = element.getroot()\n elif not isinstance(element, ElementType):\n element = get_element(element)\n\n if element is None:\n return u''\n\n element_as_string = tostring(element, encoding, method).decode(encoding=encoding)\n if include_declaration:\n return element_as_string\n else:\n return strip_xml_declaration(element_as_string)": 5459, "def _Open(self, hostname, port):\n \"\"\"Opens the RPC communication channel for clients.\n\n Args:\n hostname (str): hostname or IP address to connect to for requests.\n port (int): port to connect to for requests.\n\n Returns:\n bool: True if the communication channel was successfully opened.\n \"\"\"\n try:\n self._xmlrpc_server = SimpleXMLRPCServer.SimpleXMLRPCServer(\n (hostname, port), logRequests=False, allow_none=True)\n except SocketServer.socket.error as exception:\n logger.warning((\n 'Unable to bind a RPC server on {0:s}:{1:d} with error: '\n '{2!s}').format(hostname, port, exception))\n return False\n\n self._xmlrpc_server.register_function(\n self._callback, self._RPC_FUNCTION_NAME)\n return True": 5460, "def predict(self, X):\n \"\"\"Predict the class for X.\n\n The predicted class for each sample in X is returned.\n\n Parameters\n ----------\n X : List of ndarrays, one for each training example.\n Each training example's shape is (string1_len,\n string2_len, n_features), where string1_len and\n string2_len are the length of the two training strings and\n n_features the number of features.\n\n Returns\n -------\n y : iterable of shape = [n_samples]\n The predicted classes.\n\n \"\"\"\n return [self.classes[prediction.argmax()] for prediction in self.predict_proba(X)]": 5461, "def ParseMany(text):\n \"\"\"Parses many YAML documents into a list of Python objects.\n\n Args:\n text: A YAML source with multiple documents embedded.\n\n Returns:\n A list of Python data structures corresponding to the YAML documents.\n \"\"\"\n precondition.AssertType(text, Text)\n\n if compatibility.PY2:\n text = text.encode(\"utf-8\")\n\n return list(yaml.safe_load_all(text))": 5462, "def kill_test_logger(logger):\n \"\"\"Cleans up a test logger object by removing all of its handlers.\n\n Args:\n logger: The logging object to clean up.\n \"\"\"\n for h in list(logger.handlers):\n logger.removeHandler(h)\n if isinstance(h, logging.FileHandler):\n h.close()": 5463, "def trap_exceptions(results, handler, exceptions=Exception):\n\t\"\"\"\n\tIterate through the results, but if an exception occurs, stop\n\tprocessing the results and instead replace\n\tthe results with the output from the exception handler.\n\t\"\"\"\n\ttry:\n\t\tfor result in results:\n\t\t\tyield result\n\texcept exceptions as exc:\n\t\tfor result in always_iterable(handler(exc)):\n\t\t\tyield result": 5464, "def _return_result(self, done):\n \"\"\"Called set the returned future's state that of the future\n we yielded, and set the current future for the iterator.\n \"\"\"\n chain_future(done, self._running_future)\n\n self.current_future = done\n self.current_index = self._unfinished.pop(done)": 5465, "def start(self, test_connection=True):\n \"\"\"Starts connection to server if not existent.\n\n NO-OP if connection is already established.\n Makes ping-pong test as well if desired.\n\n \"\"\"\n if self._context is None:\n self._logger.debug('Starting Client')\n self._context = zmq.Context()\n self._poll = zmq.Poller()\n self._start_socket()\n if test_connection:\n self.test_ping()": 5466, "def _on_text_changed(self):\n \"\"\" Adjust dirty flag depending on editor's content \"\"\"\n if not self._cleaning:\n ln = TextHelper(self).cursor_position()[0]\n self._modified_lines.add(ln)": 5467, "def display_list_by_prefix(names_list, starting_spaces=0):\n \"\"\"Creates a help string for names_list grouped by prefix.\"\"\"\n cur_prefix, result_lines = None, []\n space = \" \" * starting_spaces\n for name in sorted(names_list):\n split = name.split(\"_\", 1)\n prefix = split[0]\n if cur_prefix != prefix:\n result_lines.append(space + prefix + \":\")\n cur_prefix = prefix\n result_lines.append(space + \" * \" + name)\n return \"\\n\".join(result_lines)": 5468, "def delete_lines(self):\n \"\"\"\n Deletes the document lines under cursor.\n\n :return: Method success.\n :rtype: bool\n \"\"\"\n\n cursor = self.textCursor()\n self.__select_text_under_cursor_blocks(cursor)\n cursor.removeSelectedText()\n cursor.deleteChar()\n return True": 5469, "def search(self, filterstr, attrlist):\n \"\"\"Query the configured LDAP server.\"\"\"\n return self._paged_search_ext_s(self.settings.BASE, ldap.SCOPE_SUBTREE, filterstr=filterstr,\n attrlist=attrlist, page_size=self.settings.PAGE_SIZE)": 5470, "def range(self, chromosome, start, stop, exact=False):\n \"\"\"\n Shortcut to do range filters on genomic datasets.\n \"\"\"\n return self._clone(\n filters=[GenomicFilter(chromosome, start, stop, exact)])": 5471, "def hash_producer(*args, **kwargs):\n \"\"\" Returns a random hash for a confirmation secret. \"\"\"\n return hashlib.md5(six.text_type(uuid.uuid4()).encode('utf-8')).hexdigest()": 5472, "def retrieve_import_alias_mapping(names_list):\n \"\"\"Creates a dictionary mapping aliases to their respective name.\n import_alias_names is used in module_definitions.py and visit_Call\"\"\"\n import_alias_names = dict()\n\n for alias in names_list:\n if alias.asname:\n import_alias_names[alias.asname] = alias.name\n return import_alias_names": 5473, "def get_unixtime_registered(self):\n \"\"\"Returns the user's registration date as a UNIX timestamp.\"\"\"\n\n doc = self._request(self.ws_prefix + \".getInfo\", True)\n\n return int(doc.getElementsByTagName(\"registered\")[0].getAttribute(\"unixtime\"))": 5474, "def input_dir(self):\n \"\"\"\n :returns: absolute path to where the job.ini is\n \"\"\"\n return os.path.abspath(os.path.dirname(self.inputs['job_ini']))": 5475, "def forget_xy(t):\n \"\"\"Ignore sizes of dimensions (1, 2) of a 4d tensor in shape inference.\n\n This allows using smaller input sizes, which create an invalid graph at higher\n layers (for example because a spatial dimension becomes smaller than a conv\n filter) when we only use early parts of it.\n \"\"\"\n shape = (t.shape[0], None, None, t.shape[3])\n return tf.placeholder_with_default(t, shape)": 5476, "def cell_normalize(data):\n \"\"\"\n Returns the data where the expression is normalized so that the total\n count per cell is equal.\n \"\"\"\n if sparse.issparse(data):\n data = sparse.csc_matrix(data.astype(float))\n # normalize in-place\n sparse_cell_normalize(data.data,\n data.indices,\n data.indptr,\n data.shape[1],\n data.shape[0])\n return data\n data_norm = data.astype(float)\n total_umis = []\n for i in range(data.shape[1]):\n di = data_norm[:,i]\n total_umis.append(di.sum())\n di /= total_umis[i]\n med = np.median(total_umis)\n data_norm *= med\n return data_norm": 5477, "def phase_correct_first(spec, freq, k):\n \"\"\"\n First order phase correction.\n\n Parameters\n ----------\n spec : float array\n The spectrum to be corrected.\n\n freq : float array\n The frequency axis.\n\n k : float\n The slope of the phase correction as a function of frequency.\n\n Returns\n -------\n The phase-corrected spectrum.\n\n Notes\n -----\n [Keeler2005] Keeler, J (2005). Understanding NMR Spectroscopy, 2nd\n edition. Wiley. Page 88\n\n \"\"\"\n c_factor = np.exp(-1j * k * freq)\n c_factor = c_factor.reshape((len(spec.shape) -1) * (1,) + c_factor.shape)\n return spec * c_factor": 5478, "def device_state(device_id):\n \"\"\" Get device state via HTTP GET. \"\"\"\n if device_id not in devices:\n return jsonify(success=False)\n return jsonify(state=devices[device_id].state)": 5479, "def get_readonly_fields(self, request, obj=None):\n \"\"\"Set all fields readonly.\"\"\"\n return list(self.readonly_fields) + [field.name for field in obj._meta.fields]": 5480, "def utime(self, *args, **kwargs):\n \"\"\" Set the access and modified times of the file specified by path. \"\"\"\n os.utime(self.extended_path, *args, **kwargs)": 5481, "def render_none(self, context, result):\n\t\t\"\"\"Render empty responses.\"\"\"\n\t\tcontext.response.body = b''\n\t\tdel context.response.content_length\n\t\treturn True": 5482, "def get_class_method(cls_or_inst, method_name):\n \"\"\"\n Returns a method from a given class or instance. When the method doest not exist, it returns `None`. Also works with\n properties and cached properties.\n \"\"\"\n cls = cls_or_inst if isinstance(cls_or_inst, type) else cls_or_inst.__class__\n meth = getattr(cls, method_name, None)\n if isinstance(meth, property):\n meth = meth.fget\n elif isinstance(meth, cached_property):\n meth = meth.func\n return meth": 5483, "def naturalsortkey(s):\n \"\"\"Natural sort order\"\"\"\n return [int(part) if part.isdigit() else part\n for part in re.split('([0-9]+)', s)]": 5484, "def project(self, other):\n \"\"\"Return one vector projected on the vector other\"\"\"\n n = other.normalized()\n return self.dot(n) * n": 5485, "def preprocess(string):\n \"\"\"\n Preprocess string to transform all diacritics and remove other special characters than appropriate\n \n :param string:\n :return:\n \"\"\"\n string = unicode(string, encoding=\"utf-8\")\n # convert diacritics to simpler forms\n string = regex1.sub(lambda x: accents[x.group()], string)\n # remove all rest of the unwanted characters\n return regex2.sub('', string).encode('utf-8')": 5486, "def timestamp(format=DATEFMT, timezone='Africa/Johannesburg'):\n \"\"\" Return current datetime with timezone applied\n [all timezones] print sorted(pytz.all_timezones) \"\"\"\n\n return formatdate(datetime.now(tz=pytz.timezone(timezone)))": 5487, "def _try_lookup(table, value, default = \"\"):\n \"\"\" try to get a string from the lookup table, return \"\" instead of key\n error\n \"\"\"\n try:\n string = table[ value ]\n except KeyError:\n string = default\n return string": 5488, "def write_pid_file():\n \"\"\"Write a file with the PID of this server instance.\n\n Call when setting up a command line testserver.\n \"\"\"\n pidfile = os.path.basename(sys.argv[0])[:-3] + '.pid' # strip .py, add .pid\n with open(pidfile, 'w') as fh:\n fh.write(\"%d\\n\" % os.getpid())\n fh.close()": 5489, "def inverse(d):\n \"\"\"\n reverse the k:v pairs\n \"\"\"\n output = {}\n for k, v in unwrap(d).items():\n output[v] = output.get(v, [])\n output[v].append(k)\n return output": 5490, "def plot_decision_boundary(model, X, y, step=0.1, figsize=(10, 8), alpha=0.4, size=20):\n \"\"\"Plots the classification decision boundary of `model` on `X` with labels `y`.\n Using numpy and matplotlib.\n \"\"\"\n\n x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1\n y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1\n xx, yy = np.meshgrid(np.arange(x_min, x_max, step),\n np.arange(y_min, y_max, step))\n\n f, ax = plt.subplots(figsize=figsize)\n Z = model.predict(np.c_[xx.ravel(), yy.ravel()])\n Z = Z.reshape(xx.shape)\n\n ax.contourf(xx, yy, Z, alpha=alpha)\n ax.scatter(X[:, 0], X[:, 1], c=y, s=size, edgecolor='k')\n plt.show()": 5491, "def _deserialize(cls, key, value, fields):\n \"\"\" Marshal incoming data into Python objects.\"\"\"\n converter = cls._get_converter_for_field(key, None, fields)\n return converter.deserialize(value)": 5492, "def zoom(ax, xy='x', factor=1):\n \"\"\"Zoom into axis.\n\n Parameters\n ----------\n \"\"\"\n limits = ax.get_xlim() if xy == 'x' else ax.get_ylim()\n new_limits = (0.5*(limits[0] + limits[1])\n + 1./factor * np.array((-0.5, 0.5)) * (limits[1] - limits[0]))\n if xy == 'x':\n ax.set_xlim(new_limits)\n else:\n ax.set_ylim(new_limits)": 5493, "def rowlenselect(table, n, complement=False):\n \"\"\"Select rows of length `n`.\"\"\"\n\n where = lambda row: len(row) == n\n return select(table, where, complement=complement)": 5494, "def gen_text(env: TextIOBase, package: str, tmpl: str):\n \"\"\"Create output from Jinja template.\"\"\"\n if env:\n env_args = json_datetime.load(env)\n else:\n env_args = {}\n jinja_env = template.setup(package)\n echo(jinja_env.get_template(tmpl).render(**env_args))": 5495, "def _GetFieldByName(message_descriptor, field_name):\n \"\"\"Returns a field descriptor by field name.\n\n Args:\n message_descriptor: A Descriptor describing all fields in message.\n field_name: The name of the field to retrieve.\n Returns:\n The field descriptor associated with the field name.\n \"\"\"\n try:\n return message_descriptor.fields_by_name[field_name]\n except KeyError:\n raise ValueError('Protocol message %s has no \"%s\" field.' %\n (message_descriptor.name, field_name))": 5496, "def closeEvent(self, event):\n \"\"\"closeEvent reimplementation\"\"\"\n if self.closing(True):\n event.accept()\n else:\n event.ignore()": 5497, "def full_s(self):\n \"\"\" Get the full singular value matrix of self\n\n Returns\n -------\n Matrix : Matrix\n\n \"\"\"\n x = np.zeros((self.shape),dtype=np.float32)\n\n x[:self.s.shape[0],:self.s.shape[0]] = self.s.as_2d\n s = Matrix(x=x, row_names=self.row_names,\n col_names=self.col_names, isdiagonal=False,\n autoalign=False)\n return s": 5498, "def bound_symbols(self):\n \"\"\"Set of bound SymPy symbols contained within the equation.\"\"\"\n try:\n lhs_syms = self.lhs.bound_symbols\n except AttributeError:\n lhs_syms = set()\n try:\n rhs_syms = self.rhs.bound_symbols\n except AttributeError:\n rhs_syms = set()\n return lhs_syms | rhs_syms": 5499, "def calculate_size(name, function):\n \"\"\" Calculates the request payload size\"\"\"\n data_size = 0\n data_size += calculate_size_str(name)\n data_size += calculate_size_data(function)\n return data_size": 5500, "def _parse_string_to_list_of_pairs(s, seconds_to_int=False):\n r\"\"\"Parses a string into a list of pairs.\n\n In the input string, each pair is separated by a colon, and the delimiters\n between pairs are any of \" ,.;\".\n\n e.g. \"rows:32,cols:32\"\n\n Args:\n s: str to parse.\n seconds_to_int: Boolean. If True, then the second elements are returned\n as integers; otherwise they are strings.\n\n Returns:\n List of tuple pairs.\n\n Raises:\n ValueError: Badly formatted string.\n \"\"\"\n ret = []\n for p in [s.split(\":\") for s in re.sub(\"[,.;]\", \" \", s).split()]:\n if len(p) != 2:\n raise ValueError(\"bad input to _parse_string_to_list_of_pairs %s\" % s)\n if seconds_to_int:\n ret.append((p[0], int(p[1])))\n else:\n ret.append(tuple(p))\n return ret": 5501, "def calling_logger(height=1):\n \"\"\" Obtain a logger for the calling module.\n\n Uses the inspect module to find the name of the calling function and its\n position in the module hierarchy. With the optional height argument, logs\n for caller's caller, and so forth.\n\n see: http://stackoverflow.com/a/900404/48251\n \"\"\"\n stack = inspect.stack()\n height = min(len(stack) - 1, height)\n caller = stack[height]\n scope = caller[0].f_globals\n path = scope['__name__']\n if path == '__main__':\n path = scope['__package__'] or os.path.basename(sys.argv[0])\n return logging.getLogger(path)": 5502, "def wipe(self):\n \"\"\" Wipe the store\n \"\"\"\n query = \"DELETE FROM {}\".format(self.__tablename__)\n connection = sqlite3.connect(self.sqlite_file)\n cursor = connection.cursor()\n cursor.execute(query)\n connection.commit()": 5503, "def surface(self, zdata, **kwargs):\n \"\"\"Show a 3D surface plot.\n\n Extra keyword arguments are passed to `SurfacePlot()`.\n\n Parameters\n ----------\n zdata : array-like\n A 2D array of the surface Z values.\n\n \"\"\"\n self._configure_3d()\n surf = scene.SurfacePlot(z=zdata, **kwargs)\n self.view.add(surf)\n self.view.camera.set_range()\n return surf": 5504, "def stop_logging():\n \"\"\"Stop logging to logfile and console.\"\"\"\n from . import log\n logger = logging.getLogger(\"gromacs\")\n logger.info(\"GromacsWrapper %s STOPPED logging\", get_version())\n log.clear_handlers(logger)": 5505, "def add_to_enum(self, clsdict):\n \"\"\"\n Compile XML mappings in addition to base add behavior.\n \"\"\"\n super(XmlMappedEnumMember, self).add_to_enum(clsdict)\n self.register_xml_mapping(clsdict)": 5506, "def as_dict(self):\n \"\"\"Package up the public attributes as a dict.\"\"\"\n attrs = vars(self)\n return {key: attrs[key] for key in attrs if not key.startswith('_')}": 5507, "def __run_spark_submit(lane_yaml, dist_dir, spark_home, spark_args, silent):\n \"\"\"\n Submits the packaged application to spark using a `spark-submit` subprocess\n\n Parameters\n ----------\n lane_yaml (str): Path to the YAML lane definition file\n dist_dir (str): Path to the directory where the packaged code is located\n spark_args (str): String of any additional spark config args to be passed when submitting\n silent (bool): Flag indicating whether job output should be printed to console\n \"\"\"\n # spark-submit binary\n cmd = ['spark-submit' if spark_home is None else os.path.join(spark_home, 'bin/spark-submit')]\n\n # Supplied spark arguments\n if spark_args:\n cmd += spark_args\n\n # Packaged App & lane\n cmd += ['--py-files', 'libs.zip,_framework.zip,tasks.zip', 'main.py']\n cmd += ['--lane', lane_yaml]\n\n logging.info('Submitting to Spark')\n logging.debug(str(cmd))\n\n # Submit\n devnull = open(os.devnull, 'w')\n outp = {'stderr': STDOUT, 'stdout': devnull} if silent else {}\n call(cmd, cwd=dist_dir, env=MY_ENV, **outp)\n devnull.close()": 5508, "def write_login(collector, image, **kwargs):\n \"\"\"Login to a docker registry with write permissions\"\"\"\n docker_api = collector.configuration[\"harpoon\"].docker_api\n collector.configuration[\"authentication\"].login(docker_api, image, is_pushing=True, global_docker=True)": 5509, "def redirect(cls, request, response):\n \"\"\"Redirect to the canonical URI for this resource.\"\"\"\n if cls.meta.legacy_redirect:\n if request.method in ('GET', 'HEAD',):\n # A SAFE request is allowed to redirect using a 301\n response.status = http.client.MOVED_PERMANENTLY\n\n else:\n # All other requests must use a 307\n response.status = http.client.TEMPORARY_REDIRECT\n\n else:\n # Modern redirects are allowed. Let's have some fun.\n # Hopefully you're client supports this.\n # The RFC explicitly discourages UserAgent sniffing.\n response.status = http.client.PERMANENT_REDIRECT\n\n # Terminate the connection.\n response.close()": 5510, "def _replace_variables(data, variables):\n \"\"\"Replace the format variables in all items of data.\"\"\"\n formatter = string.Formatter()\n return [formatter.vformat(item, [], variables) for item in data]": 5511, "def register_action(action):\n \"\"\"\n Adds an action to the parser cli.\n\n :param action(BaseAction): a subclass of the BaseAction class\n \"\"\"\n sub = _subparsers.add_parser(action.meta('cmd'), help=action.meta('help'))\n sub.set_defaults(cmd=action.meta('cmd'))\n for (name, arg) in action.props().items():\n sub.add_argument(arg.name, arg.flag, **arg.options)\n _actions[action.meta('cmd')] = action": 5512, "def process_wait(process, timeout=0):\n \"\"\"\n Pauses script execution until a given process exists.\n :param process:\n :param timeout:\n :return:\n \"\"\"\n ret = AUTO_IT.AU3_ProcessWait(LPCWSTR(process), INT(timeout))\n return ret": 5513, "def connection_lost(self, exc):\n \"\"\"Called when asyncio.Protocol loses the network connection.\"\"\"\n if exc is None:\n self.log.warning('eof from receiver?')\n else:\n self.log.warning('Lost connection to receiver: %s', exc)\n\n self.transport = None\n\n if self._connection_lost_callback:\n self._loop.call_soon(self._connection_lost_callback)": 5514, "def convert_timezone(obj, timezone):\n \"\"\"Convert `obj` to the timezone `timezone`.\n\n Parameters\n ----------\n obj : datetime.date or datetime.datetime\n\n Returns\n -------\n type(obj)\n \"\"\"\n if timezone is None:\n return obj.replace(tzinfo=None)\n return pytz.timezone(timezone).localize(obj)": 5515, "async def write(self, data):\n \"\"\"\n :py:func:`asyncio.coroutine`\n\n :py:meth:`aioftp.StreamIO.write` proxy\n \"\"\"\n await self.wait(\"write\")\n start = _now()\n await super().write(data)\n self.append(\"write\", data, start)": 5516, "def codebox(msg=\"\", title=\" \", text=\"\"):\n \"\"\"\n Display some text in a monospaced font, with no line wrapping.\n This function is suitable for displaying code and text that is\n formatted using spaces.\n\n The text parameter should be a string, or a list or tuple of lines to be\n displayed in the textbox.\n\n :param str msg: the msg to be displayed\n :param str title: the window title\n :param str text: what to display in the textbox\n \"\"\"\n return tb.textbox(msg, title, text, codebox=1)": 5517, "def printComparison(results, class_or_prop):\n\t\"\"\"\n\tprint(out the results of the comparison using a nice table)\n\t\"\"\"\n\n\tdata = []\n\n\tRow = namedtuple('Row',[class_or_prop,'VALIDATED'])\n\n\tfor k,v in sorted(results.items(), key=lambda x: x[1]):\n\t\tdata += [Row(k, str(v))]\n\n\tpprinttable(data)": 5518, "def split_long_sentence(sentence, words_per_line):\n \"\"\"Takes a sentence and adds a newline every \"words_per_line\" words.\n\n Parameters\n ----------\n sentence: str\n Sentene to split\n words_per_line: double\n Add a newline every this many words\n \"\"\"\n words = sentence.split(' ')\n split_sentence = ''\n for i in range(len(words)):\n split_sentence = split_sentence + words[i]\n if (i+1) % words_per_line == 0:\n split_sentence = split_sentence + '\\n'\n elif i != len(words) - 1:\n split_sentence = split_sentence + \" \"\n return split_sentence": 5519, "def hook_focus_events(self):\n \"\"\" Install the hooks for focus events.\n\n This method may be overridden by subclasses as needed.\n\n \"\"\"\n widget = self.widget\n widget.focusInEvent = self.focusInEvent\n widget.focusOutEvent = self.focusOutEvent": 5520, "async def packets_from_tshark(self, packet_callback, packet_count=None, close_tshark=True):\n \"\"\"\n A coroutine which creates a tshark process, runs the given callback on each packet that is received from it and\n closes the process when it is done.\n\n Do not use interactively. Can be used in order to insert packets into your own eventloop.\n \"\"\"\n tshark_process = await self._get_tshark_process(packet_count=packet_count)\n try:\n await self._go_through_packets_from_fd(tshark_process.stdout, packet_callback, packet_count=packet_count)\n except StopCapture:\n pass\n finally:\n if close_tshark:\n await self._close_async()": 5521, "def cast_bytes(s, encoding=None):\n \"\"\"Source: https://github.com/ipython/ipython_genutils\"\"\"\n if not isinstance(s, bytes):\n return encode(s, encoding)\n return s": 5522, "def getCachedDataKey(engineVersionHash, key):\n\t\t\"\"\"\n\t\tRetrieves the cached data value for the specified engine version hash and dictionary key\n\t\t\"\"\"\n\t\tcacheFile = CachedDataManager._cacheFileForHash(engineVersionHash)\n\t\treturn JsonDataManager(cacheFile).getKey(key)": 5523, "def remove_duplicates(seq):\n \"\"\"\n Return unique elements from list while preserving order.\n From https://stackoverflow.com/a/480227/2589328\n \"\"\"\n seen = set()\n seen_add = seen.add\n return [x for x in seq if not (x in seen or seen_add(x))]": 5524, "def sequence_molecular_weight(seq):\n \"\"\"Returns the molecular weight of the polypeptide sequence.\n\n Notes\n -----\n Units = Daltons\n\n Parameters\n ----------\n seq : str\n Sequence of amino acids.\n \"\"\"\n if 'X' in seq:\n warnings.warn(_nc_warning_str, NoncanonicalWarning)\n return sum(\n [residue_mwt[aa] * n for aa, n in Counter(seq).items()]) + water_mass": 5525, "def python(string: str):\n \"\"\"\n :param string: String can be type, resource or python case\n \"\"\"\n return underscore(singularize(string) if Naming._pluralize(string) else string)": 5526, "def update(self):\n \"\"\"Update all visuals in the attached canvas.\"\"\"\n if not self.canvas:\n return\n for visual in self.canvas.visuals:\n self.update_program(visual.program)\n self.canvas.update()": 5527, "def ask_str(question: str, default: str = None):\n \"\"\"Asks for a simple string\"\"\"\n default_q = \" [default: {0}]: \".format(\n default) if default is not None else \"\"\n answer = input(\"{0} [{1}]: \".format(question, default_q))\n\n if answer == \"\":\n return default\n return answer": 5528, "def _zeep_to_dict(cls, obj):\n \"\"\"Convert a zeep object to a dictionary.\"\"\"\n res = serialize_object(obj)\n res = cls._get_non_empty_dict(res)\n return res": 5529, "def main(source):\n \"\"\"\n For a given command line supplied argument, negotiate the content, parse\n the schema and then return any issues to stdout or if no schema issues,\n return success exit code.\n \"\"\"\n if source is None:\n click.echo(\n \"You need to supply a file or url to a schema to a swagger schema, for\"\n \"the validator to work.\"\n )\n return 1\n try:\n load(source)\n click.echo(\"Validation passed\")\n return 0\n except ValidationError as e:\n raise click.ClickException(str(e))": 5530, "def check_for_positional_argument(kwargs, name, default=False):\n \"\"\"\n @type kwargs: dict\n @type name: str\n @type default: bool, int, str\n @return: bool, int\n \"\"\"\n if name in kwargs:\n if str(kwargs[name]) == \"True\":\n return True\n elif str(kwargs[name]) == \"False\":\n return False\n else:\n return kwargs[name]\n\n return default": 5531, "def _validate_simple(email):\n \"\"\"Does a simple validation of an email by matching it to a regexps\n\n :param email: The email to check\n :return: The valid Email address\n\n :raises: ValueError if value is not a valid email\n \"\"\"\n name, address = parseaddr(email)\n if not re.match('[^@]+@[^@]+\\.[^@]+', address):\n raise ValueError('Invalid email :{email}'.format(email=email))\n return address": 5532, "def is_file_exists_error(e):\n \"\"\"\n Returns whether the exception *e* was raised due to an already existing file or directory.\n \"\"\"\n if six.PY3:\n return isinstance(e, FileExistsError) # noqa: F821\n else:\n return isinstance(e, OSError) and e.errno == 17": 5533, "def set_input_value(self, selector, value):\n \"\"\"Set the value of the input matched by given selector.\"\"\"\n script = 'document.querySelector(\"%s\").setAttribute(\"value\", \"%s\")'\n script = script % (selector, value)\n self.evaluate(script)": 5534, "def can_access(self, user):\n \"\"\"Return whether or not `user` can access a project.\n\n The project's is_ready field must be set for a user to access.\n\n \"\"\"\n return self.class_.is_admin(user) or \\\n self.is_ready and self.class_ in user.classes": 5535, "def check_dependency(self, dependency_path):\n \"\"\"Check if mtime of dependency_path is greater than stored mtime.\"\"\"\n stored_hash = self._stamp_file_hashes.get(dependency_path)\n\n # This file was newly added, or we don't have a file\n # with stored hashes yet. Assume out of date.\n if not stored_hash:\n return False\n\n return stored_hash == _sha1_for_file(dependency_path)": 5536, "def _startswith(expr, pat):\n \"\"\"\n Return boolean sequence or scalar indicating whether each string in the sequence or scalar\n starts with passed pattern. Equivalent to str.startswith().\n\n :param expr:\n :param pat: Character sequence\n :return: sequence or scalar\n \"\"\"\n\n return _string_op(expr, Startswith, output_type=types.boolean, _pat=pat)": 5537, "def is_empty(self):\n \"\"\"Returns True if this node has no children, or if all of its children are ParseNode instances\n and are empty.\n \"\"\"\n return all(isinstance(c, ParseNode) and c.is_empty for c in self.children)": 5538, "def list_view_changed(self, widget, event, data=None):\n \"\"\"\n Function shows last rows.\n \"\"\"\n adj = self.scrolled_window.get_vadjustment()\n adj.set_value(adj.get_upper() - adj.get_page_size())": 5539, "def is_natural(x):\n \"\"\"A non-negative integer.\"\"\"\n try:\n is_integer = int(x) == x\n except (TypeError, ValueError):\n return False\n return is_integer and x >= 0": 5540, "def string(value) -> str:\n \"\"\" string dict/object/value to JSON \"\"\"\n return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)": 5541, "def get_period_last_3_months() -> str:\n \"\"\" Returns the last week as a period string \"\"\"\n today = Datum()\n today.today()\n\n # start_date = today - timedelta(weeks=13)\n start_date = today.clone()\n start_date.subtract_months(3)\n\n period = get_period(start_date.date, today.date)\n return period": 5542, "def dictlist_convert_to_float(dict_list: Iterable[Dict], key: str) -> None:\n \"\"\"\n Process an iterable of dictionaries. For each dictionary ``d``, convert\n (in place) ``d[key]`` to a float. If that fails, convert it to ``None``.\n \"\"\"\n for d in dict_list:\n try:\n d[key] = float(d[key])\n except ValueError:\n d[key] = None": 5543, "def method_caller(method_name, *args, **kwargs):\n\t\"\"\"\n\tReturn a function that will call a named method on the\n\ttarget object with optional positional and keyword\n\targuments.\n\n\t>>> lower = method_caller('lower')\n\t>>> lower('MyString')\n\t'mystring'\n\t\"\"\"\n\tdef call_method(target):\n\t\tfunc = getattr(target, method_name)\n\t\treturn func(*args, **kwargs)\n\treturn call_method": 5544, "def find_first_in_list(txt: str, str_list: [str]) -> int: # type: ignore\n \"\"\"\n Returns the index of the earliest occurence of an item from a list in a string\n\n Ex: find_first_in_list('foobar', ['bar', 'fin']) -> 3\n \"\"\"\n start = len(txt) + 1\n for item in str_list:\n if start > txt.find(item) > -1:\n start = txt.find(item)\n return start if len(txt) + 1 > start > -1 else -1": 5545, "def previous_workday(dt):\n \"\"\"\n returns previous weekday used for observances\n \"\"\"\n dt -= timedelta(days=1)\n while dt.weekday() > 4:\n # Mon-Fri are 0-4\n dt -= timedelta(days=1)\n return dt": 5546, "def __gt__(self, other):\n \"\"\"Test for greater than.\"\"\"\n if isinstance(other, Address):\n return str(self) > str(other)\n raise TypeError": 5547, "def batch_split_sentences(self, texts: List[str]) -> List[List[str]]:\n \"\"\"\n This method lets you take advantage of spacy's batch processing.\n Default implementation is to just iterate over the texts and call ``split_sentences``.\n \"\"\"\n return [self.split_sentences(text) for text in texts]": 5548, "def listify(a):\n \"\"\"\n Convert a scalar ``a`` to a list and all iterables to list as well.\n\n Examples\n --------\n >>> listify(0)\n [0]\n\n >>> listify([1,2,3])\n [1, 2, 3]\n\n >>> listify('a')\n ['a']\n\n >>> listify(np.array([1,2,3]))\n [1, 2, 3]\n\n >>> listify('string')\n ['string']\n \"\"\"\n if a is None:\n return []\n elif not isinstance(a, (tuple, list, np.ndarray)):\n return [a]\n return list(a)": 5549, "def get_column_names(engine: Engine, tablename: str) -> List[str]:\n \"\"\"\n Get all the database column names for the specified table.\n \"\"\"\n return [info.name for info in gen_columns_info(engine, tablename)]": 5550, "def list_depth(list_, func=max, _depth=0):\n \"\"\"\n Returns the deepest level of nesting within a list of lists\n\n Args:\n list_ : a nested listlike object\n func : depth aggregation strategy (defaults to max)\n _depth : internal var\n\n Example:\n >>> # ENABLE_DOCTEST\n >>> from utool.util_list import * # NOQA\n >>> list_ = [[[[[1]]], [3]], [[1], [3]], [[1], [3]]]\n >>> result = (list_depth(list_, _depth=0))\n >>> print(result)\n\n \"\"\"\n depth_list = [list_depth(item, func=func, _depth=_depth + 1)\n for item in list_ if util_type.is_listlike(item)]\n if len(depth_list) > 0:\n return func(depth_list)\n else:\n return _depth": 5551, "def get_timezone() -> Tuple[datetime.tzinfo, str]:\n \"\"\"Discover the current time zone and it's standard string representation (for source{d}).\"\"\"\n dt = get_datetime_now().astimezone()\n tzstr = dt.strftime(\"%z\")\n tzstr = tzstr[:-2] + \":\" + tzstr[-2:]\n return dt.tzinfo, tzstr": 5552, "def inverted_dict(d):\n \"\"\"Return a dict with swapped keys and values\n\n >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0}\n True\n \"\"\"\n return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))": 5553, "def read_text_from_file(path: str) -> str:\n \"\"\" Reads text file contents \"\"\"\n with open(path) as text_file:\n content = text_file.read()\n\n return content": 5554, "def full(self):\n \"\"\"Return ``True`` if the queue is full, ``False``\n otherwise (not reliable!).\n\n Only applicable if :attr:`maxsize` is set.\n\n \"\"\"\n return self.maxsize and len(self.list) >= self.maxsize or False": 5555, "def top(self, topn=10):\n \"\"\"\n Get a list of the top ``topn`` features in this :class:`.Feature`\\.\n\n Examples\n --------\n\n .. code-block:: python\n\n >>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)])\n >>> myFeature.top(1)\n [('trapezoid', 5)]\n\n Parameters\n ----------\n topn : int\n\n Returns\n -------\n list\n \"\"\"\n return [self[i] for i in argsort(list(zip(*self))[1])[::-1][:topn]]": 5556, "def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]:\n \"\"\"Remove empty utterances from a list of utterances\n Args:\n utterances: The list of utterance we are processing\n \"\"\"\n return [utter for utter in utterances if utter.text.strip() != \"\"]": 5557, "def get_pij_matrix(t, diag, A, A_inv):\n \"\"\"\n Calculates the probability matrix of substitutions i->j over time t,\n given the normalised generator diagonalisation.\n\n\n :param t: time\n :type t: float\n :return: probability matrix\n :rtype: numpy.ndarray\n \"\"\"\n return A.dot(np.diag(np.exp(diag * t))).dot(A_inv)": 5558, "def flush(self):\n \"\"\"\n Flush all unwritten data to disk.\n \"\"\"\n if self._cache_modified_count > 0:\n self.storage.write(self.cache)\n self._cache_modified_count = 0": 5559, "def _sum_cycles_from_tokens(self, tokens: List[str]) -> int:\n \"\"\"Sum the total number of cycles over a list of tokens.\"\"\"\n return sum((int(self._nonnumber_pattern.sub('', t)) for t in tokens))": 5560, "def __next__(self):\n \"\"\"\n :return: int\n \"\"\"\n self.current += 1\n if self.current > self.total:\n raise StopIteration\n else:\n return self.iterable[self.current - 1]": 5561, "def get_margin(length):\n \"\"\"Add enough tabs to align in two columns\"\"\"\n if length > 23:\n margin_left = \"\\t\"\n chars = 1\n elif length > 15:\n margin_left = \"\\t\\t\"\n chars = 2\n elif length > 7:\n margin_left = \"\\t\\t\\t\"\n chars = 3\n else:\n margin_left = \"\\t\\t\\t\\t\"\n chars = 4\n return margin_left": 5562, "def from_file(file_path) -> dict:\n \"\"\" Load JSON file \"\"\"\n with io.open(file_path, 'r', encoding='utf-8') as json_stream:\n return Json.parse(json_stream, True)": 5563, "def tail(filename, number_of_bytes):\n \"\"\"Returns the last number_of_bytes of filename\"\"\"\n with open(filename, \"rb\") as f:\n if os.stat(filename).st_size > number_of_bytes:\n f.seek(-number_of_bytes, 2)\n return f.read()": 5564, "async def executemany(self, sql: str, parameters: Iterable[Iterable[Any]]) -> None:\n \"\"\"Execute the given multiquery.\"\"\"\n await self._execute(self._cursor.executemany, sql, parameters)": 5565, "def proper_round(n):\n \"\"\"\n rounds float to closest int\n :rtype: int\n :param n: float\n \"\"\"\n return int(n) + (n / abs(n)) * int(abs(n - int(n)) >= 0.5) if n != 0 else 0": 5566, "def is_integer(value: Any) -> bool:\n \"\"\"Return true if a value is an integer number.\"\"\"\n return (isinstance(value, int) and not isinstance(value, bool)) or (\n isinstance(value, float) and isfinite(value) and int(value) == value\n )": 5567, "def getDimensionForImage(filename, maxsize):\n \"\"\"Return scaled image size in (width, height) format.\n The scaling preserves the aspect ratio.\n If PIL is not found returns None.\"\"\"\n try:\n from PIL import Image\n except ImportError:\n return None\n img = Image.open(filename)\n width, height = img.size\n if width > maxsize[0] or height > maxsize[1]:\n img.thumbnail(maxsize)\n out.info(\"Downscaled display size from %s to %s\" % ((width, height), img.size))\n return img.size": 5568, "def _rindex(mylist: Sequence[T], x: T) -> int:\n \"\"\"Index of the last occurrence of x in the sequence.\"\"\"\n return len(mylist) - mylist[::-1].index(x) - 1": 5569, "def recClearTag(element):\n \"\"\"Applies maspy.xml.clearTag() to the tag attribute of the \"element\" and\n recursively to all child elements.\n\n :param element: an :instance:`xml.etree.Element`\n \"\"\"\n children = element.getchildren()\n if len(children) > 0:\n for child in children:\n recClearTag(child)\n element.tag = clearTag(element.tag)": 5570, "def split(text: str) -> List[str]:\n \"\"\"Split a text into a list of tokens.\n\n :param text: the text to split\n :return: tokens\n \"\"\"\n return [word for word in SEPARATOR.split(text) if word.strip(' \\t')]": 5571, "def clean(ctx, text):\n \"\"\"\n Removes all non-printable characters from a text string\n \"\"\"\n text = conversions.to_string(text, ctx)\n return ''.join([c for c in text if ord(c) >= 32])": 5572, "def indices_to_labels(self, indices: Sequence[int]) -> List[str]:\n \"\"\" Converts a sequence of indices into their corresponding labels.\"\"\"\n\n return [(self.INDEX_TO_LABEL[index]) for index in indices]": 5573, "def has_key(cls, *args):\n \"\"\"\n Check whether flyweight object with specified key has already been created.\n\n Returns:\n bool: True if already created, False if not\n \"\"\"\n key = args if len(args) > 1 else args[0]\n return key in cls._instances": 5574, "def get_versions(reporev=True):\n \"\"\"Get version information for components used by Spyder\"\"\"\n import sys\n import platform\n\n import qtpy\n import qtpy.QtCore\n\n revision = None\n if reporev:\n from spyder.utils import vcs\n revision, branch = vcs.get_git_revision(os.path.dirname(__dir__))\n\n if not sys.platform == 'darwin': # To avoid a crash with our Mac app\n system = platform.system()\n else:\n system = 'Darwin'\n\n return {\n 'spyder': __version__,\n 'python': platform.python_version(), # \"2.7.3\"\n 'bitness': 64 if sys.maxsize > 2**32 else 32,\n 'qt': qtpy.QtCore.__version__,\n 'qt_api': qtpy.API_NAME, # PyQt5\n 'qt_api_ver': qtpy.PYQT_VERSION,\n 'system': system, # Linux, Windows, ...\n 'release': platform.release(), # XP, 10.6, 2.2.0, etc.\n 'revision': revision, # '9fdf926eccce'\n }": 5575, "def _skip_section(self):\n \"\"\"Skip a section\"\"\"\n self._last = self._f.readline()\n while len(self._last) > 0 and len(self._last[0].strip()) == 0:\n self._last = self._f.readline()": 5576, "async def cursor(self) -> Cursor:\n \"\"\"Create an aiosqlite cursor wrapping a sqlite3 cursor object.\"\"\"\n return Cursor(self, await self._execute(self._conn.cursor))": 5577, "def last_location_of_minimum(x):\n \"\"\"\n Returns the last location of the minimal value of x.\n The position is calculated relatively to the length of x.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n x = np.asarray(x)\n return 1.0 - np.argmin(x[::-1]) / len(x) if len(x) > 0 else np.NaN": 5578, "def mmap(func, iterable):\n \"\"\"Wrapper to make map() behave the same on Py2 and Py3.\"\"\"\n\n if sys.version_info[0] > 2:\n return [i for i in map(func, iterable)]\n else:\n return map(func, iterable)": 5579, "def extend(a: dict, b: dict) -> dict:\n \"\"\"Merge two dicts and return a new dict. Much like subclassing works.\"\"\"\n res = a.copy()\n res.update(b)\n return res": 5580, "def valid_date(x: str) -> bool:\n \"\"\"\n Retrun ``True`` if ``x`` is a valid YYYYMMDD date;\n otherwise return ``False``.\n \"\"\"\n try:\n if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT):\n raise ValueError\n return True\n except ValueError:\n return False": 5581, "def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]:\n \"\"\" Helper for iterating only nonempty lines without line breaks\"\"\"\n for line in file_like:\n line = line.rstrip('\\r\\n')\n if line:\n yield line": 5582, "def strtobytes(input, encoding):\n \"\"\"Take a str and transform it into a byte array.\"\"\"\n py_version = sys.version_info[0]\n if py_version >= 3:\n return _strtobytes_py3(input, encoding)\n return _strtobytes_py2(input, encoding)": 5583, "def indexes_equal(a: Index, b: Index) -> bool:\n \"\"\"\n Are two indexes equal? Checks by comparing ``str()`` versions of them.\n (AM UNSURE IF THIS IS ENOUGH.)\n \"\"\"\n return str(a) == str(b)": 5584, "def read(self, count=0):\n \"\"\" Read \"\"\"\n return self.f.read(count) if count > 0 else self.f.read()": 5585, "def bfx(value, msb, lsb):\n \"\"\"! @brief Extract a value from a bitfield.\"\"\"\n mask = bitmask((msb, lsb))\n return (value & mask) >> lsb": 5586, "def obj_in_list_always(target_list, obj):\n \"\"\"\n >>> l = [1,1,1]\n >>> obj_in_list_always(l, 1)\n True\n >>> l.append(2)\n >>> obj_in_list_always(l, 1)\n False\n \"\"\"\n for item in set(target_list):\n if item is not obj:\n return False\n return True": 5587, "def lowercase_chars(string: any) -> str:\n \"\"\"Return all (and only) the lowercase chars in the given string.\"\"\"\n return ''.join([c if c.islower() else '' for c in str(string)])": 5588, "def is_unicode(string):\n \"\"\"Validates that the object itself is some kinda string\"\"\"\n str_type = str(type(string))\n\n if str_type.find('str') > 0 or str_type.find('unicode') > 0:\n return True\n\n return False": 5589, "def assert_valid_name(name: str) -> str:\n \"\"\"Uphold the spec rules about naming.\"\"\"\n error = is_valid_name_error(name)\n if error:\n raise error\n return name": 5590, "def datetime_iso_format(date):\n \"\"\"\n Return an ISO-8601 representation of a datetime object.\n \"\"\"\n return \"{0:0>4}-{1:0>2}-{2:0>2}T{3:0>2}:{4:0>2}:{5:0>2}Z\".format(\n date.year, date.month, date.day, date.hour,\n date.minute, date.second)": 5591, "def gen_lower(x: Iterable[str]) -> Generator[str, None, None]:\n \"\"\"\n Args:\n x: iterable of strings\n\n Yields:\n each string in lower case\n \"\"\"\n for string in x:\n yield string.lower()": 5592, "def last_commit(self) -> Tuple:\n \"\"\"Returns a tuple (hash, and commit object)\"\"\"\n from libs.repos import git\n\n return git.get_last_commit(repo_path=self.path)": 5593, "def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None:\n \"\"\"\n Process an iterable of dictionaries. For each dictionary ``d``, delete\n ``d[key]`` if it exists.\n \"\"\"\n for d in dict_list:\n d.pop(key, None)": 5594, "def lower_camel_case_from_underscores(string):\n \"\"\"generate a lower-cased camelCase string from an underscore_string.\n For example: my_variable_name -> myVariableName\"\"\"\n components = string.split('_')\n string = components[0]\n for component in components[1:]:\n string += component[0].upper() + component[1:]\n return string": 5595, "def has_synset(word: str) -> list:\n \"\"\"\" Returns a list of synsets of a word after lemmatization. \"\"\"\n\n return wn.synsets(lemmatize(word, neverstem=True))": 5596, "def is_sqlatype_string(coltype: Union[TypeEngine, VisitableType]) -> bool:\n \"\"\"\n Is the SQLAlchemy column type a string type?\n \"\"\"\n coltype = _coltype_to_typeengine(coltype)\n return isinstance(coltype, sqltypes.String)": 5597, "def list_to_str(lst):\n \"\"\"\n Turn a list into a comma- and/or and-separated string.\n\n Parameters\n ----------\n lst : :obj:`list`\n A list of strings to join into a single string.\n\n Returns\n -------\n str_ : :obj:`str`\n A string with commas and/or ands separating th elements from ``lst``.\n\n \"\"\"\n if len(lst) == 1:\n str_ = lst[0]\n elif len(lst) == 2:\n str_ = ' and '.join(lst)\n elif len(lst) > 2:\n str_ = ', '.join(lst[:-1])\n str_ += ', and {0}'.format(lst[-1])\n else:\n raise ValueError('List of length 0 provided.')\n return str_": 5598, "def dotproduct(X, Y):\n \"\"\"Return the sum of the element-wise product of vectors x and y.\n >>> dotproduct([1, 2, 3], [1000, 100, 10])\n 1230\n \"\"\"\n return sum([x * y for x, y in zip(X, Y)])": 5599, "def cli_run():\n \"\"\"docstring for argparse\"\"\"\n parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow')\n parser.add_argument('query', help=\"What's the problem ?\", type=str, nargs='+')\n parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda')\n args = parser.parse_args()\n main(args)": 5600, "def chars(string: any) -> str:\n \"\"\"Return all (and only) the chars in the given string.\"\"\"\n return ''.join([c if c.isalpha() else '' for c in str(string)])": 5601, "def SetCursorPos(x: int, y: int) -> bool:\n \"\"\"\n SetCursorPos from Win32.\n Set mouse cursor to point x, y.\n x: int.\n y: int.\n Return bool, True if succeed otherwise False.\n \"\"\"\n return bool(ctypes.windll.user32.SetCursorPos(x, y))": 5602, "def try_cast_int(s):\n \"\"\"(str) -> int\n All the digits in a given string are concatenated and converted into a single number.\n \"\"\"\n try:\n temp = re.findall('\\d', str(s))\n temp = ''.join(temp)\n return int(temp)\n except:\n return s": 5603, "def most_significant_bit(lst: np.ndarray) -> int:\n \"\"\"\n A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s,\n i.e. the first position where a 1 appears, reading left to right.\n\n :param lst: a 1d array of 0s and 1s with at least one 1\n :return: the first position in lst that a 1 appears\n \"\"\"\n return np.argwhere(np.asarray(lst) == 1)[0][0]": 5604, "def rank(tensor: BKTensor) -> int:\n \"\"\"Return the number of dimensions of a tensor\"\"\"\n if isinstance(tensor, np.ndarray):\n return len(tensor.shape)\n\n return len(tensor[0].size())": 5605, "def str_to_time(time_str: str) -> datetime.datetime:\n \"\"\"\n Convert human readable string to datetime.datetime.\n \"\"\"\n pieces: Any = [int(piece) for piece in time_str.split('-')]\n return datetime.datetime(*pieces)": 5606, "def remove_nans_1D(*args) -> tuple:\n \"\"\"Remove nans in a set of 1D arrays.\n\n Removes indicies in all arrays if any array is nan at that index.\n All input arrays must have the same size.\n\n Parameters\n ----------\n args : 1D arrays\n\n Returns\n -------\n tuple\n Tuple of 1D arrays in same order as given, with nan indicies removed.\n \"\"\"\n vals = np.isnan(args[0])\n for a in args:\n vals |= np.isnan(a)\n return tuple(np.array(a)[~vals] for a in args)": 5607, "def snake_to_camel(s: str) -> str:\n \"\"\"Convert string from snake case to camel case.\"\"\"\n\n fragments = s.split('_')\n\n return fragments[0] + ''.join(x.title() for x in fragments[1:])": 5608, "def _latex_format(obj: Any) -> str:\n \"\"\"Format an object as a latex string.\"\"\"\n if isinstance(obj, float):\n try:\n return sympy.latex(symbolize(obj))\n except ValueError:\n return \"{0:.4g}\".format(obj)\n\n return str(obj)": 5609, "def is_empty_shape(sh: ShExJ.Shape) -> bool:\n \"\"\" Determine whether sh has any value \"\"\"\n return sh.closed is None and sh.expression is None and sh.extra is None and \\\n sh.semActs is None": 5610, "def read_set_from_file(filename: str) -> Set[str]:\n \"\"\"\n Extract a de-duped collection (set) of text from a file.\n Expected file format is one item per line.\n \"\"\"\n collection = set()\n with open(filename, 'r') as file_:\n for line in file_:\n collection.add(line.rstrip())\n return collection": 5611, "def get_keys_of_max_n(dict_obj, n):\n \"\"\"Returns the keys that maps to the top n max values in the given dict.\n\n Example:\n --------\n >>> dict_obj = {'a':2, 'b':1, 'c':5}\n >>> get_keys_of_max_n(dict_obj, 2)\n ['a', 'c']\n \"\"\"\n return sorted([\n item[0]\n for item in sorted(\n dict_obj.items(), key=lambda item: item[1], reverse=True\n )[:n]\n ])": 5612, "def pmon(month):\n\t\"\"\"\n\tP the month\n\n\t>>> print(pmon('2012-08'))\n\tAugust, 2012\n\t\"\"\"\n\tyear, month = month.split('-')\n\treturn '{month_name}, {year}'.format(\n\t\tmonth_name=calendar.month_name[int(month)],\n\t\tyear=year,\n\t)": 5613, "def _lower(string):\n \"\"\"Custom lower string function.\n Examples:\n FooBar -> foo_bar\n \"\"\"\n if not string:\n return \"\"\n\n new_string = [string[0].lower()]\n for char in string[1:]:\n if char.isupper():\n new_string.append(\"_\")\n new_string.append(char.lower())\n\n return \"\".join(new_string)": 5614, "def iterate_items(dictish):\n \"\"\" Return a consistent (key, value) iterable on dict-like objects,\n including lists of tuple pairs.\n\n Example:\n\n >>> list(iterate_items({'a': 1}))\n [('a', 1)]\n >>> list(iterate_items([('a', 1), ('b', 2)]))\n [('a', 1), ('b', 2)]\n \"\"\"\n if hasattr(dictish, 'iteritems'):\n return dictish.iteritems()\n if hasattr(dictish, 'items'):\n return dictish.items()\n return dictish": 5615, "def clean_column_names(df: DataFrame) -> DataFrame:\n \"\"\"\n Strip the whitespace from all column names in the given DataFrame\n and return the result.\n \"\"\"\n f = df.copy()\n f.columns = [col.strip() for col in f.columns]\n return f": 5616, "def area (self):\n \"\"\"area() -> number\n\n Returns the area of this Polygon.\n \"\"\"\n area = 0.0\n \n for segment in self.segments():\n area += ((segment.p.x * segment.q.y) - (segment.q.x * segment.p.y))/2\n\n return area": 5617, "def get_day_name(self) -> str:\n \"\"\" Returns the day name \"\"\"\n weekday = self.value.isoweekday() - 1\n return calendar.day_name[weekday]": 5618, "def _duplicates(list_):\n \"\"\"Return dict mapping item -> indices.\"\"\"\n item_indices = {}\n for i, item in enumerate(list_):\n try:\n item_indices[item].append(i)\n except KeyError: # First time seen\n item_indices[item] = [i]\n return item_indices": 5619, "def recall_score(y_true, y_pred, average='micro', suffix=False):\n \"\"\"Compute the recall.\n\n The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of\n true positives and ``fn`` the number of false negatives. The recall is\n intuitively the ability of the classifier to find all the positive samples.\n\n The best value is 1 and the worst value is 0.\n\n Args:\n y_true : 2d array. Ground truth (correct) target values.\n y_pred : 2d array. Estimated targets as returned by a tagger.\n\n Returns:\n score : float.\n\n Example:\n >>> from seqeval.metrics import recall_score\n >>> y_true = [['O', 'O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]\n >>> y_pred = [['O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]\n >>> recall_score(y_true, y_pred)\n 0.50\n \"\"\"\n true_entities = set(get_entities(y_true, suffix))\n pred_entities = set(get_entities(y_pred, suffix))\n\n nb_correct = len(true_entities & pred_entities)\n nb_true = len(true_entities)\n\n score = nb_correct / nb_true if nb_true > 0 else 0\n\n return score": 5620, "def is_any_type_set(sett: Set[Type]) -> bool:\n \"\"\"\n Helper method to check if a set of types is the {AnyObject} singleton\n\n :param sett:\n :return:\n \"\"\"\n return len(sett) == 1 and is_any_type(min(sett))": 5621, "def unzoom_all(self, event=None):\n \"\"\" zoom out full data range \"\"\"\n if len(self.conf.zoom_lims) > 0:\n self.conf.zoom_lims = [self.conf.zoom_lims[0]]\n self.unzoom(event)": 5622, "def write_text(filename: str, text: str) -> None:\n \"\"\"\n Writes text to a file.\n \"\"\"\n with open(filename, 'w') as f: # type: TextIO\n print(text, file=f)": 5623, "def psutil_phymem_usage():\n \"\"\"\n Return physical memory usage (float)\n Requires the cross-platform psutil (>=v0.3) library\n (https://github.com/giampaolo/psutil)\n \"\"\"\n import psutil\n # This is needed to avoid a deprecation warning error with\n # newer psutil versions\n try:\n percent = psutil.virtual_memory().percent\n except:\n percent = psutil.phymem_usage().percent\n return percent": 5624, "def right_replace(string, old, new, count=1):\n \"\"\"\n Right replaces ``count`` occurrences of ``old`` with ``new`` in ``string``.\n For example::\n\n right_replace('one_two_two', 'two', 'three') -> 'one_two_three'\n \"\"\"\n if not string:\n return string\n return new.join(string.rsplit(old, count))": 5625, "def debugTreePrint(node,pfx=\"->\"):\n \"\"\"Purely a debugging aid: Ascii-art picture of a tree descended from node\"\"\"\n print pfx,node.item\n for c in node.children:\n debugTreePrint(c,\" \"+pfx)": 5626, "def exclude(self, *args, **kwargs) -> \"QuerySet\":\n \"\"\"\n Same as .filter(), but with appends all args with NOT\n \"\"\"\n return self._filter_or_exclude(negate=True, *args, **kwargs)": 5627, "def camel_to_snake(s: str) -> str:\n \"\"\"Convert string from camel case to snake case.\"\"\"\n\n return CAMEL_CASE_RE.sub(r'_\\1', s).strip().lower()": 5628, "def is_sqlatype_integer(coltype: Union[TypeEngine, VisitableType]) -> bool:\n \"\"\"\n Is the SQLAlchemy column type an integer type?\n \"\"\"\n coltype = _coltype_to_typeengine(coltype)\n return isinstance(coltype, sqltypes.Integer)": 5629, "def zfill(x, width):\n \"\"\"zfill(x, width) -> string\n\n Pad a numeric string x with zeros on the left, to fill a field\n of the specified width. The string x is never truncated.\n\n \"\"\"\n if not isinstance(x, basestring):\n x = repr(x)\n return x.zfill(width)": 5630, "def most_frequent(lst):\n \"\"\"\n Returns the item that appears most frequently in the given list.\n \"\"\"\n lst = lst[:]\n highest_freq = 0\n most_freq = None\n\n for val in unique(lst):\n if lst.count(val) > highest_freq:\n most_freq = val\n highest_freq = lst.count(val)\n \n return most_freq": 5631, "def normalize(numbers):\n \"\"\"Multiply each number by a constant such that the sum is 1.0\n >>> normalize([1,2,1])\n [0.25, 0.5, 0.25]\n \"\"\"\n total = float(sum(numbers))\n return [n / total for n in numbers]": 5632, "def attrname_to_colname_dict(cls) -> Dict[str, str]:\n \"\"\"\n Asks an SQLAlchemy class how its attribute names correspond to database\n column names.\n\n Args:\n cls: SQLAlchemy ORM class\n\n Returns:\n a dictionary mapping attribute names to database column names\n \"\"\"\n attr_col = {} # type: Dict[str, str]\n for attrname, column in gen_columns(cls):\n attr_col[attrname] = column.name\n return attr_col": 5633, "def stretch(iterable, n=2):\n r\"\"\"Repeat each item in `iterable` `n` times.\n\n Example:\n\n >>> list(stretch(range(3), 2))\n [0, 0, 1, 1, 2, 2]\n \"\"\"\n times = range(n)\n for item in iterable:\n for i in times: yield item": 5634, "async def parallel_results(future_map: Sequence[Tuple]) -> Dict:\n \"\"\"\n Run parallel execution of futures and return mapping of their results to the provided keys.\n Just a neat shortcut around ``asyncio.gather()``\n\n :param future_map: Keys to futures mapping, e.g.: ( ('nav', get_nav()), ('content, get_content()) )\n :return: Dict with futures results mapped to keys {'nav': {1:2}, 'content': 'xyz'}\n \"\"\"\n ctx_methods = OrderedDict(future_map)\n fs = list(ctx_methods.values())\n results = await asyncio.gather(*fs)\n results = {\n key: results[idx] for idx, key in enumerate(ctx_methods.keys())\n }\n return results": 5635, "def __remove_trailing_zeros(self, collection):\n \"\"\"Removes trailing zeroes from indexable collection of numbers\"\"\"\n index = len(collection) - 1\n while index >= 0 and collection[index] == 0:\n index -= 1\n\n return collection[:index + 1]": 5636, "def __replace_all(repls: dict, input: str) -> str:\n \"\"\" Replaces from a string **input** all the occurrences of some\n symbols according to mapping **repls**.\n\n :param dict repls: where #key is the old character and\n #value is the one to substitute with;\n :param str input: original string where to apply the\n replacements;\n :return: *(str)* the string with the desired characters replaced\n \"\"\"\n return re.sub('|'.join(re.escape(key) for key in repls.keys()),\n lambda k: repls[k.group(0)], input)": 5637, "def maybe_infer_dtype_type(element):\n \"\"\"Try to infer an object's dtype, for use in arithmetic ops\n\n Uses `element.dtype` if that's available.\n Objects implementing the iterator protocol are cast to a NumPy array,\n and from there the array's type is used.\n\n Parameters\n ----------\n element : object\n Possibly has a `.dtype` attribute, and possibly the iterator\n protocol.\n\n Returns\n -------\n tipo : type\n\n Examples\n --------\n >>> from collections import namedtuple\n >>> Foo = namedtuple(\"Foo\", \"dtype\")\n >>> maybe_infer_dtype_type(Foo(np.dtype(\"i8\")))\n numpy.int64\n \"\"\"\n tipo = None\n if hasattr(element, 'dtype'):\n tipo = element.dtype\n elif is_list_like(element):\n element = np.asarray(element)\n tipo = element.dtype\n return tipo": 5638, "def bytes_hack(buf):\n \"\"\"\n Hacky workaround for old installs of the library on systems without python-future that were\n keeping the 2to3 update from working after auto-update.\n \"\"\"\n ub = None\n if sys.version_info > (3,):\n ub = buf\n else:\n ub = bytes(buf)\n\n return ub": 5639, "def get_prop_value(name, props, default=None):\n # type: (str, Dict[str, Any], Any) -> Any\n \"\"\"\n Returns the value of a property or the default one\n\n :param name: Name of a property\n :param props: Dictionary of properties\n :param default: Default value\n :return: The value of the property or the default one\n \"\"\"\n if not props:\n return default\n\n try:\n return props[name]\n except KeyError:\n return default": 5640, "def _my_hash(arg_list):\n # type: (List[Any]) -> int\n \"\"\"Simple helper hash function\"\"\"\n res = 0\n for arg in arg_list:\n res = res * 31 + hash(arg)\n return res": 5641, "def create_pie_chart(self, snapshot, filename=''):\n \"\"\"\n Create a pie chart that depicts the distribution of the allocated memory\n for a given `snapshot`. The chart is saved to `filename`.\n \"\"\"\n try:\n from pylab import figure, title, pie, axes, savefig\n from pylab import sum as pylab_sum\n except ImportError:\n return self.nopylab_msg % (\"pie_chart\")\n\n # Don't bother illustrating a pie without pieces.\n if not snapshot.tracked_total:\n return ''\n\n classlist = []\n sizelist = []\n for k, v in list(snapshot.classes.items()):\n if v['pct'] > 3.0:\n classlist.append(k)\n sizelist.append(v['sum'])\n sizelist.insert(0, snapshot.asizeof_total - pylab_sum(sizelist))\n classlist.insert(0, 'Other')\n #sizelist = [x*0.01 for x in sizelist]\n\n title(\"Snapshot (%s) Memory Distribution\" % (snapshot.desc))\n figure(figsize=(8,8))\n axes([0.1, 0.1, 0.8, 0.8])\n pie(sizelist, labels=classlist)\n savefig(filename, dpi=50)\n\n return self.chart_tag % (self.relative_path(filename))": 5642, "def strings_to_integers(strings: Iterable[str]) -> Iterable[int]:\n \"\"\"\n Convert a list of strings to a list of integers.\n\n :param strings: a list of string\n :return: a list of converted integers\n\n .. doctest::\n\n >>> strings_to_integers(['1', '1.0', '-0.2'])\n [1, 1, 0]\n \"\"\"\n return strings_to_(strings, lambda x: int(float(x)))": 5643, "def _(f, x):\n \"\"\"\n filter for dict, note `f` should have signature: `f::key->value->bool`\n \"\"\"\n return {k: v for k, v in x.items() if f(k, v)}": 5644, "def get_last_day_of_month(t: datetime) -> int:\n \"\"\"\n Returns day number of the last day of the month\n :param t: datetime\n :return: int\n \"\"\"\n tn = t + timedelta(days=32)\n tn = datetime(year=tn.year, month=tn.month, day=1)\n tt = tn - timedelta(hours=1)\n return tt.day": 5645, "def samefile(a: str, b: str) -> bool:\n \"\"\"Check if two pathes represent the same file.\"\"\"\n try:\n return os.path.samefile(a, b)\n except OSError:\n return os.path.normpath(a) == os.path.normpath(b)": 5646, "def read32(bytestream):\n \"\"\"Read 4 bytes from bytestream as an unsigned 32-bit integer.\"\"\"\n dt = np.dtype(np.uint32).newbyteorder('>')\n return np.frombuffer(bytestream.read(4), dtype=dt)[0]": 5647, "def do_quit(self, _: argparse.Namespace) -> bool:\n \"\"\"Exit this application\"\"\"\n self._should_quit = True\n return self._STOP_AND_EXIT": 5648, "def astensor(array: TensorLike) -> BKTensor:\n \"\"\"Covert numpy array to tensorflow tensor\"\"\"\n tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)\n return tensor": 5649, "def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \\\n -> Generator[Any, None, None]:\n \"\"\"\n Generate the first value in each row.\n\n Args:\n cursor: the cursor\n arraysize: split fetches into chunks of this many records\n\n Yields:\n the first value of each row\n \"\"\"\n return (row[0] for row in genrows(cursor, arraysize))": 5650, "def array2string(arr: numpy.ndarray) -> str:\n \"\"\"Format numpy array as a string.\"\"\"\n shape = str(arr.shape)[1:-1]\n if shape.endswith(\",\"):\n shape = shape[:-1]\n return numpy.array2string(arr, threshold=11) + \"%s[%s]\" % (arr.dtype, shape)": 5651, "def _reshuffle(mat, shape):\n \"\"\"Reshuffle the indicies of a bipartite matrix A[ij,kl] -> A[lj,ki].\"\"\"\n return np.reshape(\n np.transpose(np.reshape(mat, shape), (3, 1, 2, 0)),\n (shape[3] * shape[1], shape[0] * shape[2]))": 5652, "def cpu_count() -> int:\n \"\"\"Returns the number of processors on this machine.\"\"\"\n if multiprocessing is None:\n return 1\n try:\n return multiprocessing.cpu_count()\n except NotImplementedError:\n pass\n try:\n return os.sysconf(\"SC_NPROCESSORS_CONF\")\n except (AttributeError, ValueError):\n pass\n gen_log.error(\"Could not detect number of processors; assuming 1\")\n return 1": 5653, "def mouse_event(dwFlags: int, dx: int, dy: int, dwData: int, dwExtraInfo: int) -> None:\n \"\"\"mouse_event from Win32.\"\"\"\n ctypes.windll.user32.mouse_event(dwFlags, dx, dy, dwData, dwExtraInfo)": 5654, "def _izip(*iterables):\n \"\"\" Iterate through multiple lists or arrays of equal size \"\"\"\n # This izip routine is from itertools\n # izip('ABCD', 'xy') --> Ax By\n\n iterators = map(iter, iterables)\n while iterators:\n yield tuple(map(next, iterators))": 5655, "def s3_get(url: str, temp_file: IO) -> None:\n \"\"\"Pull a file directly from S3.\"\"\"\n s3_resource = boto3.resource(\"s3\")\n bucket_name, s3_path = split_s3_path(url)\n s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)": 5656, "def decode_value(stream):\n \"\"\"Decode the contents of a value from a serialized stream.\n\n :param stream: Source data stream\n :type stream: io.BytesIO\n :returns: Decoded value\n :rtype: bytes\n \"\"\"\n length = decode_length(stream)\n (value,) = unpack_value(\">{:d}s\".format(length), stream)\n return value": 5657, "def flatten_list(x: List[Any]) -> List[Any]:\n \"\"\"\n Converts a list of lists into a flat list.\n \n Args:\n x: list of lists \n\n Returns:\n flat list\n \n As per\n http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python\n\n \"\"\" # noqa\n return [item for sublist in x for item in sublist]": 5658, "def is_not_null(df: DataFrame, col_name: str) -> bool:\n \"\"\"\n Return ``True`` if the given DataFrame has a column of the given\n name (string), and there exists at least one non-NaN value in that\n column; return ``False`` otherwise.\n \"\"\"\n if (\n isinstance(df, pd.DataFrame)\n and col_name in df.columns\n and df[col_name].notnull().any()\n ):\n return True\n else:\n return False": 5659, "def release_lock():\n \"\"\"Release lock on compilation directory.\"\"\"\n get_lock.n_lock -= 1\n assert get_lock.n_lock >= 0\n # Only really release lock once all lock requests have ended.\n if get_lock.lock_is_enabled and get_lock.n_lock == 0:\n get_lock.start_time = None\n get_lock.unlocker.unlock()": 5660, "def uppercase_chars(string: any) -> str:\n \"\"\"Return all (and only) the uppercase chars in the given string.\"\"\"\n return ''.join([c if c.isupper() else '' for c in str(string)])": 5661, "def read(self, start_position: int, size: int) -> memoryview:\n \"\"\"\n Return a view into the memory\n \"\"\"\n return memoryview(self._bytes)[start_position:start_position + size]": 5662, "def min(self):\n \"\"\"\n :returns the minimum of the column\n \"\"\"\n res = self._qexec(\"min(%s)\" % self._name)\n if len(res) > 0:\n self._min = res[0][0]\n return self._min": 5663, "def append_num_column(self, text: str, index: int):\n \"\"\" Add value to the output row, width based on index \"\"\"\n width = self.columns[index][\"width\"]\n return f\"{text:>{width}}\"": 5664, "def check64bit(current_system=\"python\"):\n \"\"\"checks if you are on a 64 bit platform\"\"\"\n if current_system == \"python\":\n return sys.maxsize > 2147483647\n elif current_system == \"os\":\n import platform\n pm = platform.machine()\n if pm != \"..\" and pm.endswith('64'): # recent Python (not Iron)\n return True\n else:\n if 'PROCESSOR_ARCHITEW6432' in os.environ:\n return True # 32 bit program running on 64 bit Windows\n try:\n # 64 bit Windows 64 bit program\n return os.environ['PROCESSOR_ARCHITECTURE'].endswith('64')\n except IndexError:\n pass # not Windows\n try:\n # this often works in Linux\n return '64' in platform.architecture()[0]\n except Exception:\n # is an older version of Python, assume also an older os@\n # (best we can guess)\n return False": 5665, "def _kbhit_unix() -> bool:\n \"\"\"\n Under UNIX: is a keystroke available?\n \"\"\"\n dr, dw, de = select.select([sys.stdin], [], [], 0)\n return dr != []": 5666, "def get_last_weekday_in_month(year, month, weekday):\n \"\"\"Get the last weekday in a given month. e.g:\n\n >>> # the last monday in Jan 2013\n >>> Calendar.get_last_weekday_in_month(2013, 1, MON)\n datetime.date(2013, 1, 28)\n \"\"\"\n day = date(year, month, monthrange(year, month)[1])\n while True:\n if day.weekday() == weekday:\n break\n day = day - timedelta(days=1)\n return day": 5667, "def _gaussian_function(self, datalength: int, values: np.ndarray,\n height: int, index: int) -> np.ndarray:\n \"\"\"\n i'th Regression Model Gaussian\n\n :param: len(x)\n :param: x values\n :param: height of gaussian\n :param: position of gaussian\n\n :return: gaussian bumps over domain\n \"\"\"\n return height * np.exp(-(1 / (self.spread_number * datalength)) *\n (values - ((datalength / self.function_number) * index)) ** 2)": 5668, "def _parse_tuple_string(argument):\n \"\"\" Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) \"\"\"\n if isinstance(argument, str):\n return tuple(int(p.strip()) for p in argument.split(','))\n return argument": 5669, "def year(date):\n \"\"\" Returns the year.\n\n :param date:\n The string date with this format %m/%d/%Y\n :type date:\n String\n\n :returns:\n int\n\n :example:\n >>> year('05/1/2015')\n 2015\n \"\"\"\n try:\n fmt = '%m/%d/%Y'\n return datetime.strptime(date, fmt).timetuple().tm_year\n except ValueError:\n return 0": 5670, "def SvcStop(self) -> None:\n \"\"\"\n Called when the service is being shut down.\n \"\"\"\n # tell the SCM we're shutting down\n # noinspection PyUnresolvedReferences\n self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)\n # fire the stop event\n win32event.SetEvent(self.h_stop_event)": 5671, "def _cnx_is_empty(in_file):\n \"\"\"Check if cnr or cns files are empty (only have a header)\n \"\"\"\n with open(in_file) as in_handle:\n for i, line in enumerate(in_handle):\n if i > 0:\n return False\n return True": 5672, "def grep(pattern, filename):\n \"\"\"Very simple grep that returns the first matching line in a file.\n String matching only, does not do REs as currently implemented.\n \"\"\"\n try:\n # for line in file\n # if line matches pattern:\n # return line\n return next((L for L in open(filename) if L.find(pattern) >= 0))\n except StopIteration:\n return ''": 5673, "def _newer(a, b):\n \"\"\"Inquire whether file a was written since file b.\"\"\"\n if not os.path.exists(a):\n return False\n if not os.path.exists(b):\n return True\n return os.path.getmtime(a) >= os.path.getmtime(b)": 5674, "def remove_prefix(text, prefix):\n\t\"\"\"\n\tRemove the prefix from the text if it exists.\n\n\t>>> remove_prefix('underwhelming performance', 'underwhelming ')\n\t'performance'\n\n\t>>> remove_prefix('something special', 'sample')\n\t'something special'\n\t\"\"\"\n\tnull, prefix, rest = text.rpartition(prefix)\n\treturn rest": 5675, "def _environment_variables() -> Dict[str, str]:\n \"\"\"\n Wraps `os.environ` to filter out non-encodable values.\n \"\"\"\n return {key: value\n for key, value in os.environ.items()\n if _is_encodable(value)}": 5676, "def truncate_string(value, max_width=None):\n \"\"\"Truncate string values.\"\"\"\n if isinstance(value, text_type) and max_width is not None and len(value) > max_width:\n return value[:max_width]\n return value": 5677, "def zoom_out(self):\n \"\"\"Scale the image down by one scale step.\"\"\"\n if self._scalefactor >= self._sfmin:\n self._scalefactor -= 1\n self.scale_image()\n self._adjust_scrollbar(1/self._scalestep)\n self.sig_zoom_changed.emit(self.get_scaling())": 5678, "def __init__(self, enum_obj: Any) -> None:\n \"\"\"Initialize attributes for informative output.\n\n :param enum_obj: Enum object.\n \"\"\"\n if enum_obj:\n self.name = enum_obj\n self.items = ', '.join([str(i) for i in enum_obj])\n else:\n self.items = ''": 5679, "def count(self, elem):\n \"\"\"\n Return the number of elements equal to elem present in the queue\n\n >>> pdeque([1, 2, 1]).count(1)\n 2\n \"\"\"\n return self._left_list.count(elem) + self._right_list.count(elem)": 5680, "def _run_sync(self, method: Callable, *args, **kwargs) -> Any:\n \"\"\"\n Utility method to run commands synchronously for testing.\n \"\"\"\n if self.loop.is_running():\n raise RuntimeError(\"Event loop is already running.\")\n\n if not self.is_connected:\n self.loop.run_until_complete(self.connect())\n\n task = asyncio.Task(method(*args, **kwargs), loop=self.loop)\n result = self.loop.run_until_complete(task)\n\n self.loop.run_until_complete(self.quit())\n\n return result": 5681, "def to_bool(value: Any) -> bool:\n \"\"\"Convert string or other Python object to boolean.\n\n **Rationalle**\n\n Passing flags is one of the most common cases of using environment vars and\n as values are strings we need to have an easy way to convert them to\n boolean Python value.\n\n Without this function int or float string values can be converted as false\n positives, e.g. ``bool('0') => True``, but using this function ensure that\n digit flag be properly converted to boolean value.\n\n :param value: String or other value.\n \"\"\"\n return bool(strtobool(value) if isinstance(value, str) else value)": 5682, "def resize(im, short, max_size):\n \"\"\"\n only resize input image to target size and return scale\n :param im: BGR image input by opencv\n :param short: one dimensional size (the short side)\n :param max_size: one dimensional max size (the long side)\n :return: resized image (NDArray) and scale (float)\n \"\"\"\n im_shape = im.shape\n im_size_min = np.min(im_shape[0:2])\n im_size_max = np.max(im_shape[0:2])\n im_scale = float(short) / float(im_size_min)\n # prevent bigger axis from being more than max_size:\n if np.round(im_scale * im_size_max) > max_size:\n im_scale = float(max_size) / float(im_size_max)\n im = cv2.resize(im, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.INTER_LINEAR)\n return im, im_scale": 5683, "def memory_full():\n \"\"\"Check if the memory is too full for further caching.\"\"\"\n current_process = psutil.Process(os.getpid())\n return (current_process.memory_percent() >\n config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)": 5684, "def sorted_by(key: Callable[[raw_types.Qid], Any]) -> 'QubitOrder':\n \"\"\"A basis that orders qubits ascending based on a key function.\n\n Args:\n key: A function that takes a qubit and returns a key value. The\n basis will be ordered ascending according to these key values.\n\n\n Returns:\n A basis that orders qubits ascending based on a key function.\n \"\"\"\n return QubitOrder(lambda qubits: tuple(sorted(qubits, key=key)))": 5685, "def is_finite(value: Any) -> bool:\n \"\"\"Return true if a value is a finite number.\"\"\"\n return isinstance(value, int) or (isinstance(value, float) and isfinite(value))": 5686, "def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:\n \"\"\"Rate limit a function.\"\"\"\n return util.rate_limited(max_per_hour, *args)": 5687, "def dict_to_enum_fn(d: Dict[str, Any], enum_class: Type[Enum]) -> Enum:\n \"\"\"\n Converts an ``dict`` to a ``Enum``.\n \"\"\"\n return enum_class[d['name']]": 5688, "def smooth_image(image, sigma, sigma_in_physical_coordinates=True, FWHM=False, max_kernel_width=32):\n \"\"\"\n Smooth an image\n\n ANTsR function: `smoothImage`\n\n Arguments\n ---------\n image \n Image to smooth\n \n sigma \n Smoothing factor. Can be scalar, in which case the same sigma is applied to each dimension, or a vector of length dim(inimage) to specify a unique smoothness for each dimension.\n \n sigma_in_physical_coordinates : boolean \n If true, the smoothing factor is in millimeters; if false, it is in pixels.\n \n FWHM : boolean \n If true, sigma is interpreted as the full-width-half-max (FWHM) of the filter, not the sigma of a Gaussian kernel.\n \n max_kernel_width : scalar \n Maximum kernel width\n \n Returns\n -------\n ANTsImage\n \n Example\n -------\n >>> import ants\n >>> image = ants.image_read( ants.get_ants_data('r16'))\n >>> simage = ants.smooth_image(image, (1.2,1.5))\n \"\"\"\n if image.components == 1:\n return _smooth_image_helper(image, sigma, sigma_in_physical_coordinates, FWHM, max_kernel_width)\n else:\n imagelist = utils.split_channels(image)\n newimages = []\n for image in imagelist:\n newimage = _smooth_image_helper(image, sigma, sigma_in_physical_coordinates, FWHM, max_kernel_width)\n newimages.append(newimage)\n return utils.merge_channels(newimages)": 5689, "def has_changed (filename):\n \"\"\"Check if filename has changed since the last check. If this\n is the first check, assume the file is changed.\"\"\"\n key = os.path.abspath(filename)\n mtime = get_mtime(key)\n if key not in _mtime_cache:\n _mtime_cache[key] = mtime\n return True\n return mtime > _mtime_cache[key]": 5690, "def fcast(value: float) -> TensorLike:\n \"\"\"Cast to float tensor\"\"\"\n newvalue = tf.cast(value, FTYPE)\n if DEVICE == 'gpu':\n newvalue = newvalue.gpu() # Why is this needed? # pragma: no cover\n return newvalue": 5691, "def from_buffer(buffer, mime=False):\n \"\"\"\n Accepts a binary string and returns the detected filetype. Return\n value is the mimetype if mime=True, otherwise a human readable\n name.\n\n >>> magic.from_buffer(open(\"testdata/test.pdf\").read(1024))\n 'PDF document, version 1.2'\n \"\"\"\n m = _get_magic_type(mime)\n return m.from_buffer(buffer)": 5692, "def long_substr(data):\n \"\"\"Return the longest common substring in a list of strings.\n \n Credit: http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python\n \"\"\"\n substr = ''\n if len(data) > 1 and len(data[0]) > 0:\n for i in range(len(data[0])):\n for j in range(len(data[0])-i+1):\n if j > len(substr) and all(data[0][i:i+j] in x for x in data):\n substr = data[0][i:i+j]\n elif len(data) == 1:\n substr = data[0]\n return substr": 5693, "def url_host(url: str) -> str:\n \"\"\"\n Parses hostname from URL.\n :param url: URL\n :return: hostname\n \"\"\"\n from urllib.parse import urlparse\n res = urlparse(url)\n return res.netloc.split(':')[0] if res.netloc else ''": 5694, "def suppress_stdout():\n \"\"\"\n Context manager that suppresses stdout.\n\n Examples:\n >>> with suppress_stdout():\n ... print('Test print')\n\n >>> print('test')\n test\n\n \"\"\"\n save_stdout = sys.stdout\n sys.stdout = DevNull()\n yield\n sys.stdout = save_stdout": 5695, "def first_location_of_maximum(x):\n \"\"\"\n Returns the first location of the maximum value of x.\n The position is calculated relatively to the length of x.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n if not isinstance(x, (np.ndarray, pd.Series)):\n x = np.asarray(x)\n return np.argmax(x) / len(x) if len(x) > 0 else np.NaN": 5696, "def impose_legend_limit(limit=30, axes=\"gca\", **kwargs):\n \"\"\"\n This will erase all but, say, 30 of the legend entries and remake the legend.\n You'll probably have to move it back into your favorite position at this point.\n \"\"\"\n if axes==\"gca\": axes = _pylab.gca()\n\n # make these axes current\n _pylab.axes(axes)\n\n # loop over all the lines_pylab.\n for n in range(0,len(axes.lines)):\n if n > limit-1 and not n==len(axes.lines)-1: axes.lines[n].set_label(\"_nolegend_\")\n if n == limit-1 and not n==len(axes.lines)-1: axes.lines[n].set_label(\"...\")\n\n _pylab.legend(**kwargs)": 5697, "def multi_split(s, split):\n # type: (S, Iterable[S]) -> List[S]\n \"\"\"Splits on multiple given separators.\"\"\"\n for r in split:\n s = s.replace(r, \"|\")\n return [i for i in s.split(\"|\") if len(i) > 0]": 5698, "def replace_in_list(stringlist: Iterable[str],\n replacedict: Dict[str, str]) -> List[str]:\n \"\"\"\n Returns a list produced by applying :func:`multiple_replace` to every\n string in ``stringlist``.\n\n Args:\n stringlist: list of source strings\n replacedict: dictionary mapping \"original\" to \"replacement\" strings\n\n Returns:\n list of final strings\n\n \"\"\"\n newlist = []\n for fromstring in stringlist:\n newlist.append(multiple_replace(fromstring, replacedict))\n return newlist": 5699, "def list_to_str(list, separator=','):\n \"\"\"\n >>> list = [0, 0, 7]\n >>> list_to_str(list)\n '0,0,7'\n \"\"\"\n list = [str(x) for x in list]\n return separator.join(list)": 5700, "def convert_bytes_to_ints(in_bytes, num):\n \"\"\"Convert a byte array into an integer array. The number of bytes forming an integer\n is defined by num\n\n :param in_bytes: the input bytes\n :param num: the number of bytes per int\n :return the integer array\"\"\"\n dt = numpy.dtype('>i' + str(num))\n return numpy.frombuffer(in_bytes, dt)": 5701, "def fetchallfirstvalues(self, sql: str, *args) -> List[Any]:\n \"\"\"Executes SQL; returns list of first values of each row.\"\"\"\n rows = self.fetchall(sql, *args)\n return [row[0] for row in rows]": 5702, "def read_las(source, closefd=True):\n \"\"\" Entry point for reading las data in pylas\n\n Reads the whole file into memory.\n\n >>> las = read_las(\"pylastests/simple.las\")\n >>> las.classification\n array([1, 1, 1, ..., 1, 1, 1], dtype=uint8)\n\n Parameters\n ----------\n source : str or io.BytesIO\n The source to read data from\n\n closefd: bool\n if True and the source is a stream, the function will close it\n after it is done reading\n\n\n Returns\n -------\n pylas.lasdatas.base.LasBase\n The object you can interact with to get access to the LAS points & VLRs\n \"\"\"\n with open_las(source, closefd=closefd) as reader:\n return reader.read()": 5703, "def truncate(value: Decimal, n_digits: int) -> Decimal:\n \"\"\"Truncates a value to a number of decimals places\"\"\"\n return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits)": 5704, "def flatten_list(l: List[list]) -> list:\n \"\"\" takes a list of lists, l and returns a flat list\n \"\"\"\n return [v for inner_l in l for v in inner_l]": 5705, "def MoveWindow(handle: int, x: int, y: int, width: int, height: int, repaint: int = 1) -> bool:\n \"\"\"\n MoveWindow from Win32.\n handle: int, the handle of a native window.\n x: int.\n y: int.\n width: int.\n height: int.\n repaint: int, use 1 or 0.\n Return bool, True if succeed otherwise False.\n \"\"\"\n return bool(ctypes.windll.user32.MoveWindow(ctypes.c_void_p(handle), x, y, width, height, repaint))": 5706, "def is_line_in_file(filename: str, line: str) -> bool:\n \"\"\"\n Detects whether a line is present within a file.\n\n Args:\n filename: file to check\n line: line to search for (as an exact match)\n \"\"\"\n assert \"\\n\" not in line\n with open(filename, \"r\") as file:\n for fileline in file:\n if fileline == line:\n return True\n return False": 5707, "def to_bytes(data: Any) -> bytearray:\n \"\"\"\n Convert anything to a ``bytearray``.\n \n See\n \n - http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3\n - http://stackoverflow.com/questions/10459067/how-to-convert-my-bytearrayb-x9e-x18k-x9a-to-something-like-this-x9e-x1\n \"\"\" # noqa\n if isinstance(data, int):\n return bytearray([data])\n return bytearray(data, encoding='latin-1')": 5708, "def de_duplicate(items):\n \"\"\"Remove any duplicate item, preserving order\n\n >>> de_duplicate([1, 2, 1, 2])\n [1, 2]\n \"\"\"\n result = []\n for item in items:\n if item not in result:\n result.append(item)\n return result": 5709, "def stop(self) -> None:\n \"\"\"Stops the analysis as soon as possible.\"\"\"\n if self._stop and not self._posted_kork:\n self._stop()\n self._stop = None": 5710, "def non_zero_row(arr):\n \"\"\"\n 0. Empty row returns False.\n\n >>> arr = array([])\n >>> non_zero_row(arr)\n\n False\n\n 1. Row with a zero returns False.\n\n >>> arr = array([1, 4, 3, 0, 5, -1, -2])\n >>> non_zero_row(arr)\n\n False\n 2. Row with no zeros returns True.\n\n >>> arr = array([-1, -0.1, 0.001, 2])\n >>> non_zero_row(arr)\n\n True\n\n :param arr: array\n :type arr: numpy array\n :return empty: If row is completely free of zeros\n :rtype empty: bool\n \"\"\"\n\n if len(arr) == 0:\n return False\n\n for item in arr:\n if item == 0:\n return False\n\n return True": 5711, "def unpackbools(integers, dtype='L'):\n \"\"\"Yield booleans unpacking integers of dtype bit-length.\n\n >>> list(unpackbools([42], 'B'))\n [False, True, False, True, False, True, False, False]\n \"\"\"\n atoms = ATOMS[dtype]\n\n for chunk in integers:\n for a in atoms:\n yield not not chunk & a": 5712, "def is_done(self):\n \"\"\"True if the last two moves were Pass or if the position is at a move\n greater than the max depth.\"\"\"\n return self.position.is_game_over() or self.position.n >= FLAGS.max_game_length": 5713, "def _generate(self):\n \"\"\"Parses a file or directory of files into a set of ``Document`` objects.\"\"\"\n doc_count = 0\n for fp in self.all_files:\n for doc in self._get_docs_for_path(fp):\n yield doc\n doc_count += 1\n if doc_count >= self.max_docs:\n return": 5714, "def call_spellchecker(cmd, input_text=None, encoding=None):\n \"\"\"Call spell checker with arguments.\"\"\"\n\n process = get_process(cmd)\n\n # A buffer has been provided\n if input_text is not None:\n for line in input_text.splitlines():\n # Hunspell truncates lines at `0x1fff` (at least on Windows this has been observed)\n # Avoid truncation by chunking the line on white space and inserting a new line to break it.\n offset = 0\n end = len(line)\n while True:\n chunk_end = offset + 0x1fff\n m = None if chunk_end >= end else RE_LAST_SPACE_IN_CHUNK.search(line, offset, chunk_end)\n if m:\n chunk_end = m.start(1)\n chunk = line[offset:m.start(1)]\n offset = m.end(1)\n else:\n chunk = line[offset:chunk_end]\n offset = chunk_end\n # Avoid wasted calls to empty strings\n if chunk and not chunk.isspace():\n process.stdin.write(chunk + b'\\n')\n if offset >= end:\n break\n\n return get_process_output(process, encoding)": 5715, "def multivariate_normal_tril(x,\n dims,\n layer_fn=tf.compat.v1.layers.dense,\n loc_fn=lambda x: x,\n scale_fn=tril_with_diag_softplus_and_shift,\n name=None):\n \"\"\"Constructs a trainable `tfd.MultivariateNormalTriL` distribution.\n\n This function creates a MultivariateNormal (MVN) with lower-triangular scale\n matrix. By default the MVN is parameterized via affine transformation of input\n tensor `x`. Using default args, this function is mathematically equivalent to:\n\n ```none\n Y = MVN(loc=matmul(W, x) + b,\n scale_tril=f(reshape_tril(matmul(M, x) + c)))\n\n where,\n W in R^[d, n]\n M in R^[d*(d+1)/2, n]\n b in R^d\n c in R^d\n f(S) = set_diag(S, softplus(matrix_diag_part(S)) + 1e-5)\n ```\n\n Observe that `f` makes the diagonal of the triangular-lower scale matrix be\n positive and no smaller than `1e-5`.\n\n #### Examples\n\n ```python\n # This example fits a multilinear regression loss.\n import tensorflow as tf\n import tensorflow_probability as tfp\n\n # Create fictitious training data.\n dtype = np.float32\n n = 3000 # number of samples\n x_size = 4 # size of single x\n y_size = 2 # size of single y\n def make_training_data():\n np.random.seed(142)\n x = np.random.randn(n, x_size).astype(dtype)\n w = np.random.randn(x_size, y_size).astype(dtype)\n b = np.random.randn(1, y_size).astype(dtype)\n true_mean = np.tensordot(x, w, axes=[[-1], [0]]) + b\n noise = np.random.randn(n, y_size).astype(dtype)\n y = true_mean + noise\n return y, x\n y, x = make_training_data()\n\n # Build TF graph for fitting MVNTriL maximum likelihood estimator.\n mvn = tfp.trainable_distributions.multivariate_normal_tril(x, dims=y_size)\n loss = -tf.reduce_mean(mvn.log_prob(y))\n train_op = tf.train.AdamOptimizer(learning_rate=2.**-3).minimize(loss)\n mse = tf.reduce_mean(tf.squared_difference(y, mvn.mean()))\n init_op = tf.global_variables_initializer()\n\n # Run graph 1000 times.\n num_steps = 1000\n loss_ = np.zeros(num_steps) # Style: `_` to indicate sess.run result.\n mse_ = np.zeros(num_steps)\n with tf.Session() as sess:\n sess.run(init_op)\n for it in xrange(loss_.size):\n _, loss_[it], mse_[it] = sess.run([train_op, loss, mse])\n if it % 200 == 0 or it == loss_.size - 1:\n print(\"iteration:{} loss:{} mse:{}\".format(it, loss_[it], mse_[it]))\n\n # ==> iteration:0 loss:38.2020797729 mse:4.17175960541\n # iteration:200 loss:2.90179634094 mse:0.990987896919\n # iteration:400 loss:2.82727336884 mse:0.990926623344\n # iteration:600 loss:2.82726788521 mse:0.990926682949\n # iteration:800 loss:2.82726788521 mse:0.990926682949\n # iteration:999 loss:2.82726788521 mse:0.990926682949\n ```\n\n Args:\n x: `Tensor` with floating type. Must have statically defined rank and\n statically known right-most dimension.\n dims: Scalar, `int`, `Tensor` indicated the MVN event size, i.e., the\n created MVN will be distribution over length-`dims` vectors.\n layer_fn: Python `callable` which takes input `x` and `int` scalar `d` and\n returns a transformation of `x` with shape\n `tf.concat([tf.shape(x)[:-1], [d]], axis=0)`.\n Default value: `tf.layers.dense`.\n loc_fn: Python `callable` which transforms the `loc` parameter. Takes a\n (batch of) length-`dims` vectors and returns a `Tensor` of same shape and\n `dtype`.\n Default value: `lambda x: x`.\n scale_fn: Python `callable` which transforms the `scale` parameters. Takes a\n (batch of) length-`dims * (dims + 1) / 2` vectors and returns a\n lower-triangular `Tensor` of same batch shape with rightmost dimensions\n having shape `[dims, dims]`.\n Default value: `tril_with_diag_softplus_and_shift`.\n name: A `name_scope` name for operations created by this function.\n Default value: `None` (i.e., \"multivariate_normal_tril\").\n\n Returns:\n mvntril: An instance of `tfd.MultivariateNormalTriL`.\n \"\"\"\n with tf.compat.v1.name_scope(name, 'multivariate_normal_tril', [x, dims]):\n x = tf.convert_to_tensor(value=x, name='x')\n x = layer_fn(x, dims + dims * (dims + 1) // 2)\n return tfd.MultivariateNormalTriL(\n loc=loc_fn(x[..., :dims]),\n scale_tril=scale_fn(x[..., dims:]))": 5716, "def binary(length):\n \"\"\"\n returns a a random string that represent a binary representation\n\n :param length: number of bits\n \"\"\"\n num = randint(1, 999999)\n mask = '0' * length\n return (mask + ''.join([str(num >> i & 1) for i in range(7, -1, -1)]))[-length:]": 5717, "def average_arrays(arrays: List[mx.nd.NDArray]) -> mx.nd.NDArray:\n \"\"\"\n Take a list of arrays of the same shape and take the element wise average.\n\n :param arrays: A list of NDArrays with the same shape that will be averaged.\n :return: The average of the NDArrays in the same context as arrays[0].\n \"\"\"\n if not arrays:\n raise ValueError(\"arrays is empty.\")\n if len(arrays) == 1:\n return arrays[0]\n check_condition(all(arrays[0].shape == a.shape for a in arrays), \"nd array shapes do not match\")\n return mx.nd.add_n(*arrays) / len(arrays)": 5718, "def delete(self, endpoint: str, **kwargs) -> dict:\n \"\"\"HTTP DELETE operation to API endpoint.\"\"\"\n\n return self._request('DELETE', endpoint, **kwargs)": 5719, "def is_running(process_id: int) -> bool:\n \"\"\"\n Uses the Unix ``ps`` program to see if a process is running.\n \"\"\"\n pstr = str(process_id)\n encoding = sys.getdefaultencoding()\n s = subprocess.Popen([\"ps\", \"-p\", pstr], stdout=subprocess.PIPE)\n for line in s.stdout:\n strline = line.decode(encoding)\n if pstr in strline:\n return True\n return False": 5720, "def butlast(iterable):\n \"\"\"Yield all items from ``iterable`` except the last one.\n\n >>> list(butlast(['spam', 'eggs', 'ham']))\n ['spam', 'eggs']\n\n >>> list(butlast(['spam']))\n []\n\n >>> list(butlast([]))\n []\n \"\"\"\n iterable = iter(iterable)\n try:\n first = next(iterable)\n except StopIteration:\n return\n for second in iterable:\n yield first\n first = second": 5721, "def issubset(self, other):\n \"\"\"\n Report whether another set contains this set.\n\n Example:\n >>> OrderedSet([1, 2, 3]).issubset({1, 2})\n False\n >>> OrderedSet([1, 2, 3]).issubset({1, 2, 3, 4})\n True\n >>> OrderedSet([1, 2, 3]).issubset({1, 4, 3, 5})\n False\n \"\"\"\n if len(self) > len(other): # Fast check for obvious cases\n return False\n return all(item in other for item in self)": 5722, "def _str_to_list(value, separator):\n \"\"\"Convert a string to a list with sanitization.\"\"\"\n value_list = [item.strip() for item in value.split(separator)]\n value_list_sanitized = builtins.list(filter(None, value_list))\n if len(value_list_sanitized) > 0:\n return value_list_sanitized\n else:\n raise ValueError('Invalid list variable.')": 5723, "def flatten_multidict(multidict):\n \"\"\"Return flattened dictionary from ``MultiDict``.\"\"\"\n return dict([(key, value if len(value) > 1 else value[0])\n for (key, value) in multidict.iterlists()])": 5724, "def remove_blank_lines(string):\n \"\"\" Removes all blank lines in @string\n\n -> #str without blank lines\n \"\"\"\n return \"\\n\".join(line\n for line in string.split(\"\\n\")\n if len(line.strip()))": 5725, "def incr(name, value=1, rate=1, tags=None):\n \"\"\"Increment a metric by value.\n\n >>> import statsdecor\n >>> statsdecor.incr('my.metric')\n \"\"\"\n client().incr(name, value, rate, tags)": 5726, "def name_is_valid(name):\n \"\"\"Return True if the dataset name is valid.\n\n The name can only be 80 characters long.\n Valid characters: Alpha numeric characters [0-9a-zA-Z]\n Valid special characters: - _ .\n \"\"\"\n # The name can only be 80 characters long.\n if len(name) > MAX_NAME_LENGTH:\n return False\n return bool(NAME_VALID_CHARS_REGEX.match(name))": 5727, "async def async_run(self) -> None:\n \"\"\"\n Asynchronously run the worker, does not close connections. Useful when testing.\n \"\"\"\n self.main_task = self.loop.create_task(self.main())\n await self.main_task": 5728, "def file_uptodate(fname, cmp_fname):\n \"\"\"Check if a file exists, is non-empty and is more recent than cmp_fname.\n \"\"\"\n try:\n return (file_exists(fname) and file_exists(cmp_fname) and\n getmtime(fname) >= getmtime(cmp_fname))\n except OSError:\n return False": 5729, "def __rmatmul__(self, other):\n \"\"\"\n Matrix multiplication using binary `@` operator in Python>=3.5.\n \"\"\"\n return self.T.dot(np.transpose(other)).T": 5730, "def file_exists(fname):\n \"\"\"Check if a file exists and is non-empty.\n \"\"\"\n try:\n return fname and os.path.exists(fname) and os.path.getsize(fname) > 0\n except OSError:\n return False": 5731, "def tsv_escape(x: Any) -> str:\n \"\"\"\n Escape data for tab-separated value (TSV) format.\n \"\"\"\n if x is None:\n return \"\"\n x = str(x)\n return x.replace(\"\\t\", \"\\\\t\").replace(\"\\n\", \"\\\\n\")": 5732, "def get_system_drives():\n \"\"\"\n Get the available drive names on the system. Always returns a list.\n \"\"\"\n drives = []\n if os.name == 'nt':\n import ctypes\n bitmask = ctypes.windll.kernel32.GetLogicalDrives()\n letter = ord('A')\n while bitmask > 0:\n if bitmask & 1:\n name = chr(letter) + ':' + os.sep\n if os.path.isdir(name):\n drives.append(name)\n bitmask >>= 1\n letter += 1\n else:\n current_drive = get_drive(os.getcwd())\n if current_drive:\n drive = current_drive\n else:\n drive = os.sep\n drives.append(drive)\n\n return drives": 5733, "def is_rate_limited(response):\n \"\"\"\n Checks if the response has been rate limited by CARTO APIs\n\n :param response: The response rate limited by CARTO APIs\n :type response: requests.models.Response class\n\n :return: Boolean\n \"\"\"\n if (response.status_code == codes.too_many_requests and 'Retry-After' in response.headers and\n int(response.headers['Retry-After']) >= 0):\n return True\n\n return False": 5734, "def iprotate(l, steps=1):\n r\"\"\"Like rotate, but modifies `l` in-place.\n\n >>> l = [1,2,3]\n >>> iprotate(l) is l\n True\n >>> l\n [2, 3, 1]\n >>> iprotate(iprotate(l, 2), -3)\n [1, 2, 3]\n\n \"\"\"\n if len(l):\n steps %= len(l)\n if steps:\n firstPart = l[:steps]\n del l[:steps]\n l.extend(firstPart)\n return l": 5735, "def to_int64(a):\n \"\"\"Return view of the recarray with all int32 cast to int64.\"\"\"\n # build new dtype and replace i4 --> i8\n def promote_i4(typestr):\n if typestr[1:] == 'i4':\n typestr = typestr[0]+'i8'\n return typestr\n\n dtype = [(name, promote_i4(typestr)) for name,typestr in a.dtype.descr]\n return a.astype(dtype)": 5736, "def browse_dialog_dir():\n \"\"\"\n Open up a GUI browse dialog window and let to user pick a target directory.\n :return str: Target directory path\n \"\"\"\n _go_to_package()\n logger_directory.info(\"enter browse_dialog\")\n _path_bytes = subprocess.check_output(['python', 'gui_dir_browse.py'], shell=False)\n _path = _fix_path_bytes(_path_bytes, file=False)\n if len(_path) >= 1:\n _path = _path[0]\n else:\n _path = \"\"\n logger_directory.info(\"chosen path: {}\".format(_path))\n logger_directory.info(\"exit browse_dialog\")\n return _path": 5737, "def interact(self, container: Container) -> None:\n \"\"\"\n Connects to the PTY (pseudo-TTY) for a given container.\n Blocks until the user exits the PTY.\n \"\"\"\n cmd = \"/bin/bash -c 'source /.environment && /bin/bash'\"\n cmd = \"docker exec -it {} {}\".format(container.id, cmd)\n subprocess.call(cmd, shell=True)": 5738, "def file_exists(self) -> bool:\n \"\"\" Check if the settings file exists or not \"\"\"\n cfg_path = self.file_path\n assert cfg_path\n\n return path.isfile(cfg_path)": 5739, "def _short_repr(obj):\n \"\"\"Helper function returns a truncated repr() of an object.\"\"\"\n stringified = pprint.saferepr(obj)\n if len(stringified) > 200:\n return '%s... (%d bytes)' % (stringified[:200], len(stringified))\n return stringified": 5740, "def remove_once(gset, elem):\n \"\"\"Remove the element from a set, lists or dict.\n \n >>> L = [\"Lucy\"]; S = set([\"Sky\"]); D = { \"Diamonds\": True };\n >>> remove_once(L, \"Lucy\"); remove_once(S, \"Sky\"); remove_once(D, \"Diamonds\");\n >>> print L, S, D\n [] set([]) {}\n\n Returns the element if it was removed. Raises one of the exceptions in \n :obj:`RemoveError` otherwise.\n \"\"\"\n remove = getattr(gset, 'remove', None)\n if remove is not None: remove(elem)\n else: del gset[elem]\n return elem": 5741, "def prevPlot(self):\n \"\"\"Moves the displayed plot to the previous one\"\"\"\n if self.stacker.currentIndex() > 0:\n self.stacker.setCurrentIndex(self.stacker.currentIndex()-1)": 5742, "def find_duplicates(l: list) -> set:\n \"\"\"\n Return the duplicates in a list.\n\n The function relies on\n https://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-a-list .\n Parameters\n ----------\n l : list\n Name\n\n Returns\n -------\n set\n Duplicated values\n\n >>> find_duplicates([1,2,3])\n set()\n >>> find_duplicates([1,2,1])\n {1}\n \"\"\"\n return set([x for x in l if l.count(x) > 1])": 5743, "def change_bgcolor_enable(self, state):\n \"\"\"\n This is implementet so column min/max is only active when bgcolor is\n \"\"\"\n self.dataModel.bgcolor(state)\n self.bgcolor_global.setEnabled(not self.is_series and state > 0)": 5744, "def sorted_chain(*ranges: Iterable[Tuple[int, int]]) -> List[Tuple[int, int]]:\n \"\"\"Chain & sort ranges.\"\"\"\n return sorted(itertools.chain(*ranges))": 5745, "def csv_to_numpy(string_like, dtype=None): # type: (str) -> np.array\n \"\"\"Convert a CSV object to a numpy array.\n\n Args:\n string_like (str): CSV string.\n dtype (dtype, optional): Data type of the resulting array. If None, the dtypes will be determined by the\n contents of each column, individually. This argument can only be used to\n 'upcast' the array. For downcasting, use the .astype(t) method.\n Returns:\n (np.array): numpy array\n \"\"\"\n stream = StringIO(string_like)\n return np.genfromtxt(stream, dtype=dtype, delimiter=',')": 5746, "def _check_whitespace(string):\n \"\"\"\n Make sure thre is no whitespace in the given string. Will raise a\n ValueError if whitespace is detected\n \"\"\"\n if string.count(' ') + string.count('\\t') + string.count('\\n') > 0:\n raise ValueError(INSTRUCTION_HAS_WHITESPACE)": 5747, "def clean_map(obj: Mapping[Any, Any]) -> Mapping[Any, Any]:\n \"\"\"\n Return a new copied dictionary without the keys with ``None`` values from\n the given Mapping object.\n \"\"\"\n return {k: v for k, v in obj.items() if v is not None}": 5748, "def get_pylint_options(config_dir='.'):\n # type: (str) -> List[str]\n \"\"\"Checks for local config overrides for `pylint`\n and add them in the correct `pylint` `options` format.\n\n :param config_dir:\n :return: List [str]\n \"\"\"\n if PYLINT_CONFIG_NAME in os.listdir(config_dir):\n pylint_config_path = PYLINT_CONFIG_NAME\n else:\n pylint_config_path = DEFAULT_PYLINT_CONFIG_PATH\n\n return ['--rcfile={}'.format(pylint_config_path)]": 5749, "def prin(*args, **kwargs):\n r\"\"\"Like ``print``, but a function. I.e. prints out all arguments as\n ``print`` would do. Specify output stream like this::\n\n print('ERROR', `out=\"sys.stderr\"``).\n\n \"\"\"\n print >> kwargs.get('out',None), \" \".join([str(arg) for arg in args])": 5750, "def validate_django_compatible_with_python():\n \"\"\"\n Verify Django 1.11 is present if Python 2.7 is active\n\n Installation of pinax-cli requires the correct version of Django for\n the active Python version. If the developer subsequently changes\n the Python version the installed Django may no longer be compatible.\n \"\"\"\n python_version = sys.version[:5]\n django_version = django.get_version()\n if sys.version_info == (2, 7) and django_version >= \"2\":\n click.BadArgumentUsage(\"Please install Django v1.11 for Python {}, or switch to Python >= v3.4\".format(python_version))": 5751, "def memory_usage():\n \"\"\"return memory usage of python process in MB\n\n from\n http://fa.bianp.net/blog/2013/different-ways-to-get-memory-consumption-or-lessons-learned-from-memory_profiler/\n psutil is quicker\n\n >>> isinstance(memory_usage(),float)\n True\n\n \"\"\"\n try:\n import psutil\n import os\n except ImportError:\n return _memory_usage_ps()\n\n process = psutil.Process(os.getpid())\n mem = process.memory_info()[0] / float(2 ** 20)\n return mem": 5752, "def position(self) -> Position:\n \"\"\"The current position of the cursor.\"\"\"\n return Position(self._index, self._lineno, self._col_offset)": 5753, "def find_column(token):\n \"\"\" Compute column:\n input is the input text string\n token is a token instance\n \"\"\"\n i = token.lexpos\n input = token.lexer.lexdata\n\n while i > 0:\n if input[i - 1] == '\\n':\n break\n i -= 1\n\n column = token.lexpos - i + 1\n\n return column": 5754, "def numeric_part(s):\n \"\"\"Returns the leading numeric part of a string.\n\n >>> numeric_part(\"20-alpha\")\n 20\n >>> numeric_part(\"foo\")\n >>> numeric_part(\"16b\")\n 16\n \"\"\"\n\n m = re_numeric_part.match(s)\n if m:\n return int(m.group(1))\n return None": 5755, "def numchannels(samples:np.ndarray) -> int:\n \"\"\"\n return the number of channels present in samples\n\n samples: a numpy array as returned by sndread\n\n for multichannel audio, samples is always interleaved,\n meaning that samples[n] returns always a frame, which\n is either a single scalar for mono audio, or an array\n for multichannel audio.\n \"\"\"\n if len(samples.shape) == 1:\n return 1\n else:\n return samples.shape[1]": 5756, "def exponential_backoff(attempt: int, cap: int=1200) -> timedelta:\n \"\"\"Calculate a delay to retry using an exponential backoff algorithm.\n\n It is an exponential backoff with random jitter to prevent failures\n from being retried at the same time. It is a good fit for most\n applications.\n\n :arg attempt: the number of attempts made\n :arg cap: maximum delay, defaults to 20 minutes\n \"\"\"\n base = 3\n temp = min(base * 2 ** attempt, cap)\n return timedelta(seconds=temp / 2 + random.randint(0, temp / 2))": 5757, "def is_relative_url(url):\n \"\"\" simple method to determine if a url is relative or absolute \"\"\"\n if url.startswith(\"#\"):\n return None\n if url.find(\"://\") > 0 or url.startswith(\"//\"):\n # either 'http(s)://...' or '//cdn...' and therefore absolute\n return False\n return True": 5758, "def check_consistent_length(*arrays):\n \"\"\"Check that all arrays have consistent first dimensions.\n\n Checks whether all objects in arrays have the same shape or length.\n\n Parameters\n ----------\n arrays : list or tuple of input objects.\n Objects that will be checked for consistent length.\n \"\"\"\n\n uniques = np.unique([_num_samples(X) for X in arrays if X is not None])\n if len(uniques) > 1:\n raise ValueError(\"Found arrays with inconsistent numbers of samples: %s\"\n % str(uniques))": 5759, "def segment_str(text: str, phoneme_inventory: Set[str] = PHONEMES) -> str:\n \"\"\"\n Takes as input a string in Kunwinjku and segments it into phoneme-like\n units based on the standard orthographic rules specified at\n http://bininjgunwok.org.au/\n \"\"\"\n\n text = text.lower()\n text = segment_into_tokens(text, phoneme_inventory)\n return text": 5760, "def last_modified(self) -> Optional[datetime.datetime]:\n \"\"\"The value of Last-Modified HTTP header, or None.\n\n This header is represented as a `datetime` object.\n \"\"\"\n httpdate = self._headers.get(hdrs.LAST_MODIFIED)\n if httpdate is not None:\n timetuple = parsedate(httpdate)\n if timetuple is not None:\n return datetime.datetime(*timetuple[:6],\n tzinfo=datetime.timezone.utc)\n return None": 5761, "def tofile(self, fileobj):\n\t\t\"\"\"\n\t\twrite a cache object to the fileobj as a lal cache file\n\t\t\"\"\"\n\t\tfor entry in self:\n\t\t\tprint >>fileobj, str(entry)\n\t\tfileobj.close()": 5762, "def _brief_print_list(lst, limit=7):\n \"\"\"Print at most `limit` elements of list.\"\"\"\n lst = list(lst)\n if len(lst) > limit:\n return _brief_print_list(lst[:limit//2], limit) + ', ..., ' + \\\n _brief_print_list(lst[-limit//2:], limit)\n return ', '.join([\"'%s'\"%str(i) for i in lst])": 5763, "def _tree_line(self, no_type: bool = False) -> str:\n \"\"\"Return the receiver's contribution to tree diagram.\"\"\"\n return self._tree_line_prefix() + \" \" + self.iname()": 5764, "def uconcatenate(arrs, axis=0):\n \"\"\"Concatenate a sequence of arrays.\n\n This wrapper around numpy.concatenate preserves units. All input arrays\n must have the same units. See the documentation of numpy.concatenate for\n full details.\n\n Examples\n --------\n >>> from unyt import cm\n >>> A = [1, 2, 3]*cm\n >>> B = [2, 3, 4]*cm\n >>> uconcatenate((A, B))\n unyt_array([1, 2, 3, 2, 3, 4], 'cm')\n\n \"\"\"\n v = np.concatenate(arrs, axis=axis)\n v = _validate_numpy_wrapper_units(v, arrs)\n return v": 5765, "def get_from_gnucash26_date(date_str: str) -> date:\n \"\"\" Creates a datetime from GnuCash 2.6 date string \"\"\"\n date_format = \"%Y%m%d\"\n result = datetime.strptime(date_str, date_format).date()\n return result": 5766, "def camel_to_snake_case(string):\n \"\"\"Converts 'string' presented in camel case to snake case.\n\n e.g.: CamelCase => snake_case\n \"\"\"\n s = _1.sub(r'\\1_\\2', string)\n return _2.sub(r'\\1_\\2', s).lower()": 5767, "def count(args):\n \"\"\" count occurences in a list of lists\n >>> count([['a','b'],['a']])\n defaultdict(int, {'a' : 2, 'b' : 1})\n \"\"\"\n counts = defaultdict(int)\n for arg in args:\n for item in arg:\n counts[item] = counts[item] + 1\n return counts": 5768, "def encode_list(key, list_):\n # type: (str, Iterable) -> Dict[str, str]\n \"\"\"\n Converts a list into a space-separated string and puts it in a dictionary\n\n :param key: Dictionary key to store the list\n :param list_: A list of objects\n :return: A dictionary key->string or an empty dictionary\n \"\"\"\n if not list_:\n return {}\n return {key: \" \".join(str(i) for i in list_)}": 5769, "def natural_sort(list_to_sort: Iterable[str]) -> List[str]:\n \"\"\"\n Sorts a list of strings case insensitively as well as numerically.\n\n For example: ['a1', 'A2', 'a3', 'A11', 'a22']\n\n To sort a list in place, don't call this method, which makes a copy. Instead, do this:\n\n my_list.sort(key=natural_keys)\n\n :param list_to_sort: the list being sorted\n :return: the list sorted naturally\n \"\"\"\n return sorted(list_to_sort, key=natural_keys)": 5770, "def are_token_parallel(sequences: Sequence[Sized]) -> bool:\n \"\"\"\n Returns True if all sequences in the list have the same length.\n \"\"\"\n if not sequences or len(sequences) == 1:\n return True\n return all(len(s) == len(sequences[0]) for s in sequences)": 5771, "def margin(text):\n r\"\"\"Add a margin to both ends of each line in the string.\n\n Example:\n >>> margin('line1\\nline2')\n ' line1 \\n line2 '\n \"\"\"\n lines = str(text).split('\\n')\n return '\\n'.join(' {} '.format(l) for l in lines)": 5772, "def closest_values(L):\n \"\"\"Closest values\n\n :param L: list of values\n :returns: two values from L with minimal distance\n :modifies: the order of L\n :complexity: O(n log n), for n=len(L)\n \"\"\"\n assert len(L) >= 2\n L.sort()\n valmin, argmin = min((L[i] - L[i - 1], i) for i in range(1, len(L)))\n return L[argmin - 1], L[argmin]": 5773, "def is_orthogonal(\n matrix: np.ndarray,\n *,\n rtol: float = 1e-5,\n atol: float = 1e-8) -> bool:\n \"\"\"Determines if a matrix is approximately orthogonal.\n\n A matrix is orthogonal if it's square and real and its transpose is its\n inverse.\n\n Args:\n matrix: The matrix to check.\n rtol: The per-matrix-entry relative tolerance on equality.\n atol: The per-matrix-entry absolute tolerance on equality.\n\n Returns:\n Whether the matrix is orthogonal within the given tolerance.\n \"\"\"\n return (matrix.shape[0] == matrix.shape[1] and\n np.all(np.imag(matrix) == 0) and\n np.allclose(matrix.dot(matrix.T), np.eye(matrix.shape[0]),\n rtol=rtol,\n atol=atol))": 5774, "def toStringArray(name, a, width = 0):\n \"\"\"\n Returns an array (any sequence of floats, really) as a string.\n \"\"\"\n string = name + \": \"\n cnt = 0\n for i in a:\n string += \"%4.2f \" % i \n if width > 0 and (cnt + 1) % width == 0:\n string += '\\n'\n cnt += 1\n return string": 5775, "def _isint(string):\n \"\"\"\n >>> _isint(\"123\")\n True\n >>> _isint(\"123.45\")\n False\n \"\"\"\n return type(string) is int or \\\n (isinstance(string, _binary_type) or isinstance(string, _text_type)) and \\\n _isconvertible(int, string)": 5776, "def text_coords(string, position):\n r\"\"\"\n Transform a simple index into a human-readable position in a string.\n\n This function accepts a string and an index, and will return a triple of\n `(lineno, columnno, line)` representing the position through the text. It's\n useful for displaying a string index in a human-readable way::\n\n >>> s = \"abcdef\\nghijkl\\nmnopqr\\nstuvwx\\nyz\"\n >>> text_coords(s, 0)\n (0, 0, 'abcdef')\n >>> text_coords(s, 4)\n (0, 4, 'abcdef')\n >>> text_coords(s, 6)\n (0, 6, 'abcdef')\n >>> text_coords(s, 7)\n (1, 0, 'ghijkl')\n >>> text_coords(s, 11)\n (1, 4, 'ghijkl')\n >>> text_coords(s, 15)\n (2, 1, 'mnopqr')\n \"\"\"\n line_start = string.rfind('\\n', 0, position) + 1\n line_end = string.find('\\n', position)\n lineno = string.count('\\n', 0, position)\n columnno = position - line_start\n line = string[line_start:line_end]\n return (lineno, columnno, line)": 5777, "def highlight(text: str, color_code: int, bold: bool=False) -> str:\n \"\"\"Wraps the given string with terminal color codes.\n\n Args:\n text: The content to highlight.\n color_code: The color to highlight with, e.g. 'shelltools.RED'.\n bold: Whether to bold the content in addition to coloring.\n\n Returns:\n The highlighted string.\n \"\"\"\n return '{}\\033[{}m{}\\033[0m'.format(\n '\\033[1m' if bold else '',\n color_code,\n text,)": 5778, "def assign_parent(node: astroid.node_classes.NodeNG) -> astroid.node_classes.NodeNG:\n \"\"\"return the higher parent which is not an AssignName, Tuple or List node\n \"\"\"\n while node and isinstance(node, (astroid.AssignName, astroid.Tuple, astroid.List)):\n node = node.parent\n return node": 5779, "def excel_datetime(timestamp, epoch=None):\n \"\"\"Return datetime object from timestamp in Excel serial format.\n\n Convert LSM time stamps.\n\n >>> excel_datetime(40237.029999999795)\n datetime.datetime(2010, 2, 28, 0, 43, 11, 999982)\n\n \"\"\"\n if epoch is None:\n epoch = datetime.datetime.fromordinal(693594)\n return epoch + datetime.timedelta(timestamp)": 5780, "def callable_validator(v: Any) -> AnyCallable:\n \"\"\"\n Perform a simple check if the value is callable.\n\n Note: complete matching of argument type hints and return types is not performed\n \"\"\"\n if callable(v):\n return v\n\n raise errors.CallableError(value=v)": 5781, "def pack_bits( longbits ):\n \"\"\"Crunch a 64-bit int (8 bool bytes) into a bitfield.\"\"\"\n byte = longbits & (0x0101010101010101)\n byte = (byte | (byte>>7)) & (0x0003000300030003)\n byte = (byte | (byte>>14)) & (0x0000000f0000000f)\n byte = (byte | (byte>>28)) & (0x00000000000000ff)\n return byte": 5782, "def enum_mark_last(iterable, start=0):\n \"\"\"\n Returns a generator over iterable that tells whether the current item is the last one.\n Usage:\n >>> iterable = range(10)\n >>> for index, is_last, item in enum_mark_last(iterable):\n >>> print(index, item, end='\\n' if is_last else ', ')\n \"\"\"\n it = iter(iterable)\n count = start\n try:\n last = next(it)\n except StopIteration:\n return\n for val in it:\n yield count, False, last\n last = val\n count += 1\n yield count, True, last": 5783, "def to_iso_string(self) -> str:\n \"\"\" Returns full ISO string for the given date \"\"\"\n assert isinstance(self.value, datetime)\n return datetime.isoformat(self.value)": 5784, "def timeit(func, *args, **kwargs):\n \"\"\"\n Time execution of function. Returns (res, seconds).\n\n >>> res, timing = timeit(time.sleep, 1)\n \"\"\"\n start_time = time.time()\n res = func(*args, **kwargs)\n timing = time.time() - start_time\n return res, timing": 5785, "def clean_all_buckets(self):\n \"\"\"\n Removes all buckets from all hashes and their content.\n \"\"\"\n bucket_keys = self.redis_object.keys(pattern='nearpy_*')\n if len(bucket_keys) > 0:\n self.redis_object.delete(*bucket_keys)": 5786, "def output_dir(self, *args) -> str:\n \"\"\" Directory where to store output \"\"\"\n return os.path.join(self.project_dir, 'output', *args)": 5787, "def writable_stream(handle):\n \"\"\"Test whether a stream can be written to.\n \"\"\"\n if isinstance(handle, io.IOBase) and sys.version_info >= (3, 5):\n return handle.writable()\n try:\n handle.write(b'')\n except (io.UnsupportedOperation, IOError):\n return False\n else:\n return True": 5788, "def contains(self, token: str) -> bool:\n \"\"\"Return if the token is in the list or not.\"\"\"\n self._validate_token(token)\n return token in self": 5789, "def detect_model_num(string):\n \"\"\"Takes a string related to a model name and extract its model number.\n\n For example:\n '000000-bootstrap.index' => 0\n \"\"\"\n match = re.match(MODEL_NUM_REGEX, string)\n if match:\n return int(match.group())\n return None": 5790, "def shape(self) -> Tuple[int, ...]:\n \"\"\"Shape of histogram's data.\n\n Returns\n -------\n One-element tuple with the number of bins along each axis.\n \"\"\"\n return tuple(bins.bin_count for bins in self._binnings)": 5791, "def simple_eq(one: Instance, two: Instance, attrs: List[str]) -> bool:\n \"\"\"\n Test if two objects are equal, based on a comparison of the specified\n attributes ``attrs``.\n \"\"\"\n return all(getattr(one, a) == getattr(two, a) for a in attrs)": 5792, "def imt2tup(string):\n \"\"\"\n >>> imt2tup('PGA')\n ('PGA',)\n >>> imt2tup('SA(1.0)')\n ('SA', 1.0)\n >>> imt2tup('SA(1)')\n ('SA', 1.0)\n \"\"\"\n s = string.strip()\n if not s.endswith(')'):\n # no parenthesis, PGA is considered the same as PGA()\n return (s,)\n name, rest = s.split('(', 1)\n return (name,) + tuple(float(x) for x in ast.literal_eval(rest[:-1] + ','))": 5793, "def _store_helper(model: Action, session: Optional[Session] = None) -> None:\n \"\"\"Help store an action.\"\"\"\n if session is None:\n session = _make_session()\n\n session.add(model)\n session.commit()\n session.close()": 5794, "def _cursorLeft(self):\n \"\"\" Handles \"cursor left\" events \"\"\"\n if self.cursorPos > 0:\n self.cursorPos -= 1\n sys.stdout.write(console.CURSOR_LEFT)\n sys.stdout.flush()": 5795, "def parse_reading(val: str) -> Optional[float]:\n \"\"\" Convert reading value to float (if possible) \"\"\"\n try:\n return float(val)\n except ValueError:\n logging.warning('Reading of \"%s\" is not a number', val)\n return None": 5796, "def datetime_from_isoformat(value: str):\n \"\"\"Return a datetime object from an isoformat string.\n\n Args:\n value (str): Datetime string in isoformat.\n\n \"\"\"\n if sys.version_info >= (3, 7):\n return datetime.fromisoformat(value)\n\n return datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%f')": 5797, "def get_domain(url):\n \"\"\"\n Get domain part of an url.\n\n For example: https://www.python.org/doc/ -> https://www.python.org\n \"\"\"\n parse_result = urlparse(url)\n domain = \"{schema}://{netloc}\".format(\n schema=parse_result.scheme, netloc=parse_result.netloc)\n return domain": 5798, "def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:\n \"\"\"\n Takes a list of rows and a column name and returns a list containing a single row (dict from\n columns to cells) that has the maximum numerical value in the given column. We return a list\n instead of a single dict to be consistent with the return type of ``select`` and\n ``all_rows``.\n \"\"\"\n if not rows:\n return []\n value_row_pairs = [(row.values[column.name], row) for row in rows]\n if not value_row_pairs:\n return []\n # Returns a list containing the row with the max cell value.\n return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]": 5799, "def tanimoto_set_similarity(x: Iterable[X], y: Iterable[X]) -> float:\n \"\"\"Calculate the tanimoto set similarity.\"\"\"\n a, b = set(x), set(y)\n union = a | b\n\n if not union:\n return 0.0\n\n return len(a & b) / len(union)": 5800, "def reverse_mapping(mapping):\n\t\"\"\"\n\tFor every key, value pair, return the mapping for the\n\tequivalent value, key pair\n\n\t>>> reverse_mapping({'a': 'b'}) == {'b': 'a'}\n\tTrue\n\t\"\"\"\n\tkeys, values = zip(*mapping.items())\n\treturn dict(zip(values, keys))": 5801, "def get_table_names_from_metadata(metadata: MetaData) -> List[str]:\n \"\"\"\n Returns all database table names found in an SQLAlchemy :class:`MetaData`\n object.\n \"\"\"\n return [table.name for table in metadata.tables.values()]": 5802, "def dtypes(self):\n \"\"\"Returns all column names and their data types as a list.\n\n >>> df.dtypes\n [('age', 'int'), ('name', 'string')]\n \"\"\"\n return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]": 5803, "def almost_hermitian(gate: Gate) -> bool:\n \"\"\"Return true if gate tensor is (almost) Hermitian\"\"\"\n return np.allclose(asarray(gate.asoperator()),\n asarray(gate.H.asoperator()))": 5804, "def sample_normal(mean, var, rng):\n \"\"\"Sample from independent normal distributions\n\n Each element is an independent normal distribution.\n\n Parameters\n ----------\n mean : numpy.ndarray\n Means of the normal distribution. Shape --> (batch_num, sample_dim)\n var : numpy.ndarray\n Variance of the normal distribution. Shape --> (batch_num, sample_dim)\n rng : numpy.random.RandomState\n\n Returns\n -------\n ret : numpy.ndarray\n The sampling result. Shape --> (batch_num, sample_dim)\n \"\"\"\n ret = numpy.sqrt(var) * rng.randn(*mean.shape) + mean\n return ret": 5805, "def fetchvalue(self, sql: str, *args) -> Optional[Any]:\n \"\"\"Executes SQL; returns the first value of the first row, or None.\"\"\"\n row = self.fetchone(sql, *args)\n if row is None:\n return None\n return row[0]": 5806, "def inject_nulls(data: Mapping, field_names) -> dict:\n \"\"\"Insert None as value for missing fields.\"\"\"\n\n record = dict()\n\n for field in field_names:\n record[field] = data.get(field, None)\n\n return record": 5807, "def valid_file(path: str) -> bool:\n \"\"\"\n Verifies that a string path actually exists and is a file\n\n :param path: The path to verify\n :return: **True** if path exist and is a file\n \"\"\"\n path = Path(path).expanduser()\n log.debug(\"checking if %s is a valid file\", path)\n return path.exists() and path.is_file()": 5808, "def get_deprecation_reason(\n node: Union[EnumValueDefinitionNode, FieldDefinitionNode]\n) -> Optional[str]:\n \"\"\"Given a field or enum value node, get deprecation reason as string.\"\"\"\n from ..execution import get_directive_values\n\n deprecated = get_directive_values(GraphQLDeprecatedDirective, node)\n return deprecated[\"reason\"] if deprecated else None": 5809, "def _prm_get_longest_stringsize(string_list):\n \"\"\" Returns the longest string size for a string entry across data.\"\"\"\n maxlength = 1\n\n for stringar in string_list:\n if isinstance(stringar, np.ndarray):\n if stringar.ndim > 0:\n for string in stringar.ravel():\n maxlength = max(len(string), maxlength)\n else:\n maxlength = max(len(stringar.tolist()), maxlength)\n else:\n maxlength = max(len(stringar), maxlength)\n\n # Make the string Col longer than needed in order to allow later on slightly larger strings\n return int(maxlength * 1.5)": 5810, "def cmd_dot(conf: Config):\n \"\"\"Print out a neat targets dependency tree based on requested targets.\n\n Use graphviz to render the dot file, e.g.:\n\n > ybt dot :foo :bar | dot -Tpng -o graph.png\n \"\"\"\n build_context = BuildContext(conf)\n populate_targets_graph(build_context, conf)\n if conf.output_dot_file is None:\n write_dot(build_context, conf, sys.stdout)\n else:\n with open(conf.output_dot_file, 'w') as out_file:\n write_dot(build_context, conf, out_file)": 5811, "def has_value(cls, value: int) -> bool:\n \"\"\"True if specified value exists in int enum; otherwise, False.\"\"\"\n return any(value == item.value for item in cls)": 5812, "def post(self, endpoint: str, **kwargs) -> dict:\n \"\"\"HTTP POST operation to API endpoint.\"\"\"\n\n return self._request('POST', endpoint, **kwargs)": 5813, "def auto_up(self, count=1, go_to_start_of_line_if_history_changes=False):\n \"\"\"\n If we're not on the first line (of a multiline input) go a line up,\n otherwise go back in history. (If nothing is selected.)\n \"\"\"\n if self.complete_state:\n self.complete_previous(count=count)\n elif self.document.cursor_position_row > 0:\n self.cursor_up(count=count)\n elif not self.selection_state:\n self.history_backward(count=count)\n\n # Go to the start of the line?\n if go_to_start_of_line_if_history_changes:\n self.cursor_position += self.document.get_start_of_line_position()": 5814, "def to_0d_array(value: Any) -> np.ndarray:\n \"\"\"Given a value, wrap it in a 0-D numpy.ndarray.\n \"\"\"\n if np.isscalar(value) or (isinstance(value, np.ndarray) and\n value.ndim == 0):\n return np.array(value)\n else:\n return to_0d_object_array(value)": 5815, "def gcd_float(numbers, tol=1e-8):\n \"\"\"\n Returns the greatest common divisor for a sequence of numbers.\n Uses a numerical tolerance, so can be used on floats\n\n Args:\n numbers: Sequence of numbers.\n tol: Numerical tolerance\n\n Returns:\n (int) Greatest common divisor of numbers.\n \"\"\"\n\n def pair_gcd_tol(a, b):\n \"\"\"Calculate the Greatest Common Divisor of a and b.\n\n Unless b==0, the result will have the same sign as b (so that when\n b is divided by it, the result comes out positive).\n \"\"\"\n while b > tol:\n a, b = b, a % b\n return a\n\n n = numbers[0]\n for i in numbers:\n n = pair_gcd_tol(n, i)\n return n": 5816, "def calculate_dimensions(image, long_side, short_side):\n \"\"\"Returns the thumbnail dimensions depending on the images format.\"\"\"\n if image.width >= image.height:\n return '{0}x{1}'.format(long_side, short_side)\n return '{0}x{1}'.format(short_side, long_side)": 5817, "def fmt_camel(name):\n \"\"\"\n Converts name to lower camel case. Words are identified by capitalization,\n dashes, and underscores.\n \"\"\"\n words = split_words(name)\n assert len(words) > 0\n first = words.pop(0).lower()\n return first + ''.join([word.capitalize() for word in words])": 5818, "def from_file(filename, mime=False):\n \"\"\"\"\n Accepts a filename and returns the detected filetype. Return\n value is the mimetype if mime=True, otherwise a human readable\n name.\n\n >>> magic.from_file(\"testdata/test.pdf\", mime=True)\n 'application/pdf'\n \"\"\"\n m = _get_magic_type(mime)\n return m.from_file(filename)": 5819, "def _relative_frequency(self, word):\n\t\t\"\"\"Computes the log relative frequency for a word form\"\"\"\n\n\t\tcount = self.type_counts.get(word, 0)\n\t\treturn math.log(count/len(self.type_counts)) if count > 0 else 0": 5820, "def getIndex(predicateFn: Callable[[T], bool], items: List[T]) -> int:\n \"\"\"\n Finds the index of an item in list, which satisfies predicate\n :param predicateFn: predicate function to run on items of list\n :param items: list of tuples\n :return: first index for which predicate function returns True\n \"\"\"\n try:\n return next(i for i, v in enumerate(items) if predicateFn(v))\n except StopIteration:\n return -1": 5821, "def isarray(array, test, dim=2):\n \"\"\"Returns True if test is True for all array elements.\n Otherwise, returns False.\n \"\"\"\n if dim > 1:\n return all(isarray(array[i], test, dim - 1)\n for i in range(len(array)))\n return all(test(i) for i in array)": 5822, "def is_quoted(arg: str) -> bool:\n \"\"\"\n Checks if a string is quoted\n :param arg: the string being checked for quotes\n :return: True if a string is quoted\n \"\"\"\n return len(arg) > 1 and arg[0] == arg[-1] and arg[0] in constants.QUOTES": 5823, "def get_language():\n \"\"\"\n Wrapper around Django's `get_language` utility.\n For Django >= 1.8, `get_language` returns None in case no translation is activate.\n Here we patch this behavior e.g. for back-end functionality requiring access to translated fields\n \"\"\"\n from parler import appsettings\n language = dj_get_language()\n if language is None and appsettings.PARLER_DEFAULT_ACTIVATE:\n return appsettings.PARLER_DEFAULT_LANGUAGE_CODE\n else:\n return language": 5824, "def infer_format(filename:str) -> str:\n \"\"\"Return extension identifying format of given filename\"\"\"\n _, ext = os.path.splitext(filename)\n return ext": 5825, "def _find_conda():\n \"\"\"Find the conda executable robustly across conda versions.\n\n Returns\n -------\n conda : str\n Path to the conda executable.\n\n Raises\n ------\n IOError\n If the executable cannot be found in either the CONDA_EXE environment\n variable or in the PATH.\n\n Notes\n -----\n In POSIX platforms in conda >= 4.4, conda can be set up as a bash function\n rather than an executable. (This is to enable the syntax\n ``conda activate env-name``.) In this case, the environment variable\n ``CONDA_EXE`` contains the path to the conda executable. In other cases,\n we use standard search for the appropriate name in the PATH.\n\n See https://github.com/airspeed-velocity/asv/issues/645 for more details.\n \"\"\"\n if 'CONDA_EXE' in os.environ:\n conda = os.environ['CONDA_EXE']\n else:\n conda = util.which('conda')\n return conda": 5826, "def nTimes(n, f, *args, **kwargs):\n r\"\"\"Call `f` `n` times with `args` and `kwargs`.\n Useful e.g. for simplistic timing.\n\n Examples:\n\n >>> nTimes(3, sys.stdout.write, 'hallo\\n')\n hallo\n hallo\n hallo\n\n \"\"\"\n for i in xrange(n): f(*args, **kwargs)": 5827, "def elmo_loss2ppl(losses: List[np.ndarray]) -> float:\n \"\"\" Calculates perplexity by loss\n\n Args:\n losses: list of numpy arrays of model losses\n\n Returns:\n perplexity : float\n \"\"\"\n avg_loss = np.mean(losses)\n return float(np.exp(avg_loss))": 5828, "def url_concat(url, args):\n \"\"\"Concatenate url and argument dictionary regardless of whether\n url has existing query parameters.\n\n >>> url_concat(\"http://example.com/foo?a=b\", dict(c=\"d\"))\n 'http://example.com/foo?a=b&c=d'\n \"\"\"\n if not args: return url\n if url[-1] not in ('?', '&'):\n url += '&' if ('?' in url) else '?'\n return url + urllib.urlencode(args)": 5829, "def pset(iterable=(), pre_size=8):\n \"\"\"\n Creates a persistent set from iterable. Optionally takes a sizing parameter equivalent to that\n used for :py:func:`pmap`.\n\n >>> s1 = pset([1, 2, 3, 2])\n >>> s1\n pset([1, 2, 3])\n \"\"\"\n if not iterable:\n return _EMPTY_PSET\n\n return PSet._from_iterable(iterable, pre_size=pre_size)": 5830, "def hsv2rgb_spectrum(hsv):\n \"\"\"Generates RGB values from HSV values in line with a typical light\n spectrum.\"\"\"\n h, s, v = hsv\n return hsv2rgb_raw(((h * 192) >> 8, s, v))": 5831, "def __as_list(value: List[JsonObjTypes]) -> List[JsonTypes]:\n \"\"\" Return a json array as a list\n\n :param value: array\n :return: array with JsonObj instances removed\n \"\"\"\n return [e._as_dict if isinstance(e, JsonObj) else e for e in value]": 5832, "def __add_method(m: lmap.Map, key: T, method: Method) -> lmap.Map:\n \"\"\"Swap the methods atom to include method with key.\"\"\"\n return m.assoc(key, method)": 5833, "def isfile_notempty(inputfile: str) -> bool:\n \"\"\"Check if the input filename with path is a file and is not empty.\"\"\"\n try:\n return isfile(inputfile) and getsize(inputfile) > 0\n except TypeError:\n raise TypeError('inputfile is not a valid type')": 5834, "def __iter__(self):\n \"\"\"Define a generator function and return it\"\"\"\n def generator():\n for i, obj in enumerate(self._sequence):\n if i >= self._limit:\n break\n yield obj\n raise StopIteration\n return generator": 5835, "def clean_int(x) -> int:\n \"\"\"\n Returns its parameter as an integer, or raises\n ``django.forms.ValidationError``.\n \"\"\"\n try:\n return int(x)\n except ValueError:\n raise forms.ValidationError(\n \"Cannot convert to integer: {}\".format(repr(x)))": 5836, "def format_repr(obj, attributes) -> str:\n \"\"\"Format an object's repr method with specific attributes.\"\"\"\n\n attribute_repr = ', '.join(('{}={}'.format(attr, repr(getattr(obj, attr)))\n for attr in attributes))\n return \"{0}({1})\".format(obj.__class__.__qualname__, attribute_repr)": 5837, "def _read_words(filename):\n \"\"\"Reads words from a file.\"\"\"\n with tf.gfile.GFile(filename, \"r\") as f:\n if sys.version_info[0] >= 3:\n return f.read().replace(\"\\n\", \" %s \" % EOS).split()\n else:\n return f.read().decode(\"utf-8\").replace(\"\\n\", \" %s \" % EOS).split()": 5838, "def u16le_list_to_byte_list(data):\n \"\"\"! @brief Convert a halfword array into a byte array\"\"\"\n byteData = []\n for h in data:\n byteData.extend([h & 0xff, (h >> 8) & 0xff])\n return byteData": 5839, "def sort_by_modified(files_or_folders: list) -> list:\n \"\"\"\n Sort files or folders by modified time\n\n Args:\n files_or_folders: list of files or folders\n\n Returns:\n list\n \"\"\"\n return sorted(files_or_folders, key=os.path.getmtime, reverse=True)": 5840, "def lint(fmt='colorized'):\n \"\"\"Run verbose PyLint on source. Optionally specify fmt=html for HTML output.\"\"\"\n if fmt == 'html':\n outfile = 'pylint_report.html'\n local('pylint -f %s davies > %s || true' % (fmt, outfile))\n local('open %s' % outfile)\n else:\n local('pylint -f %s davies || true' % fmt)": 5841, "def _gauss(mean: int, sigma: int) -> int:\n \"\"\"\n Creates a variation from a base value\n\n Args:\n mean: base value\n sigma: gaussian sigma\n\n Returns: random value\n\n \"\"\"\n return int(random.gauss(mean, sigma))": 5842, "def rmglob(pattern: str) -> None:\n \"\"\"\n Deletes all files whose filename matches the glob ``pattern`` (via\n :func:`glob.glob`).\n \"\"\"\n for f in glob.glob(pattern):\n os.remove(f)": 5843, "def PrintIndented(self, file, ident, code):\n \"\"\"Takes an array, add indentation to each entry and prints it.\"\"\"\n for entry in code:\n print >>file, '%s%s' % (ident, entry)": 5844, "def replace_keys(record: Mapping, key_map: Mapping) -> dict:\n \"\"\"New record with renamed keys including keys only found in key_map.\"\"\"\n\n return {key_map[k]: v for k, v in record.items() if k in key_map}": 5845, "def valid_substitution(strlen, index):\n \"\"\"\n skip performing substitutions that are outside the bounds of the string\n \"\"\"\n values = index[0]\n return all([strlen > i for i in values])": 5846, "def fast_median(a):\n \"\"\"Fast median operation for masked array using 50th-percentile\n \"\"\"\n a = checkma(a)\n #return scoreatpercentile(a.compressed(), 50)\n if a.count() > 0:\n out = np.percentile(a.compressed(), 50)\n else:\n out = np.ma.masked\n return out": 5847, "def dict_of_sets_add(dictionary, key, value):\n # type: (DictUpperBound, Any, Any) -> None\n \"\"\"Add value to a set in a dictionary by key\n\n Args:\n dictionary (DictUpperBound): Dictionary to which to add values\n key (Any): Key within dictionary\n value (Any): Value to add to set in dictionary\n\n Returns:\n None\n\n \"\"\"\n set_objs = dictionary.get(key, set())\n set_objs.add(value)\n dictionary[key] = set_objs": 5848, "def arcball_map_to_sphere(point, center, radius):\n \"\"\"Return unit sphere coordinates from window coordinates.\"\"\"\n v0 = (point[0] - center[0]) / radius\n v1 = (center[1] - point[1]) / radius\n n = v0*v0 + v1*v1\n if n > 1.0:\n # position outside of sphere\n n = math.sqrt(n)\n return numpy.array([v0/n, v1/n, 0.0])\n else:\n return numpy.array([v0, v1, math.sqrt(1.0 - n)])": 5849, "def _create_empty_array(self, frames, always_2d, dtype):\n \"\"\"Create an empty array with appropriate shape.\"\"\"\n import numpy as np\n if always_2d or self.channels > 1:\n shape = frames, self.channels\n else:\n shape = frames,\n return np.empty(shape, dtype, order='C')": 5850, "def assert_equal(first, second, msg_fmt=\"{msg}\"):\n \"\"\"Fail unless first equals second, as determined by the '==' operator.\n\n >>> assert_equal(5, 5.0)\n >>> assert_equal(\"Hello World!\", \"Goodbye!\")\n Traceback (most recent call last):\n ...\n AssertionError: 'Hello World!' != 'Goodbye!'\n\n The following msg_fmt arguments are supported:\n * msg - the default error message\n * first - the first argument\n * second - the second argument\n \"\"\"\n\n if isinstance(first, dict) and isinstance(second, dict):\n assert_dict_equal(first, second, msg_fmt)\n elif not first == second:\n msg = \"{!r} != {!r}\".format(first, second)\n fail(msg_fmt.format(msg=msg, first=first, second=second))": 5851, "def set_cell_value(cell, value):\n \"\"\"\n Convenience method for setting the value of an openpyxl cell\n\n This is necessary since the value property changed from internal_value\n to value between version 1.* and 2.*.\n \"\"\"\n if OPENPYXL_MAJOR_VERSION > 1:\n cell.value = value\n else:\n cell.internal_value = value": 5852, "def _mid(pt1, pt2):\n \"\"\"\n (Point, Point) -> Point\n Return the point that lies in between the two input points.\n \"\"\"\n (x0, y0), (x1, y1) = pt1, pt2\n return 0.5 * (x0 + x1), 0.5 * (y0 + y1)": 5853, "def _parse_date(string: str) -> datetime.date:\n \"\"\"Parse an ISO format date (YYYY-mm-dd).\n\n >>> _parse_date('1990-01-02')\n datetime.date(1990, 1, 2)\n \"\"\"\n return datetime.datetime.strptime(string, '%Y-%m-%d').date()": 5854, "def hash_file(fileobj):\n \"\"\"\n :param fileobj: a file object\n :return: a hash of the file content\n \"\"\"\n hasher = hashlib.md5()\n buf = fileobj.read(65536)\n while len(buf) > 0:\n hasher.update(buf)\n buf = fileobj.read(65536)\n return hasher.hexdigest()": 5855, "def setup_cache(app: Flask, cache_config) -> Optional[Cache]:\n \"\"\"Setup the flask-cache on a flask app\"\"\"\n if cache_config and cache_config.get('CACHE_TYPE') != 'null':\n return Cache(app, config=cache_config)\n\n return None": 5856, "def in_transaction(self):\n \"\"\"Check if this database is in a transactional context.\"\"\"\n if not hasattr(self.local, 'tx'):\n return False\n return len(self.local.tx) > 0": 5857, "def score_small_straight_yatzy(dice: List[int]) -> int:\n \"\"\"\n Small straight scoring according to yatzy rules\n \"\"\"\n dice_set = set(dice)\n if _are_two_sets_equal({1, 2, 3, 4, 5}, dice_set):\n return sum(dice)\n return 0": 5858, "def process_literal_param(self, value: Optional[List[int]],\n dialect: Dialect) -> str:\n \"\"\"Convert things on the way from Python to the database.\"\"\"\n retval = self._intlist_to_dbstr(value)\n return retval": 5859, "def label_from_bin(buf):\n \"\"\"\n Converts binary representation label to integer.\n\n :param buf: Binary representation of label.\n :return: MPLS Label and BoS bit.\n \"\"\"\n\n mpls_label = type_desc.Int3.to_user(six.binary_type(buf))\n return mpls_label >> 4, mpls_label & 1": 5860, "def has_table(self, name):\n \"\"\"Return ``True`` if the table *name* exists in the database.\"\"\"\n return len(self.sql(\"SELECT name FROM sqlite_master WHERE type='table' AND name=?\",\n parameters=(name,), asrecarray=False, cache=False)) > 0": 5861, "def rl_get_point() -> int: # pragma: no cover\n \"\"\"\n Returns the offset of the current cursor position in rl_line_buffer\n \"\"\"\n if rl_type == RlType.GNU:\n return ctypes.c_int.in_dll(readline_lib, \"rl_point\").value\n\n elif rl_type == RlType.PYREADLINE:\n return readline.rl.mode.l_buffer.point\n\n else:\n return 0": 5862, "def is_unitary(matrix: np.ndarray) -> bool:\n \"\"\"\n A helper function that checks if a matrix is unitary.\n\n :param matrix: a matrix to test unitarity of\n :return: true if and only if matrix is unitary\n \"\"\"\n rows, cols = matrix.shape\n if rows != cols:\n return False\n return np.allclose(np.eye(rows), matrix.dot(matrix.T.conj()))": 5863, "def SGT(self, a, b):\n \"\"\"Signed greater-than comparison\"\"\"\n # http://gavwood.com/paper.pdf\n s0, s1 = to_signed(a), to_signed(b)\n return Operators.ITEBV(256, s0 > s1, 1, 0)": 5864, "def replaceStrs(s, *args):\n r\"\"\"Replace all ``(frm, to)`` tuples in `args` in string `s`.\n\n >>> replaceStrs(\"nothing is better than warm beer\",\n ... ('nothing','warm beer'), ('warm beer','nothing'))\n 'warm beer is better than nothing'\n\n \"\"\"\n if args == (): return s\n mapping = dict((frm, to) for frm, to in args)\n return re.sub(\"|\".join(map(re.escape, mapping.keys())),\n lambda match:mapping[match.group(0)], s)": 5865, "def remove_falsy_values(counter: Mapping[Any, int]) -> Mapping[Any, int]:\n \"\"\"Remove all values that are zero.\"\"\"\n return {\n label: count\n for label, count in counter.items()\n if count\n }": 5866, "def normcdf(x, log=False):\n \"\"\"Normal cumulative density function.\"\"\"\n y = np.atleast_1d(x).copy()\n flib.normcdf(y)\n if log:\n if (y>0).all():\n return np.log(y)\n return -np.inf\n return y": 5867, "def zlib_compress(data):\n \"\"\"\n Compress things in a py2/3 safe fashion\n >>> json_str = '{\"test\": 1}'\n >>> blob = zlib_compress(json_str)\n \"\"\"\n if PY3K:\n if isinstance(data, str):\n return zlib.compress(bytes(data, 'utf-8'))\n return zlib.compress(data)\n return zlib.compress(data)": 5868, "def get_cursor(self):\n \"\"\"Return the virtual cursor position.\n\n The cursor can be moved with the :any:`move` method.\n\n Returns:\n Tuple[int, int]: The (x, y) coordinate of where :any:`print_str`\n will continue from.\n\n .. seealso:: :any:move`\n \"\"\"\n x, y = self._cursor\n width, height = self.parent.get_size()\n while x >= width:\n x -= width\n y += 1\n if y >= height and self.scrollMode == 'scroll':\n y = height - 1\n return x, y": 5869, "def file_lines(bblfile:str) -> iter:\n \"\"\"Yield lines found in given file\"\"\"\n with open(bblfile) as fd:\n yield from (line.rstrip() for line in fd if line.rstrip())": 5870, "def getRandomBinaryTreeLeafNode(binaryTree):\n \"\"\"Get random binary tree node.\n \"\"\"\n if binaryTree.internal == True:\n if random.random() > 0.5:\n return getRandomBinaryTreeLeafNode(binaryTree.left)\n else:\n return getRandomBinaryTreeLeafNode(binaryTree.right)\n else:\n return binaryTree": 5871, "def check_key(self, key: str) -> bool:\n \"\"\"\n Checks if key exists in datastore. True if yes, False if no.\n\n :param: SHA512 hash key\n\n :return: whether or key not exists in datastore\n \"\"\"\n keys = self.get_keys()\n return key in keys": 5872, "def split_unit(value):\n \"\"\" Split a number from its unit\n 1px -> (q, 'px')\n Args:\n value (str): input\n returns:\n tuple\n \"\"\"\n r = re.search('^(\\-?[\\d\\.]+)(.*)$', str(value))\n return r.groups() if r else ('', '')": 5873, "def rms(x):\n \"\"\"\"Root Mean Square\"\n\n Arguments:\n x (seq of float): A sequence of numerical values\n\n Returns:\n The square root of the average of the squares of the values\n\n math.sqrt(sum(x_i**2 for x_i in x) / len(x))\n\n or\n\n return (np.array(x) ** 2).mean() ** 0.5\n\n >>> rms([0, 2, 4, 4])\n 3.0\n \"\"\"\n try:\n return (np.array(x) ** 2).mean() ** 0.5\n except:\n x = np.array(dropna(x))\n invN = 1.0 / len(x)\n return (sum(invN * (x_i ** 2) for x_i in x)) ** .5": 5874, "def templategetter(tmpl):\n \"\"\"\n This is a dirty little template function generator that turns single-brace\n Mustache-style template strings into functions that interpolate dict keys:\n\n >>> get_name = templategetter(\"{first} {last}\")\n >>> get_name({'first': 'Shawn', 'last': 'Allen'})\n 'Shawn Allen'\n \"\"\"\n tmpl = tmpl.replace('{', '%(')\n tmpl = tmpl.replace('}', ')s')\n return lambda data: tmpl % data": 5875, "def to_clipboard(self, excel=True, sep=None, **kwargs):\n r\"\"\"\n Copy object to the system clipboard.\n\n Write a text representation of object to the system clipboard.\n This can be pasted into Excel, for example.\n\n Parameters\n ----------\n excel : bool, default True\n - True, use the provided separator, writing in a csv format for\n allowing easy pasting into excel.\n - False, write a string representation of the object to the\n clipboard.\n\n sep : str, default ``'\\t'``\n Field delimiter.\n **kwargs\n These parameters will be passed to DataFrame.to_csv.\n\n See Also\n --------\n DataFrame.to_csv : Write a DataFrame to a comma-separated values\n (csv) file.\n read_clipboard : Read text from clipboard and pass to read_table.\n\n Notes\n -----\n Requirements for your platform.\n\n - Linux : `xclip`, or `xsel` (with `gtk` or `PyQt4` modules)\n - Windows : none\n - OS X : none\n\n Examples\n --------\n Copy the contents of a DataFrame to the clipboard.\n\n >>> df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=['A', 'B', 'C'])\n >>> df.to_clipboard(sep=',')\n ... # Wrote the following to the system clipboard:\n ... # ,A,B,C\n ... # 0,1,2,3\n ... # 1,4,5,6\n\n We can omit the the index by passing the keyword `index` and setting\n it to false.\n\n >>> df.to_clipboard(sep=',', index=False)\n ... # Wrote the following to the system clipboard:\n ... # A,B,C\n ... # 1,2,3\n ... # 4,5,6\n \"\"\"\n from pandas.io import clipboards\n clipboards.to_clipboard(self, excel=excel, sep=sep, **kwargs)": 5876, "def get_datatype(self, table: str, column: str) -> str:\n \"\"\"Returns database SQL datatype for a column: e.g. VARCHAR.\"\"\"\n return self.flavour.get_datatype(self, table, column).upper()": 5877, "def SwitchToThisWindow(handle: int) -> None:\n \"\"\"\n SwitchToThisWindow from Win32.\n handle: int, the handle of a native window.\n \"\"\"\n ctypes.windll.user32.SwitchToThisWindow(ctypes.c_void_p(handle), 1)": 5878, "def pretty_dict(d):\n \"\"\"Return dictionary d's repr but with the items sorted.\n >>> pretty_dict({'m': 'M', 'a': 'A', 'r': 'R', 'k': 'K'})\n \"{'a': 'A', 'k': 'K', 'm': 'M', 'r': 'R'}\"\n >>> pretty_dict({z: C, y: B, x: A})\n '{x: A, y: B, z: C}'\n \"\"\"\n return '{%s}' % ', '.join('%r: %r' % (k, v)\n for k, v in sorted(d.items(), key=repr))": 5879, "def array_to_npy(array_like): # type: (np.array or Iterable or int or float) -> object\n \"\"\"Convert an array like object to the NPY format.\n\n To understand better what an array like object is see:\n https://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-python-array-like-objects-to-numpy-arrays\n\n Args:\n array_like (np.array or Iterable or int or float): array like object to be converted to NPY.\n\n Returns:\n (obj): NPY array.\n \"\"\"\n buffer = BytesIO()\n np.save(buffer, array_like)\n return buffer.getvalue()": 5880, "def read_byte_data(self, addr, cmd):\n \"\"\"read_byte_data(addr, cmd) -> result\n\n Perform SMBus Read Byte Data transaction.\n \"\"\"\n self._set_addr(addr)\n res = SMBUS.i2c_smbus_read_byte_data(self._fd, ffi.cast(\"__u8\", cmd))\n if res == -1:\n raise IOError(ffi.errno)\n return res": 5881, "def decode(self, bytes, raw=False):\n \"\"\"decode(bytearray, raw=False) -> value\n\n Decodes the given bytearray according to this PrimitiveType\n definition.\n\n NOTE: The parameter ``raw`` is present to adhere to the\n ``decode()`` inteface, but has no effect for PrimitiveType\n definitions.\n \"\"\"\n return struct.unpack(self.format, buffer(bytes))[0]": 5882, "def _parse_property(self, node):\n # type: (ElementTree.Element) -> Tuple[str, Any]\n \"\"\"\n Parses a property node\n\n :param node: The property node\n :return: A (name, value) tuple\n :raise KeyError: Attribute missing\n \"\"\"\n # Get information\n name = node.attrib[ATTR_NAME]\n vtype = node.attrib.get(ATTR_VALUE_TYPE, TYPE_STRING)\n\n # Look for a value as a single child node\n try:\n value_node = next(iter(node))\n value = self._parse_value_node(vtype, value_node)\n except StopIteration:\n # Value is an attribute\n value = self._convert_value(vtype, node.attrib[ATTR_VALUE])\n\n return name, value": 5883, "def is_intersection(g, n):\n \"\"\"\n Determine if a node is an intersection\n\n graph: 1 -->-- 2 -->-- 3\n\n >>> is_intersection(g, 2)\n False\n\n graph:\n 1 -- 2 -- 3\n |\n 4\n\n >>> is_intersection(g, 2)\n True\n\n Parameters\n ----------\n g : networkx DiGraph\n n : node id\n\n Returns\n -------\n bool\n\n \"\"\"\n return len(set(g.predecessors(n) + g.successors(n))) > 2": 5884, "def interpolate(f1: float, f2: float, factor: float) -> float:\n \"\"\" Linearly interpolate between two float values. \"\"\"\n return f1 + (f2 - f1) * factor": 5885, "def reduce(function, initval=None):\n\t\"\"\"\n\tCurried version of the built-in reduce.\n\t\n\t>>> reduce(lambda x,y: x+y)( [1, 2, 3, 4, 5] )\n\t15\n\t\"\"\"\n\tif initval is None:\n\t\treturn lambda s: __builtin__.reduce(function, s)\n\telse:\n\t\treturn lambda s: __builtin__.reduce(function, s, initval)": 5886, "def _validate_authority_uri_abs_path(host, path):\n \"\"\"Ensure that path in URL with authority starts with a leading slash.\n\n Raise ValueError if not.\n \"\"\"\n if len(host) > 0 and len(path) > 0 and not path.startswith(\"/\"):\n raise ValueError(\n \"Path in a URL with authority \" \"should start with a slash ('/') if set\"\n )": 5887, "def warn_if_nans_exist(X):\n \"\"\"Warn if nans exist in a numpy array.\"\"\"\n null_count = count_rows_with_nans(X)\n total = len(X)\n percent = 100 * null_count / total\n\n if null_count > 0:\n warning_message = \\\n 'Warning! Found {} rows of {} ({:0.2f}%) with nan values. Only ' \\\n 'complete rows will be plotted.'.format(null_count, total, percent)\n warnings.warn(warning_message, DataWarning)": 5888, "def _get_parsing_plan_for_multifile_children(self, obj_on_fs: PersistedObject, desired_type: Type[Any],\n logger: Logger) -> Dict[str, Any]:\n \"\"\"\n Implementation of AnyParser API\n \"\"\"\n raise Exception('This should never happen, since this parser relies on underlying parsers')": 5889, "def sort_key(x):\n \"\"\"\n >>> sort_key(('name', ('ROUTE', 'URL')))\n -3\n \"\"\"\n name, (r, u) = x\n return - len(u) + u.count('}') * 100": 5890, "def inverted_dict_of_lists(d):\n \"\"\"Return a dict where the keys are all the values listed in the values of the original dict\n\n >>> inverted_dict_of_lists({0: ['a', 'b'], 1: 'cd'}) == {'a': 0, 'b': 0, 'cd': 1}\n True\n \"\"\"\n new_dict = {}\n for (old_key, old_value_list) in viewitems(dict(d)):\n for new_key in listify(old_value_list):\n new_dict[new_key] = old_key\n return new_dict": 5891, "def copy_without_prompts(self):\n \"\"\"Copy text to clipboard without prompts\"\"\"\n text = self.get_selected_text()\n lines = text.split(os.linesep)\n for index, line in enumerate(lines):\n if line.startswith('>>> ') or line.startswith('... '):\n lines[index] = line[4:]\n text = os.linesep.join(lines)\n QApplication.clipboard().setText(text)": 5892, "def hex_to_int(value):\n \"\"\"\n Convert hex string like \"\\x0A\\xE3\" to 2787.\n \"\"\"\n if version_info.major >= 3:\n return int.from_bytes(value, \"big\")\n return int(value.encode(\"hex\"), 16)": 5893, "def partition_items(count, bin_size):\n\t\"\"\"\n\tGiven the total number of items, determine the number of items that\n\tcan be added to each bin with a limit on the bin size.\n\n\tSo if you want to partition 11 items into groups of 3, you'll want\n\tthree of three and one of two.\n\n\t>>> partition_items(11, 3)\n\t[3, 3, 3, 2]\n\n\tBut if you only have ten items, you'll have two groups of three and\n\ttwo of two.\n\n\t>>> partition_items(10, 3)\n\t[3, 3, 2, 2]\n\t\"\"\"\n\tnum_bins = int(math.ceil(count / float(bin_size)))\n\tbins = [0] * num_bins\n\tfor i in range(count):\n\t\tbins[i % num_bins] += 1\n\treturn bins": 5894, "def _read_section(self):\n \"\"\"Read and return an entire section\"\"\"\n lines = [self._last[self._last.find(\":\")+1:]]\n self._last = self._f.readline()\n while len(self._last) > 0 and len(self._last[0].strip()) == 0:\n lines.append(self._last)\n self._last = self._f.readline()\n return lines": 5895, "def _get_ipv6_from_binary(self, bin_addr):\n \"\"\"Converts binary address to Ipv6 format.\"\"\"\n\n hi = bin_addr >> 64\n lo = bin_addr & 0xFFFFFFFF\n return socket.inet_ntop(socket.AF_INET6, struct.pack(\"!QQ\", hi, lo))": 5896, "def connect_to_database_odbc_access(self,\n dsn: str,\n autocommit: bool = True) -> None:\n \"\"\"Connects to an Access database via ODBC, with the DSN\n prespecified.\"\"\"\n self.connect(engine=ENGINE_ACCESS, interface=INTERFACE_ODBC,\n dsn=dsn, autocommit=autocommit)": 5897, "def has_enumerated_namespace_name(self, namespace: str, name: str) -> bool:\n \"\"\"Check that the namespace is defined by an enumeration and that the name is a member.\"\"\"\n return self.has_enumerated_namespace(namespace) and name in self.namespace_to_terms[namespace]": 5898, "def Exit(msg, code=1):\n \"\"\"Exit execution with return code and message\n :param msg: Message displayed prior to exit\n :param code: code returned upon exiting\n \"\"\"\n print >> sys.stderr, msg\n sys.exit(code)": 5899, "def is_iterable(etype) -> bool:\n \"\"\" Determine whether etype is a List or other iterable \"\"\"\n return type(etype) is GenericMeta and issubclass(etype.__extra__, Iterable)": 5900, "async def fetchall(self) -> Iterable[sqlite3.Row]:\n \"\"\"Fetch all remaining rows.\"\"\"\n return await self._execute(self._cursor.fetchall)": 5901, "def get_line_number(line_map, offset):\n \"\"\"Find a line number, given a line map and a character offset.\"\"\"\n for lineno, line_offset in enumerate(line_map, start=1):\n if line_offset > offset:\n return lineno\n return -1": 5902, "def snake_to_camel(value):\n \"\"\"\n Converts a snake_case_string to a camelCaseString.\n\n >>> snake_to_camel(\"foo_bar_baz\")\n 'fooBarBaz'\n \"\"\"\n camel = \"\".join(word.title() for word in value.split(\"_\"))\n return value[:1].lower() + camel[1:]": 5903, "def factorial(n, mod=None):\n \"\"\"Calculates factorial iteratively.\n If mod is not None, then return (n! % mod)\n Time Complexity - O(n)\"\"\"\n if not (isinstance(n, int) and n >= 0):\n raise ValueError(\"'n' must be a non-negative integer.\")\n if mod is not None and not (isinstance(mod, int) and mod > 0):\n raise ValueError(\"'mod' must be a positive integer\")\n result = 1\n if n == 0:\n return 1\n for i in range(2, n+1):\n result *= i\n if mod:\n result %= mod\n return result": 5904, "def ResetConsoleColor() -> bool:\n \"\"\"\n Reset to the default text color on console window.\n Return bool, True if succeed otherwise False.\n \"\"\"\n if sys.stdout:\n sys.stdout.flush()\n bool(ctypes.windll.kernel32.SetConsoleTextAttribute(_ConsoleOutputHandle, _DefaultConsoleColor))": 5905, "def getCollectDServer(queue, cfg):\n \"\"\"Get the appropriate collectd server (multi processed or not)\"\"\"\n server = CollectDServerMP if cfg.collectd_workers > 1 else CollectDServer\n return server(queue, cfg)": 5906, "def val_mb(valstr: Union[int, str]) -> str:\n \"\"\"\n Converts a value in bytes (in string format) to megabytes.\n \"\"\"\n try:\n return \"{:.3f}\".format(int(valstr) / (1024 * 1024))\n except (TypeError, ValueError):\n return '?'": 5907, "def moving_average(iterable, n):\n \"\"\"\n From Python collections module documentation\n\n moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0\n \"\"\"\n it = iter(iterable)\n d = collections.deque(itertools.islice(it, n - 1))\n d.appendleft(0)\n s = sum(d)\n for elem in it:\n s += elem - d.popleft()\n d.append(elem)\n yield s / float(n)": 5908, "def _close(self):\n \"\"\"\n Release the USB interface again.\n \"\"\"\n self._usb_handle.releaseInterface()\n try:\n # If we're using PyUSB >= 1.0 we can re-attach the kernel driver here.\n self._usb_handle.dev.attach_kernel_driver(0)\n except:\n pass\n self._usb_int = None\n self._usb_handle = None\n return True": 5909, "def dag_longest_path(graph, source, target):\n \"\"\"\n Finds the longest path in a dag between two nodes\n \"\"\"\n if source == target:\n return [source]\n allpaths = nx.all_simple_paths(graph, source, target)\n longest_path = []\n for l in allpaths:\n if len(l) > len(longest_path):\n longest_path = l\n return longest_path": 5910, "def __remove_method(m: lmap.Map, key: T) -> lmap.Map:\n \"\"\"Swap the methods atom to remove method with key.\"\"\"\n return m.dissoc(key)": 5911, "def returned(n):\n\t\"\"\"Generate a random walk and return True if the walker has returned to\n\tthe origin after taking `n` steps.\n\t\"\"\"\n\t## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk\n\tfor pos in randwalk() >> drop(1) >> takei(xrange(n-1)):\n\t\tif pos == Origin:\n\t\t\treturn True\n\treturn False": 5912, "def looks_like_url(url):\n \"\"\" Simplified check to see if the text appears to be a URL.\n\n Similar to `urlparse` but much more basic.\n\n Returns:\n True if the url str appears to be valid.\n False otherwise.\n\n >>> url = looks_like_url(\"totalgood.org\")\n >>> bool(url)\n True\n \"\"\"\n if not isinstance(url, basestring):\n return False\n if not isinstance(url, basestring) or len(url) >= 1024 or not cre_url.match(url):\n return False\n return True": 5913, "def preconnect(self, size=-1):\n \"\"\"(pre)Connects some or all redis clients inside the pool.\n\n Args:\n size (int): number of redis clients to build and to connect\n (-1 means all clients if pool max_size > -1)\n\n Raises:\n ClientError: when size == -1 and pool max_size == -1\n \"\"\"\n if size == -1 and self.max_size == -1:\n raise ClientError(\"size=-1 not allowed with pool max_size=-1\")\n limit = min(size, self.max_size) if size != -1 else self.max_size\n clients = yield [self.get_connected_client() for _ in range(0, limit)]\n for client in clients:\n self.release_client(client)": 5914, "def left_zero_pad(s, blocksize):\n \"\"\"\n Left padding with zero bytes to a given block size\n\n :param s:\n :param blocksize:\n :return:\n \"\"\"\n if blocksize > 0 and len(s) % blocksize:\n s = (blocksize - len(s) % blocksize) * b('\\000') + s\n return s": 5915, "def str_upper(x):\n \"\"\"Converts all strings in a column to uppercase.\n\n :returns: an expression containing the converted strings.\n\n Example:\n\n >>> import vaex\n >>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']\n >>> df = vaex.from_arrays(text=text)\n >>> df\n # text\n 0 Something\n 1 very pretty\n 2 is coming\n 3 our\n 4 way.\n\n\n >>> df.text.str.upper()\n Expression = str_upper(text)\n Length: 5 dtype: str (expression)\n ---------------------------------\n 0 SOMETHING\n 1 VERY PRETTY\n 2 IS COMING\n 3 OUR\n 4 WAY.\n\n \"\"\"\n sl = _to_string_sequence(x).upper()\n return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl)": 5916, "def uuid(self, version: int = None) -> str:\n \"\"\"Generate random UUID.\n\n :param version: UUID version.\n :return: UUID\n \"\"\"\n bits = self.random.getrandbits(128)\n return str(uuid.UUID(int=bits, version=version))": 5917, "def fprint(expr, print_ascii=False):\n r\"\"\"This function chooses whether to use ascii characters to represent\n a symbolic expression in the notebook or to use sympy's pprint.\n\n >>> from sympy import cos\n >>> omega=Symbol(\"omega\")\n >>> fprint(cos(omega),print_ascii=True)\n cos(omega)\n\n\n \"\"\"\n if print_ascii:\n pprint(expr, use_unicode=False, num_columns=120)\n else:\n return expr": 5918, "def is_none(string_, default='raise'):\n \"\"\"\n Check if a string is equivalent to None.\n\n Parameters\n ----------\n string_ : str\n default : {'raise', False}\n Default behaviour if none of the \"None\" strings is detected.\n\n Returns\n -------\n is_none : bool\n\n Examples\n --------\n >>> is_none('2', default=False)\n False\n >>> is_none('undefined', default=False)\n True\n \"\"\"\n none = ['none', 'undefined', 'unknown', 'null', '']\n if string_.lower() in none:\n return True\n elif not default:\n return False\n else:\n raise ValueError('The value \\'{}\\' cannot be mapped to none.'\n .format(string_))": 5919, "async def login(\n username: str, password: str, brand: str,\n websession: ClientSession = None) -> API:\n \"\"\"Log in to the API.\"\"\"\n api = API(brand, websession)\n await api.authenticate(username, password)\n return api": 5920, "def should_rollover(self, record: LogRecord) -> bool:\n \"\"\"\n Determine if rollover should occur.\n\n record is not used, as we are just comparing times, but it is needed so\n the method signatures are the same\n \"\"\"\n t = int(time.time())\n if t >= self.rollover_at:\n return True\n return False": 5921, "def _request(self, method: str, endpoint: str, params: dict = None, data: dict = None, headers: dict = None) -> dict:\n \"\"\"HTTP request method of interface implementation.\"\"\"": 5922, "def after_epoch(self, **_) -> None:\n \"\"\"Save/override the latest model after every epoch.\"\"\"\n SaveEvery.save_model(model=self._model, name_suffix=self._OUTPUT_NAME, on_failure=self._on_save_failure)": 5923, "def last(self):\n \"\"\"Last time step available.\n\n Example:\n >>> sdat = StagyyData('path/to/run')\n >>> assert(sdat.steps.last is sdat.steps[-1])\n \"\"\"\n if self._last is UNDETERMINED:\n # not necessarily the last one...\n self._last = self.sdat.tseries.index[-1]\n return self[self._last]": 5924, "def decodebytes(input):\n \"\"\"Decode base64 string to byte array.\"\"\"\n py_version = sys.version_info[0]\n if py_version >= 3:\n return _decodebytes_py3(input)\n return _decodebytes_py2(input)": 5925, "def is_prime(n):\n \"\"\"\n Check if n is a prime number\n \"\"\"\n if n % 2 == 0 and n > 2:\n return False\n return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))": 5926, "def sortBy(self, keyfunc, ascending=True, numPartitions=None):\n \"\"\"\n Sorts this RDD by the given keyfunc\n\n >>> tmp = [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)]\n >>> sc.parallelize(tmp).sortBy(lambda x: x[0]).collect()\n [('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d', 4)]\n >>> sc.parallelize(tmp).sortBy(lambda x: x[1]).collect()\n [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)]\n \"\"\"\n return self.keyBy(keyfunc).sortByKey(ascending, numPartitions).values()": 5927, "def multiple_replace(string, replacements):\n # type: (str, Dict[str,str]) -> str\n \"\"\"Simultaneously replace multiple strigns in a string\n\n Args:\n string (str): Input string\n replacements (Dict[str,str]): Replacements dictionary\n\n Returns:\n str: String with replacements\n\n \"\"\"\n pattern = re.compile(\"|\".join([re.escape(k) for k in sorted(replacements, key=len, reverse=True)]), flags=re.DOTALL)\n return pattern.sub(lambda x: replacements[x.group(0)], string)": 5928, "def uniqued(iterable):\n \"\"\"Return unique list of ``iterable`` items preserving order.\n\n >>> uniqued('spameggs')\n ['s', 'p', 'a', 'm', 'e', 'g']\n \"\"\"\n seen = set()\n return [item for item in iterable if item not in seen and not seen.add(item)]": 5929, "def _check_samples_nodups(fnames):\n \"\"\"Ensure a set of input VCFs do not have duplicate samples.\n \"\"\"\n counts = defaultdict(int)\n for f in fnames:\n for s in get_samples(f):\n counts[s] += 1\n duplicates = [s for s, c in counts.items() if c > 1]\n if duplicates:\n raise ValueError(\"Duplicate samples found in inputs %s: %s\" % (duplicates, fnames))": 5930, "def get_window_dim():\n \"\"\" gets the dimensions depending on python version and os\"\"\"\n version = sys.version_info\n\n if version >= (3, 3):\n return _size_36()\n if platform.system() == 'Windows':\n return _size_windows()\n return _size_27()": 5931, "def decode_base64(data: str) -> bytes:\n \"\"\"Decode base64, padding being optional.\n\n :param data: Base64 data as an ASCII byte string\n :returns: The decoded byte string.\n \"\"\"\n missing_padding = len(data) % 4\n if missing_padding != 0:\n data += \"=\" * (4 - missing_padding)\n return base64.decodebytes(data.encode(\"utf-8\"))": 5932, "def is_sqlatype_numeric(coltype: Union[TypeEngine, VisitableType]) -> bool:\n \"\"\"\n Is the SQLAlchemy column type one that inherits from :class:`Numeric`,\n such as :class:`Float`, :class:`Decimal`?\n \"\"\"\n coltype = _coltype_to_typeengine(coltype)\n return isinstance(coltype, sqltypes.Numeric)": 5933, "def check_lengths(*arrays):\n \"\"\"\n tool to ensure input and output data have the same number of samples\n\n Parameters\n ----------\n *arrays : iterable of arrays to be checked\n\n Returns\n -------\n None\n \"\"\"\n lengths = [len(array) for array in arrays]\n if len(np.unique(lengths)) > 1:\n raise ValueError('Inconsistent data lengths: {}'.format(lengths))": 5934, "def isfinite(data: mx.nd.NDArray) -> mx.nd.NDArray:\n \"\"\"Performs an element-wise check to determine if the NDArray contains an infinite element or not.\n TODO: remove this funciton after upgrade to MXNet 1.4.* in favor of mx.ndarray.contrib.isfinite()\n \"\"\"\n is_data_not_nan = data == data\n is_data_not_infinite = data.abs() != np.inf\n return mx.nd.logical_and(is_data_not_infinite, is_data_not_nan)": 5935, "def set_range(self, min_val, max_val):\n \"\"\"Set the range of the colormap to [*min_val*, *max_val*]\n \"\"\"\n if min_val > max_val:\n max_val, min_val = min_val, max_val\n self.values = (((self.values * 1.0 - self.values.min()) /\n (self.values.max() - self.values.min()))\n * (max_val - min_val) + min_val)": 5936, "def execute_sql(self, query):\n \"\"\"\n Executes a given query string on an open postgres database.\n\n \"\"\"\n c = self.con.cursor()\n c.execute(query)\n result = []\n if c.rowcount > 0:\n try:\n result = c.fetchall()\n except psycopg2.ProgrammingError:\n pass\n return result": 5937, "def non_increasing(values):\n \"\"\"True if values are not increasing.\"\"\"\n return all(x >= y for x, y in zip(values, values[1:]))": 5938, "async def stdout(self) -> AsyncGenerator[str, None]:\n \"\"\"Asynchronous generator for lines from subprocess stdout.\"\"\"\n await self.wait_running()\n async for line in self._subprocess.stdout: # type: ignore\n yield line": 5939, "def same_network(atree, btree) -> bool:\n \"\"\"True if given trees share the same structure of powernodes,\n independently of (power)node names,\n and same edge topology between (power)nodes.\n\n \"\"\"\n return same_hierarchy(atree, btree) and same_topology(atree, btree)": 5940, "def is_strict_numeric(n: Node) -> bool:\n \"\"\" numeric denotes typed literals with datatypes xsd:integer, xsd:decimal, xsd:float, and xsd:double. \"\"\"\n return is_typed_literal(n) and cast(Literal, n).datatype in [XSD.integer, XSD.decimal, XSD.float, XSD.double]": 5941, "def b64_decode(data: bytes) -> bytes:\n \"\"\"\n :param data: Base 64 encoded data to decode.\n :type data: bytes\n :return: Base 64 decoded data.\n :rtype: bytes\n \"\"\"\n missing_padding = len(data) % 4\n if missing_padding != 0:\n data += b'=' * (4 - missing_padding)\n return urlsafe_b64decode(data)": 5942, "def block_diag(*blocks: np.ndarray) -> np.ndarray:\n \"\"\"Concatenates blocks into a block diagonal matrix.\n\n Args:\n *blocks: Square matrices to place along the diagonal of the result.\n\n Returns:\n A block diagonal matrix with the given blocks along its diagonal.\n\n Raises:\n ValueError: A block isn't square.\n \"\"\"\n for b in blocks:\n if b.shape[0] != b.shape[1]:\n raise ValueError('Blocks must be square.')\n\n if not blocks:\n return np.zeros((0, 0), dtype=np.complex128)\n\n n = sum(b.shape[0] for b in blocks)\n dtype = functools.reduce(_merge_dtypes, (b.dtype for b in blocks))\n\n result = np.zeros(shape=(n, n), dtype=dtype)\n i = 0\n for b in blocks:\n j = i + b.shape[0]\n result[i:j, i:j] = b\n i = j\n\n return result": 5943, "def get_now_sql_datetime():\n \"\"\"\n *A datetime stamp in MySQL format: ``YYYY-MM-DDTHH:MM:SS``*\n\n **Return:**\n - ``now`` -- current time and date in MySQL format\n\n **Usage:**\n .. code-block:: python \n\n from fundamentals import times\n now = times.get_now_sql_datetime()\n print now\n\n # OUT: 2016-03-18T11:08:23 \n \"\"\"\n ## > IMPORTS ##\n from datetime import datetime, date, time\n now = datetime.now()\n now = now.strftime(\"%Y-%m-%dT%H:%M:%S\")\n\n return now": 5944, "def percentile(sorted_list, percent, key=lambda x: x):\n \"\"\"Find the percentile of a sorted list of values.\n\n Arguments\n ---------\n sorted_list : list\n A sorted (ascending) list of values.\n percent : float\n A float value from 0.0 to 1.0.\n key : function, optional\n An optional function to compute a value from each element of N.\n\n Returns\n -------\n float\n The desired percentile of the value list.\n\n Examples\n --------\n >>> sorted_list = [4,6,8,9,11]\n >>> percentile(sorted_list, 0.4)\n 7.0\n >>> percentile(sorted_list, 0.44)\n 8.0\n >>> percentile(sorted_list, 0.6)\n 8.5\n >>> percentile(sorted_list, 0.99)\n 11.0\n >>> percentile(sorted_list, 1)\n 11.0\n >>> percentile(sorted_list, 0)\n 4.0\n \"\"\"\n if not sorted_list:\n return None\n if percent == 1:\n return float(sorted_list[-1])\n if percent == 0:\n return float(sorted_list[0])\n n = len(sorted_list)\n i = percent * n\n if ceil(i) == i:\n i = int(i)\n return (sorted_list[i-1] + sorted_list[i]) / 2\n return float(sorted_list[ceil(i)-1])": 5945, "def fib(n):\n \"\"\"Fibonacci example function\n\n Args:\n n (int): integer\n\n Returns:\n int: n-th Fibonacci number\n \"\"\"\n assert n > 0\n a, b = 1, 1\n for i in range(n - 1):\n a, b = b, a + b\n return a": 5946, "def try_instance_init(self, instance, late_start=False):\n \"\"\"Try to \"initialize\" the given module instance.\n\n :param instance: instance to init\n :type instance: object\n :param late_start: If late_start, don't look for last_init_try\n :type late_start: bool\n :return: True on successful init. False if instance init method raised any Exception.\n :rtype: bool\n \"\"\"\n try:\n instance.init_try += 1\n # Maybe it's a retry\n if not late_start and instance.init_try > 1:\n # Do not try until too frequently, or it's too loopy\n if instance.last_init_try > time.time() - MODULE_INIT_PERIOD:\n logger.info(\"Too early to retry initialization, retry period is %d seconds\",\n MODULE_INIT_PERIOD)\n # logger.info(\"%s / %s\", instance.last_init_try, time.time())\n return False\n instance.last_init_try = time.time()\n\n logger.info(\"Trying to initialize module: %s\", instance.name)\n\n # If it's an external module, create/update Queues()\n if instance.is_external:\n instance.create_queues(self.daemon.sync_manager)\n\n # The module instance init function says if initialization is ok\n if not instance.init():\n logger.warning(\"Module %s initialisation failed.\", instance.name)\n return False\n logger.info(\"Module %s is initialized.\", instance.name)\n except Exception as exp: # pylint: disable=broad-except\n # pragma: no cover, simple protection\n msg = \"The module instance %s raised an exception \" \\\n \"on initialization: %s, I remove it!\" % (instance.name, str(exp))\n self.configuration_errors.append(msg)\n logger.error(msg)\n logger.exception(exp)\n return False\n\n return True": 5947, "def add_colons(s):\n \"\"\"Add colons after every second digit.\n\n This function is used in functions to prettify serials.\n\n >>> add_colons('teststring')\n 'te:st:st:ri:ng'\n \"\"\"\n return ':'.join([s[i:i + 2] for i in range(0, len(s), 2)])": 5948, "def has_jongsung(letter):\n \"\"\"Check whether this letter contains Jongsung\"\"\"\n if len(letter) != 1:\n raise Exception('The target string must be one letter.')\n if not is_hangul(letter):\n raise NotHangulException('The target string must be Hangul')\n\n code = lt.hangul_index(letter)\n return code % NUM_JONG > 0": 5949, "def iso_string_to_python_datetime(\n isostring: str) -> Optional[datetime.datetime]:\n \"\"\"\n Takes an ISO-8601 string and returns a ``datetime``.\n \"\"\"\n if not isostring:\n return None # if you parse() an empty string, you get today's date\n return dateutil.parser.parse(isostring)": 5950, "def get_case_insensitive_dict_key(d: Dict, k: str) -> Optional[str]:\n \"\"\"\n Within the dictionary ``d``, find a key that matches (in case-insensitive\n fashion) the key ``k``, and return it (or ``None`` if there isn't one).\n \"\"\"\n for key in d.keys():\n if k.lower() == key.lower():\n return key\n return None": 5951, "def find_index(segmentation, stroke_id):\n \"\"\"\n >>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 0)\n 0\n >>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 1)\n 0\n >>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 5)\n 2\n >>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 6)\n 2\n \"\"\"\n for i, symbol in enumerate(segmentation):\n for sid in symbol:\n if sid == stroke_id:\n return i\n return -1": 5952, "def check_oneof(**kwargs):\n \"\"\"Raise ValueError if more than one keyword argument is not none.\n\n Args:\n kwargs (dict): The keyword arguments sent to the function.\n\n Returns: None\n\n Raises:\n ValueError: If more than one entry in kwargs is not none.\n \"\"\"\n # Sanity check: If no keyword arguments were sent, this is fine.\n if not kwargs:\n return None\n\n not_nones = [val for val in kwargs.values() if val is not None]\n if len(not_nones) > 1:\n raise ValueError('Only one of {fields} should be set.'.format(\n fields=', '.join(sorted(kwargs.keys())),\n ))": 5953, "def execute(cur, *args):\n \"\"\"Utility function to print sqlite queries before executing.\n\n Use instead of cur.execute(). First argument is cursor.\n\n cur.execute(stmt)\n becomes\n util.execute(cur, stmt)\n \"\"\"\n stmt = args[0]\n if len(args) > 1:\n stmt = stmt.replace('%', '%%').replace('?', '%r')\n print(stmt % (args[1]))\n return cur.execute(*args)": 5954, "def camelize(key):\n \"\"\"Convert a python_style_variable_name to lowerCamelCase.\n\n Examples\n --------\n >>> camelize('variable_name')\n 'variableName'\n >>> camelize('variableName')\n 'variableName'\n \"\"\"\n return ''.join(x.capitalize() if i > 0 else x\n for i, x in enumerate(key.split('_')))": 5955, "def _groups_of_size(iterable, n, fillvalue=None):\n \"\"\"Collect data into fixed-length chunks or blocks.\"\"\"\n # _groups_of_size('ABCDEFG', 3, 'x') --> ABC DEF Gxx\n args = [iter(iterable)] * n\n return zip_longest(fillvalue=fillvalue, *args)": 5956, "def long_substring(str_a, str_b):\n \"\"\"\n Looks for a longest common string between any two given strings passed\n :param str_a: str\n :param str_b: str\n\n Big Thanks to Pulkit Kathuria(@kevincobain2000) for the function\n The function is derived from jProcessing toolkit suite\n \"\"\"\n data = [str_a, str_b]\n substr = ''\n if len(data) > 1 and len(data[0]) > 0:\n for i in range(len(data[0])):\n for j in range(len(data[0])-i+1):\n if j > len(substr) and all(data[0][i:i+j] in x for x in data):\n substr = data[0][i:i+j]\n return substr.strip()": 5957, "def squash(self, a, b):\n \"\"\"\n Returns a generator that squashes two iterables into one.\n\n ```\n ['this', 'that'], [[' and', ' or']] => ['this and', 'this or', 'that and', 'that or']\n ```\n \"\"\"\n\n return ((''.join(x) if isinstance(x, tuple) else x) for x in itertools.product(a, b))": 5958, "def wipe_table(self, table: str) -> int:\n \"\"\"Delete all records from a table. Use caution!\"\"\"\n sql = \"DELETE FROM \" + self.delimit(table)\n return self.db_exec(sql)": 5959, "def _interface_exists(self, interface):\n \"\"\"Check whether interface exists.\"\"\"\n ios_cfg = self._get_running_config()\n parse = HTParser(ios_cfg)\n itfcs_raw = parse.find_lines(\"^interface \" + interface)\n return len(itfcs_raw) > 0": 5960, "def GetAllPixelColors(self) -> ctypes.Array:\n \"\"\"\n Return `ctypes.Array`, an iterable array of int values in argb.\n \"\"\"\n return self.GetPixelColorsOfRect(0, 0, self.Width, self.Height)": 5961, "def calculate_fft(data, tbin):\n \"\"\"\n Function to calculate the Fourier transform of data.\n \n \n Parameters\n ----------\n data : numpy.ndarray\n 1D or 2D array containing time series.\n tbin : float\n Bin size of time series (in ms).\n \n \n Returns\n -------\n freqs : numpy.ndarray\n Frequency axis of signal in Fourier space. \n fft : numpy.ndarray\n Signal in Fourier space.\n \n \"\"\"\n if len(np.shape(data)) > 1:\n n = len(data[0])\n return np.fft.fftfreq(n, tbin * 1e-3), np.fft.fft(data, axis=1)\n else:\n n = len(data)\n return np.fft.fftfreq(n, tbin * 1e-3), np.fft.fft(data)": 5962, "def get_commits_modified_file(self, filepath: str) -> List[str]:\n \"\"\"\n Given a filepath, returns all the commits that modified this file\n (following renames).\n\n :param str filepath: path to the file\n :return: the list of commits' hash\n \"\"\"\n path = str(Path(filepath))\n\n commits = []\n try:\n commits = self.git.log(\"--follow\", \"--format=%H\", path).split('\\n')\n except GitCommandError:\n logger.debug(\"Could not find information of file %s\", path)\n\n return commits": 5963, "def similarity(word1: str, word2: str) -> float:\n \"\"\"\n Get cosine similarity between two words.\n If a word is not in the vocabulary, KeyError will be raised.\n\n :param string word1: first word\n :param string word2: second word\n :return: the cosine similarity between the two word vectors\n \"\"\"\n return _MODEL.similarity(word1, word2)": 5964, "def snake_case(a_string):\n \"\"\"Returns a snake cased version of a string.\n\n :param a_string: any :class:`str` object.\n\n Usage:\n >>> snake_case('FooBar')\n \"foo_bar\"\n \"\"\"\n\n partial = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', a_string)\n return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', partial).lower()": 5965, "def get_default_bucket_key(buckets: List[Tuple[int, int]]) -> Tuple[int, int]:\n \"\"\"\n Returns the default bucket from a list of buckets, i.e. the largest bucket.\n\n :param buckets: List of buckets.\n :return: The largest bucket in the list.\n \"\"\"\n return max(buckets)": 5966, "def product(*args, **kwargs):\n \"\"\" Yields all permutations with replacement:\n list(product(\"cat\", repeat=2)) => \n [(\"c\", \"c\"), \n (\"c\", \"a\"), \n (\"c\", \"t\"), \n (\"a\", \"c\"), \n (\"a\", \"a\"), \n (\"a\", \"t\"), \n (\"t\", \"c\"), \n (\"t\", \"a\"), \n (\"t\", \"t\")]\n \"\"\"\n p = [[]]\n for iterable in map(tuple, args) * kwargs.get(\"repeat\", 1):\n p = [x + [y] for x in p for y in iterable]\n for p in p:\n yield tuple(p)": 5967, "def file_or_stdin() -> Callable:\n \"\"\"\n Returns a file descriptor from stdin or opening a file from a given path.\n \"\"\"\n\n def parse(path):\n if path is None or path == \"-\":\n return sys.stdin\n else:\n return data_io.smart_open(path)\n\n return parse": 5968, "def running_containers(name_filter: str) -> List[str]:\n \"\"\"\n :raises docker.exceptions.APIError\n \"\"\"\n return [container.short_id for container in\n docker_client.containers.list(filters={\"name\": name_filter})]": 5969, "def cookies(self) -> Dict[str, str]:\n \"\"\"The parsed cookies attached to this request.\"\"\"\n cookies = SimpleCookie()\n cookies.load(self.headers.get('Cookie', ''))\n return {key: cookie.value for key, cookie in cookies.items()}": 5970, "def docker_environment(env):\n \"\"\"\n Transform dictionary of environment variables into Docker -e parameters.\n\n >>> result = docker_environment({'param1': 'val1', 'param2': 'val2'})\n >>> result in ['-e \"param1=val1\" -e \"param2=val2\"', '-e \"param2=val2\" -e \"param1=val1\"']\n True\n \"\"\"\n return ' '.join(\n [\"-e \\\"%s=%s\\\"\" % (key, value.replace(\"$\", \"\\\\$\").replace(\"\\\"\", \"\\\\\\\"\").replace(\"`\", \"\\\\`\"))\n for key, value in env.items()])": 5971, "def call_api(self, resource_path, method,\n path_params=None, query_params=None, header_params=None,\n body=None, post_params=None, files=None,\n response_type=None, auth_settings=None, asynchronous=None,\n _return_http_data_only=None, collection_formats=None, _preload_content=True,\n _request_timeout=None):\n \"\"\"\n Makes the HTTP request (synchronous) and return the deserialized data.\n To make an async request, set the asynchronous parameter.\n\n :param resource_path: Path to method endpoint.\n :param method: Method to call.\n :param path_params: Path parameters in the url.\n :param query_params: Query parameters in the url.\n :param header_params: Header parameters to be\n placed in the request header.\n :param body: Request body.\n :param post_params dict: Request post form parameters,\n for `application/x-www-form-urlencoded`, `multipart/form-data`.\n :param auth_settings list: Auth Settings names for the request.\n :param response: Response data type.\n :param files dict: key -> filename, value -> filepath,\n for `multipart/form-data`.\n :param asynchronous bool: execute request asynchronously\n :param _return_http_data_only: response data without head status code and headers\n :param collection_formats: dict of collection formats for path, query,\n header, and post parameters.\n :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without\n reading/decoding response data. Default is True.\n :param _request_timeout: timeout setting for this request. If one number provided, it will be total request\n timeout. It can also be a pair (tuple) of (connection, read) timeouts.\n :return:\n If asynchronous parameter is True,\n the request will be called asynchronously.\n The method will return the request thread.\n If parameter asynchronous is False or missing,\n then the method will return the response directly.\n \"\"\"\n if not asynchronous:\n return self.__call_api(resource_path, method,\n path_params, query_params, header_params,\n body, post_params, files,\n response_type, auth_settings,\n _return_http_data_only, collection_formats, _preload_content, _request_timeout)\n else:\n thread = self.pool.apply_async(self.__call_api, (resource_path, method,\n path_params, query_params,\n header_params, body,\n post_params, files,\n response_type, auth_settings,\n _return_http_data_only,\n collection_formats, _preload_content, _request_timeout))\n return thread": 5972, "def parsehttpdate(string_):\n \"\"\"\n Parses an HTTP date into a datetime object.\n\n >>> parsehttpdate('Thu, 01 Jan 1970 01:01:01 GMT')\n datetime.datetime(1970, 1, 1, 1, 1, 1)\n \"\"\"\n try:\n t = time.strptime(string_, \"%a, %d %b %Y %H:%M:%S %Z\")\n except ValueError:\n return None\n return datetime.datetime(*t[:6])": 5973, "def translate_dict(cls, val):\n \"\"\"Translate dicts to scala Maps\"\"\"\n escaped = ', '.join(\n [\"{} -> {}\".format(cls.translate_str(k), cls.translate(v)) for k, v in val.items()]\n )\n return 'Map({})'.format(escaped)": 5974, "def get_bin_edges_from_axis(axis) -> np.ndarray:\n \"\"\" Get bin edges from a ROOT hist axis.\n\n Note:\n Doesn't include over- or underflow bins!\n\n Args:\n axis (ROOT.TAxis): Axis from which the bin edges should be extracted.\n Returns:\n Array containing the bin edges.\n \"\"\"\n # Don't include over- or underflow bins\n bins = range(1, axis.GetNbins() + 1)\n # Bin edges\n bin_edges = np.empty(len(bins) + 1)\n bin_edges[:-1] = [axis.GetBinLowEdge(i) for i in bins]\n bin_edges[-1] = axis.GetBinUpEdge(axis.GetNbins())\n\n return bin_edges": 5975, "def get_language(query: str) -> str:\n \"\"\"Tries to work out the highlight.js language of a given file name or\n shebang. Returns an empty string if none match.\n \"\"\"\n query = query.lower()\n for language in LANGUAGES:\n if query.endswith(language):\n return language\n return ''": 5976, "def _strip_top_comments(lines: Sequence[str], line_separator: str) -> str:\n \"\"\"Strips # comments that exist at the top of the given lines\"\"\"\n lines = copy.copy(lines)\n while lines and lines[0].startswith(\"#\"):\n lines = lines[1:]\n return line_separator.join(lines)": 5977, "def scope_logger(cls):\n \"\"\"\n Class decorator for adding a class local logger\n\n Example:\n >>> @scope_logger\n >>> class Test:\n >>> def __init__(self):\n >>> self.log.info(\"class instantiated\")\n >>> t = Test()\n \n \"\"\"\n cls.log = logging.getLogger('{0}.{1}'.format(cls.__module__, cls.__name__))\n return cls": 5978, "def read_flat(self):\n \"\"\"\n Read a PNG file and decode it into flat row flat pixel format.\n\n Returns (*width*, *height*, *pixels*, *metadata*).\n\n May use excessive memory.\n\n `pixels` are returned in flat row flat pixel format.\n\n See also the :meth:`read` method which returns pixels in the\n more stream-friendly boxed row flat pixel format.\n \"\"\"\n x, y, pixel, meta = self.read()\n arraycode = 'BH'[meta['bitdepth'] > 8]\n pixel = array(arraycode, itertools.chain(*pixel))\n return x, y, pixel, meta": 5979, "def hex_color_to_tuple(hex):\n \"\"\" convent hex color to tuple\n \"#ffffff\" -> (255, 255, 255)\n \"#ffff00ff\" -> (255, 255, 0, 255)\n \"\"\"\n hex = hex[1:]\n length = len(hex) // 2\n return tuple(int(hex[i*2:i*2+2], 16) for i in range(length))": 5980, "def capitalize(string):\n \"\"\"Capitalize a sentence.\n\n Parameters\n ----------\n string : `str`\n String to capitalize.\n\n Returns\n -------\n `str`\n Capitalized string.\n\n Examples\n --------\n >>> capitalize('worD WORD WoRd')\n 'Word word word'\n \"\"\"\n if not string:\n return string\n if len(string) == 1:\n return string.upper()\n return string[0].upper() + string[1:].lower()": 5981, "def export_to_dot(self, filename: str = 'output') -> None:\n \"\"\" Export the graph to the dot file \"filename.dot\". \"\"\"\n with open(filename + '.dot', 'w') as output:\n output.write(self.as_dot())": 5982, "def from_iso_time(timestring, use_dateutil=True):\n \"\"\"Parse an ISO8601-formatted datetime string and return a datetime.time\n object.\n \"\"\"\n if not _iso8601_time_re.match(timestring):\n raise ValueError('Not a valid ISO8601-formatted time string')\n if dateutil_available and use_dateutil:\n return parser.parse(timestring).time()\n else:\n if len(timestring) > 8: # has microseconds\n fmt = '%H:%M:%S.%f'\n else:\n fmt = '%H:%M:%S'\n return datetime.datetime.strptime(timestring, fmt).time()": 5983, "def fix_title_capitalization(title):\n \"\"\"Try to capitalize properly a title string.\"\"\"\n if re.search(\"[A-Z]\", title) and re.search(\"[a-z]\", title):\n return title\n word_list = re.split(' +', title)\n final = [word_list[0].capitalize()]\n for word in word_list[1:]:\n if word.upper() in COMMON_ACRONYMS:\n final.append(word.upper())\n elif len(word) > 3:\n final.append(word.capitalize())\n else:\n final.append(word.lower())\n return \" \".join(final)": 5984, "def argsort_k_smallest(x, k):\n \"\"\" Return no more than ``k`` indices of smallest values. \"\"\"\n if k == 0:\n return np.array([], dtype=np.intp)\n if k is None or k >= len(x):\n return np.argsort(x)\n indices = np.argpartition(x, k)[:k]\n values = x[indices]\n return indices[np.argsort(values)]": 5985, "def getElementsBy(self, cond: Callable[[Element], bool]) -> NodeList:\n \"\"\"Get elements in this document which matches condition.\"\"\"\n return getElementsBy(self, cond)": 5986, "def uuid2buid(value):\n \"\"\"\n Convert a UUID object to a 22-char BUID string\n\n >>> u = uuid.UUID('33203dd2-f2ef-422f-aeb0-058d6f5f7089')\n >>> uuid2buid(u)\n 'MyA90vLvQi-usAWNb19wiQ'\n \"\"\"\n if six.PY3: # pragma: no cover\n return urlsafe_b64encode(value.bytes).decode('utf-8').rstrip('=')\n else:\n return six.text_type(urlsafe_b64encode(value.bytes).rstrip('='))": 5987, "def replace(s, old, new, maxreplace=-1):\n \"\"\"replace (str, old, new[, maxreplace]) -> string\n\n Return a copy of string str with all occurrences of substring\n old replaced by new. If the optional argument maxreplace is\n given, only the first maxreplace occurrences are replaced.\n\n \"\"\"\n return s.replace(old, new, maxreplace)": 5988, "def get_longest_line_length(text):\n \"\"\"Get the length longest line in a paragraph\"\"\"\n lines = text.split(\"\\n\")\n length = 0\n\n for i in range(len(lines)):\n if len(lines[i]) > length:\n length = len(lines[i])\n\n return length": 5989, "def constant(times: np.ndarray, amp: complex) -> np.ndarray:\n \"\"\"Continuous constant pulse.\n\n Args:\n times: Times to output pulse for.\n amp: Complex pulse amplitude.\n \"\"\"\n return np.full(len(times), amp, dtype=np.complex_)": 5990, "def strip_codes(s: Any) -> str:\n \"\"\" Strip all color codes from a string.\n Returns empty string for \"falsey\" inputs.\n \"\"\"\n return codepat.sub('', str(s) if (s or (s == 0)) else '')": 5991, "def to_jupyter(graph: BELGraph, chart: Optional[str] = None) -> Javascript:\n \"\"\"Render the graph as JavaScript in a Jupyter Notebook.\"\"\"\n with open(os.path.join(HERE, 'render_with_javascript.js'), 'rt') as f:\n js_template = Template(f.read())\n\n return Javascript(js_template.render(**_get_context(graph, chart=chart)))": 5992, "def negate_mask(mask):\n \"\"\"Returns the negated mask.\n\n If elements of input mask have 0 and non-zero values, then the returned matrix will have all elements 0 (1) where\n the original one has non-zero (0).\n\n :param mask: Input mask\n :type mask: np.array\n :return: array of same shape and dtype=int8 as input array\n :rtype: np.array\n \"\"\"\n res = np.ones(mask.shape, dtype=np.int8)\n res[mask > 0] = 0\n\n return res": 5993, "def local_machine_uuid():\n \"\"\"Return local machine unique identifier.\n\n >>> uuid = local_machine_uuid()\n\n \"\"\"\n\n result = subprocess.check_output(\n 'hal-get-property --udi '\n '/org/freedesktop/Hal/devices/computer '\n '--key system.hardware.uuid'.split()\n ).strip()\n\n return uuid.UUID(hex=result)": 5994, "def _hash_the_file(hasher, filename):\n \"\"\"Helper function for creating hash functions.\n\n See implementation of :func:`dtoolcore.filehasher.shasum`\n for more usage details.\n \"\"\"\n BUF_SIZE = 65536\n with open(filename, 'rb') as f:\n buf = f.read(BUF_SIZE)\n while len(buf) > 0:\n hasher.update(buf)\n buf = f.read(BUF_SIZE)\n return hasher": 5995, "def get_value(self) -> Decimal:\n \"\"\" Returns the current value of stocks \"\"\"\n quantity = self.get_quantity()\n price = self.get_last_available_price()\n if not price:\n # raise ValueError(\"no price found for\", self.full_symbol)\n return Decimal(0)\n\n value = quantity * price.value\n return value": 5996, "def is_inside_lambda(node: astroid.node_classes.NodeNG) -> bool:\n \"\"\"Return true if given node is inside lambda\"\"\"\n parent = node.parent\n while parent is not None:\n if isinstance(parent, astroid.Lambda):\n return True\n parent = parent.parent\n return False": 5997, "def stdout_encode(u, default='utf-8'):\n \"\"\" Encodes a given string with the proper standard out encoding\n If sys.stdout.encoding isn't specified, it this defaults to @default\n\n @default: default encoding\n\n -> #str with standard out encoding\n \"\"\"\n # from http://stackoverflow.com/questions/3627793/best-output-type-and-\n # encoding-practices-for-repr-functions\n encoding = sys.stdout.encoding or default\n return u.encode(encoding, \"replace\").decode(encoding, \"replace\")": 5998, "def revrank_dict(dict, key=lambda t: t[1], as_tuple=False):\n \"\"\" Reverse sorts a #dict by a given key, optionally returning it as a\n #tuple. By default, the @dict is sorted by it's value.\n\n @dict: the #dict you wish to sorts\n @key: the #sorted key to use\n @as_tuple: returns result as a #tuple ((k, v),...)\n\n -> :class:OrderedDict or #tuple\n \"\"\"\n sorted_list = sorted(dict.items(), key=key, reverse=True)\n return OrderedDict(sorted_list) if not as_tuple else tuple(sorted_list)": 5999, "def remove_parenthesis_around_tz(cls, timestr):\n \"\"\"get rid of parenthesis around timezone: (GMT) => GMT\n\n :return: the new string if parenthesis were found, `None` otherwise\n \"\"\"\n parenthesis = cls.TIMEZONE_PARENTHESIS.match(timestr)\n if parenthesis is not None:\n return parenthesis.group(1)": 6000, "def __repr__(self) -> str:\n \"\"\"Return the string representation of self.\"\"\"\n return '{0}({1})'.format(type(self).__name__, repr(self.string))": 6001, "def load_yaml(yaml_file: str) -> Any:\n \"\"\"\n Load YAML from file.\n\n :param yaml_file: path to YAML file\n :return: content of the YAML as dict/list\n \"\"\"\n with open(yaml_file, 'r') as file:\n return ruamel.yaml.load(file, ruamel.yaml.RoundTripLoader)": 6002, "def quoted_or_list(items: List[str]) -> Optional[str]:\n \"\"\"Given [A, B, C] return \"'A', 'B', or 'C'\".\n\n Note: We use single quotes here, since these are also used by repr().\n \"\"\"\n return or_list([f\"'{item}'\" for item in items])": 6003, "def first_digits(s, default=0):\n \"\"\"Return the fist (left-hand) digits in a string as a single integer, ignoring sign (+/-).\n >>> first_digits('+123.456')\n 123\n \"\"\"\n s = re.split(r'[^0-9]+', str(s).strip().lstrip('+-' + charlist.whitespace))\n if len(s) and len(s[0]):\n return int(s[0])\n return default": 6004, "def run_time() -> timedelta:\n \"\"\"\n\n :return:\n \"\"\"\n\n delta = start_time if start_time else datetime.utcnow()\n return datetime.utcnow() - delta": 6005, "def to_np(*args):\n \"\"\" convert GPU arras to numpy and return them\"\"\"\n if len(args) > 1:\n return (cp.asnumpy(x) for x in args)\n else:\n return cp.asnumpy(args[0])": 6006, "def _RetryRequest(self, timeout=None, **request_args):\n \"\"\"Retry the request a few times before we determine it failed.\n\n Sometimes the frontend becomes loaded and issues a 500 error to throttle the\n clients. We wait Client.error_poll_min seconds between each attempt to back\n off the frontend. Note that this does not affect any timing algorithm in the\n client itself which is controlled by the Timer() class.\n\n Args:\n timeout: Timeout for retry.\n **request_args: Args to the requests.request call.\n\n Returns:\n a tuple of duration, urllib.request.urlopen response.\n \"\"\"\n while True:\n try:\n now = time.time()\n if not timeout:\n timeout = config.CONFIG[\"Client.http_timeout\"]\n\n result = requests.request(**request_args)\n # By default requests doesn't raise on HTTP error codes.\n result.raise_for_status()\n\n # Requests does not always raise an exception when an incorrect response\n # is received. This fixes that behaviour.\n if not result.ok:\n raise requests.RequestException(response=result)\n\n return time.time() - now, result\n\n # Catch any exceptions that dont have a code (e.g. socket.error).\n except IOError as e:\n self.consecutive_connection_errors += 1\n # Request failed. If we connected successfully before we attempt a few\n # connections before we determine that it really failed. This might\n # happen if the front end is loaded and returns a few throttling 500\n # messages.\n if self.active_base_url is not None:\n # Propagate 406 immediately without retrying, as 406 is a valid\n # response that indicates a need for enrollment.\n response = getattr(e, \"response\", None)\n if getattr(response, \"status_code\", None) == 406:\n raise\n\n if self.consecutive_connection_errors >= self.retry_error_limit:\n # We tried several times but this really did not work, just fail it.\n logging.info(\n \"Too many connection errors to %s, retrying another URL\",\n self.active_base_url)\n self.active_base_url = None\n raise e\n\n # Back off hard to allow the front end to recover.\n logging.debug(\n \"Unable to connect to frontend. Backing off %s seconds.\",\n self.error_poll_min)\n self.Wait(self.error_poll_min)\n\n # We never previously connected, maybe the URL/proxy is wrong? Just fail\n # right away to allow callers to try a different URL.\n else:\n raise e": 6007, "def duration_expired(start_time, duration_seconds):\n \"\"\"\n Return True if ``duration_seconds`` have expired since ``start_time``\n \"\"\"\n\n if duration_seconds is not None:\n delta_seconds = datetime_delta_to_seconds(dt.datetime.now() - start_time)\n\n if delta_seconds >= duration_seconds:\n return True\n\n return False": 6008, "def get_valid_filename(s):\n \"\"\"\n Shamelessly taken from Django.\n https://github.com/django/django/blob/master/django/utils/text.py\n\n Return the given string converted to a string that can be used for a clean\n filename. Remove leading and trailing spaces; convert other spaces to\n underscores; and remove anything that is not an alphanumeric, dash,\n underscore, or dot.\n >>> get_valid_filename(\"john's portrait in 2004.jpg\")\n 'johns_portrait_in_2004.jpg'\n \"\"\"\n s = str(s).strip().replace(' ', '_')\n return re.sub(r'(?u)[^-\\w.]', '', s)": 6009, "async def enter_captcha(self, url: str, sid: str) -> str:\n \"\"\"\n Override this method for processing captcha.\n\n :param url: link to captcha image\n :param sid: captcha id. I do not know why pass here but may be useful\n :return captcha value\n \"\"\"\n raise VkCaptchaNeeded(url, sid)": 6010, "def wait_for_shutdown_signal(\n self,\n please_stop=False, # ASSIGN SIGNAL TO STOP EARLY\n allow_exit=False, # ALLOW \"exit\" COMMAND ON CONSOLE TO ALSO STOP THE APP\n wait_forever=True # IGNORE CHILD THREADS, NEVER EXIT. False => IF NO CHILD THREADS LEFT, THEN EXIT\n ):\n \"\"\"\n FOR USE BY PROCESSES THAT NEVER DIE UNLESS EXTERNAL SHUTDOWN IS REQUESTED\n\n CALLING THREAD WILL SLEEP UNTIL keyboard interrupt, OR please_stop, OR \"exit\"\n\n :param please_stop:\n :param allow_exit:\n :param wait_forever:: Assume all needed threads have been launched. When done\n :return:\n \"\"\"\n self_thread = Thread.current()\n if self_thread != MAIN_THREAD or self_thread != self:\n Log.error(\"Only the main thread can sleep forever (waiting for KeyboardInterrupt)\")\n\n if isinstance(please_stop, Signal):\n # MUTUAL SIGNALING MAKES THESE TWO EFFECTIVELY THE SAME SIGNAL\n self.please_stop.on_go(please_stop.go)\n please_stop.on_go(self.please_stop.go)\n else:\n please_stop = self.please_stop\n\n if not wait_forever:\n # TRIGGER SIGNAL WHEN ALL CHILDREN THEADS ARE DONE\n with self_thread.child_lock:\n pending = copy(self_thread.children)\n children_done = AndSignals(please_stop, len(pending))\n children_done.signal.on_go(self.please_stop.go)\n for p in pending:\n p.stopped.on_go(children_done.done)\n\n try:\n if allow_exit:\n _wait_for_exit(please_stop)\n else:\n _wait_for_interrupt(please_stop)\n except KeyboardInterrupt as _:\n Log.alert(\"SIGINT Detected! Stopping...\")\n except SystemExit as _:\n Log.alert(\"SIGTERM Detected! Stopping...\")\n finally:\n self.stop()": 6011, "def strids2ids(tokens: Iterable[str]) -> List[int]:\n \"\"\"\n Returns sequence of integer ids given a sequence of string ids.\n\n :param tokens: List of integer tokens.\n :return: List of word ids.\n \"\"\"\n return list(map(int, tokens))": 6012, "def to_dict(self):\n \"\"\"\n\n Returns: the tree item as a dictionary\n\n \"\"\"\n if self.childCount() > 0:\n value = {}\n for index in range(self.childCount()):\n value.update(self.child(index).to_dict())\n else:\n value = self.value\n\n return {self.name: value}": 6013, "def python_utc_datetime_to_sqlite_strftime_string(\n value: datetime.datetime) -> str:\n \"\"\"\n Converts a Python datetime to a string literal compatible with SQLite,\n including the millisecond field.\n \"\"\"\n millisec_str = str(round(value.microsecond / 1000)).zfill(3)\n return value.strftime(\"%Y-%m-%d %H:%M:%S\") + \".\" + millisec_str": 6014, "def drop_post(self):\n \"\"\"Remove .postXXXX postfix from version\"\"\"\n post_index = self.version.find('.post')\n if post_index >= 0:\n self.version = self.version[:post_index]": 6015, "def safe_pow(base, exp):\n \"\"\"safe version of pow\"\"\"\n if exp > MAX_EXPONENT:\n raise RuntimeError(\"Invalid exponent, max exponent is {}\".format(MAX_EXPONENT))\n return base ** exp": 6016, "def mkdir(self, target_folder):\n \"\"\"\n Create a folder on S3.\n\n Examples\n --------\n >>> s3utils.mkdir(\"path/to/my_folder\")\n Making directory: path/to/my_folder\n \"\"\"\n self.printv(\"Making directory: %s\" % target_folder)\n self.k.key = re.sub(r\"^/|/$\", \"\", target_folder) + \"/\"\n self.k.set_contents_from_string('')\n self.k.close()": 6017, "def find_first(pattern: str, path: str) -> str:\n \"\"\"\n Finds first file in ``path`` whose filename matches ``pattern`` (via\n :func:`fnmatch.fnmatch`), or raises :exc:`IndexError`.\n \"\"\"\n try:\n return find(pattern, path)[0]\n except IndexError:\n log.critical('''Couldn't find \"{}\" in \"{}\"''', pattern, path)\n raise": 6018, "def issuperset(self, items):\n \"\"\"Return whether this collection contains all items.\n\n >>> Unique(['spam', 'eggs']).issuperset(['spam', 'spam', 'spam'])\n True\n \"\"\"\n return all(_compat.map(self._seen.__contains__, items))": 6019, "def union(cls, *sets):\n \"\"\"\n >>> from utool.util_set import * # NOQA\n \"\"\"\n import utool as ut\n lists_ = ut.flatten([list(s) for s in sets])\n return cls(lists_)": 6020, "def _cleanup(path: str) -> None:\n \"\"\"Cleanup temporary directory.\"\"\"\n if os.path.isdir(path):\n shutil.rmtree(path)": 6021, "def default_parser() -> argparse.ArgumentParser:\n \"\"\"Create a parser for CLI arguments and options.\"\"\"\n parser = argparse.ArgumentParser(\n prog=CONSOLE_SCRIPT,\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n )\n build_parser(parser)\n return parser": 6022, "def add_mark_at(string, index, mark):\n \"\"\"\n Add mark to the index-th character of the given string. Return the new string after applying change.\n Notice: index > 0\n \"\"\"\n if index == -1:\n return string\n # Python can handle the case which index is out of range of given string\n return string[:index] + add_mark_char(string[index], mark) + string[index+1:]": 6023, "def is_up_to_date(outfile, basedatetime):\n # type: (AnyStr, datetime) -> bool\n \"\"\"Return true if outfile exists and is no older than base datetime.\"\"\"\n if os.path.exists(outfile):\n if os.path.getmtime(outfile) >= basedatetime:\n return True\n return False": 6024, "def bulk_load_docs(es, docs):\n \"\"\"Bulk load docs\n\n Args:\n es: elasticsearch handle\n docs: Iterator of doc objects - includes index_name\n \"\"\"\n\n chunk_size = 200\n\n try:\n results = elasticsearch.helpers.bulk(es, docs, chunk_size=chunk_size)\n log.debug(f\"Elasticsearch documents loaded: {results[0]}\")\n\n # elasticsearch.helpers.parallel_bulk(es, terms, chunk_size=chunk_size, thread_count=4)\n if len(results[1]) > 0:\n log.error(\"Bulk load errors {}\".format(results))\n except elasticsearch.ElasticsearchException as e:\n log.error(\"Indexing error: {}\\n\".format(e))": 6025, "def after_third_friday(day=None):\n \"\"\" check if day is after month's 3rd friday \"\"\"\n day = day if day is not None else datetime.datetime.now()\n now = day.replace(day=1, hour=16, minute=0, second=0, microsecond=0)\n now += relativedelta.relativedelta(weeks=2, weekday=relativedelta.FR)\n return day > now": 6026, "def _write_json(obj, path): # type: (object, str) -> None\n \"\"\"Writes a serializeable object as a JSON file\"\"\"\n with open(path, 'w') as f:\n json.dump(obj, f)": 6027, "def argmax(iterable, key=None, both=False):\n \"\"\"\n >>> argmax([4,2,-5])\n 0\n >>> argmax([4,2,-5], key=abs)\n 2\n >>> argmax([4,2,-5], key=abs, both=True)\n (2, 5)\n \"\"\"\n if key is not None:\n it = imap(key, iterable)\n else:\n it = iter(iterable)\n score, argmax = reduce(max, izip(it, count()))\n if both:\n return argmax, score\n return argmax": 6028, "def get_system_flags() -> FrozenSet[Flag]:\n \"\"\"Return the set of implemented system flags.\"\"\"\n return frozenset({Seen, Recent, Deleted, Flagged, Answered, Draft})": 6029, "def timestamp_with_tzinfo(dt):\n \"\"\"\n Serialize a date/time value into an ISO8601 text representation\n adjusted (if needed) to UTC timezone.\n\n For instance:\n >>> serialize_date(datetime(2012, 4, 10, 22, 38, 20, 604391))\n '2012-04-10T22:38:20.604391Z'\n \"\"\"\n utc = tzutc()\n\n if dt.tzinfo:\n dt = dt.astimezone(utc).replace(tzinfo=None)\n return dt.isoformat() + 'Z'": 6030, "def replace_variables(self, source: str, variables: dict) -> str:\n \"\"\"Replace {{variable-name}} with stored value.\"\"\"\n try:\n replaced = re.sub(\n \"{{(.*?)}}\", lambda m: variables.get(m.group(1), \"\"), source\n )\n except TypeError:\n replaced = source\n return replaced": 6031, "def duplicates(coll):\n \"\"\"Return the duplicated items in the given collection\n\n :param coll: a collection\n :returns: a list of the duplicated items in the collection\n\n >>> duplicates([1, 1, 2, 3, 3, 4, 1, 1])\n [1, 3]\n\n \"\"\"\n return list(set(x for x in coll if coll.count(x) > 1))": 6032, "def _dfs_cycle_detect(graph, node, path, visited_nodes):\n \"\"\"\n search graph for cycle using DFS continuing from node\n path contains the list of visited nodes currently on the stack\n visited_nodes is the set of already visited nodes\n :param graph:\n :param node:\n :param path:\n :param visited_nodes:\n :return:\n \"\"\"\n visited_nodes.add(node)\n for target in graph[node]:\n if target in path:\n # cycle found => return current path\n return path + [target]\n else:\n return _dfs_cycle_detect(graph, target, path + [target], visited_nodes)\n return None": 6033, "def collect_static() -> bool:\n \"\"\"\n Runs Django ``collectstatic`` command in silent mode.\n\n :return: always ``True``\n \"\"\"\n from django.core.management import execute_from_command_line\n # from django.conf import settings\n # if not os.listdir(settings.STATIC_ROOT):\n wf('Collecting static files... ', False)\n execute_from_command_line(['./manage.py', 'collectstatic', '-c', '--noinput', '-v0'])\n wf('[+]\\n')\n return True": 6034, "def lsr_pairwise_dense(comp_mat, alpha=0.0, initial_params=None):\n \"\"\"Compute the LSR estimate of model parameters given dense data.\n\n This function implements the Luce Spectral Ranking inference algorithm\n [MG15]_ for dense pairwise-comparison data.\n\n The data is described by a pairwise-comparison matrix ``comp_mat`` such\n that ``comp_mat[i,j]`` contains the number of times that item ``i`` wins\n against item ``j``.\n\n In comparison to :func:`~choix.lsr_pairwise`, this function is particularly\n efficient for dense pairwise-comparison datasets (i.e., containing many\n comparisons for a large fraction of item pairs).\n\n The argument ``initial_params`` can be used to iteratively refine an\n existing parameter estimate (see the implementation of\n :func:`~choix.ilsr_pairwise` for an idea on how this works). If it is set\n to `None` (the default), the all-ones vector is used.\n\n The transition rates of the LSR Markov chain are initialized with\n ``alpha``. When ``alpha > 0``, this corresponds to a form of regularization\n (see :ref:`regularization` for details).\n\n Parameters\n ----------\n comp_mat : np.array\n 2D square matrix describing the pairwise-comparison outcomes.\n alpha : float, optional\n Regularization parameter.\n initial_params : array_like, optional\n Parameters used to build the transition rates of the LSR Markov chain.\n\n Returns\n -------\n params : np.array\n An estimate of model parameters.\n \"\"\"\n n_items = comp_mat.shape[0]\n ws, chain = _init_lsr(n_items, alpha, initial_params)\n denom = np.tile(ws, (n_items, 1))\n chain += comp_mat.T / (denom + denom.T)\n chain -= np.diag(chain.sum(axis=1))\n return log_transform(statdist(chain))": 6035, "def import_by_path(path: str) -> Callable:\n \"\"\"Import a class or function given it's absolute path.\n\n Parameters\n ----------\n path:\n Path to object to import\n \"\"\"\n\n module_path, _, class_name = path.rpartition('.')\n return getattr(import_module(module_path), class_name)": 6036, "def ensure_list(iterable: Iterable[A]) -> List[A]:\n \"\"\"\n An Iterable may be a list or a generator.\n This ensures we get a list without making an unnecessary copy.\n \"\"\"\n if isinstance(iterable, list):\n return iterable\n else:\n return list(iterable)": 6037, "def _protected_log(x1):\n \"\"\"Closure of log for zero arguments.\"\"\"\n with np.errstate(divide='ignore', invalid='ignore'):\n return np.where(np.abs(x1) > 0.001, np.log(np.abs(x1)), 0.)": 6038, "def load_preprocess_images(image_paths: List[str], image_size: tuple) -> List[np.ndarray]:\n \"\"\"\n Load and pre-process the images specified with absolute paths.\n\n :param image_paths: List of images specified with paths.\n :param image_size: Tuple to resize the image to (Channels, Height, Width)\n :return: A list of loaded images (numpy arrays).\n \"\"\"\n image_size = image_size[1:] # we do not need the number of channels\n images = []\n for image_path in image_paths:\n images.append(load_preprocess_image(image_path, image_size))\n return images": 6039, "def _check_update_(self):\n \"\"\"Check if the current version of the library is outdated.\"\"\"\n try:\n data = requests.get(\"https://pypi.python.org/pypi/jira/json\", timeout=2.001).json()\n\n released_version = data['info']['version']\n if parse_version(released_version) > parse_version(__version__):\n warnings.warn(\n \"You are running an outdated version of JIRA Python %s. Current version is %s. Do not file any bugs against older versions.\" % (\n __version__, released_version))\n except requests.RequestException:\n pass\n except Exception as e:\n logging.warning(e)": 6040, "def _get_or_default(mylist, i, default=None):\n \"\"\"return list item number, or default if don't exist\"\"\"\n if i >= len(mylist):\n return default\n else :\n return mylist[i]": 6041, "def version():\n \"\"\"Wrapper for opj_version library routine.\"\"\"\n OPENJPEG.opj_version.restype = ctypes.c_char_p\n library_version = OPENJPEG.opj_version()\n if sys.hexversion >= 0x03000000:\n return library_version.decode('utf-8')\n else:\n return library_version": 6042, "def is_builtin_object(node: astroid.node_classes.NodeNG) -> bool:\n \"\"\"Returns True if the given node is an object from the __builtin__ module.\"\"\"\n return node and node.root().name == BUILTINS_NAME": 6043, "def checksum(path):\n \"\"\"Calculcate checksum for a file.\"\"\"\n hasher = hashlib.sha1()\n with open(path, 'rb') as stream:\n buf = stream.read(BLOCKSIZE)\n while len(buf) > 0:\n hasher.update(buf)\n buf = stream.read(BLOCKSIZE)\n return hasher.hexdigest()": 6044, "def get_days_in_month(year: int, month: int) -> int:\n \"\"\" Returns number of days in the given month.\n 1-based numbers as arguments. i.e. November = 11 \"\"\"\n month_range = calendar.monthrange(year, month)\n return month_range[1]": 6045, "def pairwise(iterable):\n \"\"\"From itertools cookbook. [a, b, c, ...] -> (a, b), (b, c), ...\"\"\"\n first, second = tee(iterable)\n next(second, None)\n return zip(first, second)": 6046, "def to_graphviz(graph):\n \"\"\"\n\n :param graph:\n :return:\n \"\"\"\n ret = ['digraph g {']\n vertices = []\n\n node_ids = dict([(name, 'node' + idx) for (idx, name) in enumerate(list(graph))])\n\n for node in list(graph):\n ret.append(' \"%s\" [label=\"%s\"];' % (node_ids[node], node))\n for target in graph[node]:\n vertices.append(' \"%s\" -> \"%s\";' % (node_ids[node], node_ids[target]))\n\n ret += vertices\n ret.append('}')\n return '\\n'.join(ret)": 6047, "def get_file_extension(filename):\n \"\"\" Return the extension if the filename has it. None if not.\n\n :param filename: The filename.\n :return: Extension or None.\n \"\"\"\n filename_x = filename.split('.')\n if len(filename_x) > 1:\n if filename_x[-1].strip() is not '':\n return filename_x[-1]\n return None": 6048, "def normalize_column_names(df):\n r\"\"\" Clean up whitespace in column names. See better version at `pugnlp.clean_columns`\n\n >>> df = pd.DataFrame([[1, 2], [3, 4]], columns=['Hello World', 'not here'])\n >>> normalize_column_names(df)\n ['hello_world', 'not_here']\n \"\"\"\n columns = df.columns if hasattr(df, 'columns') else df\n columns = [c.lower().replace(' ', '_') for c in columns]\n return columns": 6049, "def _width_is_big_enough(image, width):\n \"\"\"Check that the image width is superior to `width`\"\"\"\n if width > image.size[0]:\n raise ImageSizeError(image.size[0], width)": 6050, "def branches():\n # type: () -> List[str]\n \"\"\" Return a list of branches in the current repo.\n\n Returns:\n list[str]: A list of branches in the current repo.\n \"\"\"\n out = shell.run(\n 'git branch',\n capture=True,\n never_pretend=True\n ).stdout.strip()\n return [x.strip('* \\t\\n') for x in out.splitlines()]": 6051, "def cache_page(page_cache, page_hash, cache_size):\n \"\"\"Add a page to the page cache.\"\"\"\n page_cache.append(page_hash)\n if len(page_cache) > cache_size:\n page_cache.pop(0)": 6052, "def _log_response(response):\n \"\"\"Log out information about a ``Request`` object.\n\n After calling ``requests.request`` or one of its convenience methods, the\n object returned can be passed to this method. If done, information about\n the object returned is logged.\n\n :return: Nothing is returned.\n\n \"\"\"\n message = u'Received HTTP {0} response: {1}'.format(\n response.status_code,\n response.text\n )\n if response.status_code >= 400: # pragma: no cover\n logger.warning(message)\n else:\n logger.debug(message)": 6053, "def empty_wav(wav_path: Union[Path, str]) -> bool:\n \"\"\"Check if a wav contains data\"\"\"\n with wave.open(str(wav_path), 'rb') as wav_f:\n return wav_f.getnframes() == 0": 6054, "def _in_qtconsole() -> bool:\n \"\"\"\n A small utility function which determines if we're running in QTConsole's context.\n \"\"\"\n try:\n from IPython import get_ipython\n try:\n from ipykernel.zmqshell import ZMQInteractiveShell\n shell_object = ZMQInteractiveShell\n except ImportError:\n from IPython.kernel.zmq import zmqshell\n shell_object = zmqshell.ZMQInteractiveShell\n return isinstance(get_ipython(), shell_object)\n except Exception:\n return False": 6055, "def sorted(self):\n \"\"\"Utility function for sort_file_tabs_alphabetically().\"\"\"\n for i in range(0, self.tabs.tabBar().count() - 1):\n if (self.tabs.tabBar().tabText(i) >\n self.tabs.tabBar().tabText(i + 1)):\n return False\n return True": 6056, "def ask_bool(question: str, default: bool = True) -> bool:\n \"\"\"Asks a question yes no style\"\"\"\n default_q = \"Y/n\" if default else \"y/N\"\n answer = input(\"{0} [{1}]: \".format(question, default_q))\n lower = answer.lower()\n if not lower:\n return default\n return lower == \"y\"": 6057, "def parse_dim(features, check=True):\n \"\"\"Return the features dimension, raise if error\n\n Raise IOError if features have not all the same positive\n dimension. Return dim (int), the features dimension.\n\n \"\"\"\n # try:\n dim = features[0].shape[1]\n # except IndexError:\n # dim = 1\n\n if check and not dim > 0:\n raise IOError('features dimension must be strictly positive')\n if check and not all([d == dim for d in [x.shape[1] for x in features]]):\n raise IOError('all files must have the same feature dimension')\n return dim": 6058, "def get_edge_relations(graph: BELGraph) -> Mapping[Tuple[BaseEntity, BaseEntity], Set[str]]:\n \"\"\"Build a dictionary of {node pair: set of edge types}.\"\"\"\n return group_dict_set(\n ((u, v), d[RELATION])\n for u, v, d in graph.edges(data=True)\n )": 6059, "def __setitem__(self, *args, **kwargs):\n \"\"\" Cut if needed. \"\"\"\n super(History, self).__setitem__(*args, **kwargs)\n if len(self) > self.size:\n self.popitem(False)": 6060, "def list_adb_devices_by_usb_id():\n \"\"\"List the usb id of all android devices connected to the computer that\n are detected by adb.\n\n Returns:\n A list of strings that are android device usb ids. Empty if there's\n none.\n \"\"\"\n out = adb.AdbProxy().devices(['-l'])\n clean_lines = new_str(out, 'utf-8').strip().split('\\n')\n results = []\n for line in clean_lines:\n tokens = line.strip().split()\n if len(tokens) > 2 and tokens[1] == 'device':\n results.append(tokens[2])\n return results": 6061, "def returns(self) -> T.Optional[DocstringReturns]:\n \"\"\"Return return information indicated in docstring.\"\"\"\n try:\n return next(\n DocstringReturns.from_meta(meta)\n for meta in self.meta\n if meta.args[0] in {\"return\", \"returns\", \"yield\", \"yields\"}\n )\n except StopIteration:\n return None": 6062, "def _infer_interval_breaks(coord):\n \"\"\"\n >>> _infer_interval_breaks(np.arange(5))\n array([-0.5, 0.5, 1.5, 2.5, 3.5, 4.5])\n\n Taken from xarray.plotting.plot module\n \"\"\"\n coord = np.asarray(coord)\n deltas = 0.5 * (coord[1:] - coord[:-1])\n first = coord[0] - deltas[0]\n last = coord[-1] + deltas[-1]\n return np.r_[[first], coord[:-1] + deltas, [last]]": 6063, "def check_max_filesize(chosen_file, max_size):\n \"\"\"\n Checks file sizes for host\n \"\"\"\n if os.path.getsize(chosen_file) > max_size:\n return False\n else:\n return True": 6064, "def pretty_describe(object, nestedness=0, indent=2):\n \"\"\"Maintain dict ordering - but make string version prettier\"\"\"\n if not isinstance(object, dict):\n return str(object)\n sep = f'\\n{\" \" * nestedness * indent}'\n out = sep.join((f'{k}: {pretty_describe(v, nestedness + 1)}' for k, v in object.items()))\n if nestedness > 0 and out:\n return f'{sep}{out}'\n return out": 6065, "def indent(text: str, num: int = 2) -> str:\n \"\"\"Indent a piece of text.\"\"\"\n lines = text.splitlines()\n return \"\\n\".join(indent_iterable(lines, num=num))": 6066, "def get_view_selection(self):\n \"\"\"Get actual tree selection object and all respective models of selected rows\"\"\"\n if not self.MODEL_STORAGE_ID:\n return None, None\n\n # avoid selection requests on empty tree views -> case warnings in gtk3\n if len(self.store) == 0:\n paths = []\n else:\n model, paths = self._tree_selection.get_selected_rows()\n\n # get all related models for selection from respective tree store field\n selected_model_list = []\n for path in paths:\n model = self.store[path][self.MODEL_STORAGE_ID]\n selected_model_list.append(model)\n return self._tree_selection, selected_model_list": 6067, "def public(self) -> 'PrettyDir':\n \"\"\"Returns public attributes of the inspected object.\"\"\"\n return PrettyDir(\n self.obj, [pattr for pattr in self.pattrs if not pattr.name.startswith('_')]\n )": 6068, "def drop_column(self, tablename: str, fieldname: str) -> int:\n \"\"\"Drops (deletes) a column from an existing table.\"\"\"\n sql = \"ALTER TABLE {} DROP COLUMN {}\".format(tablename, fieldname)\n log.info(sql)\n return self.db_exec_literal(sql)": 6069, "def _check_limit(self):\n \"\"\"Intenal method: check if current cache size exceeds maximum cache\n size and pop the oldest item in this case\"\"\"\n\n # First compress\n self._compress()\n\n # Then check the max size\n if len(self._store) >= self._max_size:\n self._store.popitem(last=False)": 6070, "def codes_get_size(handle, key):\n # type: (cffi.FFI.CData, str) -> int\n \"\"\"\n Get the number of coded value from a key.\n If several keys of the same name are present, the total sum is returned.\n\n :param bytes key: the keyword to get the size of\n\n :rtype: int\n \"\"\"\n size = ffi.new('size_t *')\n _codes_get_size(handle, key.encode(ENC), size)\n return size[0]": 6071, "def remove_namespaces(root):\n \"\"\"Call this on an lxml.etree document to remove all namespaces\"\"\"\n for elem in root.getiterator():\n if not hasattr(elem.tag, 'find'):\n continue\n\n i = elem.tag.find('}')\n if i >= 0:\n elem.tag = elem.tag[i + 1:]\n\n objectify.deannotate(root, cleanup_namespaces=True)": 6072, "def update(self, iterable):\n \"\"\"\n Return a new PSet with elements in iterable added\n\n >>> s1 = s(1, 2)\n >>> s1.update([3, 4, 4])\n pset([1, 2, 3, 4])\n \"\"\"\n e = self.evolver()\n for element in iterable:\n e.add(element)\n\n return e.persistent()": 6073, "def _exit(self, status_code):\n \"\"\"Properly kill Python process including zombie threads.\"\"\"\n # If there are active threads still running infinite loops, sys.exit\n # won't kill them but os._exit will. os._exit skips calling cleanup\n # handlers, flushing stdio buffers, etc.\n exit_func = os._exit if threading.active_count() > 1 else sys.exit\n exit_func(status_code)": 6074, "def update_kwargs(kwargs, **keyvalues):\n \"\"\"Update dict with keys and values if keys do not already exist.\n\n >>> kwargs = {'one': 1, }\n >>> update_kwargs(kwargs, one=None, two=2)\n >>> kwargs == {'one': 1, 'two': 2}\n True\n\n \"\"\"\n for key, value in keyvalues.items():\n if key not in kwargs:\n kwargs[key] = value": 6075, "def head(self) -> Any:\n \"\"\"Retrive first element in List.\"\"\"\n\n lambda_list = self._get_value()\n return lambda_list(lambda head, _: head)": 6076, "def integer_partition(size: int, nparts: int) -> Iterator[List[List[int]]]:\n \"\"\" Partition a list of integers into a list of partitions \"\"\"\n for part in algorithm_u(range(size), nparts):\n yield part": 6077, "def filter_float(n: Node, query: str) -> float:\n \"\"\"\n Filter and ensure that the returned value is of type int.\n \"\"\"\n return _scalariter2item(n, query, float)": 6078, "def lcm(num1, num2):\n \"\"\"\n Find the lowest common multiple of 2 numbers\n\n :type num1: number\n :param num1: The first number to find the lcm for\n\n :type num2: number\n :param num2: The second number to find the lcm for\n \"\"\"\n\n if num1 > num2:\n bigger = num1\n else:\n bigger = num2\n while True:\n if bigger % num1 == 0 and bigger % num2 == 0:\n return bigger\n bigger += 1": 6079, "def was_into_check(self) -> bool:\n \"\"\"\n Checks if the king of the other side is attacked. Such a position is not\n valid and could only be reached by an illegal move.\n \"\"\"\n king = self.king(not self.turn)\n return king is not None and self.is_attacked_by(self.turn, king)": 6080, "def find_unit_clause(clauses, model):\n \"\"\"Find a forced assignment if possible from a clause with only 1\n variable not bound in the model.\n >>> find_unit_clause([A|B|C, B|~C, ~A|~B], {A:True})\n (B, False)\n \"\"\"\n for clause in clauses:\n P, value = unit_clause_assign(clause, model)\n if P: return P, value\n return None, None": 6081, "def get_now_utc_notz_datetime() -> datetime.datetime:\n \"\"\"\n Get the UTC time now, but with no timezone information,\n in :class:`datetime.datetime` format.\n \"\"\"\n now = datetime.datetime.utcnow()\n return now.replace(tzinfo=None)": 6082, "def make_dep_graph(depender):\n\t\"\"\"Returns a digraph string fragment based on the passed-in module\n\t\"\"\"\n\tshutit_global.shutit_global_object.yield_to_draw()\n\tdigraph = ''\n\tfor dependee_id in depender.depends_on:\n\t\tdigraph = (digraph + '\"' + depender.module_id + '\"->\"' + dependee_id + '\";\\n')\n\treturn digraph": 6083, "def from_uuid(value: uuid.UUID) -> ulid.ULID:\n \"\"\"\n Create a new :class:`~ulid.ulid.ULID` instance from the given :class:`~uuid.UUID` value.\n\n :param value: UUIDv4 value\n :type value: :class:`~uuid.UUID`\n :return: ULID from UUID value\n :rtype: :class:`~ulid.ulid.ULID`\n \"\"\"\n return ulid.ULID(value.bytes)": 6084, "def make_indices_to_labels(labels: Set[str]) -> Dict[int, str]:\n \"\"\" Creates a mapping from indices to labels. \"\"\"\n\n return {index: label for index, label in\n enumerate([\"pad\"] + sorted(list(labels)))}": 6085, "def get_terminal_width():\n \"\"\" -> #int width of the terminal window \"\"\"\n # http://www.brandonrubin.me/2014/03/18/python-snippet-get-terminal-width/\n command = ['tput', 'cols']\n try:\n width = int(subprocess.check_output(command))\n except OSError as e:\n print(\n \"Invalid Command '{0}': exit status ({1})\".format(\n command[0], e.errno))\n except subprocess.CalledProcessError as e:\n print(\n \"'{0}' returned non-zero exit status: ({1})\".format(\n command, e.returncode))\n else:\n return width": 6086, "def flush(self):\n \"\"\"\n Ensure all logging output has been flushed\n \"\"\"\n if len(self._buffer) > 0:\n self.logger.log(self.level, self._buffer)\n self._buffer = str()": 6087, "def assert_or_raise(stmt: bool, exception: Exception,\n *exception_args, **exception_kwargs) -> None:\n \"\"\"\n If the statement is false, raise the given exception.\n \"\"\"\n if not stmt:\n raise exception(*exception_args, **exception_kwargs)": 6088, "def columns_equal(a: Column, b: Column) -> bool:\n \"\"\"\n Are two SQLAlchemy columns are equal? Checks based on:\n\n - column ``name``\n - column ``type`` (see :func:`column_types_equal`)\n - ``nullable``\n \"\"\"\n return (\n a.name == b.name and\n column_types_equal(a.type, b.type) and\n a.nullable == b.nullable\n )": 6089, "def factors(n):\n \"\"\"\n Computes all the integer factors of the number `n`\n\n Example:\n >>> # ENABLE_DOCTEST\n >>> from utool.util_alg import * # NOQA\n >>> import utool as ut\n >>> result = sorted(ut.factors(10))\n >>> print(result)\n [1, 2, 5, 10]\n\n References:\n http://stackoverflow.com/questions/6800193/finding-all-the-factors\n \"\"\"\n return set(reduce(list.__add__,\n ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))": 6090, "def get_property_as_float(self, name: str) -> float:\n \"\"\"Return the value of a float property.\n\n :return: The property value (float).\n\n Raises exception if property with name doesn't exist.\n\n .. versionadded:: 1.0\n\n Scriptable: Yes\n \"\"\"\n return float(self.__instrument.get_property(name))": 6091, "def rollapply(data, window, fn):\n \"\"\"\n Apply a function fn over a rolling window of size window.\n\n Args:\n * data (Series or DataFrame): Series or DataFrame\n * window (int): Window size\n * fn (function): Function to apply over the rolling window.\n For a series, the return value is expected to be a single\n number. For a DataFrame, it shuold return a new row.\n\n Returns:\n * Object of same dimensions as data\n \"\"\"\n res = data.copy()\n res[:] = np.nan\n n = len(data)\n\n if window > n:\n return res\n\n for i in range(window - 1, n):\n res.iloc[i] = fn(data.iloc[i - window + 1:i + 1])\n\n return res": 6092, "def clear(self) -> None:\n \"\"\"Resets all headers and content for this response.\"\"\"\n self._headers = httputil.HTTPHeaders(\n {\n \"Server\": \"TornadoServer/%s\" % tornado.version,\n \"Content-Type\": \"text/html; charset=UTF-8\",\n \"Date\": httputil.format_timestamp(time.time()),\n }\n )\n self.set_default_headers()\n self._write_buffer = [] # type: List[bytes]\n self._status_code = 200\n self._reason = httputil.responses[200]": 6093, "def is_closing(self) -> bool:\n \"\"\"Return ``True`` if this connection is closing.\n\n The connection is considered closing if either side has\n initiated its closing handshake or if the stream has been\n shut down uncleanly.\n \"\"\"\n return self.stream.closed() or self.client_terminated or self.server_terminated": 6094, "def DeleteLog() -> None:\n \"\"\"Delete log file.\"\"\"\n if os.path.exists(Logger.FileName):\n os.remove(Logger.FileName)": 6095, "def copy_session(session: requests.Session) -> requests.Session:\n \"\"\"Duplicates a requests.Session.\"\"\"\n new = requests.Session()\n new.cookies = requests.utils.cookiejar_from_dict(requests.utils.dict_from_cookiejar(session.cookies))\n new.headers = session.headers.copy()\n return new": 6096, "def __getattr__(self, item: str) -> Callable:\n \"\"\"Get a callable that sends the actual API request internally.\"\"\"\n return functools.partial(self.call_action, item)": 6097, "def calculate_single_tanimoto_set_distances(target: Iterable[X], dict_of_sets: Mapping[Y, Set[X]]) -> Mapping[Y, float]:\n \"\"\"Return a dictionary of distances keyed by the keys in the given dict.\n\n Distances are calculated based on pairwise tanimoto similarity of the sets contained\n\n :param set target: A set\n :param dict_of_sets: A dict of {x: set of y}\n :type dict_of_sets: dict\n :return: A similarity dicationary based on the set overlap (tanimoto) score between the target set and the sets in\n dos\n :rtype: dict\n \"\"\"\n target_set = set(target)\n\n return {\n k: tanimoto_set_similarity(target_set, s)\n for k, s in dict_of_sets.items()\n }": 6098, "def quaternion_imag(quaternion):\n \"\"\"Return imaginary part of quaternion.\n\n >>> quaternion_imag([3, 0, 1, 2])\n array([ 0., 1., 2.])\n\n \"\"\"\n return numpy.array(quaternion[1:4], dtype=numpy.float64, copy=True)": 6099, "def access_token(self):\n \"\"\" WeChat access token \"\"\"\n access_token = self.session.get(self.access_token_key)\n if access_token:\n if not self.expires_at:\n # user provided access_token, just return it\n return access_token\n\n timestamp = time.time()\n if self.expires_at - timestamp > 60:\n return access_token\n\n self.fetch_access_token()\n return self.session.get(self.access_token_key)": 6100, "def join_states(*states: State) -> State:\n \"\"\"Join two state vectors into a larger qubit state\"\"\"\n vectors = [ket.vec for ket in states]\n vec = reduce(outer_product, vectors)\n return State(vec.tensor, vec.qubits)": 6101, "def blk_coverage_1d(blk, size):\n \"\"\"Return the part of a 1d array covered by a block.\n\n :param blk: size of the 1d block\n :param size: size of the 1d a image\n :return: a tuple of size covered and remaining size\n\n Example:\n\n >>> blk_coverage_1d(7, 100)\n (98, 2)\n\n \"\"\"\n rem = size % blk\n maxpix = size - rem\n return maxpix, rem": 6102, "def header_status(header):\n \"\"\"Parse HTTP status line, return status (int) and reason.\"\"\"\n status_line = header[:header.find('\\r')]\n # 'HTTP/1.1 200 OK' -> (200, 'OK')\n fields = status_line.split(None, 2)\n return int(fields[1]), fields[2]": 6103, "def percent_of(percent, whole):\n \"\"\"Calculates the value of a percent of a number\n ie: 5% of 20 is what --> 1\n \n Args:\n percent (float): The percent of a number\n whole (float): The whole of the number\n \n Returns:\n float: The value of a percent\n \n Example:\n >>> percent_of(25, 100)\n 25.0\n >>> percent_of(5, 20)\n 1.0\n \n \"\"\"\n percent = float(percent)\n whole = float(whole)\n return (percent * whole) / 100": 6104, "def guess_mimetype(filename):\n \"\"\"Guesses the mimetype of a file based on the given ``filename``.\n\n .. code-block:: python\n\n >>> guess_mimetype('example.txt')\n 'text/plain'\n >>> guess_mimetype('/foo/bar/example')\n 'application/octet-stream'\n\n Parameters\n ----------\n filename : str\n The file name or path for which the mimetype is to be guessed\n \"\"\"\n fn = os.path.basename(filename)\n return mimetypes.guess_type(fn)[0] or 'application/octet-stream'": 6105, "def get_tokens(line: str) -> Iterator[str]:\n \"\"\"\n Yields tokens from input string.\n\n :param line: Input string.\n :return: Iterator over tokens.\n \"\"\"\n for token in line.rstrip().split():\n if len(token) > 0:\n yield token": 6106, "def getElementByWdomId(id: str) -> Optional[WebEventTarget]:\n \"\"\"Get element with ``wdom_id``.\"\"\"\n if not id:\n return None\n elif id == 'document':\n return get_document()\n elif id == 'window':\n return get_document().defaultView\n elm = WdomElement._elements_with_wdom_id.get(id)\n return elm": 6107, "def viewport_to_screen_space(framebuffer_size: vec2, point: vec4) -> vec2:\n \"\"\"Transform point in viewport space to screen space.\"\"\"\n return (framebuffer_size * point.xy) / point.w": 6108, "def datetime_is_iso(date_str):\n \"\"\"Attempts to parse a date formatted in ISO 8601 format\"\"\"\n try:\n if len(date_str) > 10:\n dt = isodate.parse_datetime(date_str)\n else:\n dt = isodate.parse_date(date_str)\n return True, []\n except: # Any error qualifies as not ISO format\n return False, ['Datetime provided is not in a valid ISO 8601 format']": 6109, "def index_exists(self, table: str, indexname: str) -> bool:\n \"\"\"Does an index exist? (Specific to MySQL.)\"\"\"\n # MySQL:\n sql = (\"SELECT COUNT(*) FROM information_schema.statistics\"\n \" WHERE table_name=? AND index_name=?\")\n row = self.fetchone(sql, table, indexname)\n return True if row[0] >= 1 else False": 6110, "def moving_average(arr: np.ndarray, n: int = 3) -> np.ndarray:\n \"\"\" Calculate the moving overage over an array.\n\n Algorithm from: https://stackoverflow.com/a/14314054\n\n Args:\n arr (np.ndarray): Array over which to calculate the moving average.\n n (int): Number of elements over which to calculate the moving average. Default: 3\n Returns:\n np.ndarray: Moving average calculated over n.\n \"\"\"\n ret = np.cumsum(arr, dtype=float)\n ret[n:] = ret[n:] - ret[:-n]\n return ret[n - 1:] / n": 6111, "def exclude_from(l, containing = [], equal_to = []):\n \"\"\"Exclude elements in list l containing any elements from list ex.\n Example:\n >>> l = ['bob', 'r', 'rob\\r', '\\r\\nrobert']\n >>> containing = ['\\n', '\\r']\n >>> equal_to = ['r']\n >>> exclude_from(l, containing, equal_to)\n ['bob']\n \"\"\"\n \n cont = lambda li: any(c in li for c in containing)\n eq = lambda li: any(e == li for e in equal_to)\n return [li for li in l if not (cont(li) or eq(li))]": 6112, "def to_dict(cls):\n \"\"\"Make dictionary version of enumerated class.\n\n Dictionary created this way can be used with def_num.\n\n Returns:\n A dict (name) -> number\n \"\"\"\n return dict((item.name, item.number) for item in iter(cls))": 6113, "def is_valid(cls, arg):\n \"\"\"Return True if arg is valid value for the class. If the string\n value is wrong for the enumeration, the encoding will fail.\n \"\"\"\n return (isinstance(arg, (int, long)) and (arg >= 0)) or \\\n isinstance(arg, basestring)": 6114, "def remove_links(text):\n \"\"\"\n Helper function to remove the links from the input text\n\n Args:\n text (str): A string\n\n Returns:\n str: the same text, but with any substring that matches the regex\n for a link removed and replaced with a space\n\n Example:\n >>> from tweet_parser.getter_methods.tweet_text import remove_links\n >>> text = \"lorem ipsum dolor https://twitter.com/RobotPrincessFi\"\n >>> remove_links(text)\n 'lorem ipsum dolor '\n \"\"\"\n tco_link_regex = re.compile(\"https?://t.co/[A-z0-9].*\")\n generic_link_regex = re.compile(\"(https?://)?(\\w*[.]\\w+)+([/?=&]+\\w+)*\")\n remove_tco = re.sub(tco_link_regex, \" \", text)\n remove_generic = re.sub(generic_link_regex, \" \", remove_tco)\n return remove_generic": 6115, "def trade_day(dt, cal='US'):\n \"\"\"\n Latest trading day w.r.t given dt\n\n Args:\n dt: date of reference\n cal: trading calendar\n\n Returns:\n pd.Timestamp: last trading day\n\n Examples:\n >>> trade_day('2018-12-25').strftime('%Y-%m-%d')\n '2018-12-24'\n \"\"\"\n from xone import calendar\n\n dt = pd.Timestamp(dt).date()\n return calendar.trading_dates(start=dt - pd.Timedelta('10D'), end=dt, calendar=cal)[-1]": 6116, "def numpy_to_yaml(representer: Representer, data: np.ndarray) -> Sequence[Any]:\n \"\"\" Write a numpy array to YAML.\n\n It registers the array under the tag ``!numpy_array``.\n\n Use with:\n\n .. code-block:: python\n\n >>> yaml = ruamel.yaml.YAML()\n >>> yaml.representer.add_representer(np.ndarray, yaml.numpy_to_yaml)\n\n Note:\n We cannot use ``yaml.register_class`` because it won't register the proper type.\n (It would register the type of the class, rather than of `numpy.ndarray`). Instead,\n we use the above approach to register this method explicitly with the representer.\n \"\"\"\n return representer.represent_sequence(\n \"!numpy_array\",\n data.tolist()\n )": 6117, "def is_end_of_month(self) -> bool:\n \"\"\" Checks if the date is at the end of the month \"\"\"\n end_of_month = Datum()\n # get_end_of_month(value)\n end_of_month.end_of_month()\n return self.value == end_of_month.value": 6118, "def check_valid(number, input_base=10):\n \"\"\"\n Checks if there is an invalid digit in the input number.\n\n Args:\n number: An number in the following form:\n (int, int, int, ... , '.' , int, int, int)\n (iterable container) containing positive integers of the input base\n input_base(int): The base of the input number.\n\n Returns:\n bool, True if all digits valid, else False.\n\n Examples:\n >>> check_valid((1,9,6,'.',5,1,6), 12)\n True\n >>> check_valid((8,1,15,9), 15)\n False\n \"\"\"\n for n in number:\n if n in (\".\", \"[\", \"]\"):\n continue\n elif n >= input_base:\n if n == 1 and input_base == 1:\n continue\n else:\n return False\n return True": 6119, "def upsert_multi(db, collection, object, match_params=None):\n \"\"\"\n Wrapper for pymongo.insert_many() and update_many()\n :param db: db connection\n :param collection: collection to update\n :param object: the modifications to apply\n :param match_params: a query that matches the documents to update\n :return: ids of inserted/updated document\n \"\"\"\n if isinstance(object, list) and len(object) > 0:\n return str(db[collection].insert_many(object).inserted_ids)\n elif isinstance(object, dict):\n return str(db[collection].update_many(match_params, {\"$set\": object}, upsert=False).upserted_id)": 6120, "def call_fset(self, obj, value) -> None:\n \"\"\"Store the given custom value and call the setter function.\"\"\"\n vars(obj)[self.name] = self.fset(obj, value)": 6121, "def src2ast(src: str) -> Expression:\n \"\"\"Return ast.Expression created from source code given in `src`.\"\"\"\n try:\n return ast.parse(src, mode='eval')\n except SyntaxError:\n raise ValueError(\"Not a valid expression.\") from None": 6122, "def put(self, endpoint: str, **kwargs) -> dict:\n \"\"\"HTTP PUT operation to API endpoint.\"\"\"\n\n return self._request('PUT', endpoint, **kwargs)": 6123, "def signed_distance(mesh, points):\n \"\"\"\n Find the signed distance from a mesh to a list of points.\n\n * Points OUTSIDE the mesh will have NEGATIVE distance\n * Points within tol.merge of the surface will have POSITIVE distance\n * Points INSIDE the mesh will have POSITIVE distance\n\n Parameters\n -----------\n mesh : Trimesh object\n points : (n,3) float, list of points in space\n\n Returns\n ----------\n signed_distance : (n,3) float, signed distance from point to mesh\n \"\"\"\n # make sure we have a numpy array\n points = np.asanyarray(points, dtype=np.float64)\n\n # find the closest point on the mesh to the queried points\n closest, distance, triangle_id = closest_point(mesh, points)\n\n # we only care about nonzero distances\n nonzero = distance > tol.merge\n\n if not nonzero.any():\n return distance\n\n inside = mesh.ray.contains_points(points[nonzero])\n sign = (inside.astype(int) * 2) - 1\n\n # apply sign to previously computed distance\n distance[nonzero] *= sign\n\n return distance": 6124, "def needs_check(self):\n \"\"\"\n Check if enough time has elapsed to perform a check().\n\n If this time has elapsed, a state change check through\n has_state_changed() should be performed and eventually a sync().\n\n :rtype: boolean\n \"\"\"\n if self.lastcheck is None:\n return True\n return time.time() - self.lastcheck >= self.ipchangedetection_sleep": 6125, "def get_creation_date(\n self,\n bucket: str,\n key: str,\n ) -> datetime.datetime:\n \"\"\"\n Retrieves the creation date for a given key in a given bucket.\n :param bucket: the bucket the object resides in.\n :param key: the key of the object for which the creation date is being retrieved.\n :return: the creation date\n \"\"\"\n blob_obj = self._get_blob_obj(bucket, key)\n return blob_obj.time_created": 6126, "def clip_to_seconds(m: Union[int, pd.Series]) -> Union[int, pd.Series]:\n \"\"\"Clips UTC datetime in nanoseconds to seconds.\"\"\"\n return m // pd.Timedelta(1, unit='s').value": 6127, "def setlocale(name):\n \"\"\"\n Context manager with threading lock for set locale on enter, and set it\n back to original state on exit.\n\n ::\n\n >>> with setlocale(\"C\"):\n ... ...\n \"\"\"\n with LOCALE_LOCK:\n old_locale = locale.setlocale(locale.LC_ALL)\n try:\n yield locale.setlocale(locale.LC_ALL, name)\n finally:\n locale.setlocale(locale.LC_ALL, old_locale)": 6128, "def to_javascript_(self, table_name: str=\"data\") -> str:\n \"\"\"Convert the main dataframe to javascript code\n\n :param table_name: javascript variable name, defaults to \"data\"\n :param table_name: str, optional\n :return: a javascript constant with the data\n :rtype: str\n\n :example: ``ds.to_javastript_(\"myconst\")``\n \"\"\"\n try:\n renderer = pytablewriter.JavaScriptTableWriter\n data = self._build_export(renderer, table_name)\n return data\n except Exception as e:\n self.err(e, \"Can not convert data to javascript code\")": 6129, "def availability_pdf() -> bool:\n \"\"\"\n Is a PDF-to-text tool available?\n \"\"\"\n pdftotext = tools['pdftotext']\n if pdftotext:\n return True\n elif pdfminer:\n log.warning(\"PDF conversion: pdftotext missing; \"\n \"using pdfminer (less efficient)\")\n return True\n else:\n return False": 6130, "def build(ctx):\n \"\"\"Build documentation as HTML.\n\n The build HTML site is located in the ``doc/_build/html`` directory\n of the package.\n \"\"\"\n return_code = run_sphinx(ctx.obj['root_dir'])\n if return_code > 0:\n sys.exit(return_code)": 6131, "def dictlist_replace(dict_list: Iterable[Dict], key: str, value: Any) -> None:\n \"\"\"\n Process an iterable of dictionaries. For each dictionary ``d``, change\n (in place) ``d[key]`` to ``value``.\n \"\"\"\n for d in dict_list:\n d[key] = value": 6132, "def get_account_id_by_fullname(self, fullname: str) -> str:\n \"\"\" Locates the account by fullname \"\"\"\n account = self.get_by_fullname(fullname)\n return account.guid": 6133, "def isFull(self):\n \"\"\"\n Returns True if the response buffer is full, and False otherwise.\n The buffer is full if either (1) the number of items in the value\n list is >= pageSize or (2) the total length of the serialised\n elements in the page is >= maxBufferSize.\n\n If page_size or max_response_length were not set in the request\n then they're not checked.\n \"\"\"\n return (\n (self._pageSize > 0 and self._numElements >= self._pageSize) or\n (self._bufferSize >= self._maxBufferSize)\n )": 6134, "def command(self, cmd, *args):\n \"\"\"\n Sends a command and an (optional) sequence of arguments through to the\n delegated serial interface. Note that the arguments are passed through\n as data.\n \"\"\"\n self._serial_interface.command(cmd)\n if len(args) > 0:\n self._serial_interface.data(list(args))": 6135, "def timeit (func, log, limit):\n \"\"\"Print execution time of the function. For quick'n'dirty profiling.\"\"\"\n\n def newfunc (*args, **kwargs):\n \"\"\"Execute function and print execution time.\"\"\"\n t = time.time()\n res = func(*args, **kwargs)\n duration = time.time() - t\n if duration > limit:\n print(func.__name__, \"took %0.2f seconds\" % duration, file=log)\n print(args, file=log)\n print(kwargs, file=log)\n return res\n return update_func_meta(newfunc, func)": 6136, "def date_to_datetime(d):\n \"\"\"\n >>> date_to_datetime(date(2000, 1, 2))\n datetime.datetime(2000, 1, 2, 0, 0)\n >>> date_to_datetime(datetime(2000, 1, 2, 3, 4, 5))\n datetime.datetime(2000, 1, 2, 3, 4, 5)\n \"\"\"\n if not isinstance(d, datetime):\n d = datetime.combine(d, datetime.min.time())\n return d": 6137, "def quaternion_imag(quaternion):\n \"\"\"Return imaginary part of quaternion.\n\n >>> quaternion_imag([3, 0, 1, 2])\n array([0., 1., 2.])\n\n \"\"\"\n return np.array(quaternion[1:4], dtype=np.float64, copy=True)": 6138, "def zip_with_index(rdd):\n \"\"\"\n Alternate version of Spark's zipWithIndex that eagerly returns count.\n \"\"\"\n starts = [0]\n if rdd.getNumPartitions() > 1:\n nums = rdd.mapPartitions(lambda it: [sum(1 for _ in it)]).collect()\n count = sum(nums)\n for i in range(len(nums) - 1):\n starts.append(starts[-1] + nums[i])\n else:\n count = rdd.count()\n\n def func(k, it):\n for i, v in enumerate(it, starts[k]):\n yield v, i\n\n return count, rdd.mapPartitionsWithIndex(func)": 6139, "def console_get_background_flag(con: tcod.console.Console) -> int:\n \"\"\"Return this consoles current blend mode.\n\n Args:\n con (Console): Any Console instance.\n\n .. deprecated:: 8.5\n Check :any:`Console.default_bg_blend` instead.\n \"\"\"\n return int(lib.TCOD_console_get_background_flag(_console(con)))": 6140, "def load_yaml(file):\n \"\"\"If pyyaml > 5.1 use full_load to avoid warning\"\"\"\n if hasattr(yaml, \"full_load\"):\n return yaml.full_load(file)\n else:\n return yaml.load(file)": 6141, "def iter_fields(self, schema: Schema) -> Iterable[Tuple[str, Field]]:\n \"\"\"\n Iterate through marshmallow schema fields.\n\n Generates: name, field pairs\n\n \"\"\"\n for name in sorted(schema.fields.keys()):\n field = schema.fields[name]\n yield field.dump_to or name, field": 6142, "def random_name_gen(size=6):\n \"\"\"Generate a random python attribute name.\"\"\"\n\n return ''.join(\n [random.choice(string.ascii_uppercase)] +\n [random.choice(string.ascii_uppercase + string.digits) for i in range(size - 1)]\n ) if size > 0 else ''": 6143, "def urljoin(*args):\n \"\"\"\n Joins given arguments into a url, removing duplicate slashes\n Thanks http://stackoverflow.com/a/11326230/1267398\n\n >>> urljoin('/lol', '///lol', '/lol//')\n '/lol/lol/lol'\n \"\"\"\n value = \"/\".join(map(lambda x: str(x).strip('/'), args))\n return \"/{}\".format(value)": 6144, "def stdev(self):\n \"\"\" -> #float :func:numpy.std of the timing intervals \"\"\"\n return round(np.std(self.array), self.precision)\\\n if len(self.array) else None": 6145, "def space_list(line: str) -> List[int]:\n \"\"\"\n Given a string, return a list of index positions where a blank space occurs.\n\n :param line:\n :return:\n\n >>> space_list(\" abc \")\n [0, 1, 2, 3, 7]\n \"\"\"\n spaces = []\n for idx, car in enumerate(list(line)):\n if car == \" \":\n spaces.append(idx)\n return spaces": 6146, "def get_property(self, name):\n # type: (str) -> object\n \"\"\"\n Retrieves a framework or system property. As framework properties don't\n change while it's running, this method don't need to be protected.\n\n :param name: The property name\n \"\"\"\n with self.__properties_lock:\n return self.__properties.get(name, os.getenv(name))": 6147, "def to_bool(value):\n # type: (Any) -> bool\n \"\"\"\n Convert a value into a bool but handle \"truthy\" strings eg, yes, true, ok, y\n \"\"\"\n if isinstance(value, _compat.string_types):\n return value.upper() in ('Y', 'YES', 'T', 'TRUE', '1', 'OK')\n return bool(value)": 6148, "def find_editor() -> str:\n \"\"\"Find a reasonable editor to use by default for the system that the cmd2 application is running on.\"\"\"\n editor = os.environ.get('EDITOR')\n if not editor:\n if sys.platform[:3] == 'win':\n editor = 'notepad'\n else:\n # Favor command-line editors first so we don't leave the terminal to edit\n for editor in ['vim', 'vi', 'emacs', 'nano', 'pico', 'gedit', 'kate', 'subl', 'geany', 'atom']:\n if which(editor):\n break\n return editor": 6149, "def get_pixel(framebuf, x, y):\n \"\"\"Get the color of a given pixel\"\"\"\n index = (y >> 3) * framebuf.stride + x\n offset = y & 0x07\n return (framebuf.buf[index] >> offset) & 0x01": 6150, "def is_sqlatype_text_over_one_char(\n coltype: Union[TypeEngine, VisitableType]) -> bool:\n \"\"\"\n Is the SQLAlchemy column type a string type that's more than one character\n long?\n \"\"\"\n coltype = _coltype_to_typeengine(coltype)\n return is_sqlatype_text_of_length_at_least(coltype, 2)": 6151, "def is_string_dtype(arr_or_dtype):\n \"\"\"\n Check whether the provided array or dtype is of the string dtype.\n\n Parameters\n ----------\n arr_or_dtype : array-like\n The array or dtype to check.\n\n Returns\n -------\n boolean\n Whether or not the array or dtype is of the string dtype.\n\n Examples\n --------\n >>> is_string_dtype(str)\n True\n >>> is_string_dtype(object)\n True\n >>> is_string_dtype(int)\n False\n >>>\n >>> is_string_dtype(np.array(['a', 'b']))\n True\n >>> is_string_dtype(pd.Series([1, 2]))\n False\n \"\"\"\n\n # TODO: gh-15585: consider making the checks stricter.\n def condition(dtype):\n return dtype.kind in ('O', 'S', 'U') and not is_period_dtype(dtype)\n return _is_dtype(arr_or_dtype, condition)": 6152, "def expired(self):\n \"\"\"Boolean property if this action has expired\n \"\"\"\n if self.timeout is None:\n return False\n\n return monotonic() - self.start_time > self.timeout": 6153, "def _extension(modpath: str) -> setuptools.Extension:\n \"\"\"Make setuptools.Extension.\"\"\"\n return setuptools.Extension(modpath, [modpath.replace(\".\", \"/\") + \".py\"])": 6154, "def _skip(self, cnt):\n \"\"\"Read and discard data\"\"\"\n while cnt > 0:\n if cnt > 8192:\n buf = self.read(8192)\n else:\n buf = self.read(cnt)\n if not buf:\n break\n cnt -= len(buf)": 6155, "def validate(request: Union[Dict, List], schema: dict) -> Union[Dict, List]:\n \"\"\"\n Wraps jsonschema.validate, returning the same object passed in.\n\n Args:\n request: The deserialized-from-json request.\n schema: The jsonschema schema to validate against.\n\n Raises:\n jsonschema.ValidationError\n \"\"\"\n jsonschema_validate(request, schema)\n return request": 6156, "def format_exp_floats(decimals):\n \"\"\"\n sometimes the exp. column can be too large\n \"\"\"\n threshold = 10 ** 5\n return (\n lambda n: \"{:.{prec}e}\".format(n, prec=decimals) if n > threshold else \"{:4.{prec}f}\".format(n, prec=decimals)\n )": 6157, "def login(self, user: str, passwd: str) -> None:\n \"\"\"Log in to instagram with given username and password and internally store session object.\n\n :raises InvalidArgumentException: If the provided username does not exist.\n :raises BadCredentialsException: If the provided password is wrong.\n :raises ConnectionException: If connection to Instagram failed.\n :raises TwoFactorAuthRequiredException: First step of 2FA login done, now call :meth:`Instaloader.two_factor_login`.\"\"\"\n self.context.login(user, passwd)": 6158, "def remove_leading_zeros(num: str) -> str:\n \"\"\"\n Strips zeros while handling -, M, and empty strings\n \"\"\"\n if not num:\n return num\n if num.startswith('M'):\n ret = 'M' + num[1:].lstrip('0')\n elif num.startswith('-'):\n ret = '-' + num[1:].lstrip('0')\n else:\n ret = num.lstrip('0')\n return '0' if ret in ('', 'M', '-') else ret": 6159, "def increment_frame(self):\n \"\"\"Increment a frame of the animation.\"\"\"\n self.current_frame += 1\n\n if self.current_frame >= self.end_frame:\n # Wrap back to the beginning of the animation.\n self.current_frame = 0": 6160, "def singularize(word):\n \"\"\"\n Return the singular form of a word, the reverse of :func:`pluralize`.\n\n Examples::\n\n >>> singularize(\"posts\")\n \"post\"\n >>> singularize(\"octopi\")\n \"octopus\"\n >>> singularize(\"sheep\")\n \"sheep\"\n >>> singularize(\"word\")\n \"word\"\n >>> singularize(\"CamelOctopi\")\n \"CamelOctopus\"\n\n \"\"\"\n for inflection in UNCOUNTABLES:\n if re.search(r'(?i)\\b(%s)\\Z' % inflection, word):\n return word\n\n for rule, replacement in SINGULARS:\n if re.search(rule, word):\n return re.sub(rule, replacement, word)\n return word": 6161, "def get_environment_info() -> dict:\n \"\"\"\n Information about Cauldron and its Python interpreter.\n\n :return:\n A dictionary containing information about the Cauldron and its\n Python environment. This information is useful when providing feedback\n and bug reports.\n \"\"\"\n data = _environ.systems.get_system_data()\n data['cauldron'] = _environ.package_settings.copy()\n return data": 6162, "def pruning(self, X, y, cost_mat):\n \"\"\" Function that prune the decision tree.\n\n Parameters\n ----------\n\n X : array-like of shape = [n_samples, n_features]\n The input samples.\n\n y_true : array indicator matrix\n Ground truth (correct) labels.\n\n cost_mat : array-like of shape = [n_samples, 4]\n Cost matrix of the classification problem\n Where the columns represents the costs of: false positives, false negatives,\n true positives and true negatives, for each example.\n\n \"\"\"\n self.tree_.tree_pruned = copy.deepcopy(self.tree_.tree)\n if self.tree_.n_nodes > 0:\n self._pruning(X, y, cost_mat)\n nodes_pruned = self._nodes(self.tree_.tree_pruned)\n self.tree_.n_nodes_pruned = len(nodes_pruned)": 6163, "def content_type(self) -> ContentType:\n \"\"\"Return receiver's content type.\"\"\"\n return self._ctype if self._ctype else self.parent.content_type()": 6164, "def fix_missing(df, col, name, na_dict):\n \"\"\" Fill missing data in a column of df with the median, and add a {name}_na column\n which specifies if the data was missing.\n Parameters:\n -----------\n df: The data frame that will be changed.\n col: The column of data to fix by filling in missing data.\n name: The name of the new filled column in df.\n na_dict: A dictionary of values to create na's of and the value to insert. If\n name is not a key of na_dict the median will fill any missing data. Also\n if name is not a key of na_dict and there is no missing data in col, then\n no {name}_na column is not created.\n Examples:\n ---------\n >>> df = pd.DataFrame({'col1' : [1, np.NaN, 3], 'col2' : [5, 2, 2]})\n >>> df\n col1 col2\n 0 1 5\n 1 nan 2\n 2 3 2\n >>> fix_missing(df, df['col1'], 'col1', {})\n >>> df\n col1 col2 col1_na\n 0 1 5 False\n 1 2 2 True\n 2 3 2 False\n >>> df = pd.DataFrame({'col1' : [1, np.NaN, 3], 'col2' : [5, 2, 2]})\n >>> df\n col1 col2\n 0 1 5\n 1 nan 2\n 2 3 2\n >>> fix_missing(df, df['col2'], 'col2', {})\n >>> df\n col1 col2\n 0 1 5\n 1 nan 2\n 2 3 2\n >>> df = pd.DataFrame({'col1' : [1, np.NaN, 3], 'col2' : [5, 2, 2]})\n >>> df\n col1 col2\n 0 1 5\n 1 nan 2\n 2 3 2\n >>> fix_missing(df, df['col1'], 'col1', {'col1' : 500})\n >>> df\n col1 col2 col1_na\n 0 1 5 False\n 1 500 2 True\n 2 3 2 False\n \"\"\"\n if is_numeric_dtype(col):\n if pd.isnull(col).sum() or (name in na_dict):\n df[name+'_na'] = pd.isnull(col)\n filler = na_dict[name] if name in na_dict else col.median()\n df[name] = col.fillna(filler)\n na_dict[name] = filler\n return na_dict": 6165, "def same(*values):\n \"\"\"\n Check if all values in a sequence are equal.\n\n Returns True on empty sequences.\n\n Examples\n --------\n >>> same(1, 1, 1, 1)\n True\n >>> same(1, 2, 1)\n False\n >>> same()\n True\n \"\"\"\n if not values:\n return True\n first, rest = values[0], values[1:]\n return all(value == first for value in rest)": 6166, "def trunc(obj, max, left=0):\n \"\"\"\n Convert `obj` to string, eliminate newlines and truncate the string to `max`\n characters. If there are more characters in the string add ``...`` to the\n string. With `left=True`, the string can be truncated at the beginning.\n\n @note: Does not catch exceptions when converting `obj` to string with `str`.\n\n >>> trunc('This is a long text.', 8)\n This ...\n >>> trunc('This is a long text.', 8, left)\n ...text.\n \"\"\"\n s = str(obj)\n s = s.replace('\\n', '|')\n if len(s) > max:\n if left:\n return '...'+s[len(s)-max+3:]\n else:\n return s[:(max-3)]+'...'\n else:\n return s": 6167, "def remove_blank_spaces(syllables: List[str]) -> List[str]:\n \"\"\"\n Given a list of letters, remove any blank spaces or empty strings.\n\n :param syllables:\n :return:\n\n >>> remove_blank_spaces(['', 'a', ' ', 'b', ' ', 'c', ''])\n ['a', 'b', 'c']\n \"\"\"\n cleaned = []\n for syl in syllables:\n if syl == \" \" or syl == '':\n pass\n else:\n cleaned.append(syl)\n return cleaned": 6168, "def dict_to_ddb(item):\n # type: (Dict[str, Any]) -> Dict[str, Any]\n # TODO: narrow these types down\n \"\"\"Converts a native Python dictionary to a raw DynamoDB item.\n\n :param dict item: Native item\n :returns: DynamoDB item\n :rtype: dict\n \"\"\"\n serializer = TypeSerializer()\n return {key: serializer.serialize(value) for key, value in item.items()}": 6169, "def input(prompt=\"\"):\n\t\"\"\"input([prompt]) -> value\n\nEquivalent to eval(raw_input(prompt)).\"\"\"\n\t\n\tstring = stdin_decode(raw_input(prompt))\n\t\n\tcaller_frame = sys._getframe(1)\n\tglobals = caller_frame.f_globals\n\tlocals = caller_frame.f_locals\n\t\n\treturn eval(string, globals, locals)": 6170, "def convert_to_int(x: Any, default: int = None) -> int:\n \"\"\"\n Transforms its input into an integer, or returns ``default``.\n \"\"\"\n try:\n return int(x)\n except (TypeError, ValueError):\n return default": 6171, "def filter_bool(n: Node, query: str) -> bool:\n \"\"\"\n Filter and ensure that the returned value is of type bool.\n \"\"\"\n return _scalariter2item(n, query, bool)": 6172, "def page_align_content_length(length):\n # type: (int) -> int\n \"\"\"Compute page boundary alignment\n :param int length: content length\n :rtype: int\n :return: aligned byte boundary\n \"\"\"\n mod = length % _PAGEBLOB_BOUNDARY\n if mod != 0:\n return length + (_PAGEBLOB_BOUNDARY - mod)\n return length": 6173, "def getVectorFromType(self, dtype) -> Union[bool, None, Tuple[int, int]]:\n \"\"\"\n :see: doc of method on parent class\n \"\"\"\n if dtype == BIT:\n return False\n elif isinstance(dtype, Bits):\n return [evalParam(dtype.width) - 1, hInt(0)]": 6174, "def use_kwargs(self, *args, **kwargs) -> typing.Callable:\n \"\"\"Decorator that injects parsed arguments into a view function or method.\n\n Receives the same arguments as `webargs.core.Parser.use_kwargs`.\n\n \"\"\"\n return super().use_kwargs(*args, **kwargs)": 6175, "def convert_camel_case_string(name: str) -> str:\n \"\"\"Convert camel case string to snake case\"\"\"\n string = re.sub(\"(.)([A-Z][a-z]+)\", r\"\\1_\\2\", name)\n return re.sub(\"([a-z0-9])([A-Z])\", r\"\\1_\\2\", string).lower()": 6176, "def distinct_permutations(iterable):\n \"\"\"Yield successive distinct permutations of the elements in *iterable*.\n\n >>> sorted(distinct_permutations([1, 0, 1]))\n [(0, 1, 1), (1, 0, 1), (1, 1, 0)]\n\n Equivalent to ``set(permutations(iterable))``, except duplicates are not\n generated and thrown away. For larger input sequences this is much more\n efficient.\n\n Duplicate permutations arise when there are duplicated elements in the\n input iterable. The number of items returned is\n `n! / (x_1! * x_2! * ... * x_n!)`, where `n` is the total number of\n items input, and each `x_i` is the count of a distinct item in the input\n sequence.\n\n \"\"\"\n def make_new_permutations(permutations, e):\n \"\"\"Internal helper function.\n The output permutations are built up by adding element *e* to the\n current *permutations* at every possible position.\n The key idea is to keep repeated elements (reverse) ordered:\n if e1 == e2 and e1 is before e2 in the iterable, then all permutations\n with e1 before e2 are ignored.\n\n \"\"\"\n for permutation in permutations:\n for j in range(len(permutation)):\n yield permutation[:j] + [e] + permutation[j:]\n if permutation[j] == e:\n break\n else:\n yield permutation + [e]\n\n permutations = [[]]\n for e in iterable:\n permutations = make_new_permutations(permutations, e)\n\n return (tuple(t) for t in permutations)": 6177, "def text_alignment(x, y):\n \"\"\"\n Align text labels based on the x- and y-axis coordinate values.\n\n This function is used for computing the appropriate alignment of the text\n label.\n\n For example, if the text is on the \"right\" side of the plot, we want it to\n be left-aligned. If the text is on the \"top\" side of the plot, we want it\n to be bottom-aligned.\n\n :param x, y: (`int` or `float`) x- and y-axis coordinate respectively.\n :returns: A 2-tuple of strings, the horizontal and vertical alignments\n respectively.\n \"\"\"\n if x == 0:\n ha = \"center\"\n elif x > 0:\n ha = \"left\"\n else:\n ha = \"right\"\n if y == 0:\n va = \"center\"\n elif y > 0:\n va = \"bottom\"\n else:\n va = \"top\"\n\n return ha, va": 6178, "def _validate_image_rank(self, img_array):\n \"\"\"\n Images must be either 2D or 3D.\n \"\"\"\n if img_array.ndim == 1 or img_array.ndim > 3:\n msg = \"{0}D imagery is not allowed.\".format(img_array.ndim)\n raise IOError(msg)": 6179, "def _isbool(string):\n \"\"\"\n >>> _isbool(True)\n True\n >>> _isbool(\"False\")\n True\n >>> _isbool(1)\n False\n \"\"\"\n return isinstance(string, _bool_type) or\\\n (isinstance(string, (_binary_type, _text_type))\n and\n string in (\"True\", \"False\"))": 6180, "def __gt__(self, other):\n \"\"\"Greater than ordering.\"\"\"\n if not isinstance(other, Key):\n return NotImplemented\n return self.__tuple() > other.__tuple()": 6181, "def strictly_positive_int_or_none(val):\n \"\"\"Parse `val` into either `None` or a strictly positive integer.\"\"\"\n val = positive_int_or_none(val)\n if val is None or val > 0:\n return val\n raise ValueError('\"{}\" must be strictly positive'.format(val))": 6182, "def sections(self) -> list:\n \"\"\"List of sections.\"\"\"\n self.config.read(self.filepath)\n return self.config.sections()": 6183, "def assert_raises(ex_type, func, *args, **kwargs):\n r\"\"\"\n Checks that a function raises an error when given specific arguments.\n\n Args:\n ex_type (Exception): exception type\n func (callable): live python function\n\n CommandLine:\n python -m utool.util_assert assert_raises --show\n\n Example:\n >>> # ENABLE_DOCTEST\n >>> from utool.util_assert import * # NOQA\n >>> import utool as ut\n >>> ex_type = AssertionError\n >>> func = len\n >>> # Check that this raises an error when something else does not\n >>> assert_raises(ex_type, assert_raises, ex_type, func, [])\n >>> # Check this does not raise an error when something else does\n >>> assert_raises(ValueError, [].index, 0)\n \"\"\"\n try:\n func(*args, **kwargs)\n except Exception as ex:\n assert isinstance(ex, ex_type), (\n 'Raised %r but type should have been %r' % (ex, ex_type))\n return True\n else:\n raise AssertionError('No error was raised')": 6184, "def _numbers_units(N):\n \"\"\"\n >>> _numbers_units(45)\n '123456789012345678901234567890123456789012345'\n \"\"\"\n lst = range(1, N + 1)\n return \"\".join(list(map(lambda i: str(i % 10), lst)))": 6185, "def insert_ordered(value, array):\n \"\"\"\n This will insert the value into the array, keeping it sorted, and returning the\n index where it was inserted\n \"\"\"\n\n index = 0\n\n # search for the last array item that value is larger than\n for n in range(0,len(array)):\n if value >= array[n]: index = n+1\n\n array.insert(index, value)\n return index": 6186, "def check_python_version():\n \"\"\"Check if the currently running Python version is new enough.\"\"\"\n # Required due to multiple with statements on one line\n req_version = (2, 7)\n cur_version = sys.version_info\n if cur_version >= req_version:\n print(\"Python version... %sOK%s (found %s, requires %s)\" %\n (Bcolors.OKGREEN, Bcolors.ENDC, str(platform.python_version()),\n str(req_version[0]) + \".\" + str(req_version[1])))\n else:\n print(\"Python version... %sFAIL%s (found %s, requires %s)\" %\n (Bcolors.FAIL, Bcolors.ENDC, str(cur_version),\n str(req_version)))": 6187, "def get_caller_module():\n \"\"\"\n Returns the name of the caller's module as a string.\n\n >>> get_caller_module()\n '__main__'\n \"\"\"\n stack = inspect.stack()\n assert len(stack) > 1\n caller = stack[2][0]\n return caller.f_globals['__name__']": 6188, "def memory_read(self, start_position: int, size: int) -> memoryview:\n \"\"\"\n Read and return a view of ``size`` bytes from memory starting at ``start_position``.\n \"\"\"\n return self._memory.read(start_position, size)": 6189, "def pluralize(word):\n \"\"\"\n Return the plural form of a word.\n\n Examples::\n\n >>> pluralize(\"post\")\n \"posts\"\n >>> pluralize(\"octopus\")\n \"octopi\"\n >>> pluralize(\"sheep\")\n \"sheep\"\n >>> pluralize(\"CamelOctopus\")\n \"CamelOctopi\"\n\n \"\"\"\n if not word or word.lower() in UNCOUNTABLES:\n return word\n else:\n for rule, replacement in PLURALS:\n if re.search(rule, word):\n return re.sub(rule, replacement, word)\n return word": 6190, "def positive_int(val):\n \"\"\"Parse `val` into a positive integer.\"\"\"\n if isinstance(val, float):\n raise ValueError('\"{}\" must not be a float'.format(val))\n val = int(val)\n if val >= 0:\n return val\n raise ValueError('\"{}\" must be positive'.format(val))": 6191, "def signed_area(coords):\n \"\"\"Return the signed area enclosed by a ring using the linear time\n algorithm. A value >= 0 indicates a counter-clockwise oriented ring.\n \"\"\"\n xs, ys = map(list, zip(*coords))\n xs.append(xs[1])\n ys.append(ys[1])\n return sum(xs[i]*(ys[i+1]-ys[i-1]) for i in range(1, len(coords)))/2.0": 6192, "def classify_fit(fqdn, result, *argl, **argd):\n \"\"\"Analyzes the result of a classification algorithm's fitting. See also\n :func:`fit` for explanation of arguments.\n \"\"\"\n if len(argl) > 2:\n #Usually fit is called with fit(machine, Xtrain, ytrain).\n yP = argl[2]\n out = _generic_fit(fqdn, result, classify_predict, yP, *argl, **argd)\n return out": 6193, "def thai_to_eng(text: str) -> str:\n \"\"\"\n Correct text in one language that is incorrectly-typed with a keyboard layout in another language. (type Thai with English keyboard)\n\n :param str text: Incorrect input (type English with Thai keyboard)\n :return: English text\n \"\"\"\n return \"\".join(\n [TH_EN_KEYB_PAIRS[ch] if (ch in TH_EN_KEYB_PAIRS) else ch for ch in text]\n )": 6194, "def months_ago(date, nb_months=1):\n \"\"\"\n Return the given `date` with `nb_months` substracted from it.\n \"\"\"\n nb_years = nb_months // 12\n nb_months = nb_months % 12\n\n month_diff = date.month - nb_months\n\n if month_diff > 0:\n new_month = month_diff\n else:\n new_month = 12 + month_diff\n nb_years += 1\n\n return date.replace(day=1, month=new_month, year=date.year - nb_years)": 6195, "def exists(self):\n \"\"\"\n Determine if any rows exist for the current query.\n\n :return: Whether the rows exist or not\n :rtype: bool\n \"\"\"\n limit = self.limit_\n\n result = self.limit(1).count() > 0\n\n self.limit(limit)\n\n return result": 6196, "def normalize_pattern(pattern):\n \"\"\"Converts backslashes in path patterns to forward slashes.\n\n Doesn't normalize regular expressions - they may contain escapes.\n \"\"\"\n if not (pattern.startswith('RE:') or pattern.startswith('!RE:')):\n pattern = _slashes.sub('/', pattern)\n if len(pattern) > 1:\n pattern = pattern.rstrip('/')\n return pattern": 6197, "def _collection_literal_to_py_ast(\n ctx: GeneratorContext, form: Iterable[LispForm]\n) -> Iterable[GeneratedPyAST]:\n \"\"\"Turn a quoted collection literal of Lisp forms into Python AST nodes.\n\n This function can only handle constant values. It does not call back into\n the generic AST generators, so only constant values will be generated down\n this path.\"\"\"\n yield from map(partial(_const_val_to_py_ast, ctx), form)": 6198, "def segment_intersection(start0, end0, start1, end1):\n r\"\"\"Determine the intersection of two line segments.\n\n Assumes each line is parametric\n\n .. math::\n\n \\begin{alignat*}{2}\n L_0(s) &= S_0 (1 - s) + E_0 s &&= S_0 + s \\Delta_0 \\\\\n L_1(t) &= S_1 (1 - t) + E_1 t &&= S_1 + t \\Delta_1.\n \\end{alignat*}\n\n To solve :math:`S_0 + s \\Delta_0 = S_1 + t \\Delta_1`, we use the\n cross product:\n\n .. math::\n\n \\left(S_0 + s \\Delta_0\\right) \\times \\Delta_1 =\n \\left(S_1 + t \\Delta_1\\right) \\times \\Delta_1 \\Longrightarrow\n s \\left(\\Delta_0 \\times \\Delta_1\\right) =\n \\left(S_1 - S_0\\right) \\times \\Delta_1.\n\n Similarly\n\n .. math::\n\n \\Delta_0 \\times \\left(S_0 + s \\Delta_0\\right) =\n \\Delta_0 \\times \\left(S_1 + t \\Delta_1\\right) \\Longrightarrow\n \\left(S_1 - S_0\\right) \\times \\Delta_0 =\n \\Delta_0 \\times \\left(S_0 - S_1\\right) =\n t \\left(\\Delta_0 \\times \\Delta_1\\right).\n\n .. note::\n\n Since our points are in :math:`\\mathbf{R}^2`, the \"traditional\"\n cross product in :math:`\\mathbf{R}^3` will always point in the\n :math:`z` direction, so in the above we mean the :math:`z`\n component of the cross product, rather than the entire vector.\n\n For example, the diagonal lines\n\n .. math::\n\n \\begin{align*}\n L_0(s) &= \\left[\\begin{array}{c} 0 \\\\ 0 \\end{array}\\right] (1 - s) +\n \\left[\\begin{array}{c} 2 \\\\ 2 \\end{array}\\right] s \\\\\n L_1(t) &= \\left[\\begin{array}{c} -1 \\\\ 2 \\end{array}\\right] (1 - t) +\n \\left[\\begin{array}{c} 1 \\\\ 0 \\end{array}\\right] t\n \\end{align*}\n\n intersect at :math:`L_0\\left(\\frac{1}{4}\\right) =\n L_1\\left(\\frac{3}{4}\\right) =\n \\frac{1}{2} \\left[\\begin{array}{c} 1 \\\\ 1 \\end{array}\\right]`.\n\n .. image:: ../images/segment_intersection1.png\n :align: center\n\n .. testsetup:: segment-intersection1, segment-intersection2\n\n import numpy as np\n from bezier._geometric_intersection import segment_intersection\n\n .. doctest:: segment-intersection1\n :options: +NORMALIZE_WHITESPACE\n\n >>> start0 = np.asfortranarray([0.0, 0.0])\n >>> end0 = np.asfortranarray([2.0, 2.0])\n >>> start1 = np.asfortranarray([-1.0, 2.0])\n >>> end1 = np.asfortranarray([1.0, 0.0])\n >>> s, t, _ = segment_intersection(start0, end0, start1, end1)\n >>> s\n 0.25\n >>> t\n 0.75\n\n .. testcleanup:: segment-intersection1\n\n import make_images\n make_images.segment_intersection1(start0, end0, start1, end1, s)\n\n Taking the parallel (but different) lines\n\n .. math::\n\n \\begin{align*}\n L_0(s) &= \\left[\\begin{array}{c} 1 \\\\ 0 \\end{array}\\right] (1 - s) +\n \\left[\\begin{array}{c} 0 \\\\ 1 \\end{array}\\right] s \\\\\n L_1(t) &= \\left[\\begin{array}{c} -1 \\\\ 3 \\end{array}\\right] (1 - t) +\n \\left[\\begin{array}{c} 3 \\\\ -1 \\end{array}\\right] t\n \\end{align*}\n\n we should be able to determine that the lines don't intersect, but\n this function is not meant for that check:\n\n .. image:: ../images/segment_intersection2.png\n :align: center\n\n .. doctest:: segment-intersection2\n :options: +NORMALIZE_WHITESPACE\n\n >>> start0 = np.asfortranarray([1.0, 0.0])\n >>> end0 = np.asfortranarray([0.0, 1.0])\n >>> start1 = np.asfortranarray([-1.0, 3.0])\n >>> end1 = np.asfortranarray([3.0, -1.0])\n >>> _, _, success = segment_intersection(start0, end0, start1, end1)\n >>> success\n False\n\n .. testcleanup:: segment-intersection2\n\n import make_images\n make_images.segment_intersection2(start0, end0, start1, end1)\n\n Instead, we use :func:`parallel_lines_parameters`:\n\n .. testsetup:: segment-intersection2-continued\n\n import numpy as np\n from bezier._geometric_intersection import parallel_lines_parameters\n\n start0 = np.asfortranarray([1.0, 0.0])\n end0 = np.asfortranarray([0.0, 1.0])\n start1 = np.asfortranarray([-1.0, 3.0])\n end1 = np.asfortranarray([3.0, -1.0])\n\n .. doctest:: segment-intersection2-continued\n\n >>> disjoint, _ = parallel_lines_parameters(start0, end0, start1, end1)\n >>> disjoint\n True\n\n .. note::\n\n There is also a Fortran implementation of this function, which\n will be used if it can be built.\n\n Args:\n start0 (numpy.ndarray): A 1D NumPy ``2``-array that is the start\n vector :math:`S_0` of the parametric line :math:`L_0(s)`.\n end0 (numpy.ndarray): A 1D NumPy ``2``-array that is the end\n vector :math:`E_0` of the parametric line :math:`L_0(s)`.\n start1 (numpy.ndarray): A 1D NumPy ``2``-array that is the start\n vector :math:`S_1` of the parametric line :math:`L_1(s)`.\n end1 (numpy.ndarray): A 1D NumPy ``2``-array that is the end\n vector :math:`E_1` of the parametric line :math:`L_1(s)`.\n\n Returns:\n Tuple[float, float, bool]: Pair of :math:`s_{\\ast}` and\n :math:`t_{\\ast}` such that the lines intersect:\n :math:`L_0\\left(s_{\\ast}\\right) = L_1\\left(t_{\\ast}\\right)` and then\n a boolean indicating if an intersection was found (i.e. if the lines\n aren't parallel).\n \"\"\"\n delta0 = end0 - start0\n delta1 = end1 - start1\n cross_d0_d1 = _helpers.cross_product(delta0, delta1)\n if cross_d0_d1 == 0.0:\n return None, None, False\n\n else:\n start_delta = start1 - start0\n s = _helpers.cross_product(start_delta, delta1) / cross_d0_d1\n t = _helpers.cross_product(start_delta, delta0) / cross_d0_d1\n return s, t, True": 6199, "def kernel(self, spread=1):\n \"\"\" This will return whatever kind of kernel we want to use.\n Must have signature (ndarray size NxM, ndarray size 1xM) -> ndarray size Nx1\n \"\"\"\n # TODO: use self.kernel_type to choose function\n\n def gaussian(data, pixel):\n return mvn.pdf(data, mean=pixel, cov=spread)\n\n return gaussian": 6200, "def getPiLambert(n):\n \"\"\"Returns a list containing first n digits of Pi\n \"\"\"\n mypi = piGenLambert()\n result = []\n if n > 0:\n result += [next(mypi) for i in range(n)]\n mypi.close()\n return result": 6201, "def _get_latest_version():\n \"\"\"Gets latest Dusty binary version using the GitHub api\"\"\"\n url = 'https://api.github.com/repos/{}/releases/latest'.format(constants.DUSTY_GITHUB_PATH)\n conn = urllib.urlopen(url)\n if conn.getcode() >= 300:\n raise RuntimeError('GitHub api returned code {}; can\\'t determine latest version. Aborting'.format(conn.getcode()))\n json_data = conn.read()\n return json.loads(json_data)['tag_name']": 6202, "def shift(self, m: Union[float, pd.Series]) -> Union[int, pd.Series]:\n \"\"\"Shifts floats so that the first 10 decimal digits are significant.\"\"\"\n out = m % 1 * self.TEN_DIGIT_MODULUS // 1\n if isinstance(out, pd.Series):\n return out.astype(int)\n return int(out)": 6203, "def kdot(x, y, K=2):\n \"\"\"Algorithm 5.10. Dot product algorithm in K-fold working precision,\n K >= 3.\n \"\"\"\n xx = x.reshape(-1, x.shape[-1])\n yy = y.reshape(y.shape[0], -1)\n\n xx = numpy.ascontiguousarray(xx)\n yy = numpy.ascontiguousarray(yy)\n\n r = _accupy.kdot_helper(xx, yy).reshape((-1,) + x.shape[:-1] + y.shape[1:])\n return ksum(r, K - 1)": 6204, "def pad(a, desiredlength):\n \"\"\"\n Pad an n-dimensional numpy array with zeros along the zero-th dimension\n so that it is the desired length. Return it unchanged if it is greater\n than or equal to the desired length\n \"\"\"\n\n if len(a) >= desiredlength:\n return a\n\n islist = isinstance(a, list)\n a = np.array(a)\n diff = desiredlength - len(a)\n shape = list(a.shape)\n shape[0] = diff\n\n padded = np.concatenate([a, np.zeros(shape, dtype=a.dtype)])\n return padded.tolist() if islist else padded": 6205, "def _darwin_current_arch(self):\n \"\"\"Add Mac OS X support.\"\"\"\n if sys.platform == \"darwin\":\n if sys.maxsize > 2 ** 32: # 64bits.\n return platform.mac_ver()[2] # Both Darwin and Python are 64bits.\n else: # Python 32 bits\n return platform.processor()": 6206, "def usetz_now():\n \"\"\"Determine current time depending on USE_TZ setting.\n\n Affects Django 1.4 and above only. if `USE_TZ = True`, then returns\n current time according to timezone, else returns current UTC time.\n\n \"\"\"\n USE_TZ = getattr(settings, 'USE_TZ', False)\n if USE_TZ and DJANGO_VERSION >= '1.4':\n return now()\n else:\n return datetime.utcnow()": 6207, "def get_codes(s: Union[str, 'ChainedBase']) -> List[str]:\n \"\"\" Grab all escape codes from a string.\n Returns a list of all escape codes.\n \"\"\"\n return codegrabpat.findall(str(s))": 6208, "def setdefault(self, name: str, default: Any=None) -> Any:\n \"\"\"Set an attribute with a default value.\"\"\"\n return self.__dict__.setdefault(name, default)": 6209, "def decode(string, base):\n \"\"\"\n Given a string (string) and a numeric base (base),\n decode the string into an integer.\n\n Returns the integer\n \"\"\"\n\n base = int(base)\n code_string = get_code_string(base)\n result = 0\n if base == 16:\n string = string.lower()\n while len(string) > 0:\n result *= base\n result += code_string.find(string[0])\n string = string[1:]\n return result": 6210, "def enrich_complexes(graph: BELGraph) -> None:\n \"\"\"Add all of the members of the complex abundances to the graph.\"\"\"\n nodes = list(get_nodes_by_function(graph, COMPLEX))\n for u in nodes:\n for v in u.members:\n graph.add_has_component(u, v)": 6211, "def layer_with(self, sample: np.ndarray, value: int) -> np.ndarray:\n \"\"\"Create an identical 2d array where the second row is filled with value\"\"\"\n b = np.full((2, len(sample)), value, dtype=float)\n b[0] = sample\n return b": 6212, "def input_validate_str(string, name, max_len=None, exact_len=None):\n \"\"\" Input validation for strings. \"\"\"\n if type(string) is not str:\n raise pyhsm.exception.YHSM_WrongInputType(name, str, type(string))\n if max_len != None and len(string) > max_len:\n raise pyhsm.exception.YHSM_InputTooLong(name, max_len, len(string))\n if exact_len != None and len(string) != exact_len:\n raise pyhsm.exception.YHSM_WrongInputSize(name, exact_len, len(string))\n return string": 6213, "def index(self, item):\n \"\"\" Not recommended for use on large lists due to time\n complexity, but it works\n\n -> #int list index of @item\n \"\"\"\n for i, x in enumerate(self.iter()):\n if x == item:\n return i\n return None": 6214, "def _get_tuple(self, fields):\n \"\"\"\n :param fields: a list which contains either 0,1,or 2 values\n :return: a tuple with default values of '';\n \"\"\"\n v1 = ''\n v2 = ''\n if len(fields) > 0:\n v1 = fields[0]\n if len(fields) > 1:\n v2 = fields[1]\n return v1, v2": 6215, "def autoreload(self, parameter_s=''):\n r\"\"\"%autoreload => Reload modules automatically\n\n %autoreload\n Reload all modules (except those excluded by %aimport) automatically\n now.\n\n %autoreload 0\n Disable automatic reloading.\n\n %autoreload 1\n Reload all modules imported with %aimport every time before executing\n the Python code typed.\n\n %autoreload 2\n Reload all modules (except those excluded by %aimport) every time\n before executing the Python code typed.\n\n Reloading Python modules in a reliable way is in general\n difficult, and unexpected things may occur. %autoreload tries to\n work around common pitfalls by replacing function code objects and\n parts of classes previously in the module with new versions. This\n makes the following things to work:\n\n - Functions and classes imported via 'from xxx import foo' are upgraded\n to new versions when 'xxx' is reloaded.\n\n - Methods and properties of classes are upgraded on reload, so that\n calling 'c.foo()' on an object 'c' created before the reload causes\n the new code for 'foo' to be executed.\n\n Some of the known remaining caveats are:\n\n - Replacing code objects does not always succeed: changing a @property\n in a class to an ordinary method or a method to a member variable\n can cause problems (but in old objects only).\n\n - Functions that are removed (eg. via monkey-patching) from a module\n before it is reloaded are not upgraded.\n\n - C extension modules cannot be reloaded, and so cannot be\n autoreloaded.\n\n \"\"\"\n if parameter_s == '':\n self._reloader.check(True)\n elif parameter_s == '0':\n self._reloader.enabled = False\n elif parameter_s == '1':\n self._reloader.check_all = False\n self._reloader.enabled = True\n elif parameter_s == '2':\n self._reloader.check_all = True\n self._reloader.enabled = True": 6216, "def _centroids(n_clusters: int, points: List[List[float]]) -> List[List[float]]:\n \"\"\" Return n_clusters centroids of points\n \"\"\"\n\n k_means = KMeans(n_clusters=n_clusters)\n k_means.fit(points)\n\n closest, _ = pairwise_distances_argmin_min(k_means.cluster_centers_, points)\n\n return list(map(list, np.array(points)[closest.tolist()]))": 6217, "def inner(tensor0: BKTensor, tensor1: BKTensor) -> BKTensor:\n \"\"\"Return the inner product between two tensors\"\"\"\n # Note: Relying on fact that vdot flattens arrays\n return np.vdot(tensor0, tensor1)": 6218, "def get_unique_links(self):\n \"\"\" Get all unique links in the html of the page source.\n Page links include those obtained from:\n \"a\"->\"href\", \"img\"->\"src\", \"link\"->\"href\", and \"script\"->\"src\". \"\"\"\n page_url = self.get_current_url()\n soup = self.get_beautiful_soup(self.get_page_source())\n links = page_utils._get_unique_links(page_url, soup)\n return links": 6219, "def identify_request(request: RequestType) -> bool:\n \"\"\"\n Try to identify whether this is an ActivityPub request.\n \"\"\"\n # noinspection PyBroadException\n try:\n data = json.loads(decode_if_bytes(request.body))\n if \"@context\" in data:\n return True\n except Exception:\n pass\n return False": 6220, "def get_all_args(fn) -> list:\n \"\"\"\n Returns a list of all arguments for the function fn.\n\n >>> def foo(x, y, z=100): return x + y + z\n >>> get_all_args(foo)\n ['x', 'y', 'z']\n \"\"\"\n sig = inspect.signature(fn)\n return list(sig.parameters)": 6221, "def enumerate_chunks (phrase, spacy_nlp):\n \"\"\"\n iterate through the noun phrases\n \"\"\"\n if (len(phrase) > 1):\n found = False\n text = \" \".join([rl.text for rl in phrase])\n doc = spacy_nlp(text.strip(), parse=True)\n\n for np in doc.noun_chunks:\n if np.text != text:\n found = True\n yield np.text, find_chunk(phrase, np.text.split(\" \"))\n\n if not found and all([rl.pos[0] != \"v\" for rl in phrase]):\n yield text, phrase": 6222, "def convert_column(self, values):\n \"\"\"Normalize values.\"\"\"\n assert all(values >= 0), 'Cannot normalize a column with negatives'\n total = sum(values)\n if total > 0:\n return values / total\n else:\n return values": 6223, "def uniqued(iterable):\n \"\"\"Return unique list of items preserving order.\n\n >>> uniqued([3, 2, 1, 3, 2, 1, 0])\n [3, 2, 1, 0]\n \"\"\"\n seen = set()\n add = seen.add\n return [i for i in iterable if i not in seen and not add(i)]": 6224, "def run_web(self, flask, host='127.0.0.1', port=5000, **options):\n # type: (Zsl, str, int, **Any)->None\n \"\"\"Alias for Flask.run\"\"\"\n return flask.run(\n host=flask.config.get('FLASK_HOST', host),\n port=flask.config.get('FLASK_PORT', port),\n debug=flask.config.get('DEBUG', False),\n **options\n )": 6225, "def _is_video(filepath) -> bool:\n \"\"\"Check filename extension to see if it's a video file.\"\"\"\n if os.path.exists(filepath): # Could be broken symlink\n extension = os.path.splitext(filepath)[1]\n return extension in ('.mkv', '.mp4', '.avi')\n else:\n return False": 6226, "def combine_pdf_as_bytes(pdfs: List[BytesIO]) -> bytes:\n \"\"\"Combine PDFs and return a byte-string with the result.\n\n Arguments\n ---------\n pdfs\n A list of BytesIO representations of PDFs\n\n \"\"\"\n writer = PdfWriter()\n for pdf in pdfs:\n writer.addpages(PdfReader(pdf).pages)\n bio = BytesIO()\n writer.write(bio)\n bio.seek(0)\n output = bio.read()\n bio.close()\n return output": 6227, "def session_expired(self):\n \"\"\"\n Returns True if login_time not set or seconds since\n login time is greater than 200 mins.\n \"\"\"\n if not self._login_time or (datetime.datetime.now()-self._login_time).total_seconds() > 12000:\n return True": 6228, "def repl_complete(text: str, state: int) -> Optional[str]:\n \"\"\"Completer function for Python's readline/libedit implementation.\"\"\"\n # Can't complete Keywords, Numerals\n if __NOT_COMPLETEABLE.match(text):\n return None\n elif text.startswith(\":\"):\n completions = kw.complete(text)\n else:\n ns = get_current_ns()\n completions = ns.complete(text)\n\n return list(completions)[state] if completions is not None else None": 6229, "def ranges_to_set(lst):\n \"\"\"\n Convert a list of ranges to a set of numbers::\n\n >>> ranges = [(1,3), (5,6)]\n >>> sorted(list(ranges_to_set(ranges)))\n [1, 2, 3, 5, 6]\n\n \"\"\"\n return set(itertools.chain(*(range(x[0], x[1]+1) for x in lst)))": 6230, "def supports_py3(project_name):\n \"\"\"Check with PyPI if a project supports Python 3.\"\"\"\n log = logging.getLogger(\"ciu\")\n log.info(\"Checking {} ...\".format(project_name))\n request = requests.get(\"https://pypi.org/pypi/{}/json\".format(project_name))\n if request.status_code >= 400:\n log = logging.getLogger(\"ciu\")\n log.warning(\"problem fetching {}, assuming ported ({})\".format(\n project_name, request.status_code))\n return True\n response = request.json()\n return any(c.startswith(\"Programming Language :: Python :: 3\")\n for c in response[\"info\"][\"classifiers\"])": 6231, "def get_triangles(graph: DiGraph) -> SetOfNodeTriples:\n \"\"\"Get a set of triples representing the 3-cycles from a directional graph.\n\n Each 3-cycle is returned once, with nodes in sorted order.\n \"\"\"\n return {\n tuple(sorted([a, b, c], key=str))\n for a, b in graph.edges()\n for c in graph.successors(b)\n if graph.has_edge(c, a)\n }": 6232, "def assert_in(first, second, msg_fmt=\"{msg}\"):\n \"\"\"Fail if first is not in collection second.\n\n >>> assert_in(\"foo\", [4, \"foo\", {}])\n >>> assert_in(\"bar\", [4, \"foo\", {}])\n Traceback (most recent call last):\n ...\n AssertionError: 'bar' not in [4, 'foo', {}]\n\n The following msg_fmt arguments are supported:\n * msg - the default error message\n * first - the element looked for\n * second - the container looked in\n \"\"\"\n\n if first not in second:\n msg = \"{!r} not in {!r}\".format(first, second)\n fail(msg_fmt.format(msg=msg, first=first, second=second))": 6233, "def dictfetchall(cursor: Cursor) -> List[Dict[str, Any]]:\n \"\"\"\n Return all rows from a cursor as a list of :class:`OrderedDict` objects.\n\n Args:\n cursor: the cursor\n\n Returns:\n a list (one item per row) of :class:`OrderedDict` objects whose key are\n column names and whose values are the row values\n \"\"\"\n columns = get_fieldnames_from_cursor(cursor)\n return [\n OrderedDict(zip(columns, row))\n for row in cursor.fetchall()\n ]": 6234, "def backspace(self):\n \"\"\"\n Moves the cursor one place to the left, erasing the character at the\n current position. Cannot move beyond column zero, nor onto the\n previous line.\n \"\"\"\n if self._cx + self._cw >= 0:\n self.erase()\n self._cx -= self._cw\n\n self.flush()": 6235, "def to_json(self) -> Mapping:\n \"\"\"Return the properties of this :class:`Sample` as JSON serializable.\n\n \"\"\"\n return {str(x): str(y) for x, y in self.items()}": 6236, "def remove_leading(needle, haystack):\n \"\"\"Remove leading needle string (if exists).\n\n >>> remove_leading('Test', 'TestThisAndThat')\n 'ThisAndThat'\n >>> remove_leading('Test', 'ArbitraryName')\n 'ArbitraryName'\n \"\"\"\n if haystack[:len(needle)] == needle:\n return haystack[len(needle):]\n return haystack": 6237, "def CheckDisjointCalendars(self):\n \"\"\"Check whether any old service periods intersect with any new ones.\n\n This is a rather coarse check based on\n transitfeed.SevicePeriod.GetDateRange.\n\n Returns:\n True if the calendars are disjoint or False if not.\n \"\"\"\n # TODO: Do an exact check here.\n\n a_service_periods = self.feed_merger.a_schedule.GetServicePeriodList()\n b_service_periods = self.feed_merger.b_schedule.GetServicePeriodList()\n\n for a_service_period in a_service_periods:\n a_start, a_end = a_service_period.GetDateRange()\n for b_service_period in b_service_periods:\n b_start, b_end = b_service_period.GetDateRange()\n overlap_start = max(a_start, b_start)\n overlap_end = min(a_end, b_end)\n if overlap_end >= overlap_start:\n return False\n return True": 6238, "def toHdlConversion(self, top, topName: str, saveTo: str) -> List[str]:\n \"\"\"\n :param top: object which is represenation of design\n :param topName: name which should be used for ipcore\n :param saveTo: path of directory where generated files should be stored\n\n :return: list of file namens in correct compile order\n \"\"\"\n raise NotImplementedError(\n \"Implement this function for your type of your top module\")": 6239, "def titleize(text):\n \"\"\"Capitalizes all the words and replaces some characters in the string \n to create a nicer looking title.\n \"\"\"\n if len(text) == 0: # if empty string, return it\n return text\n else:\n text = text.lower() # lower all char\n # delete redundant empty space \n chunks = [chunk[0].upper() + chunk[1:] for chunk in text.split(\" \") if len(chunk) >= 1]\n return \" \".join(chunks)": 6240, "def set_int(bytearray_, byte_index, _int):\n \"\"\"\n Set value in bytearray to int\n \"\"\"\n # make sure were dealing with an int\n _int = int(_int)\n _bytes = struct.unpack('2B', struct.pack('>h', _int))\n bytearray_[byte_index:byte_index + 2] = _bytes\n return bytearray_": 6241, "def dfromdm(dm):\n \"\"\"Returns distance given distance modulus.\n \"\"\"\n if np.size(dm)>1:\n dm = np.atleast_1d(dm)\n return 10**(1+dm/5)": 6242, "def spanning_tree_count(graph: nx.Graph) -> int:\n \"\"\"Return the number of unique spanning trees of a graph, using\n Kirchhoff's matrix tree theorem.\n \"\"\"\n laplacian = nx.laplacian_matrix(graph).toarray()\n comatrix = laplacian[:-1, :-1]\n det = np.linalg.det(comatrix)\n count = int(round(det))\n return count": 6243, "def define_struct(defn):\n \"\"\"\n Register a struct definition globally\n\n >>> define_struct('struct abcd {int x; int y;}')\n \"\"\"\n struct = parse_type(defn)\n ALL_TYPES[struct.name] = struct\n return struct": 6244, "def get_current_item(self):\n \"\"\"Returns (first) selected item or None\"\"\"\n l = self.selectedIndexes()\n if len(l) > 0:\n return self.model().get_item(l[0])": 6245, "def median(data):\n \"\"\"\n Return the median of numeric data, unsing the \"mean of middle two\" method.\n If ``data`` is empty, ``0`` is returned.\n\n Examples\n --------\n\n >>> median([1, 3, 5])\n 3.0\n\n When the number of data points is even, the median is interpolated:\n >>> median([1, 3, 5, 7])\n 4.0\n \"\"\"\n\n if len(data) == 0:\n return None\n\n data = sorted(data)\n return float((data[len(data) // 2] + data[(len(data) - 1) // 2]) / 2.)": 6246, "def get_input_nodes(G: nx.DiGraph) -> List[str]:\n \"\"\" Get all input nodes from a network. \"\"\"\n return [n for n, d in G.in_degree() if d == 0]": 6247, "def attr_names(cls) -> List[str]:\n \"\"\"\n Returns annotated attribute names\n :return: List[str]\n \"\"\"\n return [k for k, v in cls.attr_types().items()]": 6248, "def is_blankspace(self, char):\n \"\"\"\n Test if a character is a blankspace.\n\n Parameters\n ----------\n char : str\n The character to test.\n\n Returns\n -------\n ret : bool\n True if character is a blankspace, False otherwise.\n\n \"\"\"\n if len(char) > 1:\n raise TypeError(\"Expected a char.\")\n if char in self.blankspaces:\n return True\n return False": 6249, "def consistent_shuffle(*lists):\n \"\"\"\n Shuffle lists consistently.\n\n Parameters\n ----------\n *lists\n Variable length number of lists\n\n Returns\n -------\n shuffled_lists : tuple of lists\n All of the lists are shuffled consistently\n\n Examples\n --------\n >>> import mpu, random; random.seed(8)\n >>> mpu.consistent_shuffle([1,2,3], ['a', 'b', 'c'], ['A', 'B', 'C'])\n ([3, 2, 1], ['c', 'b', 'a'], ['C', 'B', 'A'])\n \"\"\"\n perm = list(range(len(lists[0])))\n random.shuffle(perm)\n lists = tuple([sublist[index] for index in perm]\n for sublist in lists)\n return lists": 6250, "def compatible_staticpath(path):\n \"\"\"\n Try to return a path to static the static files compatible all\n the way back to Django 1.2. If anyone has a cleaner or better\n way to do this let me know!\n \"\"\"\n\n if VERSION >= (1, 10):\n # Since Django 1.10, forms.Media automatically invoke static\n # lazily on the path if it is relative.\n return path\n try:\n # >= 1.4\n from django.templatetags.static import static\n return static(path)\n except ImportError:\n pass\n try:\n # >= 1.3\n return '%s/%s' % (settings.STATIC_URL.rstrip('/'), path)\n except AttributeError:\n pass\n try:\n return '%s/%s' % (settings.PAGEDOWN_URL.rstrip('/'), path)\n except AttributeError:\n pass\n return '%s/%s' % (settings.MEDIA_URL.rstrip('/'), path)": 6251, "def simple_moving_average(x, n=10):\n \"\"\"\n Calculate simple moving average\n\n Parameters\n ----------\n x : ndarray\n A numpy array\n n : integer\n The number of sample points used to make average\n\n Returns\n -------\n ndarray\n A 1 x n numpy array instance\n \"\"\"\n if x.ndim > 1 and len(x[0]) > 1:\n x = np.average(x, axis=1)\n a = np.ones(n) / float(n)\n return np.convolve(x, a, 'valid')": 6252, "def mostLikely(self, pred):\n \"\"\" Helper function to return a scalar value representing the most\n likely outcome given a probability distribution\n \"\"\"\n if len(pred) == 1:\n return pred.keys()[0]\n\n mostLikelyOutcome = None\n maxProbability = 0\n\n for prediction, probability in pred.items():\n if probability > maxProbability:\n mostLikelyOutcome = prediction\n maxProbability = probability\n\n return mostLikelyOutcome": 6253, "def has_obstory_metadata(self, status_id):\n \"\"\"\n Check for the presence of the given metadata item\n\n :param string status_id:\n The metadata item ID\n :return:\n True if we have a metadata item with this ID, False otherwise\n \"\"\"\n self.con.execute('SELECT 1 FROM archive_metadata WHERE publicId=%s;', (status_id,))\n return len(self.con.fetchall()) > 0": 6254, "def require(executable: str, explanation: str = \"\") -> None:\n \"\"\"\n Ensures that the external tool is available.\n Asserts upon failure.\n \"\"\"\n assert shutil.which(executable), \"Need {!r} on the PATH.{}\".format(\n executable, \"\\n\" + explanation if explanation else \"\")": 6255, "def without(seq1, seq2):\n r\"\"\"Return a list with all elements in `seq2` removed from `seq1`, order\n preserved.\n\n Examples:\n\n >>> without([1,2,3,1,2], [1])\n [2, 3, 2]\n \"\"\"\n if isSet(seq2): d2 = seq2\n else: d2 = set(seq2)\n return [elt for elt in seq1 if elt not in d2]": 6256, "def _check_stream_timeout(started, timeout):\n \"\"\"Check if the timeout has been reached and raise a `StopIteration` if so.\n \"\"\"\n if timeout:\n elapsed = datetime.datetime.utcnow() - started\n if elapsed.seconds > timeout:\n raise StopIteration": 6257, "def trim_decimals(s, precision=-3):\n \"\"\"\n Convert from scientific notation using precision\n \"\"\"\n encoded = s.encode('ascii', 'ignore')\n str_val = \"\"\n if six.PY3:\n str_val = str(encoded, encoding='ascii', errors='ignore')[:precision]\n else:\n # If precision is 0, this must be handled seperately\n if precision == 0:\n str_val = str(encoded)\n else:\n str_val = str(encoded)[:precision]\n if len(str_val) > 0:\n return float(str_val)\n else:\n return 0": 6258, "def test_string(self, string: str) -> bool:\n \"\"\"If `string` comes next, return ``True`` and advance offset.\n\n Args:\n string: string to test\n \"\"\"\n if self.input.startswith(string, self.offset):\n self.offset += len(string)\n return True\n return False": 6259, "def capture_stdout():\n \"\"\"Intercept standard output in a with-context\n :return: cStringIO instance\n\n >>> with capture_stdout() as stdout:\n ...\n print stdout.getvalue()\n \"\"\"\n stdout = sys.stdout\n sys.stdout = six.moves.cStringIO()\n try:\n yield sys.stdout\n finally:\n sys.stdout = stdout": 6260, "def get_valid_filename(s):\n \"\"\"\n Returns the given string converted to a string that can be used for a clean\n filename. Specifically, leading and trailing spaces are removed; other\n spaces are converted to underscores; and anything that is not a unicode\n alphanumeric, dash, underscore, or dot, is removed.\n >>> get_valid_filename(\"john's portrait in 2004.jpg\")\n 'johns_portrait_in_2004.jpg'\n \"\"\"\n s = s.strip().replace(\" \", \"_\")\n return re.sub(r\"(?u)[^-\\w.]\", \"\", s)": 6261, "def _is_numeric(self, values):\n \"\"\"Check to be sure values are numbers before doing numerical operations.\"\"\"\n if len(values) > 0:\n assert isinstance(values[0], (float, int)), \\\n \"values must be numbers to perform math operations. Got {}\".format(\n type(values[0]))\n return True": 6262, "def copen(filepath, flag='r', encoding=None):\n\n \"\"\"\n FIXME: How to test this ?\n\n >>> c = copen(__file__)\n >>> c is not None\n True\n \"\"\"\n if encoding is None:\n encoding = locale.getdefaultlocale()[1]\n\n return codecs.open(filepath, flag, encoding)": 6263, "def create_opengl_object(gl_gen_function, n=1):\n \"\"\"Returns int pointing to an OpenGL texture\"\"\"\n handle = gl.GLuint(1)\n gl_gen_function(n, byref(handle)) # Create n Empty Objects\n if n > 1:\n return [handle.value + el for el in range(n)] # Return list of handle values\n else:\n return handle.value": 6264, "def text_to_bool(value: str) -> bool:\n \"\"\"\n Tries to convert a text value to a bool. If unsuccessful returns if value is None or not\n\n :param value: Value to check\n \"\"\"\n try:\n return bool(strtobool(value))\n except (ValueError, AttributeError):\n return value is not None": 6265, "def _check_env_var(envvar: str) -> bool:\n \"\"\"Check Environment Variable to verify that it is set and not empty.\n\n :param envvar: Environment Variable to Check.\n\n :returns: True if Environment Variable is set and not empty.\n\n :raises: KeyError if Environment Variable is not set or is empty.\n\n .. versionadded:: 0.0.12\n \"\"\"\n if os.getenv(envvar) is None:\n raise KeyError(\n \"Required ENVVAR: {0} is not set\".format(envvar))\n if not os.getenv(envvar): # test if env var is empty\n raise KeyError(\n \"Required ENVVAR: {0} is empty\".format(envvar))\n return True": 6266 }