idx,query,code,docstring 1,priority queue," def push(self, item, priority=None): priority = item if priority is None else priority node = PriorityQueueNode(item, priority) for index, current in enumerate(self.priority_queue_list): if current.priority < node.priority: self.priority_queue_list.insert(index, node) return self.priority_queue_list.append(node)","Push the item in the priority queue. if priority is not given, priority is set to the value of item. when traversed complete queue" 2,custom http error response," def handle_http_error(self, response, custom_messages=None, raise_for_status=False): if not custom_messages: custom_messages = {} if response.status_code in custom_messages.keys(): raise errors.HTTPError(custom_messages[response.status_code]) if raise_for_status: response.raise_for_status()","Converts service errors to Python exceptions Parameters ---------- response : requests.Response A service response. custom_messages : dict, optional A mapping of custom exception messages to HTTP status codes. raise_for_status : bool, optional If True, the requests library provides Python exceptions. Returns ------- None" 3,get executable path,"def which(name): for p in os.environ['PATH'].split(os.pathsep): exe = os.path.join(p, name) if is_executable(exe): return os.path.abspath(exe) for ext in [''] + os.environ.get('PATHEXT', '').split(os.pathsep): exe = '{}{}'.format(exe, ext.lower()) if is_executable(exe): return os.path.abspath(exe)", 4,parse query string in url,"def strip_url_params3(url, strip=None): if not strip: strip = [] parse = urllib.parse.urlparse(url) query = urllib.parse.parse_qs(parse.query) query = {k: v[0] for k, v in query.items() if k not in strip} query = urllib.parse.urlencode(query) new = parse._replace(query=query) return new.geturl()", 5,custom http error response," def handle_http_error(self, response, custom_messages=None, raise_for_status=False): if not custom_messages: custom_messages = {} if response.status_code in custom_messages.keys(): raise errors.HTTPError(custom_messages[response.status_code]) if raise_for_status: response.raise_for_status()","Converts service errors to Python exceptions Parameters ---------- response : requests.Response A service response. custom_messages : dict, optional A mapping of custom exception messages to HTTP status codes. raise_for_status : bool, optional If True, the requests library provides Python exceptions. Returns ------- None" 6,k means clustering,"def cluster_kmeans(data, n_clusters, **kwargs): km = cl.KMeans(n_clusters, **kwargs) kmf = km.fit(data) labels = kmf.labels_ return labels, [np.nan]","Identify clusters using K - Means algorithm. Parameters ---------- data : array_like array of size [n_samples, n_features]. n_clusters : int The number of clusters expected in the data. Returns ------- dict boolean array for each identified cluster." 7,export to excel," def to_excel(self, *args): path = os.getcwd() fname = self.fname.replace("".ppl"", ""_ppl"") + "".xlsx"" if len(args) > 0 and args[0] != """": path = args[0] if os.path.exists(path) == False: os.mkdir(path) xl_file = pd.ExcelWriter(path + os.sep + fname) for idx in self.filter_data(""""): self.extract(idx) labels = list(self.filter_data("""").values()) for prof in self.data: data_df = pd.DataFrame() data_df[""X""] = self.data[prof][0] for timestep, data in zip(self.time, self.data[prof][1]): data_df[timestep] = data myvar = labels[prof-1].split("" "")[0] br_label = labels[prof-1].split(""\'"")[5] unit = labels[prof-1].split(""\'"")[7].replace(""/"", ""-"") mylabel = ""{} - {} - {}"".format(myvar, br_label, unit) data_df.to_excel(xl_file, sheet_name=mylabel) xl_file.save() ","Dump all the data to excel, fname and path can be passed as args" 8,aes encryption,"def aes_encrypt(base64_encryption_key, data): if isinstance(data, text_type): data = data.encode(""UTF-8"") aes_key_bytes, hmac_key_bytes = _extract_keys(base64_encryption_key) data = _pad(data) iv_bytes = os.urandom(AES_BLOCK_SIZE) cipher = AES.new(aes_key_bytes, mode=AES.MODE_CBC, IV=iv_bytes) data = iv_bytes + cipher.encrypt(data) hmac_signature = hmac.new(hmac_key_bytes, data, hashlib.sha256).digest() return as_base64(data + hmac_signature)","Encrypt data with AES-CBC and sign it with HMAC-SHA256 Arguments: base64_encryption_key (str): a base64-encoded string containing an AES encryption key and HMAC signing key as generated by generate_encryption_key() data (str): a byte string containing the data to be encrypted Returns: str: the encrypted data as a byte string with the HMAC signature appended to the end prepend init vector" 9,how to get current date,"def date_0utc(date): return ee.Date.fromYMD(date.get('year'), date.get('month'), date.get('day'))","Get the 0 UTC date for a date Parameters ---------- date : ee.Date Returns ------- ee.Date" 10,export to excel," def save(self): pyexcel_export.save_data(self.excel_filename, data=self.excel_raw, retain_meta=True, created=self.created, modified=datetime.now().isoformat())", 11,heatmap from 3d coordinates,"def heatmap(z, x=None, y=None, colorscale='Viridis'): z = np.atleast_1d(z) data = [go.Heatmap(z=z, x=x, y=y, colorscale=colorscale)] return Chart(data=data)","Create a heatmap. Parameters ---------- z : TODO x : TODO, optional y : TODO, optional colorscale : TODO, optional Returns ------- Chart" 12,parse json file,"def _read_json_file(path): try: with open(path) as f: return json.load(f) except: print ('Warning: Unable to read or parse json file: '+path) return None", 13,sending binary data over a serial connection," def write(self, data): try: if isinstance(data, str) or (sys.version_info < (3,) and isinstance(data, unicode)): data = data.encode('utf-8') self._device.write(data) except serial.SerialTimeoutException: pass except serial.SerialException as err: raise CommError('Error writing to device.', err) else: self.on_write(data=data)","Writes data to the device. :param data: data to write :type data: string :raises: py:class:`~alarmdecoder.util.CommError` Hack to support unicode under Python 2.x" 14,scatter plot," def scatter_plot(self, ax, topic_dims, t=None, ms_limits=True, **kwargs_plot): plot_specs = {'marker': 'o', 'linestyle': 'None'} plot_specs.update(kwargs_plot) data = self.data_t(topic_dims, t) ax.plot(*(data.T), **plot_specs) if ms_limits: ax.axis(self.axes_limits(topic_dims))","2D or 3D scatter plot. :param axes ax: matplotlib axes (use Axes3D if 3D data) :param tuple topic_dims: list of (topic, dims) tuples, where topic is a string and dims is a list of dimensions to be plotted for that topic. :param int t: time indexes to be plotted :param dict kwargs_plot: argument to be passed to matplotlib's plot function, e.g. the style of the plotted points 'or' :param bool ms_limits: if set to True, automatically set axes boundaries to the sensorimotor boundaries (default: True) t_bound = float('inf') if t is None: for topic, _ in topic_dims: t_bound = min(t_bound, self.counts[topic]) t = range(t_bound) data = self.pack(topic_dims, t)" 15,get the description of a http status code,"def error_code_to_str(code): try: name = errno.errorcode[code] except KeyError: name = ""UNKNOWN"" try: description = os.strerror(code) except ValueError: description = ""no description available"" return ""{} (errno {}): {}"".format(name, code, description)","Converts a given error code (errno) to a useful and human readable string. :param int code: a possibly invalid/unknown error code :rtype: str :returns: a string explaining and containing the given error code, or a string explaining that the errorcode is unknown if that is the case" 16,write csv,"def write_csv(filename, data, delimiter=CSV_DELIMITER): with open(filename, 'w') as file: csv_writer = csv.writer(file, delimiter=delimiter) for line in data: csv_writer.writerow(line)","Write image data to CSV file :param filename: name of CSV file to write data to :type filename: str :param data: image data to write to CSV file :type data: numpy array :param delimiter: delimiter used in CSV file. Default is ``;`` :type delimiter: str" 17,linear regression," def linear_regression(self, target, regression_length, mask=NotSpecified): from .statistical import RollingLinearRegression return RollingLinearRegression( dependent=self, independent=target, regression_length=regression_length, mask=mask, )","Construct a new Factor that performs an ordinary least-squares regression predicting the columns of `self` from `target`. This method can only be called on factors which are deemed safe for use as inputs to other factors. This includes `Returns` and any factors created from `Factor.rank` or `Factor.zscore`. Parameters ---------- target : zipline.pipeline.Term with a numeric dtype The term to use as the predictor/independent variable in each regression. This may be a Factor, a BoundColumn or a Slice. If `target` is two-dimensional, regressions are computed asset-wise. regression_length : int Length of the lookback window over which to compute each regression. mask : zipline.pipeline.Filter, optional A Filter describing which assets should be regressed with the target slice each day. Returns ------- regressions : zipline.pipeline.factors.RollingLinearRegression A new Factor that will compute linear regressions of `target` against the columns of `self`. Examples -------- Suppose we want to create a factor that regresses AAPL's 10-day returns against the 10-day returns of all other assets, computing each regression over 30 days. This can be achieved by doing the following:: returns = Returns(window_length=10) returns_slice = returns[sid(24)] aapl_regressions = returns.linear_regression( target=returns_slice, regression_length=30, ) This is equivalent to doing:: aapl_regressions = RollingLinearRegressionOfReturns( target=sid(24), returns_length=10, regression_length=30, ) See Also -------- :func:`scipy.stats.linregress` :class:`zipline.pipeline.factors.RollingLinearRegressionOfReturns`" 18,encrypt aes ctr mode," def encrypt(cls, data, key, iv_data): validate_key_size(key, cls.key_size, ""AES"") iv, ctr = iv_data ciphertext = Crypto_AES.new(key, Crypto_AES.MODE_CTR, counter=ctr).encrypt(data) return iv + ciphertext", 19,export to excel,"def export_to_xlsx(table, filename_or_fobj=None, sheet_name=""Sheet1"", *args, **kwargs): workbook = Workbook() sheet = workbook.active sheet.title = sheet_name prepared_table = prepare_to_export(table, *args, **kwargs) field_names = next(prepared_table) for col_index, field_name in enumerate(field_names): cell = sheet.cell(row=1, column=col_index + 1) cell.value = field_name _convert_row = _python_to_cell(list(map(table.fields.get, field_names))) for row_index, row in enumerate(prepared_table, start=1): for col_index, (value, number_format) in enumerate(_convert_row(row)): cell = sheet.cell(row=row_index + 1, column=col_index + 1) cell.value = value if number_format is not None: cell.number_format = number_format return_result = False if filename_or_fobj is None: filename_or_fobj = BytesIO() return_result = True source = Source.from_file(filename_or_fobj, mode=""wb"", plugin_name=""xlsx"") workbook.save(source.fobj) source.fobj.flush() if return_result: source.fobj.seek(0) result = source.fobj.read() else: result = source.fobj if source.should_close: source.fobj.close() return result","Export the rows.Table to XLSX file and return the saved file. Write header Write sheet rows" 20,copy to clipboard,"def copy_to_clipboard(i): s=i['string'] failed=False ee='' try: import pyperclip except Exception as e: ee=format(e) failed=True pass if not failed: pyperclip.copy(s) else: failed=False try: from Tkinter import Tk except ImportError as e: ee=format(e) failed=True pass if failed: failed=False try: from tkinter import Tk except ImportError as e: ee=format(e) failed=True pass if failed: return {'return':1, 'error':'none of pyperclip/Tkinter/tkinter packages is installed'} try: r = Tk() r.withdraw() r.clipboard_clear() r.clipboard_append(s) r.destroy() except Exception as e: return {'return':1, 'error':'problem copying string to clipboard ('+format(e)+')'} return {'return':0}","pragma: no cover Input: { string - string to copy Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 } Try to load pyperclip (seems to work fine on Windows) Try to load Tkinter Copy to clipboard" 21,get executable path,"def get_compiler_path(): given_binary = os.environ.get('SOLC_BINARY') if given_binary: return given_binary for path in os.getenv('PATH', '').split(os.pathsep): path = path.strip('""') executable_path = os.path.join(path, BINARY) if os.path.isfile(executable_path) and os.access( executable_path, os.X_OK): return executable_path return None","Return the path to the solc compiler. This funtion will search for the solc binary in the $PATH and return the path of the first executable occurence. If the user provides a specific solc binary let's use that" 22,converting uint8 array to image,"def _convert_uint8(im): if im.dtype != np.uint8: im = np.uint8(im * 255) return im", 23,how to check if a checkbox is checked," def checkbox_check(self, force_check=False): if not self.get_attribute('checked'): self.click(force_click=force_check)",Wrapper to check a checkbox 24,copy to clipboard,"def copy_to_clipboard(i): s=i['string'] failed=False ee='' try: import pyperclip except Exception as e: ee=format(e) failed=True pass if not failed: pyperclip.copy(s) else: failed=False try: from Tkinter import Tk except ImportError as e: ee=format(e) failed=True pass if failed: failed=False try: from tkinter import Tk except ImportError as e: ee=format(e) failed=True pass if failed: return {'return':1, 'error':'none of pyperclip/Tkinter/tkinter packages is installed'} try: r = Tk() r.withdraw() r.clipboard_clear() r.clipboard_append(s) r.destroy() except Exception as e: return {'return':1, 'error':'problem copying string to clipboard ('+format(e)+')'} return {'return':0}","pragma: no cover Input: { string - string to copy Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 } Try to load pyperclip (seems to work fine on Windows) Try to load Tkinter Copy to clipboard" 25,memoize to disk - persistent memoization,"def memoize(obj): cache = obj.cache = {} @functools.wraps(obj) def memoizer(*args, **kwargs): key = tuple(list(args) + sorted(kwargs.items())) if key not in cache: cache[key] = obj(*args, **kwargs) return cache[key] return memoizer", 26,get current process id,"Error: 404 {""message"": ""Not Found"", ""documentation_url"": ""https://docs.github.com/rest/repos/repos","get-a-repository"", ""status"": ""404""}" 27,positions of substrings in string,"def substitute_globals(string, globs=None): sub = set(re.findall('\{(.*?)\}', string)) globs = globs or inspect.currentframe().f_back.f_globals if sub: for item in map(str, sub): string = string.replace(""${%s}""%item, globs[item]) return string else: return False", 28,linear regression,"def func(X, y): from sklearn.linear_model import LinearRegression from sklearn.model_selection import cross_val_score model = LinearRegression() model.fit(X, y) return model.predict(X)", 29,binomial distribution,"def EvalBinomialPmf(k, n, p): return scipy.stats.binom.pmf(k, n, p)","Evaluates the binomial pmf. Returns the probabily of k successes in n trials with probability p." 30,unzipping large files," def unzip(self, in_file, out_file): with ZipFile(in_file) as zf: zf.extract('collection.anki2', path=self.tempdir) shutil.move(os.path.join(self.tempdir, 'collection.anki2'), out_file) return out_file", 31,copying a file to a path,"def _copy(from_path, to_path): message = ""Copying path [%s] to [%s]"" log.debug(message, from_path, to_path) copy(from_path, to_path)", 32,copying a file to a path," def _copy_file(self, file_obj, destination, suffix, overwrite): if overwrite: raise NotImplementedError filename = self._generate_new_filename(file_obj.file.name, suffix) file_obj.pk = None file_obj.id = None file_obj.save() file_obj.folder = destination file_obj._file_data_changed_hint = False file_obj.file = file_obj._copy_file(filename) file_obj.original_filename = self._generate_new_filename(file_obj.original_filename, suffix) file_obj.save()","Not yet implemented as we have to find a portable (for different storage backends) way to overwrite files We are assuming here that we are operating on an already saved database objects with current database state available Due to how inheritance works, we have to set both pk and id to None no need to update size, sha1, etc." 33,parse json file," def __parse_json_file(self, file_path): if file_path == '' or os.path.splitext(file_path)[1] != '.json': raise IOError('Invalid Json file') with open(file_path) as json_file: self._raw_data = json.load(json_file) self._json_data = copy.deepcopy(self._raw_data)","Process Json file data :@param file_path :@type file_path: string :@throws IOError" 34,copying a file to a path," def write_file_to_output(self, filename, path): path = os.path.join(self.out_path, path) if self.add_filehash_to_path and os.path.exists(path): return path_part = os.path.dirname(path) PathDumper.__makedirs(path_part) shutil.copy(filename, path) os.chmod(path, 0o666) return path",Avoid rewriting existing files 35,httpclient post json," async def _http_post(self, url, data): data = json.dumps(data) headers = {""Authorization"": ""GoogleLogin auth={0}"".format(self.token), ""Content-type"": ""application/json""} res = await self.session.request( 'POST', FULL_SJ_URL + url, data=data, headers=headers, params={'tier': 'aa', 'hl': 'en_US', 'dv': 0, 'alt': 'json'}) ret = await res.json() return ret", 36,encrypt aes ctr mode,"def _encrypt(data): BS = AES.block_size def pad(s): n = BS - len(s) % BS char = chr(n).encode('utf8') return s + n * char password = settings.GECKOBOARD_PASSWORD salt = Random.new().read(BS - len('Salted__')) key, iv = _derive_key_and_iv(password, salt, 32, BS) cipher = AES.new(key, AES.MODE_CBC, iv) encrypted = b'Salted__' + salt + cipher.encrypt(pad(data)) return base64.b64encode(encrypted)",Equivalent to OpenSSL using 256 bit AES in CBC mode 37,connect to sql," def connect(self): self.close() self._connect = pymysql.connect(**self._db_options) self._connect.autocommit(True)", 38,how to check if a checkbox is checked,"def assert_checked_checkbox(self, value): check_box = find_field(world.browser, 'checkbox', value) assert check_box, ""Cannot find checkbox '{}'."".format(value) assert check_box.is_selected(), ""Check box should be selected.""","Assert the checkbox with label (recommended), name or id is checked." 39,sending binary data over a serial connection," def send(self, msg): slipDriver = sliplib.Driver() slipData = slipDriver.send(msg) res = self._serialPort.write(slipData) return res","Encodes data to slip protocol and then sends over serial port Uses the SlipLib module to convert the message data into SLIP format. The message is then sent over the serial port opened with the instance of the Faraday class used when invoking send(). Args: msg (bytes): Bytes format message to send over serial port. Returns: int: Number of bytes transmitted over the serial port. Create a sliplib Driver Package data in slip format Send data over serial port Return number of bytes transmitted over serial port" 40,convert a date string into yyyymmdd,"def date_string_to_date(p_date): result = None if p_date: parsed_date = re.match(r'(\d{4})-(\d{2})-(\d{2})', p_date) if parsed_date: result = date( int(parsed_date.group(1)), int(parsed_date.group(2)), int(parsed_date.group(3)) ) else: raise ValueError return result","Given a date in YYYY-MM-DD, returns a Python date object. Throws a ValueError if the date is invalid. year month day" 41,how to read .csv file in an efficient way?," def read_csv(self, file_path, use_whole_file=False, names=None, skiprows=0, *args, **kwargs): def csv_file(partition_number, files): file_count = 0 for _, contents in files: if partition_number == 0 and file_count == 0 and _skiprows > 0: yield pandas.read_csv( sio(contents), *args, header=None, names=mynames, skiprows=_skiprows, **kwargs) else: file_count += 1 yield pandas.read_csv( sio(contents), *args, header=None, names=mynames, **kwargs) def csv_rows(partition_number, rows): in_str = ""\n"".join(rows) if partition_number == 0: return iter([ pandas.read_csv( sio(in_str), *args, header=None, names=mynames, skiprows=_skiprows, **kwargs)]) else: return iter([pandas.read_csv(sio(in_str), *args, header=None, names=mynames, **kwargs)]) mynames = None _skiprows = skiprows if names: mynames = names else: first_line = self.spark_ctx.textFile(file_path).first() frame = pandas.read_csv(sio(first_line), **kwargs) mynames = list(frame.columns) _skiprows += 1 if use_whole_file: return self.from_pandas_rdd( self.spark_ctx.wholeTextFiles(file_path) .mapPartitionsWithIndex(csv_file)) else: return self.from_pandas_rdd( self.spark_ctx.textFile(file_path) .mapPartitionsWithIndex(csv_rows))","Read a CSV file in and parse it into Pandas DataFrames. By default, the first row from the first partition of that data is parsed and used as the column names for the data from. If no 'names' param is provided we parse the first row of the first partition of data and use it for column names. Parameters ---------- file_path: string Path to input. Any valid file path in Spark works here, eg: 'file:///my/path/in/local/file/system' or 'hdfs:/user/juliet/' use_whole_file: boolean Whether of not to use the whole file. names: list of strings, optional skiprows: integer, optional indicates how many rows of input to skip. This will only be applied to the first partition of the data (so if #skiprows > #row in first partition this will not work). Generally this shouldn't be an issue for small values of skiprows. No other value of header is supported. All additional parameters available in pandas.read_csv() are usable here. Returns ------- A SparklingPandas DataFrame that contains the data from the specified file. pylint: disable=unexpected-keyword-arg Only skip lines on the first file pylint: disable=unexpected-keyword-arg could use .iterows instead? If we need to peak at the first partition and determine the column names In the future we could avoid this expensive call. pylint sees frame as a tuple despite it being a DataFrame Do the actual load" 42,string to date," def to_string(self): return '-'.join([d.strftime('%Y-%m-%d') for d in (self.date_a, self.date_b)])", 43,positions of substrings in string,"def get_substring_idxs(substr, string): return [match.start() for match in re.finditer(substr, string)]","Return a list of indexes of substr. If substr not found, list is empty. Arguments: substr (str): Substring to match. string (str): String to match in. Returns: list of int: Start indices of substr." 44,create cookie," def setcookie(self, key, value, max_age=None, expires=None, path='/', domain=None, secure=None, httponly=False): newcookie = Morsel() newcookie.key = key newcookie.value = value newcookie.coded_value = value if max_age is not None: newcookie['max-age'] = max_age if expires is not None: newcookie['expires'] = expires if path is not None: newcookie['path'] = path if domain is not None: newcookie['domain'] = domain if secure: newcookie['secure'] = secure if httponly: newcookie['httponly'] = httponly self.sent_cookies = [c for c in self.sent_cookies if c.key != key] self.sent_cookies.append(newcookie)",Add a new cookie 45,how to make the checkbox checked,"def check_checkbox(self, value): check_box = find_field(world.browser, 'checkbox', value) assert check_box, ""Cannot find checkbox '{}'."".format(value) if not check_box.is_selected(): check_box.click()","Check the checkbox with label (recommended), name or id." 46,pretty print json,"def json_pretty_print(d, file=None): args = {'sort_keys': True, 'indent': 2, 'separators': (',', ': ')} if file: return json.dump(d, file, **args) return json.dumps(d, **args)", 47,aes encryption,"def aes_encrypt(value, secret, block_size=AES.block_size): iv = os.urandom(block_size * 2) cipher = AES.new(secret[:32], AES.MODE_CFB, iv[:block_size]) return b'%s%s' % (iv, cipher.encrypt(value))","AES encrypt @value with @secret using the |CFB| mode of AES with a cryptographically secure initialization vector. -> (#bytes) AES encrypted @value .. from vital.security import aes_encrypt, aes_decrypt aes_encrypt(""Hello, world"", ""aLWEFlwgwlreWELFNWEFWLEgwklgbweLKWEBGW"") # -> 'zYgVYMbeOuiHR50aMFinY9JsfyMQCvpzI+LNqNcmZhw=' aes_decrypt( ""zYgVYMbeOuiHR50aMFinY9JsfyMQCvpzI+LNqNcmZhw="", ""aLWEFlwgwlreWELFNWEFWLEgwklgbweLKWEBGW"") # -> 'Hello, world' ..f" 48,how to get html of website," def get_html(self): r = requests.get(self.url) if r.status_code == 404: raise PlayerNotFoundError else: soup = BeautifulSoup(r.text, 'html.parser') return soup.find(""div"", class_=""pnl490M"")", 49,k means clustering,"def optimal_clustering(df, patch, method='kmeans', statistic='gap', max_K=5): if len(patch) == 1: return [patch] if statistic == 'db': if method == 'kmeans': if len(patch) <= 5: K_max = 2 else: K_max = min(len(patch) / 2, max_K) clustering = {} db_index = [] X = df.ix[patch, :] for k in range(2, K_max + 1): kmeans = cluster.KMeans(n_clusters=k).fit(X) clustering[k] = pd.DataFrame(kmeans.predict(X), index=patch) dist_mu = squareform(pdist(kmeans.cluster_centers_)) sigma = [] for i in range(k): points_in_cluster = clustering[k][clustering[k][0] == i].index sigma.append(sqrt(X.ix[points_in_cluster, :].var(axis=0).sum())) db_index.append(davies_bouldin(dist_mu, np.array(sigma))) db_index = np.array(db_index) k_optimal = np.argmin(db_index) + 2 return [list(clustering[k_optimal][clustering[k_optimal][0] == i].index) for i in range(k_optimal)] elif method == 'agglomerative': if len(patch) <= 5: K_max = 2 else: K_max = min(len(patch) / 2, max_K) clustering = {} db_index = [] X = df.ix[patch, :] for k in range(2, K_max + 1): agglomerative = cluster.AgglomerativeClustering(n_clusters=k, linkage='average').fit(X) clustering[k] = pd.DataFrame(agglomerative.fit_predict(X), index=patch) tmp = [list(clustering[k][clustering[k][0] == i].index) for i in range(k)] centers = np.array([np.mean(X.ix[c, :], axis=0) for c in tmp]) dist_mu = squareform(pdist(centers)) sigma = [] for i in range(k): points_in_cluster = clustering[k][clustering[k][0] == i].index sigma.append(sqrt(X.ix[points_in_cluster, :].var(axis=0).sum())) db_index.append(davies_bouldin(dist_mu, np.array(sigma))) db_index = np.array(db_index) k_optimal = np.argmin(db_index) + 2 return [list(clustering[k_optimal][clustering[k_optimal][0] == i].index) for i in range(k_optimal)] elif statistic == 'gap': X = np.array(df.ix[patch, :]) if method == 'kmeans': f = cluster.KMeans gaps = gap(X, ks=range(1, min(max_K, len(patch))), method=f) k_optimal = list(gaps).index(max(gaps))+1 clustering = pd.DataFrame(f(n_clusters=k_optimal).fit_predict(X), index=patch) return [list(clustering[clustering[0] == i].index) for i in range(k_optimal)] else: raise 'error: only db and gat statistics are supported'", 50,unzipping large files,"def unzip(zip_content, dest_dir): with zipfile.ZipFile(zip_content, ""r"") as zf: for member in zf.infolist(): words = member.filename.split('/') path = dest_dir for word in words[:-1]: drive, word = os.path.splitdrive(word) head, word = os.path.split(word) if word in (os.curdir, os.pardir, ''): continue path = os.path.join(path, word) zf.extract(member, path)","From http://stackoverflow.com/a/12886818 Path traversal defense copied from http://hg.python.org/cpython/file/tip/Lib/http/server.py#l789" 51,scatter plot,"Error: 404 {""message"": ""No commit found for the ref 50d3f979e79e63c66629065c75595696dc79802e"", ""documentation_url"": ""https://docs.github.com/v3/repos/contents/"", ""status"": ""404""}", 52,matrix multiply," def __mul__(self, other): if isinstance(other, Matrix): return Matrix(self.matrix.dot(other.matrix)) else: return Matrix(self.matrix * other)", 53,write csv,"def write_to_csv(fname, header, rows): with open(fname, 'wb') as csvfile: csvwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) csvwriter.writerow(header) for row in rows: csvwriter.writerow( [s.encode(""utf-8"").replace(',', '').replace('\n', '') for s in row])", 54,heatmap from 3d coordinates,"def colorize(img, heatmap): heatmap = viz.intensity_to_rgb(heatmap, cmap='jet')[:, :, ::-1] return img * 0.5 + heatmap * 0.5","img: bgr, [0,255] heatmap: [0,1]" 55,parse command line argument,"def parse_command_line_arguments(): parser = argparse.ArgumentParser( description='Rotates the cell lattice in VASP POSCAR files' ) parser.add_argument( 'poscar', help=""filename of the VASP POSCAR to be processed"" ) parser.add_argument( '-a', '--axis', nargs=3, type=float, help=""vector for rotation axis"", required=True ) parser.add_argument( '-d', '--degrees', type=int, help=""rotation angle in degrees"", required=True ) args = parser.parse_args() return( args )", 56,regex case insensitive," def match(self, string): if self.casesensitive: return self.pattern == os.path.normcase(string) else: return self.pattern.lower() == os.path.normcase(string).lower()",Returns True if the argument matches the constant. 57,how to make the checkbox checked," def checkbox_check(self, force_check=False): if not self.get_attribute('checked'): self.click(force_click=force_check)",Wrapper to check a checkbox 58,string similarity levenshtein,"def levenshtein(left, right): sc = SparkContext._active_spark_context jc = sc._jvm.functions.levenshtein(_to_java_column(left), _to_java_column(right)) return Column(jc)","Computes the Levenshtein distance of the two given strings. >>> df0 = spark.createDataFrame([('kitten', 'sitting',)], ['l', 'r']) >>> df0.select(levenshtein('l', 'r').alias('d')).collect() [Row(d=3)]" 59,how to read .csv file in an efficient way?,"def read_csv(filename, has_header=True): with open(filename) as fh: csv_reader = csv.reader(fh) header = None if has_header: header = csv_reader.next() rows = [row for row in csv_reader] return header, rows", 60,string to date," def to_string(self): return '-'.join([d.strftime('%Y-%m-%d') for d in (self.date_a, self.date_b)])", 61,aes encryption," def encrypt_message(self, signed_message, message, key, iv): raw = signed_message + message block_size = AES.block_size pad = lambda s: s + (block_size - len(s) % block_size) * chr(block_size - len(s) % block_size).encode('utf-8') message_to_encrypt = pad(raw) cipher = AES.new(key, AES.MODE_CBC, iv) return cipher.encrypt(message_to_encrypt)", 62,how to get html of website," def get_html_source(self): req = urllib.request.Request(self.url) req.add_header(""user-agent"", random.choice(USER_AGENTS)) req_text = urllib.request.urlopen(req).read() self.source = str(req_text) self.soup = BeautifulSoup(self.source, ""html.parser"") return self.source","Gets source page of url :return: HTML source" 63,socket recv timeout," def recvall(self, timeout=0.5): response = '' self.socket.setblocking(False) start = time.time() while True: if response and time.time() - start > timeout: break elif time.time() - start > timeout * 2: break try: data = self.socket.recv(4096) if data: response += data.replace(self._rconreplystring, '') start = time.time() else: time.sleep(0.1) except socket.error: pass return response.strip()","Receive the RCON command response :param timeout: The timeout between consequent data receive :return str: The RCON command response with header stripped out" 64,get inner html," def innerHTML(self, html: str) -> None: df = self._parse_html(html) if self.connected: self._set_inner_html_web(df.html) self._empty() self._append_child(df)","type: ignore Set innerHTML both on this node and related browser node." 65,unique elements,"def unique(list): unique = []; [unique.append(x) for x in list if x not in unique] return unique ",Returns a copy of the list without duplicates. 66,get all parents of xml node," def get_edges(self, node): return [ (node, child) for child in self.get_children(node) ] + [ (parent, node) for parent in self.get_parents(node) ]", 67,confusion matrix,"Error: 404 {""message"": ""Not Found"", ""documentation_url"": ""https://docs.github.com/rest/repos/repos","get-a-repository"", ""status"": ""404""}" 68,pretty print json,"def pprint_json(json_raw): print(json.dumps(json.loads(json_raw), indent=2, sort_keys=True))", 69,how to randomly pick a number,"def randbelow(num: int) -> int: if not isinstance(num, int): raise TypeError('number must be an integer') if num <= 0: raise ValueError('number must be greater than zero') if num == 1: return 0 nbits = num.bit_length() randnum = random_randint(nbits) while randnum >= num: randnum = random_randint(nbits) return randnum","Return a random int in the range [0,num). Raises ValueError if num <= 0, and TypeError if it's not an integer. >>> randbelow(16) #doctest:+SKIP 13 https://github.com/python/cpython/blob/3.6/Lib/random.py#L223 don't use (n-1) here because n can be 1 0 <= randnum < 2**nbits" 70,convert json to csv,"def json_to_csv(json_input): try: json_input = json.loads(json_input) except: pass headers = set() for json_row in json_input: headers.update(json_row.keys()) csv_io = StringIO.StringIO() csv_out = csv.DictWriter(csv_io,headers) csv_out.writeheader() for json_row in json_input: csv_out.writerow(json_row) csv_io.seek(0) return csv_io.read()","Convert simple JSON to CSV Accepts a JSON string or JSON object If loads fails, it's probably already parsed" 71,connect to sql," def __mysql_connect(self, connect_using_database_name=True): try: conn = self.__mysql_driver.connect(host=self.__mysql_host, port=self.__mysql_port, user=self.__mysql_user, passwd=self.__mysql_passwd) conn.set_character_set(self.__mysql_encoding) if connect_using_database_name: conn.select_db(self.__mysql_db) return conn except Exception as e: raise Exception(""could not connect to database: %s"" % e)", 72,encode url," def _urlencode(self, h): rv = [] for k,v in h.iteritems(): rv.append('%s=%s' % (urllib.quote(k.encode(""utf-8"")), urllib.quote(v.encode(""utf-8"")))) return '&'.join(rv)", 73,k means clustering," def kmeans_clustering(self, numc, X=None, npcs=15): from sklearn.cluster import KMeans if X is None: D_sub = self.adata.uns['X_processed'] X = ( D_sub - D_sub.mean(0)).dot( self.adata.uns['pca_obj'].components_[ :npcs, :].T) save = True else: save = False cl = KMeans(n_clusters=numc).fit_predict(Normalizer().fit_transform(X)) if save: self.adata.obs['kmeans_clusters'] = pd.Categorical(cl) else: return cl","Performs k-means clustering. Parameters ---------- numc - int Number of clusters npcs - int, optional, default 15 Number of principal components to use as inpute for k-means clustering." 74,aes encryption," def _cbc_encrypt(self, content, final_key): aes = AES.new(final_key, AES.MODE_CBC, self._enc_iv) padding = (16 - len(content) % AES.block_size) for _ in range(padding): content += chr(padding).encode() temp = bytes(content) return aes.encrypt(temp)",This method encrypts the content. 75,parse query string in url,"def _parse_url(url): p = urlsplit(url) query = {k: v[0] for k, v in parse_qs(p.query).items() if len(v) == 1} return ''.join([p.netloc, p.path]), query", 76,get executable path,"def get_binary_path(executable, logging_level='INFO'): if sys.platform == 'win32': if executable == 'start': return executable executable = executable + '.exe' if executable in os.listdir('.'): binary = os.path.join(os.getcwd(), executable) else: binary = next((os.path.join(path, executable) for path in os.environ['PATH'].split(os.pathsep) if os.path.isfile(os.path.join(path, executable))), None) else: venv_parent = get_venv_parent_path() venv_bin_path = os.path.join(venv_parent, '.venv', 'bin') if not venv_bin_path in os.environ.get('PATH'): if logging_level == 'DEBUG': print(f'Adding path {venv_bin_path} to environment PATH variable') os.environ['PATH'] = os.pathsep.join([os.environ['PATH'], venv_bin_path]) binary = shutil.which(executable) return binary if binary else None",Gets the software name and returns the path of the binary. 77,get current process id,"Error: 404 {""message"": ""Not Found"", ""documentation_url"": ""https://docs.github.com/rest/repos/repos","get-a-repository"", ""status"": ""404""}" 78,html encode string," def _code_no_lexer(self, text): text = text.encode(charset).strip() return( % houdini.escape_html(text) )","encode to utf8 string
%s
" 79,httpclient post json," def post(self, json=None): return self._call('post', url=self.endpoint, json=json)","Send a POST request and return the JSON decoded result. Args: json (dict, optional): Object to encode and send in request. Returns: mixed: JSON decoded response data." 80,convert int to string,"def string_to_int( s ): result = 0 for c in s: if not isinstance(c, int): c = ord( c ) result = 256 * result + c return result","Convert a string of bytes into an integer, as per X9.62." 81,copy to clipboard,"def copy_to_clipboard(text): if sys.platform == 'darwin': os.system('echo ""{0}"" | pbcopy'.format(text)) return try: from Tkinter import Tk except ImportError: return r = Tk() r.withdraw() r.clipboard_clear() r.clipboard_append(text.encode('ascii')) r.destroy()","reliable on mac okay we'll try cross-platform way" 82,encode url,"def url_encode(url): if isinstance(url, text_type): url = url.encode('utf8') return quote(url, ':/%?&=')","Convert special characters using %xx escape. :param url: str :return: str - encoded url" 83,linear regression," def linreg(self, rsq=False, conf_test=False): model='linear' if not self.datestack: self.compute_dt_stats() if np.isnan(self.min_dt_ptp): max_dt_ptp = calcperc(self.dt_stack_ptp, (4, 96))[1] self.min_dt_ptp = 0.20 * max_dt_ptp if self.robust: model='theilsen' print(""Compute stack linear trend with model: %s"" % model) self.stack_trend, self.stack_intercept, self.stack_detrended_std = \ ma_linreg(self.ma_stack, self.date_list, dt_stack_ptp=self.dt_stack_ptp, min_dt_ptp=self.min_dt_ptp, \ n_thresh=self.n_thresh, model=model, rsq=False, conf_test=False, smooth=False, n_cpu=self.n_cpu)","This could fail if stack contains a small number of inputs model='ransac'" 84,how to extract zip file recursively,"def extract_zip(zip_name, exclude_term=None): zip_dir = os.path.dirname(os.path.abspath(zip_name)) try: with zipfile.ZipFile(zip_name) as z: files = [zip_file for zip_file in z.namelist() if not zip_file.endswith('/')] print('Extracting %i files from %r.' % (len(files), zip_name)) for zip_file in files: if exclude_term: dest_file = zip_file.replace(exclude_term, '') else: dest_file = zip_file dest_file = os.path.normpath(os.path.join(zip_dir, dest_file)) dest_dir = os.path.dirname(dest_file) if not os.path.isdir(dest_dir): os.makedirs(dest_dir) data = z.read(zip_file) with open(dest_file, 'wb') as f: f.write(encode_utf8(data)) except zipfile.error as e: print(""Bad zipfile (%r): %s"" % (zip_name, e)) raise e","Extracts a zip file to its containing directory. write each zipped file out if it isn't a directory remove any provided extra directory term from zip file make directory if it does not exist read file from zip, then write to new directory" 85,how to extract zip file recursively,"def extract_zip(archive_path, dest): with zipfile.ZipFile(archive_path) as z: validate_filenames(z.namelist()) z.extractall(dest) for info in z.filelist: if not info.filename.endswith('/'): mode = (info.external_attr >> 16) & 0o777 if mode & stat.S_IXUSR: os.chmod(os.path.join(dest, info.filename), 0o755)","Set file permissions. Tar does this by default, but with zip we need to do it ourselves. This is how to get file permissions out of a zip archive, according to http://stackoverflow.com/q/434641/823869 and http://bugs.python.org/file34873/issue15795_cleaned.patch. Don't copy the whole mode, just set the executable bit. Two reasons for this. 1) This is all going to end up in a git tree, which only records the executable bit anyway. 2) Zip's support for Unix file modes is nonstandard, so the mode field is often zero and could be garbage. Mistakenly setting a file executable isn't a big deal, but e.g. removing read permissions would cause an error." 86,convert int to string,"def string_to_int( s ): result = 0 for c in s: if not isinstance(c, int): c = ord( c ) result = 256 * result + c return result","Convert a string of bytes into an integer, as per X9.62." 87,matrix multiply," def __mul__(self, other): if isinstance(other, Matrix): return Matrix(self.matrix.dot(other.matrix)) else: return Matrix(self.matrix * other)", 88,connect to sql," def connect(self, db_uri, debug=False): kwargs = {'echo': debug, 'convert_unicode': True} if 'mysql' in db_uri: kwargs['pool_recycle'] = 3600 elif '://' not in db_uri: logger.debug(""detected sqlite path URI: {}"".format(db_uri)) db_path = os.path.abspath(os.path.expanduser(db_uri)) db_uri = ""sqlite:///{}"".format(db_path) self.engine = create_engine(db_uri, **kwargs) logger.debug('connection established successfully') BASE.metadata.bind = self.engine self.session = scoped_session(sessionmaker(bind=self.engine)) self.query = self.session.query return self","Configure connection to a SQL database. Args: db_uri (str): path/URI to the database to connect to debug (Optional[bool]): whether to output logging information connect to the SQL database make sure the same engine is propagated to the BASE classes start a session shortcut to query method" 89,fuzzy match ranking," def fuzzmatch(self, fuzzkey, multi=False): keys, ratios = np.array([(f, seqm(None, fuzzkey, f).ratio()) for f in self.components.keys()]).T mratio = max(ratios) if multi: return keys[ratios == mratio] else: if sum(ratios == mratio) == 1: return keys[ratios == mratio][0] else: raise ValueError(""\nThe filter key provided ('{:}') matches two or more filter names equally well:\n"".format(fuzzkey) + ', '.join(keys[ratios == mratio]) + ""\nPlease be more specific!"")","Identify a filter by fuzzy string matching. Partial ('fuzzy') matching performed by `fuzzywuzzy.fuzzy.ratio` Parameters ---------- fuzzkey : str A string that partially matches one filter name more than the others. Returns ------- The name of the most closely matched filter. : str" 90,convert int to bool,"def convert_to_bool(x: Any, default: bool = None) -> bool: if isinstance(x, bool): return x if not x: return default try: return int(x) != 0 except (TypeError, ValueError): pass try: return float(x) != 0 except (TypeError, ValueError): pass if not isinstance(x, str): raise Exception(""Unknown thing being converted to bool: {!r}"".format(x)) x = x.upper() if x in [""Y"", ""YES"", ""T"", ""TRUE""]: return True if x in [""N"", ""NO"", ""F"", ""FALSE""]: return False raise Exception(""Unknown thing being converted to bool: {!r}"".format(x))","Transforms its input to a ``bool`` (or returns ``default`` if ``x`` is falsy but not itself a boolean). Accepts various common string versions. None, zero, blank string..." 91,create cookie,"def create_cookie( key: str, value: str='', max_age: Optional[Union[int, timedelta]]=None, expires: Optional[Union[int, float, datetime]]=None, path: str='/', domain: Optional[str]=None, secure: bool=False, httponly: bool=False, ) -> SimpleCookie: cookie = SimpleCookie() cookie[key] = value cookie[key]['path'] = path cookie[key]['httponly'] = httponly cookie[key]['secure'] = secure if isinstance(max_age, timedelta): cookie[key]['max-age'] = f""{max_age.total_seconds():d}"" if isinstance(max_age, int): cookie[key]['max-age'] = str(max_age) if expires is not None and isinstance(expires, (int, float)): cookie[key]['expires'] = format_date_time(int(expires)) elif expires is not None and isinstance(expires, datetime): cookie[key]['expires'] = format_date_time(expires.replace(tzinfo=timezone.utc).timestamp()) if domain is not None: cookie[key]['domain'] = domain return cookie","Create a Cookie given the options set The arguments are the standard cookie morsels and this is a wrapper around the stdlib SimpleCookie code. type: ignore type: ignore" 92,get current ip address," def get_ip(self, address): res = self.get_request('/ip_address/' + address) return IPAddress(cloud_manager=self, **res['ip_address'])","Get an IPAddress object with the IP address (string) from the API. e.g manager.get_ip('80.69.175.210')" 93,converting uint8 array to image,"def _convert_uint8(im): if im.dtype != np.uint8: im = np.uint8(im * 255) return im", 94,how to read .csv file in an efficient way?,"def read_csv(csv_name, usecols=None): csv_path = os.path.join(DATA_FOLDER, csv_name) csv = pd.read_csv(csv_path, low_memory=False, usecols=usecols, encoding=""utf-8"") return csv",Returns a DataFrame from a .csv file stored in /data/raw/ 95,export to excel,"def export_analytics_data_to_excel(data, output_file_name, result_info_key, identifier_keys): workbook = create_excel_workbook(data, result_info_key, identifier_keys) workbook.save(output_file_name) print('Saved Excel file to {}'.format(output_file_name))","Creates an Excel file containing data returned by the Analytics API Args: data: Analytics API data as a list of dicts output_file_name: File name for output Excel file (use .xlsx extension)." 96,unzipping large files,"def unzip_file(zip_fname): print(""Unzipping {}"".format(zip_fname)) with zipfile.ZipFile(zip_fname) as zf: zf.extractall()",Unzip the zip_fname in the current directory. 97,unzipping large files," def _unzip_file(self, src_path, dest_path, filename): self.logger.info(""unzipping file..."") unzip_path = os.path.join(dest_path, filename) utils.ensure_directory_exists(unzip_path) with zipfile.ZipFile(src_path, ""r"") as z: z.extractall(unzip_path) return True","unzips file located at src_path into destination_path construct full path (including file name) for unzipping extract data" 98,convert a utc time to epoch,"def datetime_to_epoch_seconds(value): epoch = datetime.utcfromtimestamp(0).replace(tzinfo=timezone.utc) return (value - epoch).total_seconds()", 99,write csv," def write_csv(self): csv_path = self._path/'cleaned.csv' with open(csv_path, 'w') as f: csv_writer = csv.writer(f) csv_writer.writerow(['name','label']) for pair in self._csv_dict.items(): pair = [os.path.relpath(pair[0], self._path), pair[1]] csv_writer.writerow(pair) return csv_path",Get first element's file path so we write CSV to same directory as our data 100,parse binary file to custom class,"def parse_bin(path): f = open(path, 'rb') s = {} output = [] methods = { 'GPS5': parse_gps, 'GPSU': parse_time, 'GPSF': parse_fix, 'GPSP': parse_precision, 'ACCL': parse_accl, 'GYRO': parse_gyro, } d = {'gps': []} while True: label = f.read(4) if not label: break desc = f.read(4) if '00' == binascii.hexlify(desc[0]): continue val_size = struct.unpack('>b', desc[1])[0] num_values = struct.unpack('>h', desc[2:4])[0] length = val_size * num_values if label == 'DVID': if len(d['gps']): output.append(d) d = {'gps': []} for i in range(num_values): data = f.read(val_size) if label in methods: methods[label](data, d, s) if label == 'SCAL': if 2 == val_size: s[i] = struct.unpack('>h', data)[0] elif 4 == val_size: s[i] = struct.unpack('>i', data)[0] else: raise Exception('unknown scal size') mod = length % 4 if mod != 0: seek = 4 - mod f.read(seek) return output","the current Scale data to apply to next requester handlers for various fourCC codes up to date dictionary, iterate and fill then flush eof null length print ""{} {} of size {} and type {}"".format(num_values, label, val_size, desc[0]) first one is empty reset pack discarded" 101,regex case insensitive,"def get_search_regex(query, ignore_case=True): regex_text = [char for char in query if char != ' '] regex_text = '.*'.join(regex_text) regex = r'({0})'.format(regex_text) if ignore_case: pattern = re.compile(regex, re.IGNORECASE) else: pattern = re.compile(regex) return pattern","Returns a compiled regex pattern to search for query letters in order. Parameters ---------- query : str String to search in another string (in order of character occurrence). ignore_case : True Optional value perform a case insensitive search (True by default). Returns ------- pattern : SRE_Pattern Notes ----- This function adds '.*' between the query characters and compiles the resulting regular expression." 102,httpclient post json," def request(self, url, json="""", data="""", username="""", password="""", headers=None, timout=30): raise NotImplementedError('request of HTTPClient should have been ' 'overridden on initialization. ' 'Otherwise, can be overridden to ' 'supply your own post method')","This is overridden on module initialization. This function will make an HTTP POST to a given url. Either json/data will be what is posted to the end point. he HTTP request needs to be basicAuth when username and password are provided. a headers dict maybe provided, whatever the values are should be applied. Args: url (str): url to send the POST json (dict, optional): Dict of the JSON to POST data (dict, optional): Dict, presumed flat structure of key/value of request to place as www-form username (str, optional): Username for basic auth. Must be uncluded as part of password. password (str, optional): Password for basic auth. Must be included as part of username. headers (dict, optional): Key/Value pairs of headers to include Returns: str: Raw request placed str: Raw response received int: HTTP status code, eg 200,404,401 dict: Key/Value pairs of the headers received. :param timout:" 103,get executable path,"def find_windows_executable(bin_path, exe_name): requested_path = get_windows_path(bin_path, exe_name) if os.path.isfile(requested_path): return requested_path try: pathext = os.environ[""PATHEXT""] except KeyError: pass else: for ext in pathext.split(os.pathsep): path = get_windows_path(bin_path, exe_name + ext.strip().lower()) if os.path.isfile(path): return path return find_executable(exe_name)","Given an executable name, search the given location for an executable" 104,how to read .csv file in an efficient way?,"def read_csv(csv_name, usecols=None): csv_path = os.path.join(DATA_FOLDER, csv_name) csv = pd.read_csv(csv_path, low_memory=False, usecols=usecols, encoding=""utf-8"") return csv",Returns a DataFrame from a .csv file stored in /data/raw/ 105,extract data from html content," def _ExtractDataFromShowHtml(self, html): htmlLines = html.splitlines() for count, line in enumerate(htmlLines): if line.strip() == r'
':
        startLine = count+1
      if line.strip() == r'
': endLine = count try: dataList = htmlLines[startLine:endLine] dataString = '\n'.join(dataList) return dataString.strip() except: raise Exception(""Show content not found - check EPGuides html formatting"")","Extracts csv show data from epguides html source. Parameters ---------- html : string Block of html text Returns ---------- string Show data extracted from html text in csv format." 106,heatmap from 3d coordinates," def get_figure(self, heatmap_kw=None, **kwargs): if heatmap_kw is not None: assert isinstance(heatmap_kw, dict) if heatmap_kw is None: heatmap_kw = {} return self.get_heatmap(**heatmap_kw).get_figure(**kwargs)","Generate a plotly figure showing the matrix as a heatmap. This is a shortcut for ``ExpMatrix.get_heatmap(...).get_figure(...)``. See :func:`ExpHeatmap.get_figure` for keyword arguments. Parameters ---------- heatmap_kw : dict or None If not None, dictionary containing keyword arguments to be passed to the `ExpHeatmap` constructor. Returns ------- `plotly.graph_objs.Figure` The plotly figure." 107,confusion matrix," def from_existing(cls, confusion, *args, **kwargs): df = [] for t, p in product(confusion.index.values, confusion.columns.values): df += [[t, p]] * confusion[p][t] if confusion.index.name is not None and confusion.columns.name is not None: return Confusion(pd.DataFrame(df, columns=[confusion.index.name, confusion.columns.name])) return Confusion(pd.DataFrame(df))","Creates a confusion matrix from a DataFrame that already contains confusion counts (but not meta stats) >>> df = pd.DataFrame(np.matrix([[0,1,2,0,1,2,1,2,2,1],[0,1,2,1,2,0,0,1,2,0]]).T, columns=['True', 'Pred']) >>> c = Confusion(df) >>> c2 = pd.DataFrame(c) >>> hasattr(c2, '_binary_sensitivity') False >>> c3 = Confusion.from_existing(c2) >>> hasattr(c3, '_binary_sensitivity') True >>> (c3 == c).all().all() True >>> c3 Pred 0 1 2 True 0 1 1 0 1 2 1 1 2 1 1 2 Extremely brute-force to recreate data from a confusion matrix!" 108,confusion matrix," def confusion_matrix(self): return plot.confusion_matrix(self.y_true, self.y_pred, self.target_names, ax=_gen_ax())",Confusion matrix plot 109,get current process id,"def get_pid(PROCNAME): for proc in psutil.process_iter(): if proc.name == PROCNAME: return proc.pid", 110,copying a file to a path," def copy_file(self, from_path, to_path): if not op.exists(op.dirname(to_path)): self.make_directory(op.dirname(to_path)) shutil.copy(from_path, to_path) logging.debug('File copied: {0}'.format(to_path))",Copy file. 111,how to get current date," def date(self): if self._date: return self._date return datetime.datetime.now().strftime('%Y-%m-%d')","Getter/setter for the date member. The setter can take a string or a :meth:`datetime.datetime` and will do the appropriate transformation." 112,output to html file," def to_file(self, outputfile=DEFAULT_OUTPUTFILE): if outputfile != NO_OUTPUTFILE: if outputfile == DEFAULT_OUTPUTFILE: outputfile = 'profile_' + str(hash(self)) + "".html"" with codecs.open(outputfile, 'w+b', encoding='utf8') as self.file: self.file.write(templates.template('wrapper').render(content=self.html))","Write the report to a file. By default a name is generated. Parameters: ---------- outputfile : str The name or the path of the file to generale including the extension (.html). TODO: should be done in the template" 113,aes encryption,"def aes_ctr_encrypt(text, key, params): iv = big_endian_to_int(decode_hex(params[""iv""])) ctr = Counter.new(128, initial_value=iv, allow_wraparound=True) mode = AES.MODE_CTR encryptor = AES.new(key, mode, counter=ctr) return encryptor.encrypt(text)", 114,encrypt aes ctr mode," def CTREnc(key, plaintext): iv = os.urandom(AES.block_size) cipher = _cipher(_aes(key), _ctrmode(iv), backend=_backend).encryptor() return iv + cipher.update(plaintext) + cipher.finalize()", 115,binomial distribution," def sample(self, n=1): p_vals = self._p_dist.rvs(size=n)[:, np.newaxis] return np.random.binomial(self.n, p_vals)","numpy.random.binomial supports sampling using different p values, whereas scipy does not." 116,replace in file," def _replace_in_file(self, dir_name, filename, args): path = os.path.join(dir_name, filename) with open(path, ""r"") as f: s = f.read() s = s.replace(""{%PROJECT_ID%}"", args.id) s = s.replace(""{%PROJECT_ID_UPPER%}"", self._upper_slug) s = s.replace(""{%PROJECT_ID_LOWER%}"", self._lower_slug) s = s.replace(""{%PROJECT_NAME%}"", args.name) s = s.replace(""{%PROJECT_GITHUB_USER%}"", args.github_user) with open(path, ""w"") as f: f.write(s)", 117,how to read .csv file in an efficient way?," def _read_csv(self, filename: str) -> pd.DataFrame: path = self._pathmap.get(filename) columns = self._config.nodes.get(filename, {}).get(""required_columns"", []) if path is None or os.path.getsize(path) == 0: return empty_df(columns) with open(path, ""rb"") as f: encoding = detect_encoding(f) df = pd.read_csv(path, dtype=np.unicode, encoding=encoding, index_col=False) df.rename(columns=lambda x: x.strip(), inplace=True) if not df.empty: for col in df.columns: df[col] = df[col].str.strip() return df","The file is missing or empty. Return an empty DataFrame containing any required columns. If the file isn't in the zip, return an empty DataFrame. Strip leading/trailing whitespace from column names Strip leading/trailing whitespace from column values" 118,encode url," def urlEncodeAndJoin(self, seq, sepr=','): try: from urllib.parse import quote_plus as encode return sepr.join([encode(x, encoding=CHARSET_UTF8) for x in seq]) except ImportError: from urllib import quote as encode return sepr.join([i for i in map(lambda x: encode(x), seq)])","sepr.join(urlencode(seq)) Args: seq: string list to be urlencoded sepr: join seq with sepr Returns: str" 119,html entities replace,"def replace(html, replacements=None): if not replacements: return html html = HTMLFragment(html) for r in replacements: r.replace(html) return unicode(html)","Performs replacements on given HTML string. no replacements" 120,export to excel," def to_excel(self, excel_writer, sheet_name='data', iamc_index=False, **kwargs): if not isinstance(excel_writer, pd.ExcelWriter): close = True excel_writer = pd.ExcelWriter(excel_writer) self._to_file_format(iamc_index)\ .to_excel(excel_writer, sheet_name=sheet_name, index=False, **kwargs) if close: excel_writer.close()","Write timeseries data to Excel format Parameters ---------- excel_writer: string or ExcelWriter object file path or existing ExcelWriter sheet_name: string, default 'data' name of sheet which will contain `IamDataFrame.timeseries()` data iamc_index: bool, default False if True, use `['model', 'scenario', 'region', 'variable', 'unit']`; else, use all `data` columns" 121,heatmap from 3d coordinates," def draw(self, size=None, cmap=""jet""): heatmaps_uint8 = self.to_uint8() heatmaps_drawn = [] for c in sm.xrange(heatmaps_uint8.shape[2]): heatmap_c = heatmaps_uint8[..., c:c+1] if size is not None: heatmap_c_rs = ia.imresize_single_image(heatmap_c, size, interpolation=""nearest"") else: heatmap_c_rs = heatmap_c heatmap_c_rs = np.squeeze(heatmap_c_rs).astype(np.float32) / 255.0 if cmap is not None: import matplotlib.pyplot as plt cmap_func = plt.get_cmap(cmap) heatmap_cmapped = cmap_func(heatmap_c_rs) heatmap_cmapped = np.delete(heatmap_cmapped, 3, 2) else: heatmap_cmapped = np.tile(heatmap_c_rs[..., np.newaxis], (1, 1, 3)) heatmap_cmapped = np.clip(heatmap_cmapped * 255, 0, 255).astype(np.uint8) heatmaps_drawn.append(heatmap_cmapped) return heatmaps_drawn","Render the heatmaps as RGB images. Parameters ---------- size : None or float or iterable of int or iterable of float, optional Size of the rendered RGB image as ``(height, width)``. See :func:`imgaug.imgaug.imresize_single_image` for details. If set to None, no resizing is performed and the size of the heatmaps array is used. cmap : str or None, optional Color map of ``matplotlib`` to use in order to convert the heatmaps to RGB images. If set to None, no color map will be used and the heatmaps will be converted to simple intensity maps. Returns ------- heatmaps_drawn : list of (H,W,3) ndarray Rendered heatmaps. One per heatmap array channel. Dtype is uint8. c:c+1 here, because the additional axis is needed by imresize_single_image import only when necessary (faster startup; optional dependency; less fragile -- see issue #225)" 122,how to get html of website," def get_html_source(self): req = urllib.request.Request(self.url) req.add_header(""user-agent"", random.choice(USER_AGENTS)) req_text = urllib.request.urlopen(req).read() self.source = str(req_text) self.soup = BeautifulSoup(self.source, ""html.parser"") return self.source","Gets source page of url :return: HTML source" 123,create cookie,"def create_cookie( key: str, value: str='', max_age: Optional[Union[int, timedelta]]=None, expires: Optional[Union[int, float, datetime]]=None, path: str='/', domain: Optional[str]=None, secure: bool=False, httponly: bool=False, ) -> SimpleCookie: cookie = SimpleCookie() cookie[key] = value cookie[key]['path'] = path cookie[key]['httponly'] = httponly cookie[key]['secure'] = secure if isinstance(max_age, timedelta): cookie[key]['max-age'] = f""{max_age.total_seconds():d}"" if isinstance(max_age, int): cookie[key]['max-age'] = str(max_age) if expires is not None and isinstance(expires, (int, float)): cookie[key]['expires'] = format_date_time(int(expires)) elif expires is not None and isinstance(expires, datetime): cookie[key]['expires'] = format_date_time(expires.replace(tzinfo=timezone.utc).timestamp()) if domain is not None: cookie[key]['domain'] = domain return cookie","Create a Cookie given the options set The arguments are the standard cookie morsels and this is a wrapper around the stdlib SimpleCookie code. type: ignore type: ignore" 124,encode url," def trigger(self, identifier, force=True): self.debug(identifier) url = ""{base}/{identifier}"".format( base=self.local_base_url, identifier=identifier ) param = {} if force: param['force'] = force encode = urllib.urlencode(param) if encode: url += ""?"" url += encode return self.core.update(url, {})",Trigger an upgrade task. 125,get inner html," def get_html(self, url): r = self.get(url) return self.html(r.text)", 126,copy to clipboard," def paste(self): clipboard = QApplication.clipboard() cliptext = '' if clipboard.mimeData().hasText(): cliptext = to_text_string(clipboard.text()) if cliptext.strip(): self.import_from_string(cliptext, title=_(""Import from clipboard"")) else: QMessageBox.warning(self, _( ""Empty clipboard""), _(""Nothing to be imported from clipboard."")) ",Import text/data/code from clipboard 127,confusion matrix," def confusion_matrix(self): confusion_matrix = self.pixel_classification_sum.astype(np.float) confusion_matrix = np.divide(confusion_matrix.T, self.pixel_truth_sum.T).T return confusion_matrix * 100.0",Returns the normalised confusion matrix 128,sending binary data over a serial connection," def send(self, msg): slipDriver = sliplib.Driver() slipData = slipDriver.send(msg) res = self._serialPort.write(slipData) return res","Encodes data to slip protocol and then sends over serial port Uses the SlipLib module to convert the message data into SLIP format. The message is then sent over the serial port opened with the instance of the Faraday class used when invoking send(). Args: msg (bytes): Bytes format message to send over serial port. Returns: int: Number of bytes transmitted over the serial port. Create a sliplib Driver Package data in slip format Send data over serial port Return number of bytes transmitted over serial port" 129,string similarity levenshtein,"def levenshtein(s1, s2, allow_substring=False): len1, len2 = len(s1), len(s2) lev = [] for i in range(len1 + 1): lev.append([0] * (len2 + 1)) for i in range(len1 + 1): lev[i][0] = i for j in range(len2 + 1): lev[0][j] = 0 if allow_substring else j for i in range(len1): for j in range(len2): lev[i + 1][j + 1] = min(lev[i][j + 1] + 1, lev[i + 1][j] + 1, lev[i][j] + (s1[i] != s2[j])) return min(lev[len1]) if allow_substring else lev[len1][len2]","Return the Levenshtein distance between two strings. The Levenshtein distance (a.k.a ""edit difference"") is the number of characters that need to be substituted, inserted or deleted to transform s1 into s2. Setting the `allow_substring` parameter to True allows s1 to be a substring of s2, so that, for example, ""hello"" and ""hello there"" would have a distance of zero. :param string s1: The first string :param string s2: The second string :param bool allow_substring: Whether to allow s1 to be a substring of s2 :returns: Levenshtein distance. :rtype int" 130,readonly array," def derive_readonly(self): readonly = list(self.readonly) for key, value in self.field_config.items(): if 'readonly' in value and value['readonly']: readonly.append(key) return readonly","Figures out what fields should be readonly. We iterate our field_config to find all that have a readonly of true" 131,how to make the checkbox checked," def __call__(self, *arg): if self.status: self.status = 0 self.image.fill((255, 255, 255)) ptg.Button.set_position(self, self.position, self.midpoint, self.surface) else: self.status = 1 if self.checktype == 'r': self.draw_rect_check() elif self.checktype == 'c': self.draw_circle_check() ptg.Button.set_position(self, self.position, self.midpoint, self.surface)","If the checkbox was previously checked, set the status to 0 and turn the whole box back to white. Draw the checkbox on the external surface If the checkbox was previously unchecked, set the status to 1 and draw a check in the center of the checkbox. Draw the new image on the external surface" 132,copy to clipboard,"def copy_to_clipboard(text): if sys.platform == 'darwin': os.system('echo ""{0}"" | pbcopy'.format(text)) return try: from Tkinter import Tk except ImportError: return r = Tk() r.withdraw() r.clipboard_clear() r.clipboard_append(text.encode('ascii')) r.destroy()","reliable on mac okay we'll try cross-platform way" 133,unique elements,"def unique_by_index(sequence): uniques = [] for element in sequence: if element not in uniques: uniques.append(element) return uniques","unique elements in `sequence` in the order in which they occur Parameters ---------- sequence : iterable Returns ------- uniques : list unique elements of sequence, ordered by the order in which the element occurs in `sequence`" 134,finding time elapsed using a timer,"def timer(name): startTime = time.time() yield elapsedTime = time.time() - startTime print('[{}] finished in {} ms'.format(name, int(elapsedTime * 1000)))", 135,create cookie," def create_cookie(self, value, typ, cookie_name=None, ttl=-1, kill=False): if kill: ttl = -1 elif ttl < 0: ttl = self.default_value['max_age'] if cookie_name is None: cookie_name = self.default_value['name'] c_args = {} srvdomain = self.default_value['domain'] if srvdomain and srvdomain not in ['localhost', '127.0.0.1', '0.0.0.0']: c_args['domain'] = srvdomain srvpath = self.default_value['path'] if srvpath: c_args['path'] = srvpath timestamp = str(int(time.time())) try: cookie_payload = ""::"".join([value, timestamp, typ]) except TypeError: cookie_payload = ""::"".join([value[0], timestamp, typ]) cookie = make_cookie( cookie_name, cookie_payload, self.sign_key, timestamp=timestamp, enc_key=self.enc_key, max_age=ttl, sign_alg=self.sign_alg, **c_args) return cookie",":param value: Part of the cookie payload :param typ: Type of cookie :param cookie_name: :param ttl: Number of minutes before this cookie goes stale :param kill: Whether the the cookie should expire on arrival :return: A tuple to be added to headers now create cookie payload" 136,how to randomly pick a number,"def randbelow(num: int) -> int: if not isinstance(num, int): raise TypeError('number must be an integer') if num <= 0: raise ValueError('number must be greater than zero') if num == 1: return 0 nbits = num.bit_length() randnum = random_randint(nbits) while randnum >= num: randnum = random_randint(nbits) return randnum","Return a random int in the range [0,num). Raises ValueError if num <= 0, and TypeError if it's not an integer. >>> randbelow(16) #doctest:+SKIP 13 https://github.com/python/cpython/blob/3.6/Lib/random.py#L223 don't use (n-1) here because n can be 1 0 <= randnum < 2**nbits" 137,extracting data from a text file,"def extractdata(pattern, text=None, filepath=None): y = [] if text is None: textsource = open(filepath, 'r') else: textsource = text.splitlines() for line in textsource: match = scanf(pattern, line) if match: if len(y) == 0: y = [[s] for s in match] else: for i, ydata in enumerate(y): ydata.append(match[i]) if text is None: textsource.close() return y","Read through an entire file or body of text one line at a time. Parse each line that matches the supplied pattern string and ignore the rest. If *text* is supplied, it will be parsed according to the *pattern* string. If *text* is not supplied, the file at *filepath* will be opened and parsed." 138,normal distribution," def normal_distribution(self, pos, sample): curr_sigma_sq = self.sigma_sq(sample) delta = self.trial_history[pos - 1] - self.f_comb(pos, sample) return np.exp(np.square(delta) / (-2.0 * curr_sigma_sq)) / np.sqrt(2 * np.pi * np.sqrt(curr_sigma_sq))","returns the value of normal distribution, given the weight's sample and target position Parameters ---------- pos: int the epoch number of the position you want to predict sample: list sample is a (1 * NUM_OF_FUNCTIONS) matrix, representing{w1, w2, ... wk} Returns ------- float the value of normal distribution" 139,matrix multiply," def multiply(self, matrix): if not isinstance(matrix, DenseMatrix): raise ValueError(""Only multiplication with DenseMatrix "" ""is supported."") j_model = self._java_matrix_wrapper.call(""multiply"", matrix) return RowMatrix(j_model)","Multiply this matrix by a local dense matrix on the right. :param matrix: a local dense matrix whose number of rows must match the number of columns of this matrix :returns: :py:class:`RowMatrix` >>> rm = RowMatrix(sc.parallelize([[0, 1], [2, 3]])) >>> rm.multiply(DenseMatrix(2, 2, [0, 2, 1, 3])).rows.collect() [DenseVector([2.0, 3.0]), DenseVector([6.0, 11.0])]" 140,convert decimal to hex," def hexadecimal(token): token = ''.join([ c for c in token if c.isalnum() ]) if len(token) % 2 != 0: raise ValueError(""Missing characters in hex data"") data = '' for i in compat.xrange(0, len(token), 2): x = token[i:i+2] d = int(x, 16) s = struct.pack('"") html_file.write(""

Here are some graphs for you!

"") for image in [lines_filename, bars_filename, histogram_filename]: html_file.write(""

{0}

"".format(image)) html_file.write("""") html_file.close()",Generate an HTML file incorporating the images produced by this script 151,replace in file," def replace_text(filepath, to_replace, replacement): with open(filepath) as file: s = file.read() s = s.replace(to_replace, replacement) with open(filepath, 'w') as file: file.write(s)","Replaces a string in a given file with another string :param file: the file in which the string has to be replaced :param to_replace: the string to be replaced in the file :param replacement: the string which replaces 'to_replace' in the file" 152,parse json file,"def _read_json_file(path): try: with open(path) as f: return json.load(f) except: print ('Warning: Unable to read or parse json file: '+path) return None", 153,matrix multiply," def __mul__(self, other): if self.finalized: dmat = self.__class__() dmat.shape = self.shape if isinstance(other, Sparse3DMatrix): if other.finalized: for hid in xrange(self.shape[1]): dmat.data.append(self.data[hid].multiply(other.data[hid])) else: raise RuntimeError('Both matrices must be finalized.') elif isinstance(other, (np.ndarray, csc_matrix, csr_matrix)): for hid in xrange(self.shape[1]): dmat.data.append(self.data[hid] * other) dmat.shape = (other.shape[1], self.shape[1], self.shape[2]) elif isinstance(other, (coo_matrix, lil_matrix)): other_csc = other.tocsc() for hid in xrange(self.shape[1]): dmat.data.append(self.data[hid] * other_csc) dmat.shape = (other_csc.shape[1], self.shape[1], self.shape[2]) elif isinstance(other, Number): for hid in xrange(self.shape[1]): dmat.data.append(self.data[hid] * other) else: raise TypeError('This operator is not supported between the given types.') dmat.finalized = True return dmat else: raise RuntimeError('The original matrix must be finalized.')","element-wise multiplication between same kind matrix-matrix multiplication matrix-matrix multiplication rescaling of matrix" 154,how to read the contents of a .gz compressed file?," def read(self): with gzip.GzipFile(self.path, compresslevel=self.compresslevel) as gz_file: gz_file.read1 = gz_file.read with io.TextIOWrapper(gz_file, encoding=self.encoding, errors=self.errors, newline=self.newline) as file_content: return file_content.read()", 155,group by count,"def groupby_count(i, key=None, force_keys=None): counter = defaultdict(lambda: 0) if not key: key = lambda o: o for k in i: counter[key(k)] += 1 if force_keys: for k in force_keys: counter[k] += 0 return counter.items()","Aggregate iterator values into buckets based on how frequently the values appear. Example:: >>> list(groupby_count([1, 1, 1, 2, 3])) [(1, 3), (2, 1), (3, 1)]" 156,normal distribution," def normal_distribution(self, pos, sample): curr_sigma_sq = self.sigma_sq(sample) delta = self.trial_history[pos - 1] - self.f_comb(pos, sample) return np.exp(np.square(delta) / (-2.0 * curr_sigma_sq)) / np.sqrt(2 * np.pi * np.sqrt(curr_sigma_sq))","returns the value of normal distribution, given the weight's sample and target position Parameters ---------- pos: int the epoch number of the position you want to predict sample: list sample is a (1 * NUM_OF_FUNCTIONS) matrix, representing{w1, w2, ... wk} Returns ------- float the value of normal distribution" 157,get current observable value," def _set_observable(self, observable_name, new_value): if self._has_value(observable_name): old_value = self.new_value(observable_name) must_set = np.any(new_value != old_value) if must_set: if isinstance(old_value, Observable) and isinstance(new_value, Observable): old_value.copy_observers_to(new_value) old_value._notify_observers(observable_name=None, include_everything_observers=True) for observable_name in old_value._observers.keys(): old_has_value = old_value._has_value(observable_name) new_has_value = new_value._has_value(observable_name) if old_has_value != new_has_value or (old_has_value and new_has_value and np.any(old_value._get_value(observable_name) != new_value._get_value(observable_name))): old_value._notify_observers(observable_name=observable_name, include_everything_observers=False) else: must_set = True if must_set: self._set_value(observable_name, new_value) self._notify_observers(observable_name)","# check old value # set only if different value # if values are observable_names with observers call associated observers of sub observable_names # copy observer # notify old observer # set new observable_name value and call observer" 158,create cookie," def set_cookie(self, name, value = '', expires = 0, path = '/', domain = '', secure = False, http_only = False): cook = Cookie.SimpleCookie() cook[name] = value cook[name]['expires'] = expires cook[name]['path'] = path cook[name]['domain'] = domain cook[name]['secure'] = secure cook[name]['httponly'] = http_only self.send_header('Set-Cookie', cook.output(header = ''))", 159,how to check if a checkbox is checked,"def assert_checked_checkbox(self, value): check_box = find_field(world.browser, 'checkbox', value) assert check_box, ""Cannot find checkbox '{}'."".format(value) assert check_box.is_selected(), ""Check box should be selected.""","Assert the checkbox with label (recommended), name or id is checked." 160,convert int to bool,"def _convert_to_bool(argument): lowered = argument.lower() if lowered in ('yes', 'y', 'true', 't', '1', 'enable', 'on'): return True elif lowered in ('no', 'n', 'false', 'f', '0', 'disable', 'off'): return False else: raise BadArgument(lowered + ' is not a recognised boolean option')", 161,how to make the checkbox checked," def __call__(self, *arg): if self.status: self.status = 0 self.image.fill((255, 255, 255)) ptg.Button.set_position(self, self.position, self.midpoint, self.surface) else: self.status = 1 if self.checktype == 'r': self.draw_rect_check() elif self.checktype == 'c': self.draw_circle_check() ptg.Button.set_position(self, self.position, self.midpoint, self.surface)","If the checkbox was previously checked, set the status to 0 and turn the whole box back to white. Draw the checkbox on the external surface If the checkbox was previously unchecked, set the status to 1 and draw a check in the center of the checkbox. Draw the new image on the external surface" 162,matrix multiply," def __mul__(self, other): if self.finalized: dmat = self.__class__() dmat.shape = self.shape if isinstance(other, Sparse3DMatrix): if other.finalized: for hid in xrange(self.shape[1]): dmat.data.append(self.data[hid].multiply(other.data[hid])) else: raise RuntimeError('Both matrices must be finalized.') elif isinstance(other, (np.ndarray, csc_matrix, csr_matrix)): for hid in xrange(self.shape[1]): dmat.data.append(self.data[hid] * other) dmat.shape = (other.shape[1], self.shape[1], self.shape[2]) elif isinstance(other, (coo_matrix, lil_matrix)): other_csc = other.tocsc() for hid in xrange(self.shape[1]): dmat.data.append(self.data[hid] * other_csc) dmat.shape = (other_csc.shape[1], self.shape[1], self.shape[2]) elif isinstance(other, Number): for hid in xrange(self.shape[1]): dmat.data.append(self.data[hid] * other) else: raise TypeError('This operator is not supported between the given types.') dmat.finalized = True return dmat else: raise RuntimeError('The original matrix must be finalized.')","element-wise multiplication between same kind matrix-matrix multiplication matrix-matrix multiplication rescaling of matrix" 163,write csv," def to_csv(self, fbuf, quotechar='""', delimiter=','): csvwriter = csv.writer( fbuf, quotechar=quotechar, delimiter=delimiter, lineterminator=""\n"", quoting=csv.QUOTE_ALL ) if self.headers: csvwriter.writerow(self.headers) for line in self.sylk_handler.stream_rows(): csvwriter.writerow(line)", 164,k means clustering,"Error: 404 {""message"": ""No commit found for the ref f12f46724295b57c4859e6acf7eab580fc355eb1"", ""documentation_url"": ""https://docs.github.com/v3/repos/contents/"", ""status"": ""404""}", 165,unique elements,"def unique_by_index(sequence): uniques = [] for element in sequence: if element not in uniques: uniques.append(element) return uniques","unique elements in `sequence` in the order in which they occur Parameters ---------- sequence : iterable Returns ------- uniques : list unique elements of sequence, ordered by the order in which the element occurs in `sequence`" 166,format date," def format_grouped_date(self, data, group): date = self.get_grouped_date(data, group) if group == 'week': date = u'%s — %s' % ( (date - datetime.timedelta(days=6)).strftime('%d.%m'), date.strftime('%d.%m') ) elif group == 'month': date = date.strftime('%b, %Y') else: date = formats.date_format(date, 'DATE_FORMAT') return date", 167,string similarity levenshtein,"def diff(s1, s2): return levenshtein(s1, s2) / max(len(s1), len(s2))","Return a normalised Levenshtein distance between two strings. Distance is normalised by dividing the Levenshtein distance of the two strings by the max(len(s1), len(s2)). Examples: >>> text.diff(""foo"", ""foo"") 0 >>> text.diff(""foo"", ""fooo"") 1 >>> text.diff(""foo"", """") 1 >>> text.diff(""1234"", ""1 34"") 1 Arguments: s1 (str): Argument A. s2 (str): Argument B. Returns: float: Normalised distance between the two strings." 168,group by count," def get_top_entries(self): query = 'select count(vendor_name) count, vendor_name from mac_vendor group by vendor_name having count > 10 order by count;' try: db = self.get_db() results = db.execute(query) return [i for i in results] finally: db.close()", 169,finding time elapsed using a timer,"def timer(description='Operation', log=None): start = time() yield elapsed = time() - start message = '%s took %s seconds' % (description, elapsed) (print if log is None else log.info)(message)","Simple context manager which logs (if log is provided) or prints the time taken in seconds for the block to complete. >>> with timer(): ... sleep(0.1) # doctest:+ELLIPSIS Operation took 0.1... seconds >>> with timer('Sleeping'): ... sleep(0.2) # doctest:+ELLIPSIS Sleeping took 0.2... seconds >>> with timer(description='Doing', log=PrintingLogger()): ... sleep(0.3) # doctest:+ELLIPSIS Doing took 0.3... seconds" 170,all permutations of a list,"def distinct_permutations(iterable): def make_new_permutations(permutations, e): for permutation in permutations: for j in range(len(permutation)): yield permutation[:j] + [e] + permutation[j:] if permutation[j] == e: break else: yield permutation + [e] permutations = [[]] for e in iterable: permutations = make_new_permutations(permutations, e) return (tuple(t) for t in permutations)","Yield successive distinct permutations of the elements in *iterable*. >>> sorted(distinct_permutations([1, 0, 1])) [(0, 1, 1), (1, 0, 1), (1, 1, 0)] Equivalent to ``set(permutations(iterable))``, except duplicates are not generated and thrown away. For larger input sequences this is much more efficient. Duplicate permutations arise when there are duplicated elements in the input iterable. The number of items returned is `n! / (x_1! * x_2! * ... * x_n!)`, where `n` is the total number of items input, and each `x_i` is the count of a distinct item in the input sequence. Internal helper function. The output permutations are built up by adding element *e* to the current *permutations* at every possible position. The key idea is to keep repeated elements (reverse) ordered: if e1 == e2 and e1 is before e2 in the iterable, then all permutations with e1 before e2 are ignored." 171,randomly extract x items from a list,"def sample_lists(items_list, num=1, seed=None): r if seed is not None: rng = np.random.RandomState(seed) else: rng = np.random def random_choice(items, num): size = min(len(items), num) return rng.choice(items, size, replace=False).tolist() samples_list = [random_choice(items, num) if len(items) > 0 else [] for items in items_list] return samples_list","Args: items_list (list): num (int): (default = 1) seed (None): (default = None) Returns: list: samples_list CommandLine: python -m utool.util_list --exec-sample_lists Example: >>> # DISABLE_DOCTEST >>> from utool.util_list import * # NOQA >>> items_list = [[], [1, 2, 3], [4], [5, 6], [7, 8, 9, 10]] >>> num = 2 >>> seed = 0 >>> samples_list = sample_lists(items_list, num, seed) >>> result = ('samples_list = %s' % (str(samples_list),)) >>> print(result) samples_list = [[], [3, 2], [4], [5, 6], [10, 9]]" 172,convert int to string," def convert_to_integer(self, str): if str.startswith('0x') or str.startswith('0X'): return int(str, 16) elif str.startswith('2_'): return int(str[2:], 2) else: return int(str)", 173,parse binary file to custom class," def parse_binary(self, data, display): class_type, length = struct.unpack('=HH', data[:4]) class_struct = INFO_CLASSES.get(class_type, AnyInfo) class_data, _ = class_struct.parse_binary(data, display) data = data[length * 4:] return class_data, data", 174,sending binary data over a serial connection,"def serial_send(msvr, msvr_ip, xsvr, xsvr_ip, node_sn, node_key, port): thread = termui.waiting_echo(""Getting device information..."") thread.daemon = True thread.start() flag = False try: with serial.Serial(port, 115200, timeout=5) as ser: cmd = 'Blank?\r\n' ser.write(cmd.encode('utf-8')) if 'Node' in ser.readline(): flag = True except serial.SerialException as e: thread.stop('') thread.join() click.secho('>> ', fg='red', nl=False) click.echo(e) if e.errno == 13: click.echo(""For more information, see https://github.com/Seeed-Studio/wio-cli return None thread.stop('') thread.join() if flag: click.secho('> ', fg='green', nl=False) click.secho(""Found Wio."", fg='green', bold=True) click.echo() else: click.secho('> ', fg='green', nl=False) click.secho(""No nearby Wio detected."", fg='white', bold=True) if click.confirm(click.style('? ', fg='green') + click.style(""Would you like to wait and monitor for Wio entering configure mode"", bold=True), default=True): thread = termui.waiting_echo(""Waiting for a wild Wio to appear... (press ctrl + C to exit)"") thread.daemon = True thread.start() flag = False while 1: with serial.Serial(port, 115200, timeout=5) as ser: cmd = 'Blank?\r\n' ser.write(cmd.encode('utf-8')) if 'Node' in ser.readline(): flag = True break thread.stop('') thread.join() click.secho('> ', fg='green', nl=False) click.secho(""Found Wio."", fg='green', bold=True) click.echo() else: click.secho('> ', fg='green', nl=False) click.secho(""\nQuit wio setup!"", bg='white', bold=True) while 1: if not click.confirm(click.style('? ', fg='green') + click.style(""Would you like to manually enter your Wi-Fi network configuration?"", bold=True), default=False): thread = termui.waiting_echo(""Asking the Wio to scan for nearby Wi-Fi networks..."") thread.daemon = True thread.start() flag = False with serial.Serial(port, 115200, timeout=3) as ser: cmd = 'SCAN\r\n' ser.write(cmd.encode('utf-8')) ssid_list = [] while True: ssid = ser.readline() if ssid == '\r\n': flag = True break ssid = ssid.strip('\r\n') ssid_list.append(ssid) if flag: thread.stop('') thread.join() else: thread.stop(""\rsearch failure...\n"") return None while 1: for x in range(len(ssid_list)): click.echo(""%s.) %s"" %(x, ssid_list[x])) click.secho('? ', fg='green', nl=False) value = click.prompt( click.style('Please select the network to which your Wio should connect', bold=True), type=int) if value >= 0 and value < len(ssid_list): ssid = ssid_list[value] break else: click.echo(click.style('>> ', fg='red') + ""invalid input, range 0 to %s"" %(len(ssid_list)-1)) ap = ssid else: ap = click.prompt(click.style('> ', fg='green') + click.style('Please enter the SSID of your Wi-Fi network', bold=True), type=str) ap_pwd = click.prompt(click.style('> ', fg='green') + click.style('Please enter your Wi-Fi network password (leave blank for none)', bold=True), default='', show_default=False) d_name = click.prompt(click.style('> ', fg='green') + click.style('Please enter the name of a device will be created', bold=True), type=str) click.echo(click.style('> ', fg='green') + ""Here's what we're going to send to the Wio:"") click.echo() click.echo(click.style('> ', fg='green') + ""Wi-Fi network: "" + click.style(ap, fg='green', bold=True)) ap_pwd_p = ap_pwd if ap_pwd_p == '': ap_pwd_p = 'None' click.echo(click.style('> ', fg='green') + ""Password: "" + click.style(ap_pwd_p, fg='green', bold=True)) click.echo(click.style('> ', fg='green') + ""Device name: "" + click.style(d_name, fg='green', bold=True)) click.echo() if click.confirm(click.style('? ', fg='green') + ""Would you like to continue with the information shown above?"", default=True): break click.echo() thread = termui.waiting_echo(""Sending Wi-Fi information to device..."") thread.daemon = True thread.start() version = 1.1 with serial.Serial(port, 115200, timeout=10) as ser: cmd = 'VERSION\r\n' ser.write(cmd.encode('utf-8')) res = ser.readline() try: version = float(re.match(r""([0-9]+.[0-9]+)"", res).group(0)) except Exception as e: version = 1.1 send_flag = False while 1: with serial.Serial(port, 115200, timeout=10) as ser: if version <= 1.1: cmd = ""APCFG: %s\t%s\t%s\t%s\t%s\t%s\t\r\n"" %(ap, ap_pwd, node_key, node_sn, xsvr_ip, msvr_ip) elif version >= 1.2: cmd = ""APCFG: %s\t%s\t%s\t%s\t%s\t%s\t\r\n"" %(ap, ap_pwd, node_key, node_sn, xsvr, msvr) else: cmd = ""APCFG: %s\t%s\t%s\t%s\t%s\t%s\t\r\n"" %(ap, ap_pwd, node_key, node_sn, xsvr, msvr) ser.write(cmd.encode('utf-8')) if ""ok"" in ser.readline(): click.echo(click.style('\r> ', fg='green') + ""Send Wi-Fi information to device success."") thread.stop('') thread.join() send_flag = True if send_flag: break if send_flag: return {'name': d_name} else: return None","## check is configure mode? serial-port-permissions"") waiting ui send serial command # get version click.echo(cmd)" 175,parse command line argument,"def parse_commandline(): parser = argparse.ArgumentParser( description='Intuition, the terrific trading system') parser.add_argument('-V', '--version', action='version', version='%(prog)s v{} Licence {}'.format( __version__, __licence__), help='Print program version') parser.add_argument('-v', '--showlog', action='store_true', help='Print logs on stdout') parser.add_argument('-b', '--bot', action='store_true', help='Allows the algorithm to process orders') parser.add_argument('-c', '--context', action='store', default='file::conf.yaml', help='Provides the way to build context') parser.add_argument('-i', '--id', action='store', default='gekko', help='Customize the session id') args = parser.parse_args() return { 'session': args.id, 'context': args.context, 'showlog': args.showlog, 'bot': args.bot }",Dict will be more generic to process than args namespace 176,scatter plot," def scatterplot(self, x, y, **kw): self.panel.scatterplot(x, y, **kw)",plot after clearing current plot 177,connect to sql," def _connect(self): if self._connParams: self._conn = MySQLdb.connect(**self._connParams) else: self._conn = MySQLdb.connect('')",Establish connection to MySQL Database. 178,how to randomly pick a number," def random_within(self, r): return self.random.randint(int(r[0]), int(r[1]))", 179,string similarity levenshtein,"def levenshtein(str1, s2): N1 = len(str1) N2 = len(s2) stringRange = [range(N1 + 1)] * (N2 + 1) for i in range(N2 + 1): stringRange[i] = range(i,i + N1 + 1) for i in range(0,N2): for j in range(0,N1): if str1[j] == s2[i]: stringRange[i+1][j+1] = min(stringRange[i+1][j] + 1, stringRange[i][j+1] + 1, stringRange[i][j]) else: stringRange[i+1][j+1] = min(stringRange[i+1][j] + 1, stringRange[i][j+1] + 1, stringRange[i][j] + 1) return stringRange[N2][N1]",Distance between two strings 180,replace in file,"def replaces_in_file(file, replacement_list): rs = [(re.compile(regexp), repl) for (regexp, repl) in replacement_list] file_tmp = file + ""."" + str(os.getpid()) + "".tmp"" with open(file, 'r') as f: with open(file_tmp, 'w') as f_tmp: for line in f: for r, replace in rs: match = r.search(line) if match: line = replace + ""\n"" f_tmp.write(line) shutil.move(file_tmp, file)", 181,encode url," def _list(self, domain=None): url = ""{base}"".format( base=self.local_base_url ) param = {} if domain: param['domainUuid'] = domain encode = urllib.urlencode(param) if encode: url += ""?"" url += encode return self.core.list(url)",pylint: disable=arguments-differ 182,connect to sql," def _connect(self): if mysql is None: raise ImproperlyConfigured('MySQL driver not installed!') conn = mysql.connect(db=self.database, **self.connect_params) return conn", 183,get the description of a http status code,"def get_description(status_code): description = _descriptions.get(status_code) if description is None: description = 'code = %s (no description)' % str(status_code) return description",Get the description for a status code. 184,pretty print json,"def pprint(j, no_pretty): if not no_pretty: click.echo( json.dumps(j, cls=PotionJSONEncoder, sort_keys=True, indent=4, separators=("","", "": "")) ) else: click.echo(j)",Prints as formatted JSON 185,deserialize json," def json_loads(payload): ""Log the payload that cannot be parsed"" try: return json.loads(payload) except ValueError as e: log.error(""unable to json.loads("" + payload + "")"") raise e", 186,postgresql connection,"def get_connection(engine, host, user, port, password, database, ssl={}): if engine == 'mysql': return get_mysql_connection(host, user, port, password, database, ssl) elif engine == 'postgresql': return get_pg_connection(host, user, port, password, database, ssl) else: raise RuntimeError('`%s` is not a valid engine.' % engine)","Returns a PostgreSQL or MySQL connection Connection Connection" 187,httpclient post json," def post(self, path, data, json=True, **kwargs): return self._request('post', path, data, json=json, **kwargs)", 188,write csv," def write_to_csv(self, filename): fid = open(filename, 'wt') header_info = ['Longitude', 'Latitude', 'Depth', 'Observed Count', 'Smoothed Rate', 'b-value'] writer = csv.DictWriter(fid, fieldnames=header_info) headers = dict((name0, name0) for name0 in header_info) writer.writerow(headers) for row in self.data: if row[4] == 0: continue row_dict = {'Longitude': '%g' % row[0], 'Latitude': '%g' % row[1], 'Depth': '%g' % row[2], 'Observed Count': '%d' % row[3], 'Smoothed Rate': '%.6g' % row[4], 'b-value': '%g' % self.bval} writer.writerow(row_dict) fid.close()","Exports to simple csv :param str filename: Path to file for export Create header list Write to file institute crude compression by omitting points with no seismicity and taking advantage of the %g format" 189,string similarity levenshtein,"def levenshtein(left, right): sc = SparkContext._active_spark_context jc = sc._jvm.functions.levenshtein(_to_java_column(left), _to_java_column(right)) return Column(jc)","Computes the Levenshtein distance of the two given strings. >>> df0 = spark.createDataFrame([('kitten', 'sitting',)], ['l', 'r']) >>> df0.select(levenshtein('l', 'r').alias('d')).collect() [Row(d=3)]" 190,unzipping large files,"def unzip_file(zip_fname): print(""Unzipping {}"".format(zip_fname)) with zipfile.ZipFile(zip_fname) as zf: zf.extractall()",Unzip the zip_fname in the current directory. 191,group by count," def group_by_count(self): d = OrderedDict() for item, count in self.most_common(): if count not in d: d[count] = [] d[count].append(item) return d.items()", 192,how to extract zip file recursively,"def extract_zipdir(zip_file): if not os.path.exists(zip_file): raise ValueError('{} does not exist'.format(zip_file)) directory = os.path.dirname(zip_file) filename = os.path.basename(zip_file) dirpath = os.path.join(directory, filename.replace('.zip', '')) with zipfile.ZipFile(zip_file, 'r', zipfile.ZIP_DEFLATED) as zipf: zipf.extractall(dirpath) return dirpath","Extract contents of zip file into subfolder in parent directory. Parameters ---------- zip_file : str Path to zip file Returns ------- str : folder where the zip was extracted" 193,format date,"def dateformat(value, format='%-d %B %Y'): new_date = parser.parse(value, dayfirst=True) return new_date.strftime(format)", 194,set working directory," def set_working_dir(self, working_dir): yield from self.send('hypervisor working_dir ""{}""'.format(working_dir)) self._working_dir = working_dir log.debug(""Working directory set to {}"".format(self._working_dir))","Sets the working directory for this hypervisor. :param working_dir: path to the working directory encase working_dir in quotes to protect spaces in the path" 195,write csv," def write_csv(self): csv_path = self._path/'cleaned.csv' with open(csv_path, 'w') as f: csv_writer = csv.writer(f) csv_writer.writerow(['name','label']) for pair in self._csv_dict.items(): pair = [os.path.relpath(pair[0], self._path), pair[1]] csv_writer.writerow(pair) return csv_path",Get first element's file path so we write CSV to same directory as our data 196,how to read .csv file in an efficient way?," def _read_csv(self, filename: str) -> pd.DataFrame: path = self._pathmap.get(filename) columns = self._config.nodes.get(filename, {}).get(""required_columns"", []) if path is None or os.path.getsize(path) == 0: return empty_df(columns) with open(path, ""rb"") as f: encoding = detect_encoding(f) df = pd.read_csv(path, dtype=np.unicode, encoding=encoding, index_col=False) df.rename(columns=lambda x: x.strip(), inplace=True) if not df.empty: for col in df.columns: df[col] = df[col].str.strip() return df","The file is missing or empty. Return an empty DataFrame containing any required columns. If the file isn't in the zip, return an empty DataFrame. Strip leading/trailing whitespace from column names Strip leading/trailing whitespace from column values" 197,how to get html of website," def get_html(self): r = requests.get(self.url) if r.status_code == 404: raise PlayerNotFoundError else: soup = BeautifulSoup(r.text, 'html.parser') return soup.find(""div"", class_=""pnl490M"")", 198,get executable path," def get_exe_path(cls): return os.path.abspath(os.path.join(ROOT, cls.bmds_version_dir, cls.exe + "".exe""))",Return the full path to the executable. 199,extract latitude and longitude from given input," def decode_longitude(self, longitude): match = RE_LONGITUDE.match(longitude) if not match: raise ParserError('Reading longitude failed') longitude = int(match.group(1)) + float(match.group(2)) / 60. if not (0 <= longitude <= 180): raise ParserError('Longitude out of bounds') if match.group(3).upper() == 'W': longitude = -longitude return longitude", 200,get executable path," def get_exe_path(cls): return os.path.abspath(os.path.join(ROOT, cls.bmds_version_dir, cls.exe + "".exe""))",Return the full path to the executable. 201,copy to clipboard," def copyFilepath( self ): clipboard = QApplication.instance().clipboard() clipboard.setText(self.filepath()) clipboard.setText(self.filepath(), clipboard.Selection)",Copies the current filepath contents to the current clipboard. 202,linear regression,"Error: 404 {""message"": ""Not Found"", ""documentation_url"": ""https://docs.github.com/rest/repos/repos","get-a-repository"", ""status"": ""404""}" 203,extract latitude and longitude from given input," def from_latitude_longitude(cls, latitude=0.0, longitude=0.0): assert -180.0 <= longitude <= 180.0, 'Longitude needs to be a value between -180.0 and 180.0.' assert -90.0 <= latitude <= 90.0, 'Latitude needs to be a value between -90.0 and 90.0.' return cls(latitude=latitude, longitude=longitude)",Creates a point from lat/lon in WGS84 204,how to make the checkbox checked," def addCheckBox(self, *args, **kwargs): checkbox = BeakerxCheckbox(description=self.getDescription(args, kwargs)) checkbox.value = getValue(kwargs, 'value', False) self.children += (checkbox,) self.components[checkbox.description] = checkbox return checkbox", 205,create cookie," def create_cookie(self, value, typ, cookie_name=None, ttl=-1, kill=False): if kill: ttl = -1 elif ttl < 0: ttl = self.default_value['max_age'] if cookie_name is None: cookie_name = self.default_value['name'] c_args = {} srvdomain = self.default_value['domain'] if srvdomain and srvdomain not in ['localhost', '127.0.0.1', '0.0.0.0']: c_args['domain'] = srvdomain srvpath = self.default_value['path'] if srvpath: c_args['path'] = srvpath timestamp = str(int(time.time())) try: cookie_payload = ""::"".join([value, timestamp, typ]) except TypeError: cookie_payload = ""::"".join([value[0], timestamp, typ]) cookie = make_cookie( cookie_name, cookie_payload, self.sign_key, timestamp=timestamp, enc_key=self.enc_key, max_age=ttl, sign_alg=self.sign_alg, **c_args) return cookie",":param value: Part of the cookie payload :param typ: Type of cookie :param cookie_name: :param ttl: Number of minutes before this cookie goes stale :param kill: Whether the the cookie should expire on arrival :return: A tuple to be added to headers now create cookie payload" 206,format date,"def format_date_list(dates): format = dateformat.DateFormat(""YYYY-MM-DD hh:mm:ss"") return [format.format(date) for date in dates]", 207,copy to clipboard," def copyFilepath( self ): clipboard = QApplication.instance().clipboard() clipboard.setText(self.filepath()) clipboard.setText(self.filepath(), clipboard.Selection)",Copies the current filepath contents to the current clipboard. 208,all permutations of a list,"def permutations(x): if len(x) > 1: for permutation in permutations(x[1:]): for i in xrange(len(permutation)+1): yield permutation[:i] + x[0:1] + permutation[i:] else: yield x",Stick the first digit in every position. 209,extract data from html content," def extract(self, html_text: str, extract_title: bool = False, extract_meta: bool = False, extract_microdata: bool = False, microdata_base_url: str = """", extract_json_ld: bool = False, extract_rdfa: bool = False, rdfa_base_url: str = """") \ -> List[Extraction]: res = list() soup = BeautifulSoup(html_text, 'html.parser') if soup.title and extract_title: title = self._wrap_data(""title"", soup.title.string.encode('utf-8').decode('utf-8')) res.append(title) if soup.title and extract_meta: meta_content = self._wrap_meta_content(soup.find_all(""meta"")) meta_data = self._wrap_data(""meta"", meta_content) res.append(meta_data) if extract_microdata: mde = MicrodataExtractor() mde_data = self._wrap_data(""microdata"", mde.extract(html_text, microdata_base_url)) res.append(mde_data) if extract_json_ld: jslde = JsonLdExtractor() jslde_data = self._wrap_data(""json-ld"", jslde.extract(html_text)) res.append(jslde_data) if extract_rdfa: rdfae = RDFaExtractor() rdfae_data = self._wrap_data(""rdfa"", rdfae.extract(html_text, rdfa_base_url)) res.append(rdfae_data) return res","Args: html_text (str): input html string to be extracted extract_title (bool): True if string of 'title' tag needs to be extracted, return as { ""title"": ""..."" } extract_meta (bool): True if string of 'meta' tags needs to be extracted, return as { ""meta"": { ""author"": ""..."", ...}} extract_microdata (bool): True if microdata needs to be extracted, returns as { ""microdata"": [...] } microdata_base_url (str): base namespace url for microdata, empty string if no base url is specified extract_json_ld (bool): True if json-ld needs to be extracted, return as { ""json-ld"": [...] } extract_rdfa (bool): True if rdfs needs to be extracted, returns as { ""rdfa"": [...] } rdfa_base_url (str): base namespace url for rdfa, empty string if no base url is specified Returns: List[Extraction]: the list of extraction or the empty list if there are no matches." 210,deserialize json," def json_loads(payload): ""Log the payload that cannot be parsed"" try: return json.loads(payload) except ValueError as e: log.error(""unable to json.loads("" + payload + "")"") raise e", 211,deserialize json,"def deserialize(json, cls=None): LOGGER.debug('deserialize(%s)', json) out = simplejson.loads(json) if isinstance(out, dict) and cls is not None: return cls(**out) return out","Deserialize a JSON string into a Python object. Args: json (str): the JSON string. cls (:py:class:`object`): if the ``json`` is deserialized into a ``dict`` and this argument is set, the ``dict`` keys are passed as keyword arguments to the given ``cls`` initializer. Returns: Python object representation of the given JSON string." 212,socket recv timeout," def recv_with_timeout(self, timeout=1): msg = self.ins.recv(timeout) t = time.time() if msg is None: raise Scapy_Exception(""Timeout"") return self.basecls, msg, t","Receive a complete ISOTP message, blocking until a message is received or the specified timeout is reached. If timeout is 0, then this function doesn't block and returns the first frame in the receive buffer or None if there isn't any." 213,convert html to pdf,"def html_to_pdf(tmp_filenames, output_directory, lang_options): input_html = output_directory + ""/"" + tmp_filenames[0] wkthml_cmd = [""wkhtmltopdf""] wkthml_cmd.extend([""--margin-left"", ""18""]) wkthml_cmd.extend([""--margin-right"", ""18""]) wkthml_cmd.extend([""--page-size"", ""Letter""]) header_file = pkg_resources.resource_filename(""wrc"", ""data/header.html"") footer_file = pkg_resources.resource_filename(""wrc"", ""data/footer.html"") wkthml_cmd.extend([""--header-html"", header_file]) wkthml_cmd.extend([""--footer-html"", footer_file]) wkthml_cmd.extend([""--header-spacing"", ""8""]) wkthml_cmd.extend([""--footer-spacing"", ""8""]) wkthml_cmd.append(input_html) wkthml_cmd.append(output_directory + ""/"" + lang_options['pdf'] + '.pdf') try: check_call(wkthml_cmd) print ""Successfully generated pdf file!"" print ""Cleaning temporary file (%s)..."" % input_html os.remove(input_html) except CalledProcessError as err: print ""Error while generating pdf:"" print err sys.exit(1) except OSError as err: print ""Error when running command \"""" + "" "".join(wkthml_cmd) + ""\"""" print err sys.exit(1)","Basic margins etc Header and Footer" 214,convert json to csv,"def json_to_csv(json_input): try: json_input = json.loads(json_input) except: pass headers = set() for json_row in json_input: headers.update(json_row.keys()) csv_io = StringIO.StringIO() csv_out = csv.DictWriter(csv_io,headers) csv_out.writeheader() for json_row in json_input: csv_out.writerow(json_row) csv_io.seek(0) return csv_io.read()","Convert simple JSON to CSV Accepts a JSON string or JSON object If loads fails, it's probably already parsed" 215,deserialize json," def deserialize(self, s, cls): vals = json.JSONDecoder().decode(s) return self.deserialize_map(vals, cls)", 216,read properties file,"Error: 404 {""message"": ""Not Found"", ""documentation_url"": ""https://docs.github.com/rest/repos/repos","get-a-repository"", ""status"": ""404""}" 217,socket recv timeout," def recv(self, recv_socket, llc): time.sleep(0.1) echo_buffer = queue.Queue(self.options.co_echo_buffer) send_socket = nfc.llcp.Socket(llc, nfc.llcp.DATA_LINK_CONNECTION) if self.options.pattern_number == 0x1200: send_socket.connect(self.options.sap_lt_co_out_dest) elif self.options.pattern_number == 0x1240: send_socket.connect(""urn:nfc:sn:dta-co-echo-out"") elif self.options.pattern_number == 0x1280: send_socket.connect(llc.resolve(""urn:nfc:sn:dta-co-echo-out"")) send_thread = Thread(target=self.send, args=(send_socket, echo_buffer)) send_thread.start() log.info(""receiving from sap %d"", recv_socket.getpeername()) while recv_socket.poll(""recv""): data = recv_socket.recv() if data == None: break log.info(""rcvd %d byte"", len(data)) recv_socket.setsockopt(nfc.llcp.SO_RCVBSY, echo_buffer.full()) echo_buffer.put(data) log.info(""remote side closed connection"") try: echo_buffer.put_nowait(int(0)) except queue.Full: pass send_thread.join() recv_socket.close() log.info(""recv thread terminated"")",delay to accept inbound connection before resolve 218,format date,"def datetime_from_iso8601(date): format = ISO8610_FORMAT if date.endswith(""Z""): date = date[:-1] if re.match("".*\.\d+"", date): format = ISO8610_FORMAT_MICROSECONDS return datetime.datetime.strptime(date, format)","Small helper that parses ISO-8601 date dates. >>> datetime_from_iso8601(""2013-04-10T12:52:39"") datetime.datetime(2013, 4, 10, 12, 52, 39) >>> datetime_from_iso8601(""2013-01-07T12:55:19.257"") datetime.datetime(2013, 1, 7, 12, 55, 19, 257000) Date date is UTC Date includes microseconds" 219,how to read .csv file in an efficient way?,"def read_csv(csv_path, delimiter="","", header=False): csv_data = [] with open(csv_path, 'r') as csvfile: csvreader = csv.reader(csvfile, delimiter=delimiter) if header: next(csvreader, None) csv_data = zip(*csvreader) return csv_data", 220,set working directory," def change_to_workdir(self): logger.info(""Changing working directory to: %s"", self.workdir) self.check_dir(self.workdir) try: os.chdir(self.workdir) except OSError as exp: self.exit_on_error(""Error changing to working directory: %s. Error: %s. "" ""Check the existence of %s and the %s/%s account "" ""permissions on this directory."" % (self.workdir, str(exp), self.workdir, self.user, self.group), exit_code=3) self.pre_log.append((""INFO"", ""Using working directory: %s"" % os.path.abspath(self.workdir)))","Change working directory to working attribute :return: None" 221,convert int to bool," def convert(self, value): if self._type is str: return str(value) elif self._type is int: try: return int(value) except (UnicodeError, ValueError): raise WorkflowArgumentError('Cannot convert {} to int'.format(value)) elif self._type is float: try: return float(value) except (UnicodeError, ValueError): raise WorkflowArgumentError('Cannot convert {} to float'.format(value)) elif self._type is bool: if isinstance(value, bool): return bool(value) value = value.lower() if value in ('true', '1', 'yes', 'y'): return True elif value in ('false', '0', 'no', 'n'): return False raise WorkflowArgumentError('Cannot convert {} to bool'.format(value)) else: return value","Convert the specified value to the type of the option. Args: value: The value that should be converted. Returns: The value with the type given by the option." 222,fuzzy match ranking,"def _fuzzy_match(set_a, set_b): seen = dict() scores = list() for a_pk_seq, b_pk_seq in product(set_a, set_b): a_pk, a_seq = a_pk_seq b_pk, b_seq = b_pk_seq if (a_pk, b_pk) in seen: if seen[a_pk, b_pk][0]: score = list(seen[a_pk, b_pk]) scores.append(score + [a_pk_seq, b_pk_seq]) else: match = 0 common = min((len(a_pk), len(b_pk))) no_match = max((len(a_pk), len(b_pk))) - common for i in range(0, common): if a_pk[i] == b_pk[i]: if not _nested_falsy(a_pk[i]): match += 1 else: no_match += 1 seen[a_pk, b_pk] = (match, no_match) if match: scores.append([match, no_match, a_pk_seq, b_pk_seq]) remaining_a = set(set_a) remaining_b = set(set_b) for match, no_match, a_pk_seq, b_pk_seq in sorted( scores, key=lambda x: x[0] - x[1], reverse=True, ): if a_pk_seq in remaining_a and b_pk_seq in remaining_b: remaining_a.remove(a_pk_seq) remaining_b.remove(b_pk_seq) yield a_pk_seq, b_pk_seq if not remaining_a or not remaining_b: break","Yes, this is O(n.m), but python's equality operator is fast for hashable types." 223,how to empty array,"def empty(shape, dtype=None, **kwargs): data = np.empty(shape, dtype) return dc.array(data, **kwargs)","Create an array of given shape and type, without initializing entries. Args: shape (sequence of ints): 2D shape of the array. dtype (data-type, optional): Desired data-type for the array. kwargs (optional): Other arguments of the array (*coords, attrs, and name). Returns: array (decode.array): Decode array without initializing entries." 224,parse json file," def __parse_json_file(self, file_path): if file_path == '' or os.path.splitext(file_path)[1] != '.json': raise IOError('Invalid Json file') with open(file_path) as json_file: self._raw_data = json.load(json_file) self._json_data = copy.deepcopy(self._raw_data)","Process Json file data :@param file_path :@type file_path: string :@throws IOError" 225,matrix multiply,"def mxmg(m1, m2, nrow1, ncol1, ncol2): m1 = stypes.toDoubleMatrix(m1) m2 = stypes.toDoubleMatrix(m2) mout = stypes.emptyDoubleMatrix(x=ncol2, y=nrow1) nrow1 = ctypes.c_int(nrow1) ncol1 = ctypes.c_int(ncol1) ncol2 = ctypes.c_int(ncol2) libspice.mxmg_c(m1, m2, nrow1, ncol1, ncol2, mout) return stypes.cMatrixToNumpy(mout)","Multiply two double precision matrices of arbitrary size. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mxmg_c.html :param m1: nrow1 X ncol1 double precision matrix. :type m1: NxM-Element Array of floats :param m2: ncol1 X ncol2 double precision matrix. :type m2: NxM-Element Array of floats :param nrow1: Row dimension of m1 :type nrow1: int :param ncol1: Column dimension of m1 and row dimension of m2. :type ncol1: int :param ncol2: Column dimension of m2 :type ncol2: int :return: nrow1 X ncol2 double precision matrix. :rtype: NxM-Element Array of floats" 226,pretty print json," def prettyprint(d): print(json.dumps(d, sort_keys=True, indent=4, separators=("","" , "": "")))",Print dicttree in Json-like format. keys are sorted 227,how to get current date,"def get_current_date_time(i): import datetime a={} now1=datetime.datetime.now() now=now1.timetuple() a['date_year']=now[0] a['date_month']=now[1] a['date_day']=now[2] a['time_hour']=now[3] a['time_minute']=now[4] a['time_second']=now[5] return {'return':0, 'array':a, 'iso_datetime':now1.isoformat()}","Input: {} Output: { return - return code = 0 array - array with date and time iso_datetime - date and time in ISO format }" 228,parse command line argument,"def parse_commandline(): parser = argparse.ArgumentParser( description='Intuition, the terrific trading system') parser.add_argument('-V', '--version', action='version', version='%(prog)s v{} Licence {}'.format( __version__, __licence__), help='Print program version') parser.add_argument('-v', '--showlog', action='store_true', help='Print logs on stdout') parser.add_argument('-b', '--bot', action='store_true', help='Allows the algorithm to process orders') parser.add_argument('-c', '--context', action='store', default='file::conf.yaml', help='Provides the way to build context') parser.add_argument('-i', '--id', action='store', default='gekko', help='Customize the session id') args = parser.parse_args() return { 'session': args.id, 'context': args.context, 'showlog': args.showlog, 'bot': args.bot }",Dict will be more generic to process than args namespace 229,create cookie,"def create_cookie(name, value, **kwargs): result = { 'version': 0, 'name': name, 'value': value, 'port': None, 'domain': '', 'path': '/', 'secure': False, 'expires': None, 'discard': True, 'comment': None, 'comment_url': None, 'rest': {'HttpOnly': None}, 'rfc2109': False, } badargs = set(kwargs) - set(result) if badargs: err = 'create_cookie() got unexpected keyword arguments: %s' raise TypeError(err % list(badargs)) result.update(kwargs) result['port_specified'] = bool(result['port']) result['domain_specified'] = bool(result['domain']) result['domain_initial_dot'] = result['domain'].startswith('.') result['path_specified'] = bool(result['path']) return cookielib.Cookie(**result)","Make a cookie from underspecified parameters. By default, the pair of `name` and `value` will be set for the domain '' and sent on every request (this is sometimes called a ""supercookie"")." 230,scatter plot,"def scatter(x, y, **kwargs): kwargs['x'] = x kwargs['y'] = y return _draw_mark(Scatter, **kwargs)","Draw a scatter in the current context figure. Parameters ---------- x: numpy.ndarray, 1d The x-coordinates of the data points. y: numpy.ndarray, 1d The y-coordinates of the data points. options: dict (default: {}) Options for the scales to be created. If a scale labeled 'x' is required for that mark, options['x'] contains optional keyword arguments for the constructor of the corresponding scale type. axes_options: dict (default: {}) Options for the axes to be created. If an axis labeled 'x' is required for that mark, axes_options['x'] contains optional keyword arguments for the constructor of the corresponding axis type." 231,how to read .csv file in an efficient way?,"def read_csv(filename, has_header=True): with open(filename) as fh: csv_reader = csv.reader(fh) header = None if has_header: header = csv_reader.next() rows = [row for row in csv_reader] return header, rows", 232,convert html to pdf,"def html_to_pdf(content, encoding=""utf-8"", link_callback=fetch_resources, **kwargs): src = BytesIO(content.encode(encoding)) dest = BytesIO() pdf = pisa.pisaDocument(src, dest, encoding=encoding, link_callback=link_callback, **kwargs) if pdf.err: logger.error(""Error rendering PDF document"") for entry in pdf.log: if entry[0] == xhtml2pdf.default.PML_ERROR: logger_x2p.error(""line %s, msg: %s, fragment: %s"", entry[1], entry[2], entry[3]) raise PDFRenderingError(""Errors rendering PDF"", content=content, log=pdf.log) if pdf.warn: for entry in pdf.log: if entry[0] == xhtml2pdf.default.PML_WARNING: logger_x2p.warning(""line %s, msg: %s, fragment: %s"", entry[1], entry[2], entry[3]) return dest.getvalue()","Converts html ``content`` into PDF document. :param unicode content: html content :returns: PDF content :rtype: :class:`bytes` :raises: :exc:`~easy_pdf.exceptions.PDFRenderingError`" 233,unique elements,"def unique_list_elements(x): unique_elements = [] for element in x: if element not in unique_elements: unique_elements.append(element) return unique_elements", 234,initializing array,"def zeros(stype, shape, ctx=None, dtype=None, **kwargs): if stype == 'default': return _zeros_ndarray(shape, ctx=ctx, dtype=dtype, **kwargs) if ctx is None: ctx = current_context() dtype = mx_real_t if dtype is None else dtype if stype in ('row_sparse', 'csr'): aux_types = _STORAGE_AUX_TYPES[stype] else: raise ValueError(""unknown storage type"" + stype) out = _ndarray_cls(_new_alloc_handle(stype, shape, ctx, True, dtype, aux_types)) return _internal._zeros(shape=shape, ctx=ctx, dtype=dtype, out=out, **kwargs)","Return a new array of given shape and type, filled with zeros. Parameters ---------- stype: string The storage type of the empty array, such as 'row_sparse', 'csr', etc shape : int or tuple of int The shape of the empty array ctx : Context, optional An optional device context (default is the current default context) dtype : str or numpy.dtype, optional An optional value type (default is `float32`) Returns ------- RowSparseNDArray or CSRNDArray A created array Examples -------- >>> mx.nd.sparse.zeros('csr', (1,2)) >>> mx.nd.sparse.zeros('row_sparse', (1,2), ctx=mx.cpu(), dtype='float16').asnumpy() array([[ 0., 0.]], dtype=float16) pylint: disable= no-member, protected-access" 235,how to randomly pick a number," def pick(self): while True: idx = random.randint(0, len(self.values) - 1) v, p = self.values[idx] if p >= random.uniform(0, 1): return v", 236,initializing array,"def _GetRealImagArray(Array): ImagArray = _np.array([num.imag for num in Array]) RealArray = _np.array([num.real for num in Array]) return RealArray, ImagArray","Returns the real and imaginary components of each element in an array and returns them in 2 resulting arrays. Parameters ---------- Array : ndarray Input array Returns ------- RealArray : ndarray The real components of the input array ImagArray : ndarray The imaginary components of the input array" 237,httpclient post json,"Error: 404 {""message"": ""Not Found"", ""documentation_url"": ""https://docs.github.com/rest/repos/repos","get-a-repository"", ""status"": ""404""}" 238,convert string to number,"def str2num(num_str, convert_type=""float""): num = float(grep_comma(num_str)) return num if convert_type == ""float"" else int(num)", 239,read properties file,"def read_properties(fname): parser = configparser.SafeConfigParser() parser.optionxform = str try: with open(fname) as f: parser_read(parser, AddSectionWrapper(f)) except IOError as e: if e.errno != errno.ENOENT: raise return None return dict(parser.items(AddSectionWrapper.SEC_NAME))","preserve key case compile time, prop file is not there" 240,how to randomly pick a number," def pick(self): v = random.uniform(0, self.ub) d = self.dist c = self.vc - 1 s = self.vc while True: s = s / 2 if s == 0: break if v <= d[c][1]: c -= s else: c += s while len(d) <= c: s = s / 2 c -= s if s == 0: break if c == len(d) or v <= d[c][1]: c -= 1 return d[c][0]","picks a value accoriding to the given density we only need this logic when increasing c we may have converged from the left, instead of the right" 241,export to excel," def to_excel(self, excel_writer, sheet_name='data', iamc_index=False, **kwargs): if not isinstance(excel_writer, pd.ExcelWriter): close = True excel_writer = pd.ExcelWriter(excel_writer) self._to_file_format(iamc_index)\ .to_excel(excel_writer, sheet_name=sheet_name, index=False, **kwargs) if close: excel_writer.close()","Write timeseries data to Excel format Parameters ---------- excel_writer: string or ExcelWriter object file path or existing ExcelWriter sheet_name: string, default 'data' name of sheet which will contain `IamDataFrame.timeseries()` data iamc_index: bool, default False if True, use `['model', 'scenario', 'region', 'variable', 'unit']`; else, use all `data` columns" 242,get executable path,"def get_binary_path(executable, logging_level='INFO'): if sys.platform == 'win32': if executable == 'start': return executable executable = executable + '.exe' if executable in os.listdir('.'): binary = os.path.join(os.getcwd(), executable) else: binary = next((os.path.join(path, executable) for path in os.environ['PATH'].split(os.pathsep) if os.path.isfile(os.path.join(path, executable))), None) else: venv_parent = get_venv_parent_path() venv_bin_path = os.path.join(venv_parent, '.venv', 'bin') if not venv_bin_path in os.environ.get('PATH'): if logging_level == 'DEBUG': print(f'Adding path {venv_bin_path} to environment PATH variable') os.environ['PATH'] = os.pathsep.join([os.environ['PATH'], venv_bin_path]) binary = shutil.which(executable) return binary if binary else None",Gets the software name and returns the path of the binary. 243,how to check if a checkbox is checked,"def assert_not_checked_checkbox(step, value): check_box = find_field(world.browser, 'checkbox', value) assert_true(step, not check_box.is_selected())", 244,parse command line argument,"def parse_command_line_arguments(): parser = argparse.ArgumentParser() parser.add_argument( 'xdatcar' ) args = parser.parse_args() return( args )",command line arguments 245,encode url," def urlEncode(self, url, path, params=[]): return url + path + '?' + urllib.parse.urlencode(params)", 246,convert html to pdf,"def make_pdf_from_html( on_disk: bool, html: str, output_path: str = None, header_html: str = None, footer_html: str = None, wkhtmltopdf_filename: str = _WKHTMLTOPDF_FILENAME, wkhtmltopdf_options: Dict[str, Any] = None, file_encoding: str = ""utf-8"", debug_options: bool = False, debug_content: bool = False, debug_wkhtmltopdf_args: bool = True, fix_pdfkit_encoding_bug: bool = None, processor: str = _DEFAULT_PROCESSOR) -> Union[bytes, bool]: wkhtmltopdf_options = wkhtmltopdf_options or {} assert_processor_available(processor) if debug_content: log.debug(""html: {}"", html) log.debug(""header_html: {}"", header_html) log.debug(""footer_html: {}"", footer_html) if fix_pdfkit_encoding_bug is None: fix_pdfkit_encoding_bug = get_default_fix_pdfkit_encoding_bug() if processor == Processors.XHTML2PDF: if on_disk: with open(output_path, mode='wb') as outfile: xhtml2pdf.document.pisaDocument(html, outfile) return True else: memfile = io.BytesIO() xhtml2pdf.document.pisaDocument(html, memfile) memfile.seek(0) return memfile.read() elif processor == Processors.WEASYPRINT: if on_disk: return weasyprint.HTML(string=html).write_pdf(output_path) else: return weasyprint.HTML(string=html).write_pdf() elif processor == Processors.PDFKIT: if not wkhtmltopdf_filename: config = None else: if fix_pdfkit_encoding_bug: log.debug(""Attempting to fix bug in pdfkit (e.g. version 0.5.0)"" "" by encoding wkhtmltopdf_filename to UTF-8"") config = pdfkit.configuration( wkhtmltopdf=wkhtmltopdf_filename.encode('utf-8')) else: config = pdfkit.configuration(wkhtmltopdf=wkhtmltopdf_filename) h_filename = None f_filename = None try: if header_html: h_fd, h_filename = tempfile.mkstemp(suffix='.html') os.write(h_fd, header_html.encode(file_encoding)) os.close(h_fd) wkhtmltopdf_options[""header-html""] = h_filename if footer_html: f_fd, f_filename = tempfile.mkstemp(suffix='.html') os.write(f_fd, footer_html.encode(file_encoding)) os.close(f_fd) wkhtmltopdf_options[""footer-html""] = f_filename if debug_options: log.debug(""wkhtmltopdf config: {!r}"", config) log.debug(""wkhtmltopdf_options: {}"", pformat(wkhtmltopdf_options)) kit = pdfkit.pdfkit.PDFKit(html, 'string', configuration=config, options=wkhtmltopdf_options) if on_disk: path = output_path else: path = None if debug_wkhtmltopdf_args: log.debug(""Probable current user: {!r}"", getpass.getuser()) log.debug(""wkhtmltopdf arguments will be: {!r}"", kit.command(path=path)) return kit.to_pdf(path=path) finally: if h_filename: os.remove(h_filename) if f_filename: os.remove(f_filename) else: raise AssertionError(""Unknown PDF engine"")","Mandatory parameters: Disk options: Shared options: Takes HTML and either returns a PDF in memory or makes one on disk. For preference, uses ``wkhtmltopdf`` (with ``pdfkit``): - faster than ``xhtml2pdf`` - tables not buggy like ``Weasyprint`` - however, doesn't support CSS Paged Media, so we have the ``header_html`` and ``footer_html`` options to allow you to pass appropriate HTML content to serve as the header/footer (rather than passing it within the main HTML). Args: on_disk: make file on disk (rather than returning it in memory)? html: main HTML output_path: if ``on_disk``, the output filename header_html: optional page header, as HTML footer_html: optional page footer, as HTML wkhtmltopdf_filename: filename of the ``wkhtmltopdf`` executable wkhtmltopdf_options: options for ``wkhtmltopdf`` file_encoding: encoding to use when writing the header/footer to disk debug_options: log ``wkhtmltopdf`` config/options passed to ``pdfkit``? debug_content: log the main/header/footer HTML? debug_wkhtmltopdf_args: log the final command-line arguments to that will be used by ``pdfkit`` when it calls ``wkhtmltopdf``? fix_pdfkit_encoding_bug: attempt to work around bug in e.g. ``pdfkit==0.5.0`` by encoding ``wkhtmltopdf_filename`` to UTF-8 before passing it to ``pdfkit``? If you pass ``None`` here, then a default value is used, from :func:`get_default_fix_pdfkit_encoding_bug`. processor: a PDF processor type from :class:`Processors` Returns: the PDF binary as a ``bytes`` object Raises: AssertionError: if bad ``processor`` RuntimeError: if requested processor is unavailable type: Dict[str, Any] noinspection PyUnresolvedReferences noinspection PyUnresolvedReferences ... returns a document, but we don't use it, so we don't store it to stop pychecker complaining http://xhtml2pdf.appspot.com/static/pisa-en.html http://stackoverflow.com/questions/3310584 http://ampad.de/blog/generating-pdfs-django/ Config: needs to be True for pdfkit==0.5.0 the bug is that pdfkit.pdfkit.PDFKit.__init__ will attempt to decode the string in its configuration object; https://github.com/JazzCore/python-pdfkit/issues/32 Temporary files that a subprocess can read: http://stackoverflow.com/questions/15169101 wkhtmltopdf requires its HTML files to have "".html"" extensions: http://stackoverflow.com/questions/5776125 With ""path=None"", the to_pdf() function directly returns stdout from a subprocess.Popen().communicate() call (see pdfkit.py). Since universal_newlines is not set, stdout will be bytes in Python 3." 247,how to read the contents of a .gz compressed file?,"def read_output(filename): if os.path.isfile(filename): with open(filename, 'rb') as f: return f.read().decode('utf-8') elif os.path.isfile('{}.gz'.format(filename)): with gzip.open('{}.gz'.format(filename), 'rb') as f: return f.read().decode('utf-8') elif HAS_LZMA and os.path.isfile('{}.xz'.format(filename)): with open('{}.xz'.format(filename), 'rb') as f: return lzma.LZMADecompressor().decompress(f.read()).decode('utf-8') else: return None", 248,convert a utc time to epoch,"def utc_epoch(): d = dt.datetime(1970, 1, 1) d = d.replace(tzinfo=utc) return d","Gets the epoch in the users timezone :return: pendulum utcnow() is not used as that sets a TimezoneInfo object instead of a Timezone. This is not pickable and also creates issues when using replace()" 249,positions of substrings in string,"def findAllSubstrings(string, substring): start = 0 positions = [] while True: start = string.find(substring, start) if start == -1: break positions.append(start) start += 1 return positions","Returns a list of all substring starting positions in string or an empty list if substring is not present in string. :param string: a template string :param substring: a string, which is looked for in the ``string`` parameter. :returns: a list of substring starting positions in the template string TODO: solve with regex? what about '.': return [m.start() for m in re.finditer('(?='+substring+')', string)] +1 instead of +len(substring) to also find overlapping matches" 250,get executable path,"def find_executable(executable, path=None): if path is None: path = os.environ['PATH'] paths = path.split(os.pathsep) base, ext = os.path.splitext(executable) if (sys.platform == 'win32' or os.name == 'os2') and (ext != '.exe'): executable = executable + '.exe' if not os.path.isfile(executable): for p in paths: f = os.path.join(p, executable) if os.path.isfile(f): return f return None else: return executable","Tries to find 'executable' in the directories listed in 'path'. A string listing directories separated by 'os.pathsep'; defaults to os.environ['PATH']. Returns the complete filename or None if not found. the file exists, we have a shot at spawn working" 251,sort string list," def list(self, base, filter=None, type=None, sort=None, limit=None, page=None, format=None): if sort != None: if not isinstance(sort, list): sort = [sort] sort = ','.join(sort) return self.get(base, params={'filter': filter, 'type': type, 'sort': sort, 'limit': limit, 'page': page, 'format': format})",pylint: disable=redefined-builtin 252,pretty print json,"def ppjson(dumpit: Any, elide_to: int = None) -> str: if elide_to is not None: elide_to = max(elide_to, 3) try: rv = json.dumps(json.loads(dumpit) if isinstance(dumpit, str) else dumpit, indent=4) except TypeError: rv = '{}'.format(pformat(dumpit, indent=4, width=120)) return rv if elide_to is None or len(rv) <= elide_to else '{}...'.format(rv[0 : elide_to - 3])","JSON pretty printer, whether already json-encoded or not :param dumpit: object to pretty-print :param elide_to: optional maximum length including ellipses ('...') :return: json pretty-print make room for ellipses '...'" 253,parse command line argument,"def parse_command_line_arguments(): parser = argparse.ArgumentParser( description='Manipulates VASP POSCAR files' ) parser.add_argument( 'poscar', help=""filename of the VASP POSCAR to be processed"" ) parser.add_argument( '-l', '--label', type=int, choices=[ 1, 4 ], help=""label coordinates with atom name at position {1,4}"" ) parser.add_argument( '-c', '--coordinates-only', help='only output coordinates', action='store_true' ) parser.add_argument( '-t', '--coordinate-type', type=str, choices=[ 'c', 'cartesian', 'd', 'direct' ], default='direct', help=""specify coordinate type for output {(c)artesian|(d)irect} [default = (d)irect]"" ) parser.add_argument( '-g', '--group', help='group atoms within supercell', action='store_true' ) parser.add_argument( '-s', '--supercell', type=int, nargs=3, metavar=( 'h', 'k', 'l' ), help='construct supercell by replicating (h,k,l) times along [a b c]' ) parser.add_argument( '-b', '--bohr', action='store_true', help='assumes the input file is in Angstrom, and converts everything to bohr') parser.add_argument( '-n', '--number-atoms', action='store_true', help='label coordinates with atom number' ) parser.add_argument( '--scale', action='store_true', help='scale the lattice parameters by the scaling factor' ) parser.add_argument( '--selective', choices=[ 'T', 'F' ], help='generate Selective Dynamics POSCAR with all values set to T / F' ) args = parser.parse_args() return( args )",command line arguments 254,get current ip address,"def get_ip(request): if config.BEHIND_REVERSE_PROXY: ip_address = request.META.get(config.REVERSE_PROXY_HEADER, '') ip_address = ip_address.split("","", 1)[0].strip() if ip_address == '': ip_address = get_ip_address_from_request(request) else: ip_address = get_ip_address_from_request(request) return ip_address",get the ip address from the request 255,convert decimal to hex,"def int_to_hex(i): s = hex(i)[2:].upper() if six.PY2 is True and isinstance(i, long): s = s[:-1] return add_colons(s)","Create a hex-representation of the given serial. >>> int_to_hex(12345678) 'BC:61:4E' pragma: only py2 # NOQA Strip the ""L"" suffix, since hex(1L) -> 0x1L. NOTE: Do not convert to int earlier. int() is still long" 256,extracting data from a text file," def from_text_file(file_path): results = [] with io.open(file_path, 'r', encoding='utf-8') as f: data_strs = f.read().split(MonsoonData.delimiter) for data_str in data_strs: results.append(MonsoonData.from_string(data_str)) return results","Load MonsoonData objects from a text file generated by MonsoonData.save_to_text_file. Args: file_path: The full path of the file load from, including the file name. Returns: A list of MonsoonData objects." 257,encode url,"def urlencode(params): utf8_params = encode_params_utf8(params) urlencoded = _urlencode(utf8_params) if isinstance(urlencoded, unicode_type): return urlencoded else: return urlencoded.decode(""utf-8"")",PY3 returns unicode 258,export to excel," def on_excel(self): from pylon.io.excel import ExcelWriter filename = asksaveasfilename(filetypes=[(""Excel file"", "".xls"")]) if filename: ExcelWriter(self.case).write(filename)", 259,string to date," def _ConvertToTimestamp(self, date, time): if len(date) != 8: raise ValueError( 'Unsupported length of date string: {0!s}'.format(repr(date))) if len(time) < 3 or len(time) > 4: raise ValueError( 'Unsupported length of time string: {0!s}'.format(repr(time))) try: year = int(date[:4], 10) month = int(date[4:6], 10) day = int(date[6:8], 10) except (TypeError, ValueError): raise ValueError('Unable to parse date string: {0!s}'.format(repr(date))) try: hour = int(time[:-2], 10) minutes = int(time[-2:], 10) except (TypeError, ValueError): raise ValueError('Unable to parse time string: {0!s}'.format(repr(date))) time_elements_tuple = (year, month, day, hour, minutes, 0) date_time = dfdatetime_time_elements.TimeElements( time_elements_tuple=time_elements_tuple) date_time.is_local_time = True date_time._precision = dfdatetime_definitions.PRECISION_1_MINUTE return date_time","Converts date and time strings into a timestamp. Recent versions of Office Scan write a log field with a Unix timestamp. Older versions may not write this field; their logs only provide a date and a time expressed in the local time zone. This functions handles the latter case. Args: date (str): date as an 8-character string in the YYYYMMDD format. time (str): time as a 3 or 4-character string in the [H]HMM format or a 6-character string in the HHMMSS format. Returns: dfdatetime_time_elements.TimestampElements: the parsed timestamp. Raises: ValueError: if the date and time values cannot be parsed. Check that the strings have the correct length. Extract the date. Extract the time. Note that a single-digit hour value has no leading zero. TODO: add functionality to dfdatetime to control precision. pylint: disable=protected-access" 260,how to empty array," def default_array(self, array_size): array = np.empty(array_size, dtype = self.dtype) if self.value_type == Enum: array.fill(self.default_value.index) return EnumArray(array, self.possible_values) array.fill(self.default_value) return array", 261,get inner html," def innerHTML(self) -> str: if self._inner_element: return self._inner_element.innerHTML return super().innerHTML",Get innerHTML of the inner node. 262,encrypt aes ctr mode," def encrypt(self, raw, mode=AES.MODE_CBC): raw = self._pad(raw, AES.block_size) iv = Random.new().read(AES.block_size) cipher = AES.new(self.key, mode, iv) return base64.b64encode(iv + cipher.encrypt(raw)).decode('utf-8')", 263,how to get database table name," def get_table(self, database_name, table_name): database = self.get_database(database_name) try: return database.tables[table_name] except KeyError: raise TableNotFoundException(table_name)", 264,output to html file," def html_index(self,launch=True): html=""

MENU

"" htmlFiles=[x for x in self.files2 if x.endswith("".html"")] for htmlFile in cm.abfSort(htmlFiles): if not htmlFile.endswith('_basic.html'): continue name=htmlFile.split(""_"")[0] if name in self.groups.keys(): html+='%s '%(htmlFile,name) html+='SPLASH"" style.save(html,os.path.abspath(self.folder2+""/index_splash.html"")) style.frames(os.path.abspath(self.folder2+""/index.html""),launch=launch) return","CCC;"">'" 265,get inner html," def html(self) -> str: if self._inner_element: return self.start_tag + self._inner_element.html + self.end_tag return super().html",Get whole html representation of this node. 266,convert html to pdf,"def html_to_pdf(content, encoding=""utf-8"", link_callback=fetch_resources, **kwargs): src = BytesIO(content.encode(encoding)) dest = BytesIO() pdf = pisa.pisaDocument(src, dest, encoding=encoding, link_callback=link_callback, **kwargs) if pdf.err: logger.error(""Error rendering PDF document"") for entry in pdf.log: if entry[0] == xhtml2pdf.default.PML_ERROR: logger_x2p.error(""line %s, msg: %s, fragment: %s"", entry[1], entry[2], entry[3]) raise PDFRenderingError(""Errors rendering PDF"", content=content, log=pdf.log) if pdf.warn: for entry in pdf.log: if entry[0] == xhtml2pdf.default.PML_WARNING: logger_x2p.warning(""line %s, msg: %s, fragment: %s"", entry[1], entry[2], entry[3]) return dest.getvalue()","Converts html ``content`` into PDF document. :param unicode content: html content :returns: PDF content :rtype: :class:`bytes` :raises: :exc:`~easy_pdf.exceptions.PDFRenderingError`" 267,convert a date string into yyyymmdd," def yyyymmdd(self, auto=None, datetime=None, timezone=None, timestamp=None, ms=False, concat=''): datetime = self.convert(auto=auto, datetime=datetime, timezone=timezone, timestamp=timestamp, ms=ms) return '%04d%s%02d%s%02d' % (datetime.year, concat, datetime.month, concat, datetime.day)", 268,deducting the median from each column," def median(self, **kwargs): if self._is_transposed: kwargs[""axis""] = kwargs.get(""axis"", 0) ^ 1 return self.transpose().median(**kwargs) axis = kwargs.get(""axis"", 0) func = self._build_mapreduce_func(pandas.DataFrame.median, **kwargs) return self._full_axis_reduce(axis, func)","Returns median of each column or row. Returns: A new QueryCompiler object containing the median of each column or row. Pandas default is 0 (though not mentioned in docs)" 269,positions of substrings in string,"def _string_substr(self, start, length=None): op = ops.Substring(self, start, length) return op.to_expr()","Pull substrings out of each string value by position and maximum length. Parameters ---------- start : int First character to start splitting, indices starting at 0 (like Python) length : int, optional Maximum length of each substring. If not supplied, splits each string to the end Returns ------- substrings : type of caller" 270,linear regression,"def fit_model(regressor_type, regressor_kwargs, tf_matrix, target_gene_expression, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, seed=DEMON_SEED): regressor_type = regressor_type.upper() assert tf_matrix.shape[0] == len(target_gene_expression) def do_sklearn_regression(): regressor = SKLEARN_REGRESSOR_FACTORY[regressor_type](random_state=seed, **regressor_kwargs) with_early_stopping = is_oob_heuristic_supported(regressor_type, regressor_kwargs) if with_early_stopping: regressor.fit(tf_matrix, target_gene_expression, monitor=EarlyStopMonitor(early_stop_window_length)) else: regressor.fit(tf_matrix, target_gene_expression) return regressor if is_sklearn_regressor(regressor_type): return do_sklearn_regression() else: raise ValueError('Unsupported regressor type: {0}'.format(regressor_type))",":param regressor_type: string. Case insensitive. :param regressor_kwargs: a dictionary of key-value pairs that configures the regressor. :param tf_matrix: the predictor matrix (transcription factor matrix) as a numpy array. :param target_gene_expression: the target (y) gene expression to predict in function of the tf_matrix (X). :param early_stop_window_length: window length of the early stopping monitor. :param seed: (optional) random seed for the regressors. :return: a trained regression model. elif is_xgboost_regressor(regressor_type): raise ValueError('XGB regressor not yet supported')" 271,map to json,"def maps_json(): map_sources = { id: { ""id"": map_source.id, ""name"": map_source.name, ""folder"": map_source.folder, ""min_zoom"": map_source.min_zoom, ""max_zoom"": map_source.max_zoom, ""layers"": [ { ""min_zoom"": layer.min_zoom, ""max_zoom"": layer.max_zoom, ""tile_url"": layer.tile_url.replace(""$"", """"), } for layer in map_source.layers ] } for id, map_source in app.config[""mapsources""].items() } return jsonify(map_sources)","Generates a json object which serves as bridge between the web interface and the map source collection. All attributes relevant for openlayers are converted into JSON and served through this route. Returns: Response: All map sources as JSON object." 272,socket recv timeout," def recv(self): try: msg_bytes = self.c.recv() except socket.timeout: msg_bytes = b"""" return self.prot.input(msg_bytes)","print(""socket recv timeout"")" 273,regex case insensitive,"def regex(regex, case=False, _value=None, *args, **kwargs): if kwargs.get('case'): regex = re.compile(regex) else: regex = re.compile(regex, re.IGNORECASE) if not regex.match(_value): raise ValidationError('The _value must match the regex %s' % regex) return _value", 274,how to extract zip file recursively,"def extract_zipdir(zip_file): if not os.path.exists(zip_file): raise ValueError('{} does not exist'.format(zip_file)) directory = os.path.dirname(zip_file) filename = os.path.basename(zip_file) dirpath = os.path.join(directory, filename.replace('.zip', '')) with zipfile.ZipFile(zip_file, 'r', zipfile.ZIP_DEFLATED) as zipf: zipf.extractall(dirpath) return dirpath","Extract contents of zip file into subfolder in parent directory. Parameters ---------- zip_file : str Path to zip file Returns ------- str : folder where the zip was extracted" 275,encrypt aes ctr mode," def aes_cbc_encrypt(plain_text: bytes, key: bytes, iv: bytes = b''): if len(iv) == 0: iv = AESHandler.generate_iv() cipher = AES.new(key=key, mode=AES.MODE_CBC, iv=iv) return cipher.IV, cipher.encrypt(pad(plain_text, AES.block_size))", 276,normal distribution,"def normal_h1(size: int = 10000, mean: float = 0, sigma: float = 1) -> Histogram1D: data = np.random.normal(mean, sigma, (size,)) return h1(data, name=""normal"", axis_name=""x"", title=""1D normal distribution"")","A simple 1D histogram with normal distribution. Parameters ---------- size : Number of points mean : Mean of the distribution sigma : Sigma of the distribution" 277,converting uint8 array to image," def uint8_to_uint32(self, element): img = np.dstack([element.dimension_values(d, flat=False) for d in element.vdims]) if img.shape[2] == 3: alpha = np.ones(img.shape[:2]) if img.dtype.name == 'uint8': alpha = (alpha*255).astype('uint8') img = np.dstack([img, alpha]) if img.dtype.name != 'uint8': img = (img*255).astype(np.uint8) N, M, _ = img.shape return img.view(dtype=np.uint32).reshape((N, M))",alpha channel not included 278,convert string to number," def __convert_num(number): try: return float(number) except ValueError as e: logger_noaa_lpd.warn(""convert_num: ValueError: {}"".format(e)) return number","All path items are automatically strings. If you think it's an int or float, this attempts to convert it. :param str number: :return float or str:" 279,pretty print json," def printJson(self): jsonobject = self.getJson() print(json.dumps(jsonobject, indent=1, sort_keys=True))", 280,create cookie,"def create_cookie(name, value, **kwargs): result = { 'version': 0, 'name': name, 'value': value, 'port': None, 'domain': '', 'path': '/', 'secure': False, 'expires': None, 'discard': True, 'comment': None, 'comment_url': None, 'rest': {'HttpOnly': None}, 'rfc2109': False, } badargs = set(kwargs) - set(result) if badargs: err = 'create_cookie() got unexpected keyword arguments: %s' raise TypeError(err % list(badargs)) result.update(kwargs) result['port_specified'] = bool(result['port']) result['domain_specified'] = bool(result['domain']) result['domain_initial_dot'] = result['domain'].startswith('.') result['path_specified'] = bool(result['path']) return cookielib.Cookie(**result)","Make a cookie from underspecified parameters. By default, the pair of `name` and `value` will be set for the domain '' and sent on every request (this is sometimes called a ""supercookie"")." 281,copy to clipboard," def copy_to_clipboard(self, event): log.critical(""Copy to clipboard"") text = self.text.get(""1.0"", tkinter.END) print(text) self.root.clipboard_clear() self.root.clipboard_append(text)", 282,regex case insensitive,"def _regex_span(_regex, _str, case_insensitive=True): if case_insensitive: flags = regex.IGNORECASE | regex.FULLCASE | regex.VERSION1 else: flags = regex.VERSION1 comp = regex.compile(_regex, flags=flags) matches = comp.finditer(_str) for match in matches: yield match","Return all matches in an input string. :rtype : regex.match.span :param _regex: A regular expression pattern. :param _str: Text on which to run the pattern." 283,output to html file," def to_file(self, outputfile=DEFAULT_OUTPUTFILE): if outputfile != NO_OUTPUTFILE: if outputfile == DEFAULT_OUTPUTFILE: outputfile = 'profile_' + str(hash(self)) + "".html"" with codecs.open(outputfile, 'w+b', encoding='utf8') as self.file: self.file.write(templates.template('wrapper').render(content=self.html))","Write the report to a file. By default a name is generated. Parameters: ---------- outputfile : str The name or the path of the file to generale including the extension (.html). TODO: should be done in the template" 284,scatter plot,"def sentiment_scatter(sms=sms): plt.figure(figsize=(10, 7.5)) ax = plt.subplot(1, 1, 1) ax = sms.plot.scatter(x='topic4', y='line', ax=ax, color='g', marker='+', alpha=.6) ax = sms.plot.scatter(x='topic4', y='sgd', ax=ax, color='r', marker='x', alpha=.4) ax = sms.plot.scatter(x='topic4', y='vader', ax=ax, color='k', marker='.', alpha=.3) ax = sms.plot.scatter(x='topic4', y='sgd', ax=ax, color='c', marker='s', alpha=.6) ax = sms.plot.scatter(x='topic4', y='pca_lda_spaminess', ax=ax, color='b', marker='o', alpha=.6) plt.ylabel('Sentiment') plt.xlabel('Topic 4') plt.legend(['LinearRegressor', 'SGDRegressor', 'Vader', 'OneNeuronRegresor', 'PCA->LDA->spaminess']) plt.tight_layout() plt.show()", 285,httpclient post json," def make_jsonrpc_call(self, url, method, params): client = HTTPClient() body = json.dumps({ ""jsonrpc"": ""2.0"", ""method"": method, ""params"": params, ""id"": """".join([random.choice(string.ascii_letters) for _ in range(10)]) }) request = HTTPRequest(url, method=""POST"", headers={""content-type"": ""application/json""}, body=body) result = client.fetch(request) return result", 286,heatmap from 3d coordinates," def heatmap(self, partition=None, cmap=CM.Blues): if isinstance(self.dm, DistanceMatrix): length = self.dm.values.shape[0] else: length = self.dm.shape[0] datamax = float(np.abs(self.dm).max()) fig = plt.figure() ax = fig.add_subplot(111) ticks_at = [0, 0.5 * datamax, datamax] if partition: sorting = flatten_list(partition.get_membership()) self.dm = self.dm.reorder(sorting) cax = ax.imshow( self.dm.values, interpolation='nearest', origin='lower', extent=[0., length, 0., length], vmin=0, vmax=datamax, cmap=cmap, ) cbar = fig.colorbar(cax, ticks=ticks_at, format='%1.2g') cbar.set_label('Distance') return fig",Plots a visual representation of a distance matrix 287,html entities replace," def replace_entities(self, html): def fixup(text): text = text.group(0) if text[:2] == ""& try: if text[:3] == ""& return chr(int(text[3:-1], 16)) else: return chr(int(text[2:-1])) except ValueError: pass else: try: text = chr(htmlentitydefs.name2codepoint[text[1:-1]]) except KeyError: pass return text return re.sub(r""&","Replace htmlentities with unicode characters @Params html - html source to replace entities in @Returns String html with entities replaced replace the htmlentities in some text "": character reference x"": named entity leave as is ?\w+;"", fixup, html)" 288,convert decimal to hex," def _hexvalue_to_rgb(hexvalue): r = int(hexvalue[0:2], 16) g = int(hexvalue[2:4], 16) b = int(hexvalue[4:6], 16) return (r, g, b)","Converts the hexvalue used by tuya for colour representation into an RGB value. Args: hexvalue(string): The hex representation generated by BulbDevice._rgb_to_hexvalue()" 289,memoize to disk - persistent memoization,"def memoize(f): cache_dirname = os.path.join(_get_xdg_cache_home(), 'proselint') legacy_cache_dirname = os.path.join(os.path.expanduser(""~""), "".proselint"") if not os.path.isdir(cache_dirname): if os.path.isdir(legacy_cache_dirname): os.rename(legacy_cache_dirname, cache_dirname) else: os.makedirs(cache_dirname) cache_filename = f.__module__ + ""."" + f.__name__ cachepath = os.path.join(cache_dirname, cache_filename) @functools.wraps(f) def wrapped(*args, **kwargs): if hasattr(f, '__self__'): args = args[1:] signature = (f.__module__ + '.' + f.__name__).encode(""utf-8"") tempargdict = inspect.getcallargs(f, *args, **kwargs) for item in list(tempargdict.items()): signature += item[1].encode(""utf-8"") key = hashlib.sha256(signature).hexdigest() try: cache = _get_cache(cachepath) return cache[key] except KeyError: value = f(*args, **kwargs) cache[key] = value cache.sync() return value except TypeError: call_to = f.__module__ + '.' + f.__name__ print('Warning: could not disk cache call to %s;' 'it probably has unhashable args. Error: %s' % (call_to, traceback.format_exc())) return f(*args, **kwargs) return wrapped","Cache results of computations on disk. Determine the location of the cache. Migrate the cache from the legacy path to XDG complaint location. Create the cache if it does not already exist. handle instance methods" 290,aes encryption,"def decode_aes256(cipher, iv, data, encryption_key): if cipher == 'cbc': aes = AES.new(encryption_key, AES.MODE_CBC, iv) elif cipher == 'ecb': aes = AES.new(encryption_key, AES.MODE_ECB) else: raise ValueError('Unknown AES mode') d = aes.decrypt(data) unpad = lambda s: s[0:-ord(d[-1:])] return unpad(d)","Decrypt AES-256 bytes. Allowed ciphers are: :ecb, :cbc. If for :ecb iv is not used and should be set to """". http://passingcuriosity.com/2009/aes-encryption-in-python-with-m2crypto/" 291,string to date,"Error: 404 {""message"": ""Not Found"", ""documentation_url"": ""https://docs.github.com/rest/repos/repos","get-a-repository"", ""status"": ""404""}" 292,convert int to bool,"def _convert(value, default=None, convert=None): def convert_bool(value): if value.lower() in ('true', 't', 'yes', 'y'): return True if value.lower() in ('false', 'f', 'no', 'n'): return False raise ValueError('{} cannot be converted to bool'.format(value)) if value == '': value = None if convert is None: if default is not None: convert = type(default) else: convert = str if convert == bool: convert = convert_bool if value is None: return default else: return convert(value)", 293,aes encryption,"def _encrypt(data): BS = AES.block_size def pad(s): n = BS - len(s) % BS char = chr(n).encode('utf8') return s + n * char password = settings.GECKOBOARD_PASSWORD salt = Random.new().read(BS - len('Salted__')) key, iv = _derive_key_and_iv(password, salt, 32, BS) cipher = AES.new(key, AES.MODE_CBC, iv) encrypted = b'Salted__' + salt + cipher.encrypt(pad(data)) return base64.b64encode(encrypted)",Equivalent to OpenSSL using 256 bit AES in CBC mode 294,linear regression," def lreg(self, xcol, ycol, name=""Regression""): try: x = self.df[xcol].values.reshape(-1, 1) y = self.df[ycol] lm = linear_model.LinearRegression() lm.fit(x, y) predictions = lm.predict(x) self.df[name] = predictions except Exception as e: self.err(e, ""Can not calculate linear regression"")","Add a column to the main dataframe populted with the model's linear regression for a column" 295,string similarity levenshtein,"def levenshtein_dist(s1: str, s2: str) -> int: if len(s1) < len(s2): return levenshtein_dist(s2, s1) if len(s2) == 0: return len(s1) previous_row = range(len(s2) + 1) for i, c1 in enumerate(s1): current_row = [i + 1] for j, c2 in enumerate(s2): insertions = previous_row[j + 1] + 1 deletions = current_row[j] + 1 substitutions = previous_row[j] + (c1 != c2) current_row.append(min(insertions, deletions, substitutions)) previous_row = current_row return previous_row[-1]","len(s1) >= len(s2) j+1 instead of j since previous_row and current_row are one character longer than s2" 296,html entities replace,"def escape(t): return (t .replace(""&"", ""&"").replace(""<"", ""<"").replace("">"", "">"") .replace(""'"", ""& .replace("" "", ""  "") .replace("" "", ""  "") )","HTML-escape the text in `t`. Convert HTML special chars into HTML entities. 39;"").replace('""', """"") Convert runs of spaces: ""......"" -> "" . . ."" To deal with odd-length runs, convert the final pair of spaces so that ""....."" -> "" .  .""" 297,httpclient post json," def post(self, json=None): response = self._http(requests.post, json=json) if response.status_code == 201: return response.json()", 298,get inner html," def innerHTML(self) -> str: if self._inner_element: return self._inner_element.innerHTML return super().innerHTML",Get innerHTML of the inner node. 299,convert html to pdf," def toPdf(self): html = safe_unicode(self.template()).encode('utf-8') pdf_data = createPdf(html) return pdf_data", 300,linear regression," def linear_regression(self): model = LinearRegression() scores = [] kfold = KFold(n_splits=self.cv, shuffle=True, random_state=42) for i, (train, test) in enumerate(kfold.split(self.baseline_in, self.baseline_out)): model.fit(self.baseline_in.iloc[train], self.baseline_out.iloc[train]) scores.append(model.score(self.baseline_in.iloc[test], self.baseline_out.iloc[test])) mean_score = sum(scores) / len(scores) self.models.append(model) self.model_names.append('Linear Regression') self.max_scores.append(mean_score) self.metrics['Linear Regression'] = {} self.metrics['Linear Regression']['R2'] = mean_score self.metrics['Linear Regression']['Adj R2'] = self.adj_r2(mean_score, self.baseline_in.shape[0], self.baseline_in.shape[1])","Linear Regression. This function runs linear regression and stores the, 1. Model 2. Model name 3. Mean score of cross validation 4. Metrics" 301,convert decimal to hex,"def dec2str(n): s = hex(int(n))[2:].rstrip('L') if len(s) % 2 != 0: s = '0' + s return hex2str(s)",decimal number to string. 302,copy to clipboard," def paste(self): clipboard = QApplication.clipboard() cliptext = '' if clipboard.mimeData().hasText(): cliptext = to_text_string(clipboard.text()) if cliptext.strip(): self.import_from_string(cliptext, title=_(""Import from clipboard"")) else: QMessageBox.warning(self, _( ""Empty clipboard""), _(""Nothing to be imported from clipboard."")) ",Import text/data/code from clipboard 303,pretty print json,"def json_pretty_print(s): s = json.loads(s) return json.dumps(s, sort_keys=True, indent=4, separators=(',', ': '))",pretty print JSON 304,all permutations of a list,"def permutations(x): yield list(x) x = np.array(x) a = np.arange(len(x)) while True: ak_lt_ak_next = np.argwhere(a[:-1] < a[1:]) if len(ak_lt_ak_next) == 0: raise StopIteration() k = ak_lt_ak_next[-1, 0] ak_lt_al = np.argwhere(a[k] < a) l = ak_lt_al[-1, 0] a[k], a[l] = (a[l], a[k]) if k < len(x)-1: a[k+1:] = a[:k:-1].copy() yield x[a].tolist()","Given a listlike, x, return all permutations of x Returns the permutations of x in the lexical order of their indices: e.g. >>> x = [ 1, 2, 3, 4 ] >>> for p in permutations(x): >>> print p [ 1, 2, 3, 4 ] [ 1, 2, 4, 3 ] [ 1, 3, 2, 4 ] [ 1, 3, 4, 2 ] [ 1, 4, 2, 3 ] [ 1, 4, 3, 2 ] [ 2, 1, 3, 4 ] ... [ 4, 3, 2, 1 ] The algorithm is attributed to Narayana Pandit from his Ganita Kaumundi (1356). The following is from http://en.wikipedia.org/wiki/Permutation#Systematic_generation_of_all_permutations 1. Find the largest index k such that a[k] < a[k + 1]. If no such index exists, the permutation is the last permutation. 2. Find the largest index l such that a[k] < a[l]. Since k + 1 is such an index, l is well defined and satisfies k < l. 3. Swap a[k] with a[l]. 4. Reverse the sequence from a[k + 1] up to and including the final element a[n]. don't forget to do the first one 1 - find largest or stop 2 - find largest a[l] < a[k] 3 - swap 4 - reverse" 305,export to excel," def to_excel(self, xl_app=None, resize_columns=True): from win32com.client import Dispatch, gencache if xl_app is None: xl_app = Dispatch(""Excel.Application"") xl_app = gencache.EnsureDispatch(xl_app) assert self.worksheets, ""Can't export workbook with no worksheets"" sheets_in_new_workbook = xl_app.SheetsInNewWorkbook try: xl_app.SheetsInNewWorkbook = float(len(self.worksheets)) self.workbook_obj = xl_app.Workbooks.Add() finally: xl_app.SheetsInNewWorkbook = sheets_in_new_workbook sheet_names = {s.name for s in self.worksheets} assert len(sheet_names) == len(self.worksheets), ""Worksheets must have unique names"" for worksheet in self.workbook_obj.Sheets: i = 1 original_name = worksheet.Name while worksheet.Name in sheet_names: worksheet.Name = ""%s_%d"" % (original_name, i) i += 1 for worksheet, sheet in zip(self.workbook_obj.Sheets, self.worksheets): worksheet.Name = sheet.name for worksheet, sheet in zip(self.workbook_obj.Sheets, self.itersheets()): worksheet.Select() sheet.to_excel(workbook=self, worksheet=worksheet, xl_app=xl_app, rename=False, resize_columns=resize_columns) return self.workbook_obj","Add a new workbook with the correct number of sheets. We aren't allowed to create an empty one. Rename the worksheets, ensuring that there can never be two sheets with the same name due to the sheets default names conflicting with the new names. Export each sheet (have to use itersheets for this as it sets the current active sheet before yielding each one)." 306,format date," def format_date(self, value, format_): date_ = make_date(value) return dates.format_date(date_, format_, locale=self.lang)",Format the date using Babel 307,deserialize json,"def deserialize(s): if isinstance(s, bytes): return json.loads(s.decode('utf-8')) return json.loads(s)", 308,print model summary," def summary(self, header=True): table = [] for model in self.models: model_summary = model._model_json[""output""][""model_summary""] r_values = list(model_summary.cell_values[0]) r_values[0] = model.model_id table.append(r_values) print() if header: print('Grid Summary:') print() H2ODisplay(table, ['Model Id'] + model_summary.col_header[1:], numalign=""left"", stralign=""left"")","Print a detailed summary of the explored models. if h2o.can_use_pandas(): import pandas pandas.options.display.max_rows = 20 print pandas.DataFrame(table,columns=self.col_header) return" 309,scatter plot,"def scatter(x, y, z, color=(1, 0, 0), s=0.01): global _last_figure fig = _last_figure if fig is None: fig = volshow(None) fig.scatter = Scatter(x=x, y=y, z=z, color=color, size=s) fig.volume.scatter = fig.scatter return fig", 310,string to date,"def get_date(date_string): d=None try: d=datetime.datetime.strptime(date_string, ""%d %B %Y"").date() except: d=datetime.datetime.strptime(date_string, ""%Y-%m-%d"").date() if d: return d.strftime(""%Y-%m-%d"") else: return date_string", 311,find int in string,"def find_number(regex, s): result = find_string(regex, s) if result is None: return None return int(result)","Find a number using a given regular expression. If the string cannot be found, returns None. The regex should contain one matching group, as only the result of the first group is returned. The group should only contain numeric characters ([0-9]+). s - The string to search. regex - A string containing the regular expression. Returns an integer or None." 312,output to html file,"def generate_html(): html_file = open(html_filename, ""w"") html_file.write("""") html_file.write(""

Here are some graphs for you!

"") for image in [lines_filename, bars_filename, histogram_filename]: html_file.write(""

{0}

"".format(image)) html_file.write("""") html_file.close()",Generate an HTML file incorporating the images produced by this script 313,heatmap from 3d coordinates,"def heatmap(z, x=None, y=None, colorscale='Viridis'): z = np.atleast_1d(z) data = [go.Heatmap(z=z, x=x, y=y, colorscale=colorscale)] return Chart(data=data)","Create a heatmap. Parameters ---------- z : TODO x : TODO, optional y : TODO, optional colorscale : TODO, optional Returns ------- Chart" 314,all permutations of a list,"def distinct_permutations(iterable): def make_new_permutations(permutations, e): for permutation in permutations: for j in range(len(permutation)): yield permutation[:j] + [e] + permutation[j:] if permutation[j] == e: break else: yield permutation + [e] permutations = [[]] for e in iterable: permutations = make_new_permutations(permutations, e) return (tuple(t) for t in permutations)","Yield successive distinct permutations of the elements in *iterable*. >>> sorted(distinct_permutations([1, 0, 1])) [(0, 1, 1), (1, 0, 1), (1, 1, 0)] Equivalent to ``set(permutations(iterable))``, except duplicates are not generated and thrown away. For larger input sequences this is much more efficient. Duplicate permutations arise when there are duplicated elements in the input iterable. The number of items returned is `n! / (x_1! * x_2! * ... * x_n!)`, where `n` is the total number of items input, and each `x_i` is the count of a distinct item in the input sequence. Internal helper function. The output permutations are built up by adding element *e* to the current *permutations* at every possible position. The key idea is to keep repeated elements (reverse) ordered: if e1 == e2 and e1 is before e2 in the iterable, then all permutations with e1 before e2 are ignored." 315,finding time elapsed using a timer,"def timer(name): startTime = time.time() yield elapsedTime = time.time() - startTime print('[{}] finished in {} ms'.format(name, int(elapsedTime * 1000)))", 316,print model summary," def summary(self, header=True): table = [] for model in self.models: model_summary = model._model_json[""output""][""model_summary""] r_values = list(model_summary.cell_values[0]) r_values[0] = model.model_id table.append(r_values) print() if header: print('Grid Summary:') print() H2ODisplay(table, ['Model Id'] + model_summary.col_header[1:], numalign=""left"", stralign=""left"")","Print a detailed summary of the explored models. if h2o.can_use_pandas(): import pandas pandas.options.display.max_rows = 20 print pandas.DataFrame(table,columns=self.col_header) return" 317,readonly array,"def broadcast_to(array, shape, subok=False): return _broadcast_to(array, shape, subok=subok, readonly=True)","Broadcast an array to a new shape. Parameters ---------- array : array_like The array to broadcast. shape : tuple The shape of the desired array. subok : bool, optional If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (default). Returns ------- broadcast : array A readonly view on the original array with the given shape. It is typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. Raises ------ ValueError If the array is not compatible with the new shape according to NumPy's broadcasting rules. Notes ----- .. versionadded:: 1.10.0 Examples -------- >>> x = np.array([1, 2, 3]) >>> np.broadcast_to(x, (3, 3)) array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])" 318,all permutations of a list,"def permutations(x): yield list(x) x = np.array(x) a = np.arange(len(x)) while True: ak_lt_ak_next = np.argwhere(a[:-1] < a[1:]) if len(ak_lt_ak_next) == 0: raise StopIteration() k = ak_lt_ak_next[-1, 0] ak_lt_al = np.argwhere(a[k] < a) l = ak_lt_al[-1, 0] a[k], a[l] = (a[l], a[k]) if k < len(x)-1: a[k+1:] = a[:k:-1].copy() yield x[a].tolist()","Given a listlike, x, return all permutations of x Returns the permutations of x in the lexical order of their indices: e.g. >>> x = [ 1, 2, 3, 4 ] >>> for p in permutations(x): >>> print p [ 1, 2, 3, 4 ] [ 1, 2, 4, 3 ] [ 1, 3, 2, 4 ] [ 1, 3, 4, 2 ] [ 1, 4, 2, 3 ] [ 1, 4, 3, 2 ] [ 2, 1, 3, 4 ] ... [ 4, 3, 2, 1 ] The algorithm is attributed to Narayana Pandit from his Ganita Kaumundi (1356). The following is from http://en.wikipedia.org/wiki/Permutation#Systematic_generation_of_all_permutations 1. Find the largest index k such that a[k] < a[k + 1]. If no such index exists, the permutation is the last permutation. 2. Find the largest index l such that a[k] < a[l]. Since k + 1 is such an index, l is well defined and satisfies k < l. 3. Swap a[k] with a[l]. 4. Reverse the sequence from a[k + 1] up to and including the final element a[n]. don't forget to do the first one 1 - find largest or stop 2 - find largest a[l] < a[k] 3 - swap 4 - reverse" 319,aes encryption,"def aes_encrypt(value, secret, block_size=AES.block_size): iv = os.urandom(block_size * 2) cipher = AES.new(secret[:32], AES.MODE_CFB, iv[:block_size]) return b'%s%s' % (iv, cipher.encrypt(value))","AES encrypt @value with @secret using the |CFB| mode of AES with a cryptographically secure initialization vector. -> (#bytes) AES encrypted @value .. from vital.security import aes_encrypt, aes_decrypt aes_encrypt(""Hello, world"", ""aLWEFlwgwlreWELFNWEFWLEgwklgbweLKWEBGW"") # -> 'zYgVYMbeOuiHR50aMFinY9JsfyMQCvpzI+LNqNcmZhw=' aes_decrypt( ""zYgVYMbeOuiHR50aMFinY9JsfyMQCvpzI+LNqNcmZhw="", ""aLWEFlwgwlreWELFNWEFWLEgwklgbweLKWEBGW"") # -> 'Hello, world' ..f" 320,parse query string in url," def url(self) -> str: url_str = self.parse_url.path or """" if self.parse_url.querystring is not None: url_str += ""?"" + self.parse_url.querystring return url_str",path + query çš„url 321,sorting multiple arrays based on another arrays sorted order,"def sort_numpy(array, col=0, order_back=False): x = array[:,col] sorted_index = np.argsort(x, kind = 'quicksort') sorted_array = array[sorted_index] if not order_back: return sorted_array else: n_points = sorted_index.shape[0] order_back = np.empty(n_points, dtype=int) order_back[sorted_index] = np.arange(n_points) return [sorted_array, order_back] ","Sorts the columns for an entire ``ndarrray`` according to sorting one of them. :param array: Array to sort. :type array: ndarray :param col: Master column to sort. :type col: int :param order_back: If True, also returns the index to undo the new order. :type order_back: bool :returns: sorted_array or [sorted_array, order_back] :rtype: ndarray, list" 322,string similarity levenshtein," def diff_levenshtein(self, diffs): levenshtein = 0 insertions = 0 deletions = 0 for (op, data) in diffs: if op == self.DIFF_INSERT: insertions += len(data) elif op == self.DIFF_DELETE: deletions += len(data) elif op == self.DIFF_EQUAL: levenshtein += max(insertions, deletions) insertions = 0 deletions = 0 levenshtein += max(insertions, deletions) return levenshtein","Compute the Levenshtein distance; the number of inserted, deleted or substituted characters. Args: diffs: Array of diff tuples. Returns: Number of changes. A deletion and an insertion is one substitution." 323,replace in file," def replace_text(filepath, to_replace, replacement): with open(filepath) as file: s = file.read() s = s.replace(to_replace, replacement) with open(filepath, 'w') as file: file.write(s)","Replaces a string in a given file with another string :param file: the file in which the string has to be replaced :param to_replace: the string to be replaced in the file :param replacement: the string which replaces 'to_replace' in the file" 324,write csv,"def write_csv(filename, T, header = None): with open(filename,'w') as fh: csv_writer = csv.writer(fh, delimiter=',') if header != None: csv_writer.writerow(header) [csv_writer.writerow(T[i]) for i in range(len(T))]", 325,convert a utc time to epoch,"def to_epoch(t): if isinstance(t, str): if '+' not in t: t = t + '+00:00' t = parser.parse(t) elif t.tzinfo is None or t.tzinfo.utcoffset(t) is None: t = t.replace(tzinfo=pytz.timezone('utc')) t0 = datetime.datetime(1970, 1, 1, 0, 0, 0, 0, pytz.timezone('utc')) delta = t - t0 return int(delta.total_seconds())","Take a datetime, either as a string or a datetime.datetime object, and return the corresponding epoch" 326,parse query string in url,"def _urlparse_qs(url): querystring = urlparse(url)[4] pairs = [s2 for s1 in querystring.split('&') for s2 in s1.split(';')] result = OrderedDefaultDict(list) for name_value in pairs: pair = name_value.split('=', 1) if len(pair) != 2: continue if len(pair[1]) > 0: name = _unquote(pair[0].replace('+', ' ')) value = _unquote(pair[1].replace('+', ' ')) result[name].append(value) return result","Parse a URL query string and return the components as a dictionary. Based on the cgi.parse_qs method.This is a utility function provided with urlparse so that users need not use cgi module for parsing the url query string. Arguments: :type url: str :param url: URL with query string to be parsed Extract the query part from the URL. Split the query into name/value pairs. Split the name/value pairs." 327,unique elements,"def unique(list): unique = []; [unique.append(x) for x in list if x not in unique] return unique ",Returns a copy of the list without duplicates. 328,deducting the median from each column,"def median_abs_dev(values): median = float(statistics.median(values)) return statistics.median([abs(median - sample) for sample in values])",Median Absolute Deviation 329,encode url," def _urlencode(self, url): if is_python3(): return urllib.parse.urlencode(url) else: return urllib.urlencode(url)", 330,extract data from html content,"def run(args): html_content_extractor = HTMLContentExtractor() with warnings.catch_warnings(): warnings.simplefilter('ignore') extractions = html_content_extractor.extract(html_text=args.input_file) for e in extractions: print(e.value)","Args: args (argparse.Namespace)" 331,aes encryption," def encrypt_message(self, signed_message, message, key, iv): raw = signed_message + message block_size = AES.block_size pad = lambda s: s + (block_size - len(s) % block_size) * chr(block_size - len(s) % block_size).encode('utf-8') message_to_encrypt = pad(raw) cipher = AES.new(key, AES.MODE_CBC, iv) return cipher.encrypt(message_to_encrypt)", 332,nelder mead optimize,"def minimize(func, x0, args=(), options={}, method=None): return _minimize_neldermead(func, x0, args=args, **options)", 333,memoize to disk - persistent memoization,"def memoize(f): cache_dirname = os.path.join(_get_xdg_cache_home(), 'proselint') legacy_cache_dirname = os.path.join(os.path.expanduser(""~""), "".proselint"") if not os.path.isdir(cache_dirname): if os.path.isdir(legacy_cache_dirname): os.rename(legacy_cache_dirname, cache_dirname) else: os.makedirs(cache_dirname) cache_filename = f.__module__ + ""."" + f.__name__ cachepath = os.path.join(cache_dirname, cache_filename) @functools.wraps(f) def wrapped(*args, **kwargs): if hasattr(f, '__self__'): args = args[1:] signature = (f.__module__ + '.' + f.__name__).encode(""utf-8"") tempargdict = inspect.getcallargs(f, *args, **kwargs) for item in list(tempargdict.items()): signature += item[1].encode(""utf-8"") key = hashlib.sha256(signature).hexdigest() try: cache = _get_cache(cachepath) return cache[key] except KeyError: value = f(*args, **kwargs) cache[key] = value cache.sync() return value except TypeError: call_to = f.__module__ + '.' + f.__name__ print('Warning: could not disk cache call to %s;' 'it probably has unhashable args. Error: %s' % (call_to, traceback.format_exc())) return f(*args, **kwargs) return wrapped","Cache results of computations on disk. Determine the location of the cache. Migrate the cache from the legacy path to XDG complaint location. Create the cache if it does not already exist. handle instance methods" 334,positions of substrings in string,"def get_substring_idxs(substr, string): return [match.start() for match in re.finditer(substr, string)]","Return a list of indexes of substr. If substr not found, list is empty. Arguments: substr (str): Substring to match. string (str): String to match in. Returns: list of int: Start indices of substr." 335,binomial distribution," def sample(self, n=1): p_vals = self._p_dist.rvs(size=n)[:, np.newaxis] return np.random.binomial(self.n, p_vals)","numpy.random.binomial supports sampling using different p values, whereas scipy does not." 336,write csv," def write_csv(self): csv_path = self._path/'cleaned.csv' with open(csv_path, 'w') as f: csv_writer = csv.writer(f) csv_writer.writerow(['name','label']) for pair in self._csv_dict.items(): pair = [os.path.relpath(pair[0], self._path), pair[1]] csv_writer.writerow(pair) return csv_path",Get first element's file path so we write CSV to same directory as our data 337,string similarity levenshtein,"def levenshtein(s1, s2, allow_substring=False): len1, len2 = len(s1), len(s2) lev = [] for i in range(len1 + 1): lev.append([0] * (len2 + 1)) for i in range(len1 + 1): lev[i][0] = i for j in range(len2 + 1): lev[0][j] = 0 if allow_substring else j for i in range(len1): for j in range(len2): lev[i + 1][j + 1] = min(lev[i][j + 1] + 1, lev[i + 1][j] + 1, lev[i][j] + (s1[i] != s2[j])) return min(lev[len1]) if allow_substring else lev[len1][len2]","Return the Levenshtein distance between two strings. The Levenshtein distance (a.k.a ""edit difference"") is the number of characters that need to be substituted, inserted or deleted to transform s1 into s2. Setting the `allow_substring` parameter to True allows s1 to be a substring of s2, so that, for example, ""hello"" and ""hello there"" would have a distance of zero. :param string s1: The first string :param string s2: The second string :param bool allow_substring: Whether to allow s1 to be a substring of s2 :returns: Levenshtein distance. :rtype int" 338,binomial distribution,"def Binomial(n, p, tag=None): assert ( int(n) == n and n > 0 ), 'Binomial number of trials ""n"" must be an integer greater than zero' assert ( 0 < p < 1 ), 'Binomial probability ""p"" must be between zero and one, non-inclusive' return uv(ss.binom(n, p), tag=tag)","A Binomial random variate Parameters ---------- n : int The number of trials p : scalar The probability of success" 339,initializing array," def initialize(self): for ls in self.lslist: ls.initialize() self.ncp = self.nls * self.lslist[0].ncp self.nparam = self.nls * self.lslist[0].nparam self.nunknowns = self.nparam self.xls = np.empty((self.nls, 2)) self.yls = np.empty((self.nls, 2)) for i, ls in enumerate(self.lslist): self.xls[i, :] = [ls.x1, ls.x2] self.yls[i, :] = [ls.y1, ls.y2] if self.aq is None: self.aq = self.model.aq.find_aquifer_data(self.lslist[0].xc, self.lslist[0].yc) self.parameters = np.zeros((self.nparam, 1)) self.xc = np.array([ls.xc for ls in self.lslist]).flatten() self.yc = np.array([ls.yc for ls in self.lslist]).flatten() self.xcin = np.array([ls.xcin for ls in self.lslist]).flatten() self.ycin = np.array([ls.ycin for ls in self.lslist]).flatten() self.xcout = np.array([ls.xcout for ls in self.lslist]).flatten() self.ycout = np.array([ls.ycout for ls in self.lslist]).flatten() self.cosnorm = np.array([ls.cosnorm for ls in self.lslist]).flatten() self.sinnorm = np.array([ls.sinnorm for ls in self.lslist]).flatten() self.aqin = self.model.aq.find_aquifer_data(self.xcin[0], self.ycin[0]) self.aqout = self.model.aq.find_aquifer_data(self.xcout[0], self.ycout[0])","Same order for all elements in string As parameters are only stored for the element not the list, we need to combine the following" 340,convert int to bool,"def boolval(v): if isinstance(v, bool): return v if isinstance(v, int): return bool(v) if is_string(v): v = v.lower() if v in {'j', 'y', 'ja', 'yes', '1', 'true'}: return True if v in {'n', 'nei', 'no', '0', 'false'}: return False raise ValueError(""Don't know how to convert %r to bool"" % v) ", 341,connect to sql," def __mysql_connect(self, connect_using_database_name=True): try: conn = self.__mysql_driver.connect(host=self.__mysql_host, port=self.__mysql_port, user=self.__mysql_user, passwd=self.__mysql_passwd) conn.set_character_set(self.__mysql_encoding) if connect_using_database_name: conn.select_db(self.__mysql_db) return conn except Exception as e: raise Exception(""could not connect to database: %s"" % e)", 342,get the description of a http status code," def get(self): if PyFunceble.HTTP_CODE[""active""]: http_code = self._access() list_of_valid_http_code = [] for codes in [ PyFunceble.HTTP_CODE[""list""][""up""], PyFunceble.HTTP_CODE[""list""][""potentially_down""], PyFunceble.HTTP_CODE[""list""][""potentially_up""], ]: list_of_valid_http_code.extend(codes) if http_code not in list_of_valid_http_code or http_code is None: return ""*"" * 3 return http_code return None","Return the HTTP code status. :return: The matched and formatted status code. :rtype: str|int|None The http status code extraction is activated. We get the http status code. We initiate a variable which will save the list of allowed http status code. We loop throught the list of http status code. We extend the list of valid with the currently read codes. * The extracted http code is not in the list of valid http code. or * The extracted http code is equal to `None`. We return 3 star in order to mention that we were not eable to extract the http status code. * The extracted http code is in the list of valid http code. or * The extracted http code is not equal to `None`. We return the extracted http status code. The http status code extraction is activated. We return None." 343,get current process id,"Error: 404 {""message"": ""Not Found"", ""documentation_url"": ""https://docs.github.com/rest/repos/repos","get-a-repository"", ""status"": ""404""}" 344,k means clustering,"def cluster_kmeans(data=None, k=None, max_iter=10, tolerance=1e-5, stride=1, metric='euclidean', init_strategy='kmeans++', fixed_seed=False, n_jobs=None, chunksize=None, skip=0, keep_data=False, clustercenters=None, **kwargs): r from pyemma.coordinates.clustering.kmeans import KmeansClustering res = KmeansClustering(n_clusters=k, max_iter=max_iter, metric=metric, tolerance=tolerance, init_strategy=init_strategy, fixed_seed=fixed_seed, n_jobs=n_jobs, skip=skip, keep_data=keep_data, clustercenters=clustercenters, stride=stride) from pyemma.util.reflection import get_default_args cs = _check_old_chunksize_arg(chunksize, get_default_args(cluster_kmeans)['chunksize'], **kwargs) if data is not None: res.estimate(data, chunksize=cs) else: res.chunksize = cs return res","k-means clustering If data is given, it performs a k-means clustering and then assigns the data using a Voronoi discretization. It returns a :class:`KmeansClustering ` object that can be used to extract the discretized data sequences, or to assign other data points to the same partition. If data is not given, an empty :class:`KmeansClustering ` will be created that still needs to be parametrized, e.g. in a :func:`pipeline`. Parameters ---------- data: ndarray (T, d) or list of ndarray (T_i, d) or a reader created by :func:`source` input data, if available in memory k: int the number of cluster centers. When not specified (None), min(sqrt(N), 5000) is chosen as default value, where N denotes the number of data points max_iter : int maximum number of iterations before stopping. When not specified (None), min(sqrt(N),5000) is chosen as default value, where N denotes the number of data points tolerance : float stop iteration when the relative change in the cost function :math:`C(S) = \sum_{i=1}^{k} \sum_{\mathbf x \in S_i} \left\| \mathbf x - \boldsymbol\mu_i \right\|^2` is smaller than tolerance. stride : int, optional, default = 1 If set to 1, all input data will be used for estimation. Note that this could cause this calculation to be very slow for large data sets. Since molecular dynamics data is usually correlated at short timescales, it is often sufficient to estimate transformations at a longer stride. Note that the stride option in the get_output() function of the returned object is independent, so you can parametrize at a long stride, and still map all frames through the transformer. metric : str metric to use during clustering ('euclidean', 'minRMSD') init_strategy : str determines if the initial cluster centers are chosen according to the kmeans++-algorithm or drawn uniformly distributed from the provided data set fixed_seed : bool or (positive) integer if set to true, the random seed gets fixed resulting in deterministic behavior; default is false. If an integer >= 0 is given, use this to initialize the random generator. n_jobs : int or None, default None Number of threads to use during assignment of the data. If None, all available CPUs will be used. chunksize: int, default=None Number of data frames to process at once. Choose a higher value here, to optimize thread usage and gain processing speed. If None is passed, use the default value of the underlying reader/data source. Choose zero to disable chunking at all. skip : int, default=0 skip the first initial n frames per trajectory. keep_data: boolean, default=False if you intend to quickly resume a non-converged kmeans iteration, set this to True. Otherwise the linear memory array will have to be re-created. Note that the data will also be deleted, if and only if the estimation converged within the given tolerance parameter. clustercenters: ndarray (k, dim), default=None if passed, the init_strategy is ignored and these centers will be iterated. Returns ------- kmeans : a :class:`KmeansClustering ` clustering object Object for kmeans clustering. It holds discrete trajectories and cluster center information. Examples -------- >>> import numpy as np >>> from pyemma.util.contexts import settings >>> import pyemma.coordinates as coor >>> traj_data = [np.random.random((100, 3)), np.random.random((100,3))] >>> with settings(show_progress_bars=False): ... cluster_obj = coor.cluster_kmeans(traj_data, k=20, stride=1) ... cluster_obj.get_output() # doctest: +ELLIPSIS [array([... .. seealso:: **Theoretical background**: `Wiki page `_ .. autoclass:: pyemma.coordinates.clustering.kmeans.KmeansClustering :members: :undoc-members: .. rubric:: Methods .. autoautosummary:: pyemma.coordinates.clustering.kmeans.KmeansClustering :methods: .. rubric:: Attributes .. autoautosummary:: pyemma.coordinates.clustering.kmeans.KmeansClustering :attributes: References ---------- The k-means algorithms was invented in [1]_. The term k-means was first used in [2]_. .. [1] Steinhaus, H. (1957). Sur la division des corps materiels en parties. Bull. Acad. Polon. Sci. (in French) 4, 801-804. .. [2] MacQueen, J. B. (1967). Some Methods for classification and Analysis of Multivariate Observations. Proceedings of 5th Berkeley Symposium on Mathematical Statistics and Probability 1. University of California Press. pp. 281-297" 345,aes encryption," def aes_cbc_encrypt(plain_text: bytes, key: bytes, iv: bytes = b''): if len(iv) == 0: iv = AESHandler.generate_iv() cipher = AES.new(key=key, mode=AES.MODE_CBC, iv=iv) return cipher.IV, cipher.encrypt(pad(plain_text, AES.block_size))", 346,scatter plot," def scatter(self, ax, X, Y, Z=None, color=Tango.colorsHex['mediumBlue'], label=None, marker='o', **kwargs): if Z is not None: return ax.scatter(X, Y, c=color, zs=Z, label=label, marker=marker, **kwargs) return ax.scatter(X, Y, c=color, label=label, marker=marker, **kwargs)", 347,custom http error response," def handle_http_error(self, response, custom_messages=None, raise_for_status=False): if not custom_messages: custom_messages = {} if response.status_code in custom_messages.keys(): raise requests.exceptions.HTTPError( custom_messages[response.status_code]) if raise_for_status: response.raise_for_status()", 348,extract data from html content,"def text_filter(html): if isinstance(html, list): html = """".join(html) ok, content = SoupOps.extract_text(html) if ok: return content else: raise RuntimeError(""Extract text failed"")", 349,scatter plot,"def scatter( adata, x=None, y=None, color=None, use_raw=None, layers='X', sort_order=True, alpha=None, basis=None, groups=None, components=None, projection='2d', legend_loc='right margin', legend_fontsize=None, legend_fontweight=None, color_map=None, palette=None, frameon=None, right_margin=None, left_margin=None, size=None, title=None, show=None, save=None, ax=None): if basis is not None: axs = _scatter_obs( adata=adata, x=x, y=y, color=color, use_raw=use_raw, layers=layers, sort_order=sort_order, alpha=alpha, basis=basis, groups=groups, components=components, projection=projection, legend_loc=legend_loc, legend_fontsize=legend_fontsize, legend_fontweight=legend_fontweight, color_map=color_map, palette=palette, frameon=frameon, right_margin=right_margin, left_margin=left_margin, size=size, title=title, show=show, save=save, ax=ax) elif x is not None and y is not None: if ((x in adata.obs.keys() or x in adata.var.index) and (y in adata.obs.keys() or y in adata.var.index) and (color is None or color in adata.obs.keys() or color in adata.var.index)): axs = _scatter_obs( adata=adata, x=x, y=y, color=color, use_raw=use_raw, layers=layers, sort_order=sort_order, alpha=alpha, basis=basis, groups=groups, components=components, projection=projection, legend_loc=legend_loc, legend_fontsize=legend_fontsize, legend_fontweight=legend_fontweight, color_map=color_map, palette=palette, frameon=frameon, right_margin=right_margin, left_margin=left_margin, size=size, title=title, show=show, save=save, ax=ax) elif ((x in adata.var.keys() or x in adata.obs.index) and (y in adata.var.keys() or y in adata.obs.index) and (color is None or color in adata.var.keys() or color in adata.obs.index)): axs = _scatter_var( adata=adata, x=x, y=y, color=color, use_raw=use_raw, layers=layers, sort_order=sort_order, alpha=alpha, basis=basis, groups=groups, components=components, projection=projection, legend_loc=legend_loc, legend_fontsize=legend_fontsize, legend_fontweight=legend_fontweight, color_map=color_map, palette=palette, frameon=frameon, right_margin=right_margin, left_margin=left_margin, size=size, title=title, show=show, save=save, ax=ax) else: raise ValueError( '`x`, `y`, and potential `color` inputs must all come from either `.obs` or `.var`') else: raise ValueError('Either provide a `basis` or `x` and `y`.') return axs","\ Scatter plot along observations or variables axes. Color the plot using annotations of observations (`.obs`), variables (`.var`) or expression of genes (`.var_names`). Parameters ---------- adata : :class:`~anndata.AnnData` Annotated data matrix. x : `str` or `None` x coordinate. y : `str` or `None` y coordinate. color : string or list of strings, optional (default: `None`) Keys for annotations of observations/cells or variables/genes, e.g., `'ann1'` or `['ann1', 'ann2']`. use_raw : `bool`, optional (default: `None`) Use `raw` attribute of `adata` if present. layers : `str` or tuple of strings, optional (default: `X`) Use the `layers` attribute of `adata` if present: specify the layer for `x`, `y` and `color`. If `layers` is a string, then it is expanded to `(layers, layers, layers)`. basis : {{'pca', 'tsne', 'umap', 'diffmap', 'draw_graph_fr', etc.}} String that denotes a plotting tool that computed coordinates. {scatter_temp} {show_save_ax} Returns ------- If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it." 350,k means clustering,"def cluster_mini_batch_kmeans(data=None, k=100, max_iter=10, batch_size=0.2, metric='euclidean', init_strategy='kmeans++', n_jobs=None, chunksize=None, skip=0, clustercenters=None, **kwargs): r from pyemma.coordinates.clustering.kmeans import MiniBatchKmeansClustering res = MiniBatchKmeansClustering(n_clusters=k, max_iter=max_iter, metric=metric, init_strategy=init_strategy, batch_size=batch_size, n_jobs=n_jobs, skip=skip, clustercenters=clustercenters) from pyemma.util.reflection import get_default_args cs = _check_old_chunksize_arg(chunksize, get_default_args(cluster_mini_batch_kmeans)['chunksize'], **kwargs) if data is not None: res.estimate(data, chunksize=cs) else: res.chunksize = chunksize return res","k-means clustering with mini-batch strategy Mini-batch k-means is an approximation to k-means which picks a randomly selected subset of data points to be updated in each iteration. Usually much faster than k-means but will likely deliver a less optimal result. Returns ------- kmeans_mini : a :class:`MiniBatchKmeansClustering ` clustering object Object for mini-batch kmeans clustering. It holds discrete trajectories and cluster center information. See also -------- :func:`kmeans ` : for full k-means clustering .. autoclass:: pyemma.coordinates.clustering.kmeans.MiniBatchKmeansClustering :members: :undoc-members: .. rubric:: Methods .. autoautosummary:: pyemma.coordinates.clustering.kmeans.MiniBatchKmeansClustering :methods: .. rubric:: Attributes .. autoautosummary:: pyemma.coordinates.clustering.kmeans.MiniBatchKmeansClustering :attributes: References ---------- .. [1] http://www.eecs.tufts.edu/~dsculley/papers/fastkmeans.pdf" 351,aes encryption," def encrypt_message(self, signed_message, message, key, iv): raw = signed_message + message block_size = AES.block_size pad = lambda s: s + (block_size - len(s) % block_size) * chr(block_size - len(s) % block_size).encode('utf-8') message_to_encrypt = pad(raw) cipher = AES.new(key, AES.MODE_CBC, iv) return cipher.encrypt(message_to_encrypt)", 352,group by count,"def groupby_count(i, key=None, force_keys=None): counter = defaultdict(lambda: 0) if not key: key = lambda o: o for k in i: counter[key(k)] += 1 if force_keys: for k in force_keys: counter[k] += 0 return counter.items()","Aggregate iterator values into buckets based on how frequently the values appear. Example:: >>> list(groupby_count([1, 1, 1, 2, 3])) [(1, 3), (2, 1), (3, 1)]" 353,parse query string in url,"def _urlparse_qs(url): querystring = urlparse(url)[4] pairs = [s2 for s1 in querystring.split('&') for s2 in s1.split(';')] result = OrderedDefaultDict(list) for name_value in pairs: pair = name_value.split('=', 1) if len(pair) != 2: continue if len(pair[1]) > 0: name = _unquote(pair[0].replace('+', ' ')) value = _unquote(pair[1].replace('+', ' ')) result[name].append(value) return result","Parse a URL query string and return the components as a dictionary. Based on the cgi.parse_qs method.This is a utility function provided with urlparse so that users need not use cgi module for parsing the url query string. Arguments: :type url: str :param url: URL with query string to be parsed Extract the query part from the URL. Split the query into name/value pairs. Split the name/value pairs." 354,linear regression,"def linear_regression(X, y, add_intercept=True, coef_only=False, alpha=0.05, as_dataframe=True, remove_na=False): if isinstance(X, pd.DataFrame): names = X.keys().tolist() elif isinstance(X, pd.Series): names = [X.name] else: names = [] assert 0 < alpha < 1 assert y.ndim == 1, 'y must be one-dimensional.' X = np.asarray(X) y = np.asarray(y) if X.ndim == 1: X = X[..., np.newaxis] if remove_na: X, y = rm_na(X, y[..., np.newaxis], paired=True, axis='rows') y = np.squeeze(y) y_gd = np.isfinite(y).all() X_gd = np.isfinite(X).all() assert y_gd, 'Target (y) contains NaN or Inf. Please remove them.' assert X_gd, 'Predictors (X) contain NaN or Inf. Please remove them.' assert y.shape[0] == X.shape[0], 'X and y must have same number of samples' if not names: names = ['x' + str(i + 1) for i in range(X.shape[1])] if add_intercept: X = np.column_stack((np.ones(X.shape[0]), X)) names.insert(0, ""Intercept"") coef = np.linalg.lstsq(X, y, rcond=None)[0] if coef_only: return coef pred = np.dot(X, coef) resid = np.square(y - pred) ss_res = resid.sum() n, p = X.shape[0], X.shape[1] dof = n - p if add_intercept else n - p - 1 MSE = ss_res / dof beta_var = MSE * (np.linalg.pinv(np.dot(X.T, X)).diagonal()) beta_se = np.sqrt(beta_var) ss_tot = np.square(y - y.mean()).sum() r2 = 1 - (ss_res / ss_tot) adj_r2 = 1 - (1 - r2) * (n - 1) / dof T = coef / beta_se pval = np.array([2 * t.sf(np.abs(i), dof) for i in T]) crit = t.ppf(1 - alpha / 2, dof) marg_error = crit * beta_se ll = coef - marg_error ul = coef + marg_error ll_name = 'CI[%.1f%%]' % (100 * alpha / 2) ul_name = 'CI[%.1f%%]' % (100 * (1 - alpha / 2)) stats = {'names': names, 'coef': coef, 'se': beta_se, 'T': T, 'pval': pval, 'r2': r2, 'adj_r2': adj_r2, ll_name: ll, ul_name: ul} if as_dataframe: return pd.DataFrame.from_dict(stats) else: return stats","(Multiple) Linear regression. Parameters ---------- X : np.array or list Predictor(s). Shape = (n_samples, n_features) or (n_samples,). y : np.array or list Dependent variable. Shape = (n_samples). add_intercept : bool If False, assume that the data are already centered. If True, add a constant term to the model. In this case, the first value in the output dict is the intercept of the model. coef_only : bool If True, return only the regression coefficients. alpha : float Alpha value used for the confidence intervals. CI = [alpha / 2 ; 1 - alpha / 2] as_dataframe : bool If True, returns a pandas DataFrame. If False, returns a dictionnary. remove_na : bool If True, apply a listwise deletion of missing values (i.e. the entire row is removed). Returns ------- stats : dataframe or dict Linear regression summary:: 'names' : name of variable(s) in the model (e.g. x1, x2...) 'coef' : regression coefficients 'se' : standard error of the estimate 'T' : T-values 'pval' : p-values 'r2' : coefficient of determination (R2) 'adj_r2' : adjusted R2 'CI[2.5%]' : lower confidence interval 'CI[97.5%]' : upper confidence interval Notes ----- The beta coefficients of the regression are estimated using the :py:func:`numpy.linalg.lstsq` function. It is generally recommanded to include a constant term (intercept) to the model to limit the bias and force the residual mean to equal zero. Note that intercept coefficient and p-values are however rarely meaningful. The standard error of the estimates is a measure of the accuracy of the prediction defined as: .. math:: se = \\sqrt{MSE \\cdot (X^TX)^{-1}} where :math:`MSE` is the mean squared error, .. math:: MSE = \\frac{\\sum{(true - pred)^2}}{n - p - 1} :math:`p` is the total number of explanatory variables in the model (excluding the intercept) and :math:`n` is the sample size. Using the coefficients and the standard errors, the T-values can be obtained: .. math:: T = \\frac{coef}{se} and the p-values can then be approximated using a T-distribution with :math:`n - p - 1` degrees of freedom. The coefficient of determination (:math:`R^2`) is defined as: .. math:: R^2 = 1 - (\\frac{SS_{resid}}{SS_{total}}) The adjusted :math:`R^2` is defined as: .. math:: \\overline{R}^2 = 1 - (1 - R^2) \\frac{n - 1}{n - p - 1} Results have been compared against sklearn, statsmodels and JASP. This function will not run if NaN values are either present in the target or predictors variables. Please remove them before runing the function. Examples -------- 1. Simple linear regression >>> import numpy as np >>> from pingouin import linear_regression >>> np.random.seed(123) >>> mean, cov, n = [4, 6], [[1, 0.5], [0.5, 1]], 30 >>> x, y = np.random.multivariate_normal(mean, cov, n).T >>> lm = linear_regression(x, y) >>> lm.round(2) names coef se T pval r2 adj_r2 CI[2.5%] CI[97.5%] 0 Intercept 4.40 0.54 8.16 0.00 0.24 0.21 3.29 5.50 1 x1 0.39 0.13 2.99 0.01 0.24 0.21 0.12 0.67 2. Multiple linear regression >>> np.random.seed(42) >>> z = np.random.normal(size=n) >>> X = np.column_stack((x, z)) >>> lm = linear_regression(X, y) >>> print(lm['coef'].values) [4.54123324 0.36628301 0.17709451] 3. Using a Pandas DataFrame >>> import pandas as pd >>> df = pd.DataFrame({'x': x, 'y': y, 'z': z}) >>> lm = linear_regression(df[['x', 'z']], df['y']) >>> print(lm['coef'].values) [4.54123324 0.36628301 0.17709451] 4. No intercept and return coef only >>> linear_regression(X, y, add_intercept=False, coef_only=True) array([ 1.40935593, -0.2916508 ]) 5. Return a dictionnary instead of a DataFrame >>> lm_dict = linear_regression(X, y, as_dataframe=False) 6. Remove missing values >>> X[4, 1] = np.nan >>> y[7] = np.nan >>> linear_regression(X, y, remove_na=True, coef_only=True) array([4.64069731, 0.35455398, 0.1888135 ]) Extract names if X is a Dataframe or Series Convert input to numpy array Convert to (n_samples, n_features) shape Check for NaN / Inf Check that X and y have same length Add intercept Compute beta coefficient and predictions Degrees of freedom should not include the intercept Compute mean squared error, variance and SE Compute R2, adjusted R2 and RMSE ss_exp = np.square(pred - y.mean()).sum() Compute T and p-values Compute confidence intervals Rename CI Create dict" 355,matrix multiply,"def mxmg(m1, m2, nrow1, ncol1, ncol2): m1 = stypes.toDoubleMatrix(m1) m2 = stypes.toDoubleMatrix(m2) mout = stypes.emptyDoubleMatrix(x=ncol2, y=nrow1) nrow1 = ctypes.c_int(nrow1) ncol1 = ctypes.c_int(ncol1) ncol2 = ctypes.c_int(ncol2) libspice.mxmg_c(m1, m2, nrow1, ncol1, ncol2, mout) return stypes.cMatrixToNumpy(mout)","Multiply two double precision matrices of arbitrary size. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mxmg_c.html :param m1: nrow1 X ncol1 double precision matrix. :type m1: NxM-Element Array of floats :param m2: ncol1 X ncol2 double precision matrix. :type m2: NxM-Element Array of floats :param nrow1: Row dimension of m1 :type nrow1: int :param ncol1: Column dimension of m1 and row dimension of m2. :type ncol1: int :param ncol2: Column dimension of m2 :type ncol2: int :return: nrow1 X ncol2 double precision matrix. :rtype: NxM-Element Array of floats" 356,parse command line argument,"def parse_command_line_arguments(): parser = argparse.ArgumentParser() parser.add_argument( 'xdatcar' ) parser.add_argument( 'label', nargs = 2 ) parser.add_argument( 'max_r', type = float ) parser.add_argument( 'n_bins', type = int ) args = parser.parse_args() return( args )",command line arguments 357,nelder mead optimize,"def minimize(func, x0, args=(), options={}, method=None): return _minimize_neldermead(func, x0, args=args, **options)", 358,get current process id," def process_id(self): ret = """" if thread: f = getattr(os, 'getpid', None) if f: ret = str(f()) return ret", 359,httpclient post json," def _post_json(self, url, data, **kwargs): data2 = {} if data is not None and isinstance(data, dict): for k, v in six.iteritems(data): if v is not None: data2[k] = v elif data is not None: data2 = data if 'headers' not in kwargs: kwargs['headers'] = {} kwargs['headers']['Content-Type'] = 'application/json' return self._post(url, data=json.dumps(data2), **kwargs)","Go <1.1 can't unserialize null to a string so we do this disgusting thing here." 360,encode url," def urlEncodeAndJoin(self, seq, sepr=','): try: from urllib.parse import quote_plus as encode return sepr.join([encode(x, encoding=CHARSET_UTF8) for x in seq]) except ImportError: from urllib import quote as encode return sepr.join([i for i in map(lambda x: encode(x), seq)])","sepr.join(urlencode(seq)) Args: seq: string list to be urlencoded sepr: join seq with sepr Returns: str" 361,parse query string in url,"def update_query(url, params, remove=None): if remove is None: remove = [] parts = urllib.parse.urlparse(url) query_params = urllib.parse.parse_qs(parts.query) query_params.update(params) query_params = { key: value for key, value in six.iteritems(query_params) if key not in remove} new_query = urllib.parse.urlencode(query_params, doseq=True) new_parts = parts._replace(query=new_query) return urllib.parse.urlunparse(new_parts)","Updates a URL's query parameters. Replaces any current values if they are already present in the URL. Args: url (str): The URL to update. params (Mapping[str, str]): A mapping of query parameter keys to values. remove (Sequence[str]): Parameters to remove from the query string. Returns: str: The URL with updated query parameters. Examples: >>> url = 'http://example.com?a=1' >>> update_query(url, {'a': '2'}) http://example.com?a=2 >>> update_query(url, {'b': '3'}) http://example.com?a=1&b=3 >> update_query(url, {'b': '3'}, remove=['a']) http://example.com?b=3 Split the URL into parts. Parse the query string. Update the query parameters with the new parameters. Remove any values specified in remove. Re-encoded the query string. Unsplit the url." 362,how to get current date," def date(self): if self._date: return self._date return datetime.datetime.now().strftime('%Y-%m-%d')","Getter/setter for the date member. The setter can take a string or a :meth:`datetime.datetime` and will do the appropriate transformation." 363,encode url," def _urlencode(self, url): if is_python3(): return urllib.parse.urlencode(url) else: return urllib.urlencode(url)", 364,matrix multiply," def multiply(self, matrix): positions = [matrix * x for x in self.positions] normals = list(self.normals) uvs = list(self.uvs) return Mesh(positions, normals, uvs)", 365,print model summary,"def summary(model, print_layer_links, print_barracuda_json, print_tensors): def array_without_brackets(arr): return str(arr)[1:-1] if print_layer_links: for l in model.layers: print(l.name, "" <= "", l.inputs) if print_barracuda_json: print(to_json(model)) if model.globals: if isinstance(model.globals, dict): model.globals = {x.name:x.shape for x in model.globals} print(""GLOBALS:"", array_without_brackets(model.globals)) for l in model.layers: if isinstance(model.inputs, dict): ins = {i:model.inputs[i] for i in l.inputs if i in model.inputs} else: ins = [i for i in l.inputs if i in model.inputs] if ins: print(""IN: %s => '%s'"" % (array_without_brackets(ins), l.name)) for mem_in, mem_out in zip(model.memories[1::3], model.memories[2::3]): print(""MEM: '%s' => '%s'"" % (mem_in, mem_out)) print(""OUT:"", array_without_brackets(model.outputs)) if (print_tensors): for l in model.layers: for x in l.tensors: print(x.name, x.shape, x.data.dtype, x.data)",array to string without brackets 366,how to check if a checkbox is checked," def __call__(self, *arg): if self.status: self.status = 0 self.image.fill((255, 255, 255)) ptg.Button.set_position(self, self.position, self.midpoint, self.surface) else: self.status = 1 if self.checktype == 'r': self.draw_rect_check() elif self.checktype == 'c': self.draw_circle_check() ptg.Button.set_position(self, self.position, self.midpoint, self.surface)","If the checkbox was previously checked, set the status to 0 and turn the whole box back to white. Draw the checkbox on the external surface If the checkbox was previously unchecked, set the status to 1 and draw a check in the center of the checkbox. Draw the new image on the external surface" 367,connect to sql," def _connect(self): if mysql_connector is None: raise ImproperlyConfigured('MySQL connector not installed!') return mysql_connector.connect(db=self.database, **self.connect_params)", 368,priority queue," def enqueue(self, data, priority=None): if priority: raise NotImplementedError('Task priorities are not supported by ' 'this storage.') self.conn.lpush(self.queue_key, data)", 369,unique elements,"def uniq_stable(elems): unique = [] unique_dict = {} for nn in elems: if nn not in unique_dict: unique.append(nn) unique_dict[nn] = None return unique","uniq_stable(elems) -> list Return from an iterable, a list of all the unique elements in the input, but maintaining the order in which they first appear. A naive solution to this problem which just makes a dictionary with the elements as keys fails to respect the stability condition, since dictionaries are unsorted by nature. Note: All elements in the input must be valid dictionary keys for this routine to work, as it internally uses a dictionary for efficiency reasons." 370,linear regression,"def linear_regression(X, y, add_intercept=True, coef_only=False, alpha=0.05, as_dataframe=True, remove_na=False): if isinstance(X, pd.DataFrame): names = X.keys().tolist() elif isinstance(X, pd.Series): names = [X.name] else: names = [] assert 0 < alpha < 1 assert y.ndim == 1, 'y must be one-dimensional.' X = np.asarray(X) y = np.asarray(y) if X.ndim == 1: X = X[..., np.newaxis] if remove_na: X, y = rm_na(X, y[..., np.newaxis], paired=True, axis='rows') y = np.squeeze(y) y_gd = np.isfinite(y).all() X_gd = np.isfinite(X).all() assert y_gd, 'Target (y) contains NaN or Inf. Please remove them.' assert X_gd, 'Predictors (X) contain NaN or Inf. Please remove them.' assert y.shape[0] == X.shape[0], 'X and y must have same number of samples' if not names: names = ['x' + str(i + 1) for i in range(X.shape[1])] if add_intercept: X = np.column_stack((np.ones(X.shape[0]), X)) names.insert(0, ""Intercept"") coef = np.linalg.lstsq(X, y, rcond=None)[0] if coef_only: return coef pred = np.dot(X, coef) resid = np.square(y - pred) ss_res = resid.sum() n, p = X.shape[0], X.shape[1] dof = n - p if add_intercept else n - p - 1 MSE = ss_res / dof beta_var = MSE * (np.linalg.pinv(np.dot(X.T, X)).diagonal()) beta_se = np.sqrt(beta_var) ss_tot = np.square(y - y.mean()).sum() r2 = 1 - (ss_res / ss_tot) adj_r2 = 1 - (1 - r2) * (n - 1) / dof T = coef / beta_se pval = np.array([2 * t.sf(np.abs(i), dof) for i in T]) crit = t.ppf(1 - alpha / 2, dof) marg_error = crit * beta_se ll = coef - marg_error ul = coef + marg_error ll_name = 'CI[%.1f%%]' % (100 * alpha / 2) ul_name = 'CI[%.1f%%]' % (100 * (1 - alpha / 2)) stats = {'names': names, 'coef': coef, 'se': beta_se, 'T': T, 'pval': pval, 'r2': r2, 'adj_r2': adj_r2, ll_name: ll, ul_name: ul} if as_dataframe: return pd.DataFrame.from_dict(stats) else: return stats","(Multiple) Linear regression. Parameters ---------- X : np.array or list Predictor(s). Shape = (n_samples, n_features) or (n_samples,). y : np.array or list Dependent variable. Shape = (n_samples). add_intercept : bool If False, assume that the data are already centered. If True, add a constant term to the model. In this case, the first value in the output dict is the intercept of the model. coef_only : bool If True, return only the regression coefficients. alpha : float Alpha value used for the confidence intervals. CI = [alpha / 2 ; 1 - alpha / 2] as_dataframe : bool If True, returns a pandas DataFrame. If False, returns a dictionnary. remove_na : bool If True, apply a listwise deletion of missing values (i.e. the entire row is removed). Returns ------- stats : dataframe or dict Linear regression summary:: 'names' : name of variable(s) in the model (e.g. x1, x2...) 'coef' : regression coefficients 'se' : standard error of the estimate 'T' : T-values 'pval' : p-values 'r2' : coefficient of determination (R2) 'adj_r2' : adjusted R2 'CI[2.5%]' : lower confidence interval 'CI[97.5%]' : upper confidence interval Notes ----- The beta coefficients of the regression are estimated using the :py:func:`numpy.linalg.lstsq` function. It is generally recommanded to include a constant term (intercept) to the model to limit the bias and force the residual mean to equal zero. Note that intercept coefficient and p-values are however rarely meaningful. The standard error of the estimates is a measure of the accuracy of the prediction defined as: .. math:: se = \\sqrt{MSE \\cdot (X^TX)^{-1}} where :math:`MSE` is the mean squared error, .. math:: MSE = \\frac{\\sum{(true - pred)^2}}{n - p - 1} :math:`p` is the total number of explanatory variables in the model (excluding the intercept) and :math:`n` is the sample size. Using the coefficients and the standard errors, the T-values can be obtained: .. math:: T = \\frac{coef}{se} and the p-values can then be approximated using a T-distribution with :math:`n - p - 1` degrees of freedom. The coefficient of determination (:math:`R^2`) is defined as: .. math:: R^2 = 1 - (\\frac{SS_{resid}}{SS_{total}}) The adjusted :math:`R^2` is defined as: .. math:: \\overline{R}^2 = 1 - (1 - R^2) \\frac{n - 1}{n - p - 1} Results have been compared against sklearn, statsmodels and JASP. This function will not run if NaN values are either present in the target or predictors variables. Please remove them before runing the function. Examples -------- 1. Simple linear regression >>> import numpy as np >>> from pingouin import linear_regression >>> np.random.seed(123) >>> mean, cov, n = [4, 6], [[1, 0.5], [0.5, 1]], 30 >>> x, y = np.random.multivariate_normal(mean, cov, n).T >>> lm = linear_regression(x, y) >>> lm.round(2) names coef se T pval r2 adj_r2 CI[2.5%] CI[97.5%] 0 Intercept 4.40 0.54 8.16 0.00 0.24 0.21 3.29 5.50 1 x1 0.39 0.13 2.99 0.01 0.24 0.21 0.12 0.67 2. Multiple linear regression >>> np.random.seed(42) >>> z = np.random.normal(size=n) >>> X = np.column_stack((x, z)) >>> lm = linear_regression(X, y) >>> print(lm['coef'].values) [4.54123324 0.36628301 0.17709451] 3. Using a Pandas DataFrame >>> import pandas as pd >>> df = pd.DataFrame({'x': x, 'y': y, 'z': z}) >>> lm = linear_regression(df[['x', 'z']], df['y']) >>> print(lm['coef'].values) [4.54123324 0.36628301 0.17709451] 4. No intercept and return coef only >>> linear_regression(X, y, add_intercept=False, coef_only=True) array([ 1.40935593, -0.2916508 ]) 5. Return a dictionnary instead of a DataFrame >>> lm_dict = linear_regression(X, y, as_dataframe=False) 6. Remove missing values >>> X[4, 1] = np.nan >>> y[7] = np.nan >>> linear_regression(X, y, remove_na=True, coef_only=True) array([4.64069731, 0.35455398, 0.1888135 ]) Extract names if X is a Dataframe or Series Convert input to numpy array Convert to (n_samples, n_features) shape Check for NaN / Inf Check that X and y have same length Add intercept Compute beta coefficient and predictions Degrees of freedom should not include the intercept Compute mean squared error, variance and SE Compute R2, adjusted R2 and RMSE ss_exp = np.square(pred - y.mean()).sum() Compute T and p-values Compute confidence intervals Rename CI Create dict" 371,set working directory," def set_working_directory(self, dirname): if dirname: self.main.workingdirectory.chdir(dirname, refresh_explorer=True, refresh_console=False) ","Set current working directory. In the workingdirectory and explorer plugins." 372,get current process id," def get_pid(self): if self.dwProcessId is None: if self.__process is not None: self.dwProcessId = self.get_process().get_pid() else: try: hThread = self.get_handle( win32.THREAD_QUERY_LIMITED_INFORMATION) self.dwProcessId = win32.GetProcessIdOfThread(hThread) except AttributeError: self.dwProcessId = self.__get_pid_by_scanning() return self.dwProcessId","@rtype: int @return: Parent process global ID. @raise WindowsError: An error occured when calling a Win32 API function. @raise RuntimeError: The parent process ID can't be found. Infinite loop if self.__process is None I wish this had been implemented before Vista... XXX TODO find the real ntdll call under this api This method really sucks :P" 373,parse json file,"Error: 404 {""message"": ""Not Found"", ""documentation_url"": ""https://docs.github.com/rest/repos/repos","get-a-repository"", ""status"": ""404""}" 374,confusion matrix,"def plot_confusion_reports(y, y_hat, class_names=None): if class_names is None: class_names = list(set(y).union(set(y_hat))) cnf_matrix = confusion_matrix(y, y_hat) np.set_printoptions(precision=2) plt.figure() plot_confusion_matrix(cnf_matrix, classes=class_names, title='Confusion matrix, without normalization') plt.figure() plot_confusion_matrix(cnf_matrix, classes=class_names, normalize=True, title='Normalized confusion matrix') plt.show()","Compute confusion matrix Plot non-normalized confusion matrix Plot normalized confusion matrix" 375,how to extract zip file recursively," def _extract_zip(self, url, content, value): zipinmemory = IO(content) zcopied = 0 with zipfile.ZipFile(zipinmemory) as zipf: progress_logger.debug('%d files in zip archive', len(zipf.namelist())) for filepath in zipf.namelist(): if filepath.endswith('/'): continue regex_pattern, targets = None, None for r, t in value.items(): if re.match(r, filepath): regex_pattern, targets = r, t break if regex_pattern is None: progress_logger.debug('""%s"" no target found', filepath) elif targets is None: progress_logger.debug('""%s"" skipping (regex: ""%s"")', filepath, regex_pattern) else: if isinstance(targets, str): targets = [targets] for target in targets: new_path = self._file_path(filepath, target, regex=regex_pattern) progress_logger.debug('""%s"" ➤ ""%s"" (regex: ""%s"")', filepath, new_path.relative_to(self.download_root), regex_pattern) self._write(new_path, zipf.read(filepath), url) zcopied += 1 return zcopied", 376,convert a date string into yyyymmdd," def yyyymmdd(self, auto=None, datetime=None, timezone=None, timestamp=None, ms=False, concat=''): datetime = self.convert(auto=auto, datetime=datetime, timezone=timezone, timestamp=timestamp, ms=ms) return '%04d%s%02d%s%02d' % (datetime.year, concat, datetime.month, concat, datetime.day)", 377,k means clustering,"def cluster_mini_batch_kmeans(data=None, k=100, max_iter=10, batch_size=0.2, metric='euclidean', init_strategy='kmeans++', n_jobs=None, chunksize=None, skip=0, clustercenters=None, **kwargs): r from pyemma.coordinates.clustering.kmeans import MiniBatchKmeansClustering res = MiniBatchKmeansClustering(n_clusters=k, max_iter=max_iter, metric=metric, init_strategy=init_strategy, batch_size=batch_size, n_jobs=n_jobs, skip=skip, clustercenters=clustercenters) from pyemma.util.reflection import get_default_args cs = _check_old_chunksize_arg(chunksize, get_default_args(cluster_mini_batch_kmeans)['chunksize'], **kwargs) if data is not None: res.estimate(data, chunksize=cs) else: res.chunksize = chunksize return res","k-means clustering with mini-batch strategy Mini-batch k-means is an approximation to k-means which picks a randomly selected subset of data points to be updated in each iteration. Usually much faster than k-means but will likely deliver a less optimal result. Returns ------- kmeans_mini : a :class:`MiniBatchKmeansClustering ` clustering object Object for mini-batch kmeans clustering. It holds discrete trajectories and cluster center information. See also -------- :func:`kmeans ` : for full k-means clustering .. autoclass:: pyemma.coordinates.clustering.kmeans.MiniBatchKmeansClustering :members: :undoc-members: .. rubric:: Methods .. autoautosummary:: pyemma.coordinates.clustering.kmeans.MiniBatchKmeansClustering :methods: .. rubric:: Attributes .. autoautosummary:: pyemma.coordinates.clustering.kmeans.MiniBatchKmeansClustering :attributes: References ---------- .. [1] http://www.eecs.tufts.edu/~dsculley/papers/fastkmeans.pdf" 378,html encode string," def html(self, html: str) -> None: self._html = html.encode(self.encoding)", 379,initializing array," def _init_arrays(self, size=0): if self.initialized: self._cluster_hits = np.zeros(shape=(size, ), dtype=np.dtype(self._cluster_hits_descr)) self._clusters = np.zeros(shape=(size, ), dtype=np.dtype(self._cluster_descr)) self._assigned_hit_array = np.zeros(shape=(size, ), dtype=np.bool) self._cluster_hit_indices = np.empty(shape=(size, ), dtype=np_int_type_chooser(size)) self._cluster_hit_indices.fill(-1)", 380,convert string to number,"def convert_string_to_number(value): if value is None: return 1 if isinstance(value, int): return value if value.isdigit(): return int(value) num_list = map(lambda s: NUMBERS[s], re.findall(numbers + '+', value.lower())) return sum(num_list)",Convert strings to numbers 381,read text file line by line,"def check(conf, line): if line.end == len(line.buffer) and line.end > line.start: yield LintProblem(line.line_no, line.end - line.start + 1, 'no new line character at the end of file')", 382,pretty print json,"def json_pretty_print(s): s = json.loads(s) return json.dumps(s, sort_keys=True, indent=4, separators=(',', ': '))",pretty print JSON 383,deserialize json," def deserialize(self, s, cls): vals = json.JSONDecoder().decode(s) return self.deserialize_map(vals, cls)", 384,how to check if a checkbox is checked,"def check_checkbox(self, value): check_box = find_field(world.browser, 'checkbox', value) assert check_box, ""Cannot find checkbox '{}'."".format(value) if not check_box.is_selected(): check_box.click()","Check the checkbox with label (recommended), name or id." 385,convert html to pdf," def pdf_from_post(self): html = self.request.form.get(""html"") style = self.request.form.get(""style"") reporthtml = ""{0}{1}"" reporthtml = reporthtml.format(style, html) reporthtml = safe_unicode(reporthtml).encode(""utf-8"") pdf_fn = tempfile.mktemp(suffix="".pdf"") pdf_file = createPdf(htmlreport=reporthtml, outfile=pdf_fn) return pdf_file",Returns a pdf stream with the stickers 386,set working directory," def set_workdir(self, workdir, chroot=False): super().set_workdir(workdir, chroot=chroot) self.output_file = self.log_file","Set the working directory of the task. Small hack: the log file of optics is actually the main output file." 387,binomial distribution,"def EvalBinomialPmf(k, n, p): return scipy.stats.binom.pmf(k, n, p)","Evaluates the binomial pmf. Returns the probabily of k successes in n trials with probability p." 388,format date,"def format_date(date, timestamp_format): try: date = DATE_ADD.format(int(date)) except ValueError: date = timestamp_format.format(date) return date", 389,format date,"def format_date_for_input(date): date_fmt = get_locale().date_formats[""short""].pattern date_fmt = date_fmt.replace(""MMMM"", ""MM"").replace(""MMM"", ""MM"") return format_date(date, date_fmt)",force numerical months 390,get the description of a http status code,"def get_http_status_string(v): code = get_http_status_code(v) try: return ERROR_DESCRIPTIONS[code] except KeyError: return ""{} Status"".format(code)","Return HTTP response string, e.g. 204 -> ('204 No Content'). The return string always includes descriptive text, to satisfy Apache mod_dav. `v`: status code or DAVError" 391,confusion matrix,"def confusion_matrix(actual=[], pred=[]): idx = { 'ADJ' : 0, 'ADV' : 1, 'CONJ': 2, 'DET' : 3, 'NOUN': 4, 'NUM' : 5, 'OTH' : 6, 'PART': 7, 'PRON': 8, 'SYM' : 9, 'VERB': 10 } matrix = [[0 for i in range(11)] for j in range(11)] for i in range(0, len(actual)): matrix[idx[actual[i]]][idx[pred[i]]] += 1 return matrix", 392,socket recv timeout," def recv(self, amt, flags=0): if select.select([self.sock], [], [], self.timeout)[0]: return self.sock.recv(amt, flags) raise TimeoutError('socket recv() timeout.')", 393,print model summary,"def _print_summary(module, case, summary): try: module.print_summary(case, summary) except (NotImplementedError, AttributeError): print("" Ran "" + case + ""!"") print("""")", 394,how to get current date,"def get_current_date_time(i): import datetime a={} now1=datetime.datetime.now() now=now1.timetuple() a['date_year']=now[0] a['date_month']=now[1] a['date_day']=now[2] a['time_hour']=now[3] a['time_minute']=now[4] a['time_second']=now[5] return {'return':0, 'array':a, 'iso_datetime':now1.isoformat()}","Input: {} Output: { return - return code = 0 array - array with date and time iso_datetime - date and time in ISO format }" 395,copying a file to a path,"def copy_file(src, dst, ignore=None): src = re.sub('[^\w/\-\.\*]', '', src) dst = re.sub('[^\w/\-\.\*]', '', dst) if len(re.sub('[\W]', '', src)) < 5 or len(re.sub('[\W]', '', dst)) < 5: debug.log(""Error: Copying file failed. Provided paths are invalid! src='%s' dst='%s'""%(src, dst)) else: check = False if dst[-1] == '/': if os.path.exists(dst): check = True else: debug.log(""Error: Copying file failed. Destination directory does not exist (%s)""%(dst)) elif os.path.exists(dst): if os.path.isdir(dst): check = True dst += '/' else: debug.log(""Error: Copying file failed. %s exists!""%dst) elif os.path.exists(os.path.dirname(dst)): check = True else: debug.log(""Error: Copying file failed. %s is an invalid distination!""%dst) if check: files = glob.glob(src) if ignore is not None: files = [fil for fil in files if not ignore in fil] if len(files) != 0: debug.log(""Copying File(s)..."", ""Copy from %s""%src, ""to %s""%dst) for file_ in files: if os.path.isfile(file_): debug.log(""Copying file: %s""%file_) shutil.copy(file_, dst) else: debug.log(""Error: Copying file failed. %s is not a regular file!""%file_) else: debug.log(""Error: Copying file failed. No files were found! (%s)""%src) ","this function will simply copy the file from the source path to the dest path given as input Sanity checkpoint Check destination Valid Dir DEBUG Valid Dir Add missing slash Valid file path Check source DEBUG Check file exists DEBUG DEBUG DEBUG" 396,html encode string," def html(self, html: str) -> None: self._html = html.encode(self.encoding)", 397,how to determine a string is a valid word," def get_most_used_words(words, stopwords): valid_words = [word.lower() for word in words if StringHelper.is_valid_word(word, stopwords)] return dict(Counter(valid_words).most_common(5))", 398,how to empty array," def default_array(self, array_size): array = np.empty(array_size, dtype = self.dtype) if self.value_type == Enum: array.fill(self.default_value.index) return EnumArray(array, self.possible_values) array.fill(self.default_value) return array", 399,create cookie," def _set_cookie(self, name, value): cookie_domain = self._config.cookie_domain cookie_path = self._config.cookie_path cookie_expires = self._config.cookie_expires if self._config.secure: return self.handler.set_secure_cookie( name, value, expires_days=cookie_expires / (3600 * 24), domain=cookie_domain, path=cookie_path) else: return self.handler.set_cookie(name, value, expires=cookie_expires, domain=cookie_domain, path=cookie_path)", 400,parse command line argument,"def parse_command_line_arguments(): parser = argparse.ArgumentParser( description='Rotates the cell lattice in VASP POSCAR files' ) parser.add_argument( 'poscar', help=""filename of the VASP POSCAR to be processed"" ) parser.add_argument( '-a', '--axis', nargs=3, type=float, help=""vector for rotation axis"", required=True ) parser.add_argument( '-d', '--degrees', type=int, help=""rotation angle in degrees"", required=True ) args = parser.parse_args() return( args )", 401,parse command line argument,"def parse_command_line_arguments(): parser = argparse.ArgumentParser( description='Rotates the cell lattice in VASP POSCAR files' ) parser.add_argument( 'poscar', help=""filename of the VASP POSCAR to be processed"" ) parser.add_argument( '-a', '--axis', nargs=3, type=float, help=""vector for rotation axis"", required=True ) parser.add_argument( '-d', '--degrees', type=int, help=""rotation angle in degrees"", required=True ) args = parser.parse_args() return( args )", 402,parse json file,"Error: 404 {""message"": ""Not Found"", ""documentation_url"": ""https://docs.github.com/rest/repos/repos","get-a-repository"", ""status"": ""404""}" 403,binomial distribution,"def Binomial(n, p, tag=None): assert ( int(n) == n and n > 0 ), 'Binomial number of trials ""n"" must be an integer greater than zero' assert ( 0 < p < 1 ), 'Binomial probability ""p"" must be between zero and one, non-inclusive' return uv(ss.binom(n, p), tag=tag)","A Binomial random variate Parameters ---------- n : int The number of trials p : scalar The probability of success" 404,custom http error response," def raise_for_status(self, response): http_error_msg = '' if 400 <= response.status_code < 500: try: http_error_msg = response.json() except: http_error_msg = ('{code} Client Error: {reason} for url: {url}'.format( code=response.status_code, reason=response.reason, url=response.url) ) elif 500 <= response.status_code < 600: http_error_msg = ('{code} Server Error: {reason} for url: {url}'.format( code=response.status_code, reason=response.reason, url=response.url) ) if http_error_msg: raise HTTPError(http_error_msg, response=response)", 405,regex case insensitive,"def _regex_span(_regex, _str, case_insensitive=True): if case_insensitive: flags = regex.IGNORECASE | regex.FULLCASE | regex.VERSION1 else: flags = regex.VERSION1 comp = regex.compile(_regex, flags=flags) matches = comp.finditer(_str) for match in matches: yield match","Return all matches in an input string. :rtype : regex.match.span :param _regex: A regular expression pattern. :param _str: Text on which to run the pattern." 406,how to make the checkbox checked,"def assert_checked_checkbox(self, value): check_box = find_field(world.browser, 'checkbox', value) assert check_box, ""Cannot find checkbox '{}'."".format(value) assert check_box.is_selected(), ""Check box should be selected.""","Assert the checkbox with label (recommended), name or id is checked." 407,read text file line by line," def readline(self): if self._current_line >= len(self._linelist): line = '' else: line = self._linelist[self._current_line] + '\n' self._current_line += 1 self._current_indx += len( '\n'.join(self._linelist[0:self._current_line])) if self._encoding is not None: line = line.encode(self._encoding) return line", 408,string similarity levenshtein,"def levenshtein_distance(word1, word2): if len(word1) < len(word2): return levenshtein_distance(word2, word1) if len(word2) == 0: return len(word1) previous_row = list(range(len(word2) + 1)) for i, char1 in enumerate(word1): current_row = [i + 1] for j, char2 in enumerate(word2): insertions = previous_row[j + 1] + 1 deletions = current_row[j] + 1 substitutions = previous_row[j] + (char1 != char2) current_row.append(min(insertions, deletions, substitutions)) previous_row = current_row return previous_row[-1]","Computes the Levenshtein distance. [Reference]: https://en.wikipedia.org/wiki/Levenshtein_distance [Article]: Levenshtein, Vladimir I. (February 1966). ""Binary codes capable of correcting deletions, insertions,and reversals"". Soviet Physics Doklady 10 (8): 707–710. [Implementation]: https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Python" 409,get current ip address," def get_ip(self): if self._ip is not None: ret = self._ip else: ret = self.ip_addr return ret", 410,how to extract zip file recursively," def extract_zip(self): assert self.FILE_COUNT>0 try: with zipfile.ZipFile(self.archive_path, ""r"") as zip: namelist = zip.namelist() print(""namelist():"", namelist) if len(namelist) != self.FILE_COUNT: msg = ( ""Wrong archive content?!?"" "" There exists %i files, but it should exist %i."" ""Existing names are: %r"" ) % (len(namelist), self.FILE_COUNT, namelist) log.error(msg) raise RuntimeError(msg) for filename in namelist: content = zip.read(filename) dst = self.file_rename(filename) out_filename=os.path.join(self.ROM_PATH, dst) with open(out_filename, ""wb"") as f: f.write(content) if dst == filename: print(""%r extracted"" % out_filename) else: print(""%r extracted to %r"" % (filename, out_filename)) self.post_processing(out_filename) except BadZipFile as err: msg = ""Error extracting archive %r: %s"" % (self.archive_path, err) log.error(msg) raise BadZipFile(msg)", 411,memoize to disk - persistent memoization,"def memoize(func): cache = func._util_decor_memoize_cache = {} def memoizer(*args, **kwargs): key = str(args) + str(kwargs) if key not in cache: cache[key] = func(*args, **kwargs) return cache[key] memoizer = preserve_sig(memoizer, func) memoizer.cache = cache return memoizer","simple memoization decorator References: https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize Args: func (function): live python function Returns: func: CommandLine: python -m utool.util_decor memoize Example: >>> # ENABLE_DOCTEST >>> from utool.util_decor import * # NOQA >>> import utool as ut >>> closure = {'a': 'b', 'c': 'd'} >>> incr = [0] >>> def foo(key): >>> value = closure[key] >>> incr[0] += 1 >>> return value >>> foo_memo = memoize(foo) >>> assert foo('a') == 'b' and foo('c') == 'd' >>> assert incr[0] == 2 >>> print('Call memoized version') >>> assert foo_memo('a') == 'b' and foo_memo('c') == 'd' >>> assert incr[0] == 4 >>> assert foo_memo('a') == 'b' and foo_memo('c') == 'd' >>> print('Counter should no longer increase') >>> assert incr[0] == 4 >>> print('Closure changes result without memoization') >>> closure = {'a': 0, 'c': 1} >>> assert foo('a') == 0 and foo('c') == 1 >>> assert incr[0] == 6 >>> assert foo_memo('a') == 'b' and foo_memo('c') == 'd' @functools.wraps(func)" 412,get executable path," def _search_for_executable(self, executable): if os.path.isfile(executable): return os.path.abspath(executable) else: envpath = os.getenv('PATH') if envpath is None: return for path in envpath.split(os.pathsep): exe = os.path.join(path, executable) if os.path.isfile(exe): return os.path.abspath(exe)","Search for file give in ""executable"". If it is not found, we try the environment PATH. Returns either the absolute path to the found executable, or None if the executable couldn't be found." 413,convert int to bool,"def boolval(v): if isinstance(v, bool): return v if isinstance(v, int): return bool(v) if is_string(v): v = v.lower() if v in {'j', 'y', 'ja', 'yes', '1', 'true'}: return True if v in {'n', 'nei', 'no', '0', 'false'}: return False raise ValueError(""Don't know how to convert %r to bool"" % v) ", 414,connect to sql," def _connect(self): if self._connParams: self._conn = MySQLdb.connect(**self._connParams) else: self._conn = MySQLdb.connect('')",Establish connection to MySQL Database. 415,convert json to csv,"def json_to_csv(json_input): try: json_input = json.loads(json_input) except: pass headers = set() for json_row in json_input: headers.update(json_row.keys()) csv_io = StringIO.StringIO() csv_out = csv.DictWriter(csv_io,headers) csv_out.writeheader() for json_row in json_input: csv_out.writerow(json_row) csv_io.seek(0) return csv_io.read()","Convert simple JSON to CSV Accepts a JSON string or JSON object If loads fails, it's probably already parsed" 416,convert html to pdf,"def html_to_pdf(tmp_filenames, output_directory, lang_options): input_html = output_directory + ""/"" + tmp_filenames[0] wkthml_cmd = [""wkhtmltopdf""] wkthml_cmd.extend([""--margin-left"", ""18""]) wkthml_cmd.extend([""--margin-right"", ""18""]) wkthml_cmd.extend([""--page-size"", ""Letter""]) header_file = pkg_resources.resource_filename(""wrc"", ""data/header.html"") footer_file = pkg_resources.resource_filename(""wrc"", ""data/footer.html"") wkthml_cmd.extend([""--header-html"", header_file]) wkthml_cmd.extend([""--footer-html"", footer_file]) wkthml_cmd.extend([""--header-spacing"", ""8""]) wkthml_cmd.extend([""--footer-spacing"", ""8""]) wkthml_cmd.append(input_html) wkthml_cmd.append(output_directory + ""/"" + lang_options['pdf'] + '.pdf') try: check_call(wkthml_cmd) print ""Successfully generated pdf file!"" print ""Cleaning temporary file (%s)..."" % input_html os.remove(input_html) except CalledProcessError as err: print ""Error while generating pdf:"" print err sys.exit(1) except OSError as err: print ""Error when running command \"""" + "" "".join(wkthml_cmd) + ""\"""" print err sys.exit(1)","Basic margins etc Header and Footer" 417,copy to clipboard," def copy_to_clipboard(self, event): log.critical(""Copy to clipboard"") text = self.text.get(""1.0"", tkinter.END) print(text) self.root.clipboard_clear() self.root.clipboard_append(text)", 418,copy to clipboard," def copy_clipboard(self): if self.get_has_selection(): super(GuakeTerminal, self).copy_clipboard() elif self.matched_value: guake_clipboard = Gtk.Clipboard.get_default(self.guake.window.get_display()) guake_clipboard.set_text(self.matched_value, len(self.matched_value))", 419,get all parents of xml node," def get_ancestor_ephemeral_nodes(self, selected_nodes): node_names = {} for node_id in selected_nodes: if node_id not in self.manifest.nodes: continue node = self.manifest.nodes[node_id] if node.resource_type == NodeType.Source: continue node_names[node_id] = node.name include_spec = [ '+{}'.format(node_names[node]) for node in selected_nodes if node in node_names ] if not include_spec: return set() all_ancestors = self.select_nodes(self.linker.graph, include_spec, []) res = [] for ancestor in all_ancestors: ancestor_node = self.manifest.nodes.get(ancestor, None) if ancestor_node and self.is_ephemeral_model(ancestor_node): res.append(ancestor) return set(res)",sources don't have ancestors and this results in a silly select() 420,parse command line argument,"def parse_cmdln_args(): parser = argparse.ArgumentParser(description='Process command line args') parser.add_argument('--log', help='log help', default='INFO') parser.add_argument( '--tc', help='tc help') parser.add_argument( '--ts', help='ts help') args = parser.parse_args() return (args.log.upper(), args.tc, args.ts)", 421,export to excel," def to_excel(self, xl_app=None, resize_columns=True): from win32com.client import Dispatch, gencache if xl_app is None: xl_app = Dispatch(""Excel.Application"") xl_app = gencache.EnsureDispatch(xl_app) assert self.worksheets, ""Can't export workbook with no worksheets"" sheets_in_new_workbook = xl_app.SheetsInNewWorkbook try: xl_app.SheetsInNewWorkbook = float(len(self.worksheets)) self.workbook_obj = xl_app.Workbooks.Add() finally: xl_app.SheetsInNewWorkbook = sheets_in_new_workbook sheet_names = {s.name for s in self.worksheets} assert len(sheet_names) == len(self.worksheets), ""Worksheets must have unique names"" for worksheet in self.workbook_obj.Sheets: i = 1 original_name = worksheet.Name while worksheet.Name in sheet_names: worksheet.Name = ""%s_%d"" % (original_name, i) i += 1 for worksheet, sheet in zip(self.workbook_obj.Sheets, self.worksheets): worksheet.Name = sheet.name for worksheet, sheet in zip(self.workbook_obj.Sheets, self.itersheets()): worksheet.Select() sheet.to_excel(workbook=self, worksheet=worksheet, xl_app=xl_app, rename=False, resize_columns=resize_columns) return self.workbook_obj","Add a new workbook with the correct number of sheets. We aren't allowed to create an empty one. Rename the worksheets, ensuring that there can never be two sheets with the same name due to the sheets default names conflicting with the new names. Export each sheet (have to use itersheets for this as it sets the current active sheet before yielding each one)." 422,memoize to disk - persistent memoization," def memoize(self, obj): if isinstance(obj, _bytes_or_unicode): return Pickler.memoize(self, obj)","We want hashing to be sensitive to value instead of reference. For example we want ['aa', 'aa'] and ['aa', 'aaZ'[:2]] to hash to the same value and that's why we disable memoization for strings" 423,how to extract zip file recursively," def extract_zip(self): assert self.FILE_COUNT>0 try: with zipfile.ZipFile(self.archive_path, ""r"") as zip: namelist = zip.namelist() print(""namelist():"", namelist) if namelist != self.ARCHIVE_NAMES: msg = ( ""Wrong archive content?!?"" "" namelist should be: %r"" ) % self.ARCHIVE_NAMES log.error(msg) raise RuntimeError(msg) zip.extractall(path=self.ROM_PATH) except BadZipFile as err: msg = ""Error extracting archive %r: %s"" % (self.archive_path, err) log.error(msg) raise BadZipFile(msg) hex2bin( src=os.path.join(self.ROM_PATH, ""ExBasROM.hex""), dst=self.rom_path, verbose=False )", 424,k means clustering," def kmeans_clustering(self, numc, X=None, npcs=15): from sklearn.cluster import KMeans if X is None: D_sub = self.adata.uns['X_processed'] X = ( D_sub - D_sub.mean(0)).dot( self.adata.uns['pca_obj'].components_[ :npcs, :].T) save = True else: save = False cl = KMeans(n_clusters=numc).fit_predict(Normalizer().fit_transform(X)) if save: self.adata.obs['kmeans_clusters'] = pd.Categorical(cl) else: return cl","Performs k-means clustering. Parameters ---------- numc - int Number of clusters npcs - int, optional, default 15 Number of principal components to use as inpute for k-means clustering." 425,string similarity levenshtein,"def levenshtein_dist(s1: str, s2: str) -> int: if len(s1) < len(s2): return levenshtein_dist(s2, s1) if len(s2) == 0: return len(s1) previous_row = range(len(s2) + 1) for i, c1 in enumerate(s1): current_row = [i + 1] for j, c2 in enumerate(s2): insertions = previous_row[j + 1] + 1 deletions = current_row[j] + 1 substitutions = previous_row[j] + (c1 != c2) current_row.append(min(insertions, deletions, substitutions)) previous_row = current_row return previous_row[-1]","len(s1) >= len(s2) j+1 instead of j since previous_row and current_row are one character longer than s2" 426,aes encryption,"def aes_encrypt(base64_encryption_key, data): if isinstance(data, text_type): data = data.encode(""UTF-8"") aes_key_bytes, hmac_key_bytes = _extract_keys(base64_encryption_key) data = _pad(data) iv_bytes = os.urandom(AES_BLOCK_SIZE) cipher = AES.new(aes_key_bytes, mode=AES.MODE_CBC, IV=iv_bytes) data = iv_bytes + cipher.encrypt(data) hmac_signature = hmac.new(hmac_key_bytes, data, hashlib.sha256).digest() return as_base64(data + hmac_signature)","Encrypt data with AES-CBC and sign it with HMAC-SHA256 Arguments: base64_encryption_key (str): a base64-encoded string containing an AES encryption key and HMAC signing key as generated by generate_encryption_key() data (str): a byte string containing the data to be encrypted Returns: str: the encrypted data as a byte string with the HMAC signature appended to the end prepend init vector" 427,convert a date string into yyyymmdd,"def day_to_month(timeperiod): t = datetime.strptime(timeperiod, SYNERGY_DAILY_PATTERN) return t.strftime(SYNERGY_MONTHLY_PATTERN)",":param timeperiod: as string in YYYYMMDD00 format :return string in YYYYMM0000 format" 428,write csv,"def write_to_csv(fname, header, rows): with open(fname, 'wb') as csvfile: csvwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) csvwriter.writerow(header) for row in rows: csvwriter.writerow( [s.encode(""utf-8"").replace(',', '').replace('\n', '') for s in row])", 429,parse command line argument,"def parse_command_line_arguments(): parser = argparse.ArgumentParser() parser.add_argument( 'xdatcar' ) parser.add_argument( 'label', nargs = 2 ) parser.add_argument( 'max_r', type = float ) parser.add_argument( 'n_bins', type = int ) args = parser.parse_args() return( args )",command line arguments 430,how to check if a checkbox is checked,"def assert_not_checked_checkbox(step, value): check_box = find_field(world.browser, 'checkbox', value) assert_true(step, not check_box.is_selected())", 431,string to date," def datetime(self): date_string = '%s %s' % (self._date, self._year) date_string = re.sub(r' \(\d+\)', '', date_string) return datetime.strptime(date_string, '%A, %b %d %Y')","Returns a datetime object of the month, day, year, and time the game was played." 432,how to make the checkbox checked," def checkbox_uncheck(self, force_check=False): if self.get_attribute('checked'): self.click(force_click=force_check)",Wrapper to uncheck a checkbox 433,underline text in label widget,"Error: 404 {""message"": ""Not Found"", ""documentation_url"": ""https://docs.github.com/rest/repos/repos","get-a-repository"", ""status"": ""404""}" 434,parse binary file to custom class," def binary_file(self, file=None): if file is None: file = BytesIO() self._binary_file(file) return file",Same as :meth:`file` but for binary content. 435,binomial distribution,"def binomial(n,k): if n==k: return 1 assert n>k, ""Attempting to call binomial(%d,%d)"" % (n,k) return factorial(n)//(factorial(k)*factorial(n-k))","Binomial coefficient >>> binomial(5,2) 10 >>> binomial(10,5) 252" 436,how to randomly pick a number,"def get_random_int(min_v=0, max_v=10, number=5, seed=None): rnd = random.Random() if seed: rnd = random.Random(seed) return [rnd.randint(min_v, max_v) for p in range(0, number)]","Return a list of random integer by the given range and quantity. Parameters ----------- min_v : number The minimum value. max_v : number The maximum value. number : int Number of value. seed : int or None The seed for random. Examples --------- >>> r = get_random_int(min_v=0, max_v=10, number=5) [10, 2, 3, 3, 7] return [random.randint(min,max) for p in range(0, number)]" 437,copy to clipboard,"Error: 404 {""message"": ""Not Found"", ""documentation_url"": ""https://docs.github.com/rest/repos/repos","get-a-repository"", ""status"": ""404""}" 438,parse binary file to custom class," def parse_binary(self, data, display, rawdict = 0): ret = {} val = struct.unpack(self.static_codes, data[:self.static_size]) lengths = {} formats = {} vno = 0 for f in self.static_fields: if not f.name: pass elif isinstance(f, LengthField): f_names = [f.name] if f.other_fields: f_names.extend(f.other_fields) field_val = val[vno] if f.parse_value is not None: field_val = f.parse_value(field_val, display) for f_name in f_names: lengths[f_name] = field_val elif isinstance(f, FormatField): formats[f.name] = val[vno] else: if f.structvalues == 1: field_val = val[vno] else: field_val = val[vno:vno+f.structvalues] if f.parse_value is not None: field_val = f.parse_value(field_val, display) ret[f.name] = field_val vno = vno + f.structvalues data = data[self.static_size:] for f in self.var_fields: ret[f.name], data = f.parse_binary_value(data, display, lengths.get(f.name), formats.get(f.name), ) if not rawdict: ret = DictWrapper(ret) return ret, data","values, remdata = s.parse_binary(data, display, rawdict = 0) Convert a binary representation of the structure into Python values. DATA is a string or a buffer containing the binary data. DISPLAY should be a Xlib.protocol.display.Display object if there are any Resource fields or Lists with ResourceObjs. The Python values are returned as VALUES. If RAWDICT is true, a Python dictionary is returned, where the keys are field names and the values are the corresponding Python value. If RAWDICT is false, a DictWrapper will be returned where all fields are available as attributes. REMDATA are the remaining binary data, unused by the Struct object. Fields without name should be ignored. This is typically pad and constant fields Store index in val for Length and Format fields, to be used when treating varfields. Treat value fields the same was as in parse_value. Call parse_binary_value for each var_field, passing the length and format values from the unpacked val." 439,how to read the contents of a .gz compressed file?," def read(self): with gzip.GzipFile(self.path, compresslevel=self.compresslevel) as gz_file: gz_file.read1 = gz_file.read with io.TextIOWrapper(gz_file, encoding=self.encoding, errors=self.errors, newline=self.newline) as file_content: return file_content.read()", 440,get name of enumerated value," def _to_string(self): enum_name = None value = self._get_calculated_value(self.value) for enum, enum_value in vars(self.enum_type).items(): if value == enum_value: enum_name = enum break if enum_name is None: return ""(%d) UNKNOWN_ENUM"" % value else: return ""(%d) %s"" % (value, enum_name)", 441,how to read the contents of a .gz compressed file?,"def _file_size(file_path, uncompressed=False): _, ext = os.path.splitext(file_path) if uncompressed: if ext in {"".gz"", "".gzip""}: with gzip.GzipFile(file_path, mode=""rb"") as fp: try: fp.seek(0, os.SEEK_END) return fp.tell() except ValueError: fp.seek(0) while len(fp.read(8192)) != 0: pass return fp.tell() elif ext in {"".bz"", "".bz2"", "".bzip"", "".bzip2""}: with bz2.BZ2File(file_path, mode=""rb"") as fp: fp.seek(0, os.SEEK_END) return fp.tell() return os.path.getsize(file_path)","Return size of a single file, compressed or uncompressed on python2, cannot seek from end and must instead read to end" 442,get executable path,"def find_executable(executable: str, *paths: str) -> typing.Optional[Path]: if not executable.endswith('.exe'): executable = f'{executable}.exe' if executable in _KNOWN_EXECUTABLES: return _KNOWN_EXECUTABLES[executable] output = f'{executable}' if not paths: path = os.environ['PATH'] paths = tuple([str(Path(sys.exec_prefix, 'Scripts').absolute())] + path.split(os.pathsep)) executable_path = Path(executable).absolute() if not executable_path.is_file(): for path_ in paths: executable_path = Path(path_, executable).absolute() if executable_path.is_file(): break else: _LOGGER.error('%s -> not found', output) return None _KNOWN_EXECUTABLES[executable] = executable_path _LOGGER.info('%s -> %s', output, str(executable_path)) return executable_path","Based on: https://gist.github.com/4368898 Public domain code by anatoly techtonik Programmatic equivalent to Linux `which` and Windows `where` Find if ´executable´ can be run. Looks for it in 'path' (string that lists directories separated by 'os.pathsep'; defaults to os.environ['PATH']). Checks for all executable extensions. Returns full path or None if no command is found. Args: executable: executable name to look for paths: root paths to examine (defaults to system PATH) Returns: executable path as string or None" 443,how to make the checkbox checked,"def check_checkbox(step, value): with AssertContextManager(step): check_box = find_field(world.browser, 'checkbox', value) if not check_box.is_selected(): check_box.click()", 444,how to get database table name," def get_table(self, table_name, db='default'): if db == 'default' and '.' in table_name: db, table_name = table_name.split('.')[:2] with self.metastore as client: return client.get_table(dbname=db, tbl_name=table_name)","Get a metastore table object >>> hh = HiveMetastoreHook() >>> t = hh.get_table(db='airflow', table_name='static_babynames') >>> t.tableName 'static_babynames' >>> [col.name for col in t.sd.cols] ['state', 'year', 'name', 'gender', 'num']" 445,filter array," def params(self): if not any(filter.params for filter in self): return None else: return Array(filter.params or Null() for filter in self)", 446,encrypt aes ctr mode," def aes_ctr_encrypt(plain_text: bytes, key: bytes): cipher = AES.new(key=key, mode=AES.MODE_CTR) cipher_text = cipher.encrypt(plain_text) nonce = cipher.nonce return nonce, cipher_text", 447,create cookie," def _set_cookie(self, name, value): cookie_domain = self._config.cookie_domain cookie_path = self._config.cookie_path cookie_expires = self._config.cookie_expires if self._config.secure: return self.handler.set_secure_cookie( name, value, expires_days=cookie_expires / (3600 * 24), domain=cookie_domain, path=cookie_path) else: return self.handler.set_cookie(name, value, expires=cookie_expires, domain=cookie_domain, path=cookie_path)", 448,confusion matrix," def confusion_matrix(self): confusion_matrix = self.pixel_classification_sum.astype(np.float) confusion_matrix = np.divide(confusion_matrix.T, self.pixel_truth_sum.T).T return confusion_matrix * 100.0",Returns the normalised confusion matrix 449,string to date,"def parse_date(date_str): if date_str: date = datetime.strptime(date_str, '%Y%m%d') return date.year, date.month - 1, date.day return '', '', ''", 450,print model summary,"def _print_summary(module, case, summary): try: try: module.print_summary(summary[case]) except TypeError: module.print_summary(case, summary[case]) except (NotImplementedError, AttributeError): print("" Ran "" + case + ""!"") print("""")", 451,memoize to disk - persistent memoization," def _run_node(self, node): res = None if ('memoize' in self.afferents and self.afferents['memoize']) and node.memoize: memdat = self.plan._memoized_data try: h = qhash({k:self.afferents[k] for k in self.plan.afferent_dependencies[node.name]}) ho = (node.name, h) if ho in memdat: res = memdat[ho] h = None ho = None else: cpath = self.afferents['cache_directory'] \ if node.cache and 'cache_directory' in self.afferents else \ None if cpath is not None: ureg = self.afferents['unit_registry'] \ if 'unit_registry' in self.afferents else \ 'pimms' cpath = os.path.join(cpath, node.name, ('0' + str(-h)) if h < 0 else str(h)) try: res = self._uncache(cpath, node, ureg) cpath = None except: pass except: h = None ho = None res = None else: h = None ho = None if res is None: res = node(self) effs = reduce(lambda m,v: m.set(v[0],v[1]), six.iteritems(res), self.efferents) object.__setattr__(self, 'efferents', effs) if h is not None: memdat[ho] = res if cpath is not None: try: self._cache(cpath, res) except: pass","calc_dict._run_node(node) calculates the results of the given calculation node in the calc_dict's calculation plan and caches the results in the calc_dict. This should only be called by calc_dict itself internally. print IMap.indent, ('Node: %s' % node.name) #dbg IMap.indent = ' ' + IMap.indent #dbg We need to pause here and handle caching, if needed. memoization success; no need to memoize the result after processing it print(IMap.indent, 'retrieved') #dbg print(IMap.indent, 'loaded cache') #dbg memoization failure, must run the node normally (don't memoize/cache) ensure we have a result process the result: Handle the caching if needed: if cpath is None: print IMap.indent, 'hashed' #dbg print IMap.indent, 'saved cache' #dbg" 452,pretty print json,"def pprint_json(json_raw): print(json.dumps(json.loads(json_raw), indent=2, sort_keys=True))", 453,format date,"def format_date_for_input(date): date_fmt = get_locale().date_formats[""short""].pattern date_fmt = date_fmt.replace(""MMMM"", ""MM"").replace(""MMM"", ""MM"") return format_date(date, date_fmt)",force numerical months 454,convert int to bool," def to_bool(self, value): if value == None: return False elif isinstance(value, bool): return value else: if str(value).lower() in [""true"", ""1"", ""yes""]: return True else: return False", 455,binomial distribution,"def binomial(n,k): if n==k: return 1 assert n>k, ""Attempting to call binomial(%d,%d)"" % (n,k) return factorial(n)//(factorial(k)*factorial(n-k))","Binomial coefficient >>> binomial(5,2) 10 >>> binomial(10,5) 252" 456,encode url," def encode(self): opt_dict = {} for k, v in self.options.items(): opt_dict[k] = v[0] ss = '{0}://{1}'.format(self.scheme, ','.join(self.hosts)) if self.bucket: ss += '/' + self.bucket ss += '?' + urlencode(opt_dict).replace('%2F', '/') return ss","Encodes the current state of the object into a string. :return: The encoded string URL encode options then decoded forward slash /" 457,get current ip address," def get_ip(self): if self._ip is None: self._ip = self.fetch_ip() return self._ip", 458,socket recv timeout,"def recv_response(socket, acceptable_length, timeout): if socket.poll(""recv"", timeout): snep_response = socket.recv() if len(snep_response) < 6: log.debug(""snep response initial fragment too short"") return None version, status, length = struct.unpack("">BBL"", snep_response[:6]) if length > acceptable_length: log.debug(""snep response exceeds acceptable length"") return None if len(snep_response) - 6 < length: socket.send(b""\x10\x00\x00\x00\x00\x00"") while len(snep_response) - 6 < length: if socket.poll(""recv"", timeout): snep_response += socket.recv() else: return None return bytearray(snep_response)",request remaining fragments 459,convert a utc time to epoch," def _dt_to_epoch(self, dt): if PY2: time_delta = dt - datetime(1970, 1, 1).replace(tzinfo=dt.tzinfo) return int(time_delta.total_seconds()) else: return int(dt.timestamp())","Convert a offset-aware datetime to POSIX time. The input datetime is from botocore unmarshalling and it is offset-aware so the timedelta of subtracting this time to 01/01/1970 using the same tzinfo gives us Unix Time (also known as POSIX Time). Added in python 3.3+ and directly returns POSIX time." 460,html entities replace,"def htmlentityreplace_errors(ex): if isinstance(ex, UnicodeEncodeError): bad_text = ex.object[ex.start:ex.end] text = _html_entities_escaper.escape(bad_text) return (compat.text_type(text), ex.end) raise ex","An encoding error handler. This python `codecs`_ error handler replaces unencodable characters with HTML entities, or, if no HTML entity exists for the character, XML character references. >>> u'The cost was \u20ac12.'.encode('latin1', 'htmlentityreplace') 'The cost was €12.' Handle encoding errors" 461,parse binary file to custom class,"def _from_binary_reparse(cls, binary_stream): reparse_tag, data_len = cls._REPR.unpack(binary_stream[:cls._REPR.size]) reparse_type = ReparseType(reparse_tag & 0x0000FFFF) reparse_flags = ReparseFlags((reparse_tag & 0xF0000000) >> 28) guid = None if reparse_flags & ReparseFlags.IS_MICROSOFT: if reparse_type is ReparseType.SYMLINK: data = SymbolicLink.create_from_binary(binary_stream[cls._REPR.size:]) elif reparse_type is ReparseType.MOUNT_POINT: data = JunctionOrMount.create_from_binary(binary_stream[cls._REPR.size:]) else: data = binary_stream[cls._REPR.size:].tobytes() else: guid = UUID(bytes_le=binary_stream[cls._REPR.size:cls._REPR.size+16].tobytes()) data = binary_stream[cls._REPR.size+16:].tobytes() nw_obj = cls((reparse_type, reparse_flags, data_len, guid, data)) _MOD_LOGGER.debug(""Attempted to unpack REPARSE_POINT from \""%s\""\nResult: %s"", binary_stream.tobytes(), nw_obj) return nw_obj","See base class. Reparse type flags - 4 Reparse tag - 4 bits Reserved - 12 bits Reparse type - 2 bits Reparse data length - 2 Padding - 2 content = cls._REPR.unpack(binary_view[:cls._REPR.size]) reparse_tag (type, flags) data_len, guid, data guid exists only in third party reparse points a microsoft tag" 462,binomial distribution,"def binomial(n,k): if n==k: return 1 assert n>k, ""Attempting to call binomial(%d,%d)"" % (n,k) return factorial(n)//(factorial(k)*factorial(n-k))","Binomial coefficient >>> binomial(5,2) 10 >>> binomial(10,5) 252" 463,deserialize json,"def deserialize(s): if isinstance(s, bytes): return json.loads(s.decode('utf-8')) return json.loads(s)", 464,parse command line argument,"def parse_cmdln_args(): parser = argparse.ArgumentParser(description='Process command line args') parser.add_argument('--log', help='log help', default='INFO') parser.add_argument( '--tc', help='tc help') parser.add_argument( '--ts', help='ts help') args = parser.parse_args() return (args.log.upper(), args.tc, args.ts)", 465,how to get html of website," def update_website(self, website): self.connect() website = self.server.update_website( self.session_id, website['name'], website['ip'], website['https'], website['subdomains'], website['certificate'], *website['website_apps'] ) return website", 466,copy to clipboard," def create_clipboard(self, text, selection=Gdk.SELECTION_CLIPBOARD): clipboard = Gtk.Clipboard.get(selection) clipboard.set_text('\n'.join(text), -1) clipboard.store() return clipboard",Function creates a clipboard 467,get inner html," def innerHTML(self, html: str) -> None: df = self._parse_html(html) if self.connected: self._set_inner_html_web(df.html) self._empty() self._append_child(df)","type: ignore Set innerHTML both on this node and related browser node." 468,copying a file to a path," def copy_file(self, from_path, to_path): if not op.exists(op.dirname(to_path)): self.make_directory(op.dirname(to_path)) shutil.copy(from_path, to_path) logging.debug('File copied: {0}'.format(to_path))",Copy file. 469,get current process id," def process_id(self): ret = """" if thread: f = getattr(os, 'getpid', None) if f: ret = str(f()) return ret", 470,string to date,"def datestr2date(date_str): if any(c not in '0123456789-/' for c in date_str): raise ValueError('Illegal character in date string') if '/' in date_str: try: m, d, y = date_str.split('/') except: raise ValueError('Date {} must have no or exactly 2 slashes. {}'. format(date_str, VALID_DATE_FORMATS_TEXT)) elif '-' in date_str: try: d, m, y = date_str.split('-') except: raise ValueError('Date {} must have no or exactly 2 dashes. {}'. format(date_str, VALID_DATE_FORMATS_TEXT)) elif len(date_str) == 8 or len(date_str) == 6: d = date_str[-2:] m = date_str[-4:-2] y = date_str[:-4] else: raise ValueError('Date format not recognised. {}'.format( VALID_DATE_FORMATS_TEXT)) if len(y) == 2: year = 2000 + int(y) elif len(y) == 4: year = int(y) else: raise ValueError('year must be 2 or 4 digits') for s in (m, d): if 1 <= len(s) <= 2: month, day = int(m), int(d) else: raise ValueError('m and d must be 1 or 2 digits') try: return datetime.date(year, month, day) except ValueError: raise ValueError('Invalid date {}. {}'.format(date_str, VALID_DATE_FORMATS_TEXT))","Turns a string into a datetime.date object. This will only work if the format can be ""guessed"", so the string must have one of the formats from VALID_DATE_FORMATS_TEXT. Args: date_str (str) a string that represents a date Returns: datetime.date object Raises: ValueError if the input string does not have a valid format." 471,connect to sql," def _connect(self, engine: str = None, interface: str = None, host: str = None, port: int = None, database: str = None, driver: str = None, dsn: str = None, odbc_connection_string: str = None, user: str = None, password: str = None, autocommit: bool = True, charset: str = ""utf8"", use_unicode: bool = True) -> bool: if engine == ENGINE_MYSQL: self.flavour = MySQL() self.schema = database elif engine == ENGINE_SQLSERVER: self.flavour = SQLServer() if database: self.schema = database else: self.schema = ""dbo"" elif engine == ENGINE_ACCESS: self.flavour = Access() self.schema = ""dbo"" else: raise ValueError(""Unknown engine"") if interface is None: if engine == ENGINE_MYSQL: interface = INTERFACE_MYSQL else: interface = INTERFACE_ODBC if port is None: if engine == ENGINE_MYSQL: port = 3306 elif engine == ENGINE_SQLSERVER: port = 1433 if driver is None: if engine == ENGINE_MYSQL and interface == INTERFACE_ODBC: driver = ""{MySQL ODBC 5.1 Driver}"" self._engine = engine self._interface = interface self._server = host self._port = port self._database = database self._user = user self._password = password self._charset = charset self._use_unicode = use_unicode self.autocommit = autocommit log.info( ""Opening database: engine={e}, interface={i}, "" ""use_unicode={u}, autocommit={a}"".format( e=engine, i=interface, u=use_unicode, a=autocommit)) if interface == INTERFACE_MYSQL: if pymysql: self.db_pythonlib = PYTHONLIB_PYMYSQL elif MySQLdb: self.db_pythonlib = PYTHONLIB_MYSQLDB else: raise ImportError(_MSG_MYSQL_DRIVERS_UNAVAILABLE) elif interface == INTERFACE_ODBC: if not pyodbc: raise ImportError(_MSG_PYODBC_UNAVAILABLE) self.db_pythonlib = PYTHONLIB_PYODBC elif interface == INTERFACE_JDBC: if not jaydebeapi: raise ImportError(_MSG_JDBC_UNAVAILABLE) if host is None: raise ValueError(""Missing host parameter"") if port is None: raise ValueError(""Missing port parameter"") if user is None: raise ValueError(""Missing user parameter"") self.db_pythonlib = PYTHONLIB_JAYDEBEAPI else: raise ValueError(""Unknown interface"") if engine == ENGINE_MYSQL and interface == INTERFACE_MYSQL: datetimetype = datetime.datetime converters = mysql.converters.conversions.copy() converters[datetimetype] = datetime2literal_rnc log.info( ""{i} connect: host={h}, port={p}, user={u}, "" ""database={d}"".format( i=interface, h=host, p=port, u=user, d=database)) self.db = mysql.connect( host=host, port=port, user=user, passwd=password, db=database, charset=charset, use_unicode=use_unicode, conv=converters ) self.db.autocommit(autocommit) elif engine == ENGINE_MYSQL and interface == INTERFACE_ODBC: log.info( ""ODBC connect: DRIVER={dr};SERVER={s};PORT={p};"" ""DATABASE={db};USER={u};PASSWORD=[censored]"".format( dr=driver, s=host, p=port, db=database, u=user)) dsn = ( ""DRIVER={0};SERVER={1};PORT={2};DATABASE={3};"" ""USER={4};PASSWORD={5}"".format(driver, host, port, database, user, password) ) self.db = pyodbc.connect(dsn) self.db.autocommit = autocommit elif engine == ENGINE_MYSQL and interface == INTERFACE_JDBC: jclassname = ""com.mysql.jdbc.Driver"" url = ""jdbc:mysql://{host}:{port}/{database}"".format( host=host, port=port, database=database) driver_args = [url, user, password] jars = None libs = None log.info( ""JDBC connect: jclassname={jclassname}, "" ""url={url}, user={user}, password=[censored]"".format( jclassname=jclassname, url=url, user=user, ) ) self._jdbc_connect(jclassname, driver_args, jars, libs, autocommit) elif engine == ENGINE_SQLSERVER and interface == INTERFACE_ODBC: if odbc_connection_string: log.info(""Using raw ODBC connection string [censored]"") connectstring = odbc_connection_string elif dsn: log.info( ""ODBC connect: DSN={dsn};UID={u};PWD=[censored]"".format( dsn=dsn, u=user)) connectstring = ""DSN={};UID={};PWD={}"".format(dsn, user, password) else: log.info( ""ODBC connect: DRIVER={dr};SERVER={s};DATABASE={db};"" ""UID={u};PWD=[censored]"".format( dr=driver, s=host, db=database, u=user)) connectstring = ( ""DRIVER={};SERVER={};DATABASE={};UID={};PWD={}"".format( driver, host, database, user, password) ) self.db = pyodbc.connect(connectstring, unicode_results=True) self.db.autocommit = autocommit elif engine == ENGINE_SQLSERVER and interface == INTERFACE_JDBC: jclassname = 'com.microsoft.sqlserver.jdbc.SQLServerDriver' urlstem = 'jdbc:sqlserver://{host}:{port};'.format( host=host, port=port ) nvp = {} if database: nvp['databaseName'] = database nvp['user'] = user nvp['password'] = password nvp['responseBuffering'] = 'adaptive' nvp['selectMethod'] = 'cursor' url = urlstem + ';'.join( '{}={}'.format(x, y) for x, y in nvp.items()) nvp['password'] = '[censored]' url_censored = urlstem + ';'.join( '{}={}'.format(x, y) for x, y in nvp.items()) log.info( 'jdbc connect: jclassname={jclassname}, url = {url}'.format( jclassname=jclassname, url=url_censored ) ) driver_args = [url] jars = None libs = None self._jdbc_connect(jclassname, driver_args, jars, libs, autocommit) elif engine == ENGINE_ACCESS and interface == INTERFACE_ODBC: dsn = ""DSN={}"".format(dsn) log.info(""ODBC connect: DSN={}"", dsn) self.db = pyodbc.connect(dsn) self.db.autocommit = autocommit else: raise ValueError( ""Unknown 'engine'/'interface' combination: {}/{}"".format( engine, interface ) ) return True","Check engine default for SQL server default for SQL server Default interface Default port Default driver Report intent Interface if database is None: raise ValueError(""Missing database parameter"") --------------------------------------------------------------------- Connect --------------------------------------------------------------------- Connects to a MySQL database via MySQLdb/PyMySQL. http://dev.mysql.com/doc/refman/5.1/en/connector-odbc-configuration-connection-parameters.html # noqa http://code.google.com/p/pyodbc/wiki/ConnectionStrings Between MySQLdb 1.2.3 and 1.2.5, the DateTime2literal function stops producing e.g. '2014-01-03 18:15:51' and starts producing e.g. '2014-01-03 18:15:51.842097+00:00'. Let's fix that... as per MySQLdb times.py See also: http://stackoverflow.com/questions/11053941 noinspection PyCallingNonCallable http://mysql-python.sourceforge.net/MySQLdb.html http://dev.mysql.com/doc/refman/5.0/en/mysql-autocommit.html https://github.com/PyMySQL/PyMySQL/blob/master/pymysql/connections.py # noqa MySQL character sets and collations: http://dev.mysql.com/doc/refman/5.1/en/charset.html Create a database using UTF8: ... CREATE DATABASE mydb DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci; What is my database using? ... SHOW VARIABLES LIKE 'character_set_%'; Change a database character set: ... ALTER DATABASE mydatabasename charset=utf8; http://docs.moodle.org/23/en/ Converting_your_MySQL_database_to_UTF8 Python talking to MySQL in Unicode: http://www.harelmalka.com/?p=81 http://stackoverflow.com/questions/6001104 http://stackoverflow.com/questions/1063770 https://help.ubuntu.com/community/JDBCAndMySQL https://github.com/baztian/jaydebeapi/issues/1 SQL Server: http://code.google.com/p/pyodbc/wiki/ConnectionStrings http://stackoverflow.com/questions/1063770 jar tvf sqljdbc41.jar https://msdn.microsoft.com/en-us/sqlserver/aa937724.aspx https://msdn.microsoft.com/en-us/library/ms378428(v=sql.110).aspx https://msdn.microsoft.com/en-us/library/ms378988(v=sql.110).aspx default is 'full' ... THIS CHANGE (responseBuffering = adaptive) stops the JDBC driver crashing on cursor close [in a socket recv() call] when it's fetched a VARBINARY(MAX) field. trying this; default is 'direct' http://stackoverflow.com/questions/1063770" 472,output to html file,"def to_html(doc, output=""/tmp"", style=""dep""): file_name = ""-"".join([w.text for w in doc[:6] if not w.is_punct]) + "".html"" html = displacy.render(doc, style=style, page=True) if output is not None: output_path = Path(output) if not output_path.exists(): output_path.mkdir() output_file = Path(output) / file_name output_file.open(""w"", encoding=""utf-8"").write(html) print(""Saved HTML to {}"".format(output_file)) else: print(html)","Doc method extension for saving the current state as a displaCy visualization. generate filename from first six non-punct tokens render markup save to file" 473,parse command line argument,"def parse_command_line_arguments(): parser = argparse.ArgumentParser( description='Rotates the cell lattice in VASP POSCAR files' ) parser.add_argument( 'poscar', help=""filename of the VASP POSCAR to be processed"" ) parser.add_argument( '-a', '--axis', nargs=3, type=float, help=""vector for rotation axis"", required=True ) parser.add_argument( '-d', '--degrees', type=int, help=""rotation angle in degrees"", required=True ) args = parser.parse_args() return( args )", 474,set working directory," def __set_workdir(self): fname = self.get_current_filename() if fname is not None: directory = osp.dirname(osp.abspath(fname)) self.open_dir.emit(directory) ",Set current script directory as working directory 475,create cookie," def __call__(self, req, res): if hasattr(req, 'cookies'): return req.cookies, res.cookies = SimpleCookie(), SimpleCookie() log.info(""{:d} built with {}"", id(self), json.dumps(self.opts)) req.cookies.load(req.headers.get('COOKIE', '')) def _gen_cookie(): if res.cookies: cookie_string = res.cookies.output(header='', sep=res.EOL) return cookie_string res.headers['Set-Cookie'] = _gen_cookie","Parses cookies of the header request (using the 'cookie' header key) and adds a callback to the 'on_headerstrings' response event. Do not clobber cookies Create an empty cookie state If the request had a cookie, load it!" 476,get the description of a http status code," def get(cls): if Check().is_url_valid() or PyFunceble.CONFIGURATION[""local""]: if ""current_test_data"" in PyFunceble.INTERN: PyFunceble.INTERN[""current_test_data""][""url_syntax_validation""] = True PyFunceble.INTERN.update({""http_code"": HTTPCode().get()}) active_list = [] active_list.extend(PyFunceble.HTTP_CODE[""list""][""potentially_up""]) active_list.extend(PyFunceble.HTTP_CODE[""list""][""up""]) inactive_list = [] inactive_list.extend(PyFunceble.HTTP_CODE[""list""][""potentially_down""]) inactive_list.append(""*"" * 3) if PyFunceble.INTERN[""http_code""] in active_list: return URLStatus(PyFunceble.STATUS[""official""][""up""]).handle() if PyFunceble.INTERN[""http_code""] in inactive_list: return URLStatus(PyFunceble.STATUS[""official""][""down""]).handle() if ""current_test_data"" in PyFunceble.INTERN: PyFunceble.INTERN[""current_test_data""][""url_syntax_validation""] = False return URLStatus(PyFunceble.STATUS[""official""][""invalid""]).handle()","pragma: no cover Execute the logic behind the URL handling. :return: The status of the URL. :rtype: str * The url is valid. or * We are testing in/for a local or private network. We initiate the HTTP status code. We initiate the list of active status code. We initiate the list of inactive status code. The extracted HTTP status code is in the list of active list. We handle and return the up status. The extracted HTTP status code is in the list of inactive list. We handle and return the down status. The extracted HTTP status code is not in the list of active nor invalid list. The end-user want more information whith his test. We update the url_syntax_validation index. We handle and return the invalid down status." 477,encode url," def encode(self): opt_dict = {} for k, v in self.options.items(): opt_dict[k] = v[0] ss = '{0}://{1}'.format(self.scheme, ','.join(self.hosts)) if self.bucket: ss += '/' + self.bucket ss += '?' + urlencode(opt_dict).replace('%2F', '/') return ss","Encodes the current state of the object into a string. :return: The encoded string URL encode options then decoded forward slash /" 478,positions of substrings in string,"def findAllSubstrings(string, substring): start = 0 positions = [] while True: start = string.find(substring, start) if start == -1: break positions.append(start) start += 1 return positions","Returns a list of all substring starting positions in string or an empty list if substring is not present in string. :param string: a template string :param substring: a string, which is looked for in the ``string`` parameter. :returns: a list of substring starting positions in the template string TODO: solve with regex? what about '.': return [m.start() for m in re.finditer('(?='+substring+')', string)] +1 instead of +len(substring) to also find overlapping matches" 479,scatter plot,"def scatter(x, y, z, color=(1, 0, 0), s=0.01): global _last_figure fig = _last_figure if fig is None: fig = volshow(None) fig.scatter = Scatter(x=x, y=y, z=z, color=color, size=s) fig.volume.scatter = fig.scatter return fig", 480,output to html file,"def to_html(doc, output=""/tmp"", style=""dep""): file_name = ""-"".join([w.text for w in doc[:6] if not w.is_punct]) + "".html"" html = displacy.render(doc, style=style, page=True) if output is not None: output_path = Path(output) if not output_path.exists(): output_path.mkdir() output_file = Path(output) / file_name output_file.open(""w"", encoding=""utf-8"").write(html) print(""Saved HTML to {}"".format(output_file)) else: print(html)","Doc method extension for saving the current state as a displaCy visualization. generate filename from first six non-punct tokens render markup save to file" 481,string similarity levenshtein,"def levenshtein_dist(s1: str, s2: str) -> int: if len(s1) < len(s2): return levenshtein_dist(s2, s1) if len(s2) == 0: return len(s1) previous_row = range(len(s2) + 1) for i, c1 in enumerate(s1): current_row = [i + 1] for j, c2 in enumerate(s2): insertions = previous_row[j + 1] + 1 deletions = current_row[j] + 1 substitutions = previous_row[j] + (c1 != c2) current_row.append(min(insertions, deletions, substitutions)) previous_row = current_row return previous_row[-1]","len(s1) >= len(s2) j+1 instead of j since previous_row and current_row are one character longer than s2" 482,print model summary,"def summary(model, input_size): def register_hook(module): def hook(module, input, output): class_name = str(module.__class__).split('.')[-1].split(""'"")[0] module_idx = len(summary) m_key = '%s-%i' % (class_name, module_idx + 1) summary[m_key] = OrderedDict() summary[m_key]['input_shape'] = list(input[0].size()) summary[m_key]['input_shape'][0] = -1 if isinstance(output, (list, tuple)): summary[m_key]['output_shape'] = [[-1] + list(o.size())[1:] for o in output] else: summary[m_key]['output_shape'] = list(output.size()) summary[m_key]['output_shape'][0] = -1 params = 0 if hasattr(module, 'weight') and hasattr(module.weight, 'size'): params += torch.prod(torch.LongTensor(list(module.weight.size()))) summary[m_key]['trainable'] = module.weight.requires_grad if hasattr(module, 'bias') and hasattr(module.bias, 'size'): params += torch.prod(torch.LongTensor(list(module.bias.size()))) summary[m_key]['nb_params'] = params if (not isinstance(module, nn.Sequential) and not isinstance(module, nn.ModuleList) and not (module == model)): hooks.append(module.register_forward_hook(hook)) if torch.cuda.is_available(): dtype = torch.cuda.FloatTensor model = model.cuda() else: dtype = torch.FloatTensor model = model.cpu() if isinstance(input_size[0], (list, tuple)): x = [Variable(torch.rand(2, *in_size)).type(dtype) for in_size in input_size] else: x = Variable(torch.rand(2, *input_size)).type(dtype) summary = OrderedDict() hooks = [] model.apply(register_hook) model(x) for h in hooks: h.remove() print('----------------------------------------------------------------') line_new = '{:>20} {:>25} {:>15}'.format('Layer (type)', 'Output Shape', 'Param print(line_new) print('================================================================') total_params = 0 trainable_params = 0 for layer in summary: line_new = '{:>20} {:>25} {:>15}'.format(layer, str(summary[layer]['output_shape']), '{0:,}'.format(summary[layer]['nb_params'])) total_params += summary[layer]['nb_params'] if 'trainable' in summary[layer]: if summary[layer]['trainable'] == True: trainable_params += summary[layer]['nb_params'] print(line_new) print('================================================================') print('Total params: {0:,}'.format(total_params)) print('Trainable params: {0:,}'.format(trainable_params)) print('Non-trainable params: {0:,}'.format(total_params - trainable_params)) print('----------------------------------------------------------------')","Print summary of the model check if there are multiple inputs to the network print(type(x[0])) create properties register hook make a forward pass print(x.shape) remove these hooks ') input_shape, output_shape, trainable, nb_params" 483,how to get database table name," def get_tables(self, database_name): database = self.get_database(database_name) return [table for table_name, table in database.tables.items()]", 484,sorting multiple arrays based on another arrays sorted order," def sort(self, sort_list): order = [] for sort in sort_list: if sort_list[sort] == ""asc"": order.append(asc(getattr(self.model, sort, None))) elif sort_list[sort] == ""desc"": order.append(desc(getattr(self.model, sort, None))) return order",Sort 485,how to empty array," def empty(self): return self.awkward.numpy.empty((0, self.numbytes), dtype=self.todtype)", 486,connect to sql," def connect(self): future = super(RecordQueryConnection, self).connect() origin_query = self._connection.query def query(sql, unbuffered=False): self._last_query_sql = sql return origin_query(sql, unbuffered) self._connection.query = query return future", 487,k means clustering,"def cluster_mini_batch_kmeans(data=None, k=100, max_iter=10, batch_size=0.2, metric='euclidean', init_strategy='kmeans++', n_jobs=None, chunksize=None, skip=0, clustercenters=None, **kwargs): r from pyemma.coordinates.clustering.kmeans import MiniBatchKmeansClustering res = MiniBatchKmeansClustering(n_clusters=k, max_iter=max_iter, metric=metric, init_strategy=init_strategy, batch_size=batch_size, n_jobs=n_jobs, skip=skip, clustercenters=clustercenters) from pyemma.util.reflection import get_default_args cs = _check_old_chunksize_arg(chunksize, get_default_args(cluster_mini_batch_kmeans)['chunksize'], **kwargs) if data is not None: res.estimate(data, chunksize=cs) else: res.chunksize = chunksize return res","k-means clustering with mini-batch strategy Mini-batch k-means is an approximation to k-means which picks a randomly selected subset of data points to be updated in each iteration. Usually much faster than k-means but will likely deliver a less optimal result. Returns ------- kmeans_mini : a :class:`MiniBatchKmeansClustering ` clustering object Object for mini-batch kmeans clustering. It holds discrete trajectories and cluster center information. See also -------- :func:`kmeans ` : for full k-means clustering .. autoclass:: pyemma.coordinates.clustering.kmeans.MiniBatchKmeansClustering :members: :undoc-members: .. rubric:: Methods .. autoautosummary:: pyemma.coordinates.clustering.kmeans.MiniBatchKmeansClustering :methods: .. rubric:: Attributes .. autoautosummary:: pyemma.coordinates.clustering.kmeans.MiniBatchKmeansClustering :attributes: References ---------- .. [1] http://www.eecs.tufts.edu/~dsculley/papers/fastkmeans.pdf" 488,httpclient post json,"def post_json(session, url, json): res = session.post(url, json=json) if res.status_code >= 400: raise parse_error(res) return res",Post JSON to the Forest endpoint. 489,convert string to number,"def convert_string_to_number(value): if value is None: return 1 if isinstance(value, int): return value if value.isdigit(): return int(value) num_list = map(lambda s: NUMBERS[s], re.findall(numbers + '+', value.lower())) return sum(num_list)",Convert strings to numbers 490,parse command line argument,"def parse_command_line_arguments(): parser = argparse.ArgumentParser() parser.add_argument( 'xdatcar' ) args = parser.parse_args() return( args )",command line arguments 491,finding time elapsed using a timer,"def timer(description='Operation', log=None): start = time() yield elapsed = time() - start message = '%s took %s seconds' % (description, elapsed) (print if log is None else log.info)(message)","Simple context manager which logs (if log is provided) or prints the time taken in seconds for the block to complete. >>> with timer(): ... sleep(0.1) # doctest:+ELLIPSIS Operation took 0.1... seconds >>> with timer('Sleeping'): ... sleep(0.2) # doctest:+ELLIPSIS Sleeping took 0.2... seconds >>> with timer(description='Doing', log=PrintingLogger()): ... sleep(0.3) # doctest:+ELLIPSIS Doing took 0.3... seconds" 492,pretty print json,"def ppjson(dumpit: Any, elide_to: int = None) -> str: if elide_to is not None: elide_to = max(elide_to, 3) try: rv = json.dumps(json.loads(dumpit) if isinstance(dumpit, str) else dumpit, indent=4) except TypeError: rv = '{}'.format(pformat(dumpit, indent=4, width=120)) return rv if elide_to is None or len(rv) <= elide_to else '{}...'.format(rv[0 : elide_to - 3])","JSON pretty printer, whether already json-encoded or not :param dumpit: object to pretty-print :param elide_to: optional maximum length including ellipses ('...') :return: json pretty-print make room for ellipses '...'" 493,json to xml conversion," def convert(self, content, conversion): if not conversion: data = content elif self.format == 'json': data = json.loads(content) elif self.format == 'xml': content = xml(content) first = list(content.keys())[0] data = content[first] else: data = content return data",Convert content to Python data structures. 494,output to html file," def _tmp_html_file( self, content): self.log.debug('starting the ``_tmp_html_file`` method') content = % locals() now = datetime.now() now = now.strftime(""%Y%m%dt%H%M%S%f"") pathToWriteFile = ""/tmp/%(now)s.html"" % locals() try: self.log.debug(""attempting to open the file %s"" % (pathToWriteFile,)) writeFile = codecs.open( pathToWriteFile, encoding='utf-8', mode='w') except IOError, e: message = 'could not open the file %s' % (pathToWriteFile,) self.log.critical(message) raise IOError(message) writeFile.write(content) writeFile.close() self.log.debug('completed the ``_tmp_html_file`` method') return pathToWriteFile","*create a tmp html file with some content used for the header or footer of the ebook* **Key Arguments:** - ``content`` -- the content to include in the HTML file.
%(content)s

" 495,deserialize json," def deserialize_json(cls, serialized_json): serialized = json.loads(serialized_json) return Macaroon.from_dict(serialized)","Return a macaroon deserialized from a string @param serialized_json The string to decode {str} @return {Macaroon}" 496,create cookie," def setcookie(self, key, value, max_age=None, expires=None, path='/', domain=None, secure=None, httponly=False): newcookie = Morsel() newcookie.key = key newcookie.value = value newcookie.coded_value = value if max_age is not None: newcookie['max-age'] = max_age if expires is not None: newcookie['expires'] = expires if path is not None: newcookie['path'] = path if domain is not None: newcookie['domain'] = domain if secure: newcookie['secure'] = secure if httponly: newcookie['httponly'] = httponly self.sent_cookies = [c for c in self.sent_cookies if c.key != key] self.sent_cookies.append(newcookie)",Add a new cookie 497,encode url," def urlEncode(self, url, path, params=[]): return url + path + '?' + urllib.parse.urlencode(params)", 498,reading element from html - ,"def html_row_with_ordered_headers(data, headers): html = '\n\t' for header in headers: element = data[header] if isinstance(element, list): element = html_list(element) if is_email(element): element = html_email(element) html += '{}'.format(element) return html + ''",">>> headers = ['administrators', 'key', 'leader', 'project'] >>> data = {'key': 'DEMO', 'project': 'Demonstration', 'leader': 'leader@example.com', 'administrators': ['admin1@example.com', 'admin2@example.com']} >>> html_row_with_ordered_headers(data, headers) '\\n\\tDEMOleader@example.comDemonstration' >>> headers = ['key', 'project', 'leader', 'administrators'] >>> html_row_with_ordered_headers(data, headers) '\\n\\tDEMODemonstrationleader@example.com'" 499,write csv,"def write_csv_header(mol, csv_writer): line = [] line.append('id') line.append('status') queryList = mol.properties.keys() for queryLabel in queryList: line.append(queryLabel) csv_writer.writerow(line)","Write the csv header create line list where line elements for writing will be stored ID status query labels write line" 500,string to date," def datetime(self): date_string = '%s %s' % (self._date, self._year) date_string = re.sub(r' \(\d+\)', '', date_string) return datetime.strptime(date_string, '%A, %b %d %Y')","Returns a datetime object of the month, day, year, and time the game was played." 501,sort string list," def _sort(self, items, sort, language='en', reverse=False): if sort is None: sort = 'id' if sort == 'sortlabel': sort='label' items.sort(key=lambda item: item[sort], reverse=reverse) return items", 502,convert html to pdf," def pdf_from_post(self): html = self.request.form.get(""html"") style = self.request.form.get(""style"") reporthtml = ""{0}{1}"" reporthtml = reporthtml.format(style, html) reporthtml = safe_unicode(reporthtml).encode(""utf-8"") pdf_fn = tempfile.mktemp(suffix="".pdf"") pdf_file = createPdf(htmlreport=reporthtml, outfile=pdf_fn) return pdf_file",Returns a pdf stream with the stickers 503,all permutations of a list,"def permutations(x): if len(x) > 1: for permutation in permutations(x[1:]): for i in xrange(len(permutation)+1): yield permutation[:i] + x[0:1] + permutation[i:] else: yield x",Stick the first digit in every position. 504,confusion matrix,"Error: 404 {""message"": ""Not Found"", ""documentation_url"": ""https://docs.github.com/rest/repos/repos","get-a-repository"", ""status"": ""404""}" 505,get executable path,"def getPathOfExecutable(executable): exe_paths = os.environ['PATH'].split(':') for exe_path in exe_paths: exe_file = os.path.join(exe_path, executable) if os.path.isfile(exe_file) and os.access(exe_file, os.X_OK): return exe_file return None","Returns the full path of the executable, or None if the executable can not be found." 506,format date,"def format_date(date, timestamp_format): try: date = DATE_ADD.format(int(date)) except ValueError: date = timestamp_format.format(date) return date", 507,unzipping large files,"def unzip(zip_content, dest_dir): with zipfile.ZipFile(zip_content, ""r"") as zf: for member in zf.infolist(): words = member.filename.split('/') path = dest_dir for word in words[:-1]: drive, word = os.path.splitdrive(word) head, word = os.path.split(word) if word in (os.curdir, os.pardir, ''): continue path = os.path.join(path, word) zf.extract(member, path)","From http://stackoverflow.com/a/12886818 Path traversal defense copied from http://hg.python.org/cpython/file/tip/Lib/http/server.py#l789" 508,get all parents of xml node," def get_xml_node(self): xb = xmlapi.XmlBuilder() ret = [] if self.access_hosts is not None: ret.append(xb.list_elements('AccessHosts', self.access_hosts)) if self.rw_hosts is not None: ret.append(xb.list_elements('RwHosts', self.rw_hosts)) if self.ro_hosts is not None: ret.append(xb.list_elements('RoHosts', self.ro_hosts)) if self.root_hosts is not None: ret.append(xb.list_elements('RootHosts', self.root_hosts)) return ret", 509,read properties file,"def read_properties(fname): parser = configparser.SafeConfigParser() parser.optionxform = str try: with open(fname) as f: parser_read(parser, AddSectionWrapper(f)) except IOError as e: if e.errno != errno.ENOENT: raise return None return dict(parser.items(AddSectionWrapper.SEC_NAME))","preserve key case compile time, prop file is not there" 510,connect to sql," def execute(self, sql, args=()): if isinstance(sql, (list, tuple)): sql = ' '.join(sql) with sqlite3.connect(self.path) as con: return con.execute(sql, args)", 511,how to determine a string is a valid word," def isWord(self,word,ret_ref_trie=False): letters = utf8.get_letters(word) wLen = len(letters) ref_trie = self.trie ref_word_limits = self.word_limits for itr,letter in enumerate(letters): idx = self.getidx( letter ) if itr == (wLen-1): break if not ref_trie[idx][1]: return False ref_trie = ref_trie[idx][1] ref_word_limits = ref_word_limits[idx][1] if ret_ref_trie: return ref_word_limits[idx][0],ref_trie,ref_word_limits return ref_word_limits[idx][0]","see if @word is present in the current Trie; return True or False print(idx, letter) this branch of Trie did not exist" 512,write csv," def write_csvs(self, asset_map, show_progress=False, invalid_data_behavior='warn'): read = partial( read_csv, parse_dates=['day'], index_col='day', dtype=self._csv_dtypes, ) return self.write( ((asset, read(path)) for asset, path in iteritems(asset_map)), assets=viewkeys(asset_map), show_progress=show_progress, invalid_data_behavior=invalid_data_behavior, )","Read CSVs as DataFrames from our asset map. Parameters ---------- asset_map : dict[int -> str] A mapping from asset id to file path with the CSV data for that asset show_progress : bool Whether or not to show a progress bar while writing. invalid_data_behavior : {'warn', 'raise', 'ignore'} What to do when data is encountered that is outside the range of a uint32." 513,extract data from html content,"def extract_content(html, encoding=None, as_blocks=False): if 'content' not in _LOADED_MODELS: _LOADED_MODELS['content'] = load_pickled_model( 'kohlschuetter_readability_weninger_content_model.pkl.gz') return _LOADED_MODELS['content'].extract(html, encoding=encoding, as_blocks=as_blocks)", 514,extract data from html content,"def text_filter(html): if isinstance(html, list): html = """".join(html) ok, content = SoupOps.extract_text(html) if ok: return content else: raise RuntimeError(""Extract text failed"")", 515,unzipping large files," def _unzip_file(self, src_path, dest_path, filename): self.logger.info(""unzipping file..."") unzip_path = os.path.join(dest_path, filename) utils.ensure_directory_exists(unzip_path) with zipfile.ZipFile(src_path, ""r"") as z: z.extractall(unzip_path) return True","unzips file located at src_path into destination_path construct full path (including file name) for unzipping extract data" 516,aes encryption," def _cbc_encrypt(self, content, final_key): aes = AES.new(final_key, AES.MODE_CBC, self._enc_iv) padding = (16 - len(content) % AES.block_size) for _ in range(padding): content += chr(padding).encode() temp = bytes(content) return aes.encrypt(temp)",This method encrypts the content. 517,how to get html of website,"def get_website(bucket_name, **conn): try: result = get_bucket_website(Bucket=bucket_name, **conn) except ClientError as e: if ""NoSuchWebsiteConfiguration"" not in str(e): raise e return None website = {} if result.get(""IndexDocument""): website[""IndexDocument""] = result[""IndexDocument""] if result.get(""RoutingRules""): website[""RoutingRules""] = result[""RoutingRules""] if result.get(""RedirectAllRequestsTo""): website[""RedirectAllRequestsTo""] = result[""RedirectAllRequestsTo""] if result.get(""ErrorDocument""): website[""ErrorDocument""] = result[""ErrorDocument""] return website", 518,parse command line argument,"def parse_cmdln_args(): parser = argparse.ArgumentParser(description='Process command line args') parser.add_argument('--log', help='log help', default='INFO') parser.add_argument( '--tc', help='tc help') parser.add_argument( '--ts', help='ts help') args = parser.parse_args() return (args.log.upper(), args.tc, args.ts)", 519,replace in file,"def replaces_in_file(file, replacement_list): rs = [(re.compile(regexp), repl) for (regexp, repl) in replacement_list] file_tmp = file + ""."" + str(os.getpid()) + "".tmp"" with open(file, 'r') as f: with open(file_tmp, 'w') as f_tmp: for line in f: for r, replace in rs: match = r.search(line) if match: line = replace + ""\n"" f_tmp.write(line) shutil.move(file_tmp, file)", 520,extracting data from a text file," def _ExtractMetadataFromFileEntry(self, mediator, file_entry, data_stream): if file_entry.IsRoot() and file_entry.type_indicator not in ( self._TYPES_WITH_ROOT_METADATA): return if data_stream and not data_stream.IsDefault(): return display_name = mediator.GetDisplayName() logger.debug( '[ExtractMetadataFromFileEntry] processing file entry: {0:s}'.format( display_name)) self.processing_status = definitions.STATUS_INDICATOR_EXTRACTING if self._processing_profiler: self._processing_profiler.StartTiming('extracting') self._event_extractor.ParseFileEntryMetadata(mediator, file_entry) if self._processing_profiler: self._processing_profiler.StopTiming('extracting') self.processing_status = definitions.STATUS_INDICATOR_RUNNING","Extracts metadata from a file entry. Args: mediator (ParserMediator): mediates the interactions between parsers and other components, such as storage and abort signals. file_entry (dfvfs.FileEntry): file entry to extract metadata from. data_stream (dfvfs.DataStream): data stream or None if the file entry has no data stream. Do not extract metadata from the root file entry when it is virtual. We always want to extract the file entry metadata but we only want to parse it once per file entry, so we only use it if we are processing the default data stream of regular files." 521,aes encryption,"def aes_ctr_encrypt(text, key, params): iv = big_endian_to_int(decode_hex(params[""iv""])) ctr = Counter.new(128, initial_value=iv, allow_wraparound=True) mode = AES.MODE_CTR encryptor = AES.new(key, mode, counter=ctr) return encryptor.encrypt(text)", 522,create cookie,"def create_cookie(name, value, domain, httponly=None, **kwargs): if domain == 'localhost': domain = '' config = dict( name=name, value=value, version=0, port=None, domain=domain, path='/', secure=False, expires=None, discard=True, comment=None, comment_url=None, rfc2109=False, rest={'HttpOnly': httponly}, ) for key in kwargs: if key not in config: raise GrabMisuseError('Function `create_cookie` does not accept ' '`%s` argument' % key) config.update(**kwargs) config['rest']['HttpOnly'] = httponly config['port_specified'] = bool(config['port']) config['domain_specified'] = bool(config['domain']) config['domain_initial_dot'] = (config['domain'] or '').startswith('.') config['path_specified'] = bool(config['path']) return Cookie(**config)",Creates `cookielib.Cookie` instance 523,converting uint8 array to image,"def toUIntArray(img, dtype=None, cutNegative=True, cutHigh=True, range=None, copy=True): mn, mx = None, None if range is not None: mn, mx = range if dtype is None: if mx is None: mx = np.nanmax(img) dtype = np.uint16 if mx > 255 else np.uint8 dtype = np.dtype(dtype) if dtype == img.dtype: return img b = {'uint8': 255, 'uint16': 65535, 'uint32': 4294967295, 'uint64': 18446744073709551615}[dtype.name] if copy: img = img.copy() if range is not None: img = np.asfarray(img) img -= mn img *= b / (mx - mn) img = np.clip(img, 0, b) else: if cutNegative: img[img < 0] = 0 else: mn = np.min(img) if mn < 0: img -= mn if cutHigh: img[img > b] = b else: mx = np.nanmax(img) img = np.asfarray(img) * (float(b) / mx) img = img.astype(dtype) return img ","transform a float to an unsigned integer array of a fitting dtype adds an offset, to get rid of negative values range = (min, max) - scale values between given range cutNegative - all values <0 will be set to 0 cutHigh - set to False to rather scale values to fit get max px value: img[img<0]=0 print np.nanmin(img), np.nanmax(img), mn, mx, range, b print np.nanmin(img), np.nanmax(img), mn, mx, range, b add an offset to all values: set minimum to 0 ind = img > b scale values if range is not None and cutHigh: img[ind] = b" 524,connect to sql," def _connect(self): if mysql is None: raise ImproperlyConfigured('MySQL driver not installed!') conn = mysql.connect(db=self.database, **self.connect_params) return conn", 525,format date,"def format_date(date, gmt_offset=0, relative=True, shorter=False, full_format=False): if not date: return '-' if isinstance(date, float) or isinstance(date, int): date = datetime.datetime.utcfromtimestamp(date) now = datetime.datetime.utcnow() if date > now: if relative and (date - now).seconds < 60: date = now else: full_format = True local_date = date - datetime.timedelta(minutes=gmt_offset) local_now = now - datetime.timedelta(minutes=gmt_offset) local_yesterday = local_now - datetime.timedelta(hours=24) difference = now - date seconds = difference.seconds days = difference.days format = None if not full_format: ret_, fff_format = fix_full_format(days, seconds, relative, shorter, local_date, local_yesterday) format = fff_format if ret_: return format else: format = format if format is None: format = ""%(month_name)s %(day)s, %(year)s"" if shorter else \ ""%(month_name)s %(day)s, %(year)s at %(time)s"" str_time = ""%d:%02d"" % (local_date.hour, local_date.minute) return format % { ""month_name"": local_date.strftime('%b'), ""weekday"": local_date.strftime('%A'), ""day"": str(local_date.day), ""year"": str(local_date.year), ""month"": local_date.month, ""time"": str_time }","Formats the given date (which should be GMT). By default, we return a relative time (e.g., ""2 minutes ago""). You can return an absolute date string with ``relative=False``. You can force a full format date (""July 10, 1980"") with ``full_format=True``. This method is primarily intended for dates in the past. For dates in the future, we fall back to full format. From tornado Due to click skew, things are some things slightly in the future. Round timestamps in the immediate future down to now in relative mode. Otherwise, future dates always use the full format." 526,finding time elapsed using a timer,"def timed(func): @functools.wraps(func) def timer(*args, **kwargs): start_time = time() result = func(*args, **kwargs) elapsed_time = str(timedelta(seconds=int(time() - start_time))) print('Elapsed time is {}'.format(elapsed_time)) return result return timer", 527,pretty print json,"def pretty_print(response): parsed = json.loads(json.dumps(response)) click.echo(json.dumps(parsed, indent=4, sort_keys=True))", 528,httpclient post json," def request(self, url, json="""", data="""", username="""", password="""", headers=None, timout=30): raise NotImplementedError('request of HTTPClient should have been ' 'overridden on initialization. ' 'Otherwise, can be overridden to ' 'supply your own post method')","This is overridden on module initialization. This function will make an HTTP POST to a given url. Either json/data will be what is posted to the end point. he HTTP request needs to be basicAuth when username and password are provided. a headers dict maybe provided, whatever the values are should be applied. Args: url (str): url to send the POST json (dict, optional): Dict of the JSON to POST data (dict, optional): Dict, presumed flat structure of key/value of request to place as www-form username (str, optional): Username for basic auth. Must be uncluded as part of password. password (str, optional): Password for basic auth. Must be included as part of username. headers (dict, optional): Key/Value pairs of headers to include Returns: str: Raw request placed str: Raw response received int: HTTP status code, eg 200,404,401 dict: Key/Value pairs of the headers received. :param timout:" 529,scatter plot,"Error: 404 {""message"": ""No commit found for the ref 50d3f979e79e63c66629065c75595696dc79802e"", ""documentation_url"": ""https://docs.github.com/v3/repos/contents/"", ""status"": ""404""}", 530,binomial distribution,"def binomial(n,k): if n==k: return 1 assert n>k, ""Attempting to call binomial(%d,%d)"" % (n,k) return factorial(n)//(factorial(k)*factorial(n-k))","Binomial coefficient >>> binomial(5,2) 10 >>> binomial(10,5) 252" 531,socket recv timeout,"def recv_response(socket, acceptable_length, timeout): if socket.poll(""recv"", timeout): snep_response = socket.recv() if len(snep_response) < 6: log.debug(""snep response initial fragment too short"") return None version, status, length = struct.unpack("">BBL"", snep_response[:6]) if length > acceptable_length: log.debug(""snep response exceeds acceptable length"") return None if len(snep_response) - 6 < length: socket.send(b""\x10\x00\x00\x00\x00\x00"") while len(snep_response) - 6 < length: if socket.poll(""recv"", timeout): snep_response += socket.recv() else: return None return bytearray(snep_response)",request remaining fragments 532,convert a utc time to epoch," def _dt_to_epoch(self, dt): if PY2: time_delta = dt - datetime(1970, 1, 1).replace(tzinfo=dt.tzinfo) return int(time_delta.total_seconds()) else: return int(dt.timestamp())","Convert a offset-aware datetime to POSIX time. The input datetime is from botocore unmarshalling and it is offset-aware so the timedelta of subtracting this time to 01/01/1970 using the same tzinfo gives us Unix Time (also known as POSIX Time). Added in python 3.3+ and directly returns POSIX time." 533,string similarity levenshtein,"def levenshtein(str1, s2): N1 = len(str1) N2 = len(s2) stringRange = [range(N1 + 1)] * (N2 + 1) for i in range(N2 + 1): stringRange[i] = range(i,i + N1 + 1) for i in range(0,N2): for j in range(0,N1): if str1[j] == s2[i]: stringRange[i+1][j+1] = min(stringRange[i+1][j] + 1, stringRange[i][j+1] + 1, stringRange[i][j]) else: stringRange[i+1][j+1] = min(stringRange[i+1][j] + 1, stringRange[i][j+1] + 1, stringRange[i][j] + 1) return stringRange[N2][N1]",Distance between two strings 534,save list to file," def saveParList(self, *args, **kw): if 'filename' in kw: filename = kw['filename'] if not filename: filename = self.getFilename() if not filename: raise ValueError(""No filename specified to save parameters"") if hasattr(filename,'write'): fh = filename absFileName = os.path.abspath(fh.name) else: absFileName = os.path.expanduser(filename) absDir = os.path.dirname(absFileName) if len(absDir) and not os.path.isdir(absDir): os.makedirs(absDir) fh = open(absFileName,'w') numpars = len(self.__paramList) if self._forUseWithEpar: numpars -= 1 if not self.final_comment: self.final_comment = [''] while len(self.defaults): self.defaults.pop(-1) for key in self._neverWrite: self.defaults.append(key) self.write(fh) fh.close() retval = str(numpars) + "" parameters written to "" + absFileName self.filename = absFileName self.debug('Keys not written: '+str(self.defaults)) return retval","Write parameter data to filename (string or filehandle) force \n at EOF Empty the ConfigObj version of section.defaults since that is based on an assumption incorrect for us, and override with our own list. THIS IS A BIT OF MONKEY-PATCHING! WATCH FUTURE VERSION CHANGES! See Trac ticket #762. empty it, keeping ref Note also that we are only overwriting the top/main section's ""defaults"" list, but EVERY [sub-]section has such an attribute... Now write to file, delegating work to ConfigObj (note that ConfigObj write() skips any items listed by name in the self.defaults list) reset our own ConfigObj filename attr" 535,randomly extract x items from a list,"def random_sample(list_, nSample, strict=False, rng=None, seed=None): rng = ensure_rng(seed if rng is None else rng) if isinstance(list_, list): list2_ = list_[:] else: list2_ = np.copy(list_) if len(list2_) == 0 and not strict: return list2_ rng.shuffle(list2_) if nSample is None and strict is False: return list2_ if not strict: nSample = min(max(0, nSample), len(list2_)) sample_list = list2_[:nSample] return sample_list","Grabs data randomly Args: list_ (list): nSample (?): strict (bool): (default = False) rng (module): random number generator(default = numpy.random) seed (None): (default = None) Returns: list: sample_list CommandLine: python -m utool.util_numpy --exec-random_sample Example: >>> # DISABLE_DOCTEST >>> from utool.util_numpy import * # NOQA >>> list_ = np.arange(10) >>> nSample = 4 >>> strict = False >>> rng = np.random.RandomState(0) >>> seed = None >>> sample_list = random_sample(list_, nSample, strict, rng, seed) >>> result = ('sample_list = %s' % (str(sample_list),)) >>> print(result)" 536,randomly extract x items from a list,"def random_sample(list_, nSample, strict=False, rng=None, seed=None): rng = ensure_rng(seed if rng is None else rng) if isinstance(list_, list): list2_ = list_[:] else: list2_ = np.copy(list_) if len(list2_) == 0 and not strict: return list2_ rng.shuffle(list2_) if nSample is None and strict is False: return list2_ if not strict: nSample = min(max(0, nSample), len(list2_)) sample_list = list2_[:nSample] return sample_list","Grabs data randomly Args: list_ (list): nSample (?): strict (bool): (default = False) rng (module): random number generator(default = numpy.random) seed (None): (default = None) Returns: list: sample_list CommandLine: python -m utool.util_numpy --exec-random_sample Example: >>> # DISABLE_DOCTEST >>> from utool.util_numpy import * # NOQA >>> list_ = np.arange(10) >>> nSample = 4 >>> strict = False >>> rng = np.random.RandomState(0) >>> seed = None >>> sample_list = random_sample(list_, nSample, strict, rng, seed) >>> result = ('sample_list = %s' % (str(sample_list),)) >>> print(result)" 537,export to excel,"def export_xlsx(wb, output, fn): wb.close() output.seek(0) response = HttpResponse(output.read(), content_type=""application/vnd.ms-excel"") cd = codecs.encode('attachment;filename=%s' % fn, 'utf-8') response['Content-Disposition'] = cd return response","export as excel wb: output: fn: file name" 538,convert a utc time to epoch," def epoch(self): epoch_sec = pytz.utc.localize(datetime.utcfromtimestamp(0)) now_sec = pytz.utc.normalize(self._dt) delta_sec = now_sec - epoch_sec return get_total_second(delta_sec)","Returns the total seconds since epoch associated with the Delorean object. .. testsetup:: from datetime import datetime from delorean import Delorean .. doctest:: >>> d = Delorean(datetime(2015, 1, 1), timezone='US/Pacific') >>> d.epoch 1420099200.0" 539,read properties file,"def read_properties(entry): stream = entry.get('properties') if stream is None: raise Exception(""can not find properties"") s = stream.open() f = BytesIO(s.read()) byte_order = read_u8(f) if byte_order != 0x4c: raise NotImplementedError(""be byteorder"") version = read_u8(f) entry_count = read_u16le(f) props = [] for i in range(entry_count): pid = read_u16le(f) format = read_u16le(f) byte_size = read_u16le(f) props.append([pid, format, byte_size]) property_entries = {} for pid, format, byte_size in props: data = f.read(byte_size) property_entries[pid] = data return property_entries",read the whole stream 540,get name of enumerated value," def EnumValueName(self, enum, value): return self.enum_types_by_name[enum].values_by_number[value].name","Returns the string name of an enum value. This is just a small helper method to simplify a common operation. Args: enum: string name of the Enum. value: int, value of the enum. Returns: string name of the enum value. Raises: KeyError if either the Enum doesn't exist or the value is not a valid value for the enum." 541,binomial distribution,"def Binomial(n, p, tag=None): assert ( int(n) == n and n > 0 ), 'Binomial number of trials ""n"" must be an integer greater than zero' assert ( 0 < p < 1 ), 'Binomial probability ""p"" must be between zero and one, non-inclusive' return uv(ss.binom(n, p), tag=tag)","A Binomial random variate Parameters ---------- n : int The number of trials p : scalar The probability of success"