content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def create_transaction(): """ Input Payload: { "sender": "address_1" "recipient": "address_2", "amount": 3 } """ transaction_data = request.get_json() index = blockchain.create_new_transaction(**transaction_data) response = { 'message': 'Transaction has ...
be2876bf0c901d7176d521207522effff29a131c
61,078
def build_config(config): """ Determines the configuration of the metadata service. :type config: akanda.router.models.Configuration :param config: :rtype: akanda.router.models.Configuration """ config_data = {} for net in config.networks: if not net.is_tenant_network: ...
5ba48ee05e30b87ff331881d5ea511de79dee105
61,079
def has_an_update(page_data: dict, tracker_data: dict) -> bool: """Checks if there was an update comparing two story mappings of the same story. Arguments: page_data {dict} -- Requested story mapping, from `get_story_data`. tracker_data {dict} -- Story mapping from the tracked list. Re...
a7374a167c368f85bdab6ec68dbea044c801ef90
61,080
def meaning(of=None): """The meaning of life?""" if of == "life": return 42 return None
ee85e2cd0caa1c0780e11eb3759b8e0d74031209
61,081
def merge_explicit(matmul): """ Merge explicit MatrixBase arguments >>> from sympy import MatrixSymbol, Matrix, MatMul, pprint >>> from sympy.matrices.expressions.matmul import merge_explicit >>> A = MatrixSymbol('A', 2, 2) >>> B = Matrix([[1, 1], [1, 1]]) >>> C = Matrix([[1, 2], [3, 4]]) >...
536209c6c6f4ed121b496b06610234b6321ee351
61,082
import codecs import json from typing import OrderedDict def _load_json_result(result_file): """ Load the result file as utf-8 JSON and strip test_dir prefix from locations. Sort the results by location. """ with codecs.open(result_file, encoding='utf-8') as res: scan_result = json.loa...
c313a2bbf000cb3e3b48ea9314f48188243ecf9b
61,083
def get_total_contacts(res_pair_file, with_nnc=False): """ Take res pair file and extract the amount of native contacts for the dataset. Also option to use 'with nnc=True' which allows extraction of total nc and nnc values. Returns int: amount of nc, optionally: amount of nnc """ total_contacts ...
e1d061c5d4c76647f0c825165fd305e76f00c5f8
61,085
def bg_subtract(im, radius): """ Subtracts a gaussian blurred image from itself smoothing uneven illumination. Parameters ---------- im : 2d-array Image to be subtracted radius : int or float Radius of gaussian blur Returns ------- im_sub : 2d-array, float ...
bcaedb54a252adf88283a37e65c700f140590384
61,086
def named_param(argnames, argvalues): """ Improve pytest's native labeling of test case parameterization. This function thinly wraps the 'parametrize' mark from pytest, adding clearer labeling of each individual parameterized test case, overriding the index-based labeling that pytest uses by defaul...
a9055016bdd600eec5695f2a2a6e44460e2af12f
61,087
def apply(sliced, input_image, has_affine_term=True, name=None): """Applies a sliced affined model to the input image. Args: sliced: (Tensor) [batch_size, h, w, n_output, n_input+1] affine coefficients input_image: (Tensor) [batch_size, h, w, n_input] input data onto which to apply the affi...
8b68f0f02c7f6a52018c994f8c99b0ea76f8811b
61,088
import torch def propagate(T0, Sigma, Upsilon, Q, method, dt, g, cholQ=0): """ Propagate an extended pose and its uncertainty """ Gamma = f_Gamma(g, dt) Phi = f_flux(T0, dt) # compound the mean T = Gamma.mm(Phi).mm(Upsilon) # Jacobian for propagating prior along time F = torch.eye...
dd6acdad16d0d5287eba0d8b46e7261fbcbc1427
61,089
def shared_hive_instance(): """ This method will initialize ``SharedInstance.instance`` and return it. The purpose of this method is to have offer single default steem instance that can be reused by multiple classes. .. code-block:: python from beem.account import Account ...
f7e9a3ee09731370dab09649a417145772f53cf3
61,090
def aperture_fields(guide_width, horn_effective_length, frequency, x, y): """ Calculate the electric and magnetic fields at the aperture of the horn. Assuming that the fields of the feeding waveguide are those of the dominant TE10 mode. And that the horn length is large compared to the dimensions of the...
bf69e31adfd7e7b91b5b09103e57b0086c81a0d6
61,091
def get_greeting_2(): """Greets and optionally compliments(3 random compliments) a user""" username = request.args["username"] wants = request.args.get("wants_compliments") nice_things = sample(COMPLIMENTS, 3) return render_template("greet_2.html", username=username, wants_compliments=wants, complim...
bd1c248adb072f07cdd7a0552f9771a5e8873588
61,092
import requests def proxy(path): """ HTTP Proxy """ query = '' if request.query_string is not None: query = '?' + request.query_string.decode("utf-8") bokeh_url = BOKEH_URL.replace('$PORT', get_bokeh_port()) request_url = f"{bokeh_url}/{path}{query}" resp = requests.get(request_url) ...
16ad1b0c037238e4a55ac153d731c4dff4e9ac0a
61,093
def requires_auth(f): """Minimal implementation of authentication. Will be refactored.""" @wraps(f) def decorated_function(*args, **kws): if session.get('user', None) is None: return redirect(url_for('login')) else: return f(*args, **kws) return decorated_function
3d09db7ae3452101ad454073923f3dac279ff07f
61,094
import requests def dwCover(SONG_INFO, index): """Download the song cover img from itunes.""" # Try to download the cover art as cover.jpg in temp try: imgURL = SONG_INFO[index].artwork_url_100 try: # Try to get 512 cover art imgURL = imgURL.replace('100x100', '2048...
d76bdd3513b6b6f0d6256341e8e75ce4635106f8
61,095
def asMFnSkinCluster(obj): """ OpenMaya.MObject -> OpenMaya.MFnSkinCluster :param OpenMaya.MObject obj: :rtype: OpenMaya.MFnSkinCluster """ iter = OpenMaya.MItDependencyGraph( obj, OpenMaya.MFn.kSkinClusterFilter, OpenMaya.MItDependencyGraph.kUpstream ) wh...
efba63d2548ab7d6a00f460363577261a102ba0c
61,096
def before_lock(aqi_array: np.ndarray, datetime_index: np.ndarray, after_lock: np.ndarray, before_lock_date: str) -> np.ndarray: """Grab period before lock down.""" return aqi_array[np.where(datetime_index <= np.datetime64(before_lock_date))][-(after_lock.shape[0]...
764b70ce70ac53ff48867c5a53bf319cd524770d
61,097
def rdkitSubstrMatch(targetRdkitMol, refRdkitMol, *args, **kwargs): """ Matches two rdkit mol object graphs with each other. Outputs a single tuple of corresponding atoms indices. Arguments: ---------- targetRdkitMol : object target rdkit molecule object refRdkitMol : object ...
9978dce4381f2e49c6f2926594a0a5f58dd33368
61,098
import numpy as np def from_a_to_b(source="Munich, Germany", destination="Augsburg, Germany", resolution=50): """ Try to print the way from source to destination :param source: The starting place :param destination: The destination place :param resolution: (minimum) resolution of height results in...
94a6d309fe272432fe32778fe7503856f31758d0
61,099
import functools def single(window, config): """Single theme ===== Header ===== = items = ================== """ cordx = round(config.get('cordx', 0)) color = config.get('color', red) icon = config.get('icon', '=') align = config.get('align', 'left') term = window.ter...
61f481ff43100bcd1b4f88c087dfdecdc7336681
61,100
def table_exists(table_or_name): """ Determines if a table exists in the database :param table_or_name: a sqlalchemy table object or the name of a table to query :return: True if table exists, otherwise False """ if isinstance(table_or_name, str): table = get_table(table_or_name, ignore...
bda7243311ba83771575eb0cfa66ea34a978e94c
61,102
def vectorCosine(v, u): """ Calculates the cosine between two vectors (because they are both normal and have length 1). """ cosine = np.dot(v, u) return cosine
130ea9d8dd57c0988efee6491449a7270ff6c97a
61,103
def get_segment_probs(all_b_samples, all_masks, segment_id): """Get segment probabilities for a particular segment ID.""" neg_cumsum = 1 - jnp.cumsum(all_b_samples[segment_id], axis=1) if segment_id > 0: return neg_cumsum * all_masks[segment_id - 1] else: return neg_cumsum
1684a2daaf9c59f23eaf8af5f325c3457eed4627
61,104
def find_and_instantiate_clazz(obj, instancelize_clazz_fce=None): """ Got through json-like object and find all classes definitions and instantiate them. Class definition is dict with `class` key and optionally `args` and `kwargs` keys. """ if instancelize_clazz_fce is None: instancelize_cl...
f06c346e333bb8d8d70a84050d1baecc0d5c77a5
61,105
def flow_to_rgb(flow): """Compute an RGB visualization of a flow field.""" shape = tf.cast(tf.shape(flow), tf.float32) height, width = shape[-3], shape[-2] scaling = _FLOW_SCALING_FACTOR / (height**2 + width**2)**0.5 # Compute angles and lengths of motion vectors. motion_angle = tf.atan2(flow[Ellipsis, 1],...
0cdef99bf519b83640923096b474d5de1e37a4c8
61,106
from typing import Callable from typing import Any from typing import OrderedDict def multimap(f: Callable, *xs: Any) -> Any: """ Each x in xs is a tree of the same structure. Apply f at each leaf of the tree with len(xs) arguments. Return a tree of the same structure, where each leaf contains f's ret...
7c81deab0875b2396a2127b504a4ce8773ab356c
61,107
def partition_for_vitis_ai(mod, params=None, dpu=None, **opts): """Partition the Relay expression for offloading operators to Vitis AI DPU Parameters ---------- mod : Module The module to run passes on. params : Optional[Dict[str, NDArray]] Constant input parameters. dpu : str ...
56a485f36513d459c5e6c445815060fd0f237947
61,108
def serialize_user_list_default(user: User, context: Context): """ Actually, roles are serialized as users (with minimal information) :param role: :param context: :return: """ result = DictLikeClass() result['id'] = user.user_id result['name'] = user.get_display_name() result['em...
fe718642bb059853bcdd0735b5f1fd340e79d51b
61,109
def rooms_n9(): """ Complicated arrangement of rooms """ rooms = [] rooms.append(Room('rm1', 1e3, [[0,0], [5,0], [5,5], [0,5]])) rooms.append(Room('rm2', 2e3, [[5,0], [10,0], [10,2], [10,4], [10,5], [5,5]])) rooms.append(Room('rm3', 3e3, [[0,5], [5,5], [10,5], [10,6], [10,8], [10,10]])) ...
1ac6c1817b6e82304c251bcaa2281125794f8629
61,110
def transitive_reduction(G): """ Returns transitive reduction of a directed graph The transitive reduction of G = (V,E) is a graph G- = (V,E-) such that for all v,w in V there is an edge (v,w) in E- if and only if (v,w) is in E and there is no path from v to w in G with length greater than 1. Para...
bd7b31648b013bea07e01f74ccacdcb23f001d48
61,111
def parse_addr_file(filename): """Parse an address file, called filename. An address file is in the form: <name>: <base0>,<end0> <base1>,<end1> <name>: <base0>,<end0> <base1>,<end1> Each line represents a set of disjoint set of memory with a particular name. The each item in the set is a range ...
dcf79cfd3d7c2272f5407f2fabe4d77fe3d81eff
61,112
import random def generate_palette( count, ranges, offset_angles, saturation_range, luminance_range): """ -Analogous: Choose second and third ranges 0 -Complementary: Choose the third range 0, and first offset angle 180 -Split Complementary: Choose offset angles 180 +/- a small angle. The seco...
645d6f309c9446bd6a97007662ca56d0cddb7d73
61,113
def xml_reader(fh, filesize): """Read XML from file and return as xml.ElementTree root Element.""" xml = unicode(stripnull(fh.read(filesize)), 'utf-8') return etree.fromstring(xml)
c17639a38b0cca8e9d48d57763ad23b7c971772a
61,114
from typing import Optional from typing import List import torch def push1d(inp, g, shape: Optional[List[int]], bound: List[Bound], extrapolate: int = 1): """ inp: (B, C, iX, iY) tensor g: (B, iX, iY, 2) tensor shape: List{2}[int], optional bound: List{2}[Bound] tensor extrapolate: ...
d6175e1b27d0d5d3e4f0eaeafbe9e1851f5129f2
61,115
def superuser(db) -> "User": """Gets the sample super user :param db: Database connection :return: Super User model """ return _get_user(db, "superuser@email.com")
80ca0e9a00892b4a2dae9cd180caf1d685b26b3d
61,116
def default(value, default): """ Returns a specified default value if the provided value is None. Args: value (object): The value. default (object): The default value to use if value is None. Returns: object: Either value, or the default. """ return value if value is no...
99fddb624594c837218d6b1ca7f6d49d94e05031
61,117
def String_Rules_From_Binary(node_rules_binary_dictionary): """Convert from binary dictionary rule format to BooleanNet format. Parameters ---------- node_rules_binary_dictionary : dictionary Binary dictionary representation of rules. Returns ------- str BooleanNet represen...
deffbfc51d4fc5d35cb8e1a24f8aa9a65c08039b
61,118
import numpy def sqft_homes_select(data, sel): """Extract and restructure home count or square footage for a microsegment Similar to nrg_stock_select, for the microsegment identified by 'sel,' this function extracts the corresponding house count (total homes or new homes) or square footage from the E...
1b896a67e11fa687a7de3f008db1f0722175b1f8
61,119
def crscode_to_string(codetype, code, format): """ Lookup crscode and return in specified format. Uses epsg.io for epsg code, or spatialreference.org for esri or sr codes. Arguments: - *codetype*: "epsg", "esri", or "sr-org". - *code*: The code. - *format*: The crs format of the returned s...
4cc61c5c89d2edd417dfc47dc8edf9d530dabc5f
61,121
def get_atom_target_index(target_index, input_index, resindices): """get target indices of input atom Arguments: target_index {array} -- target(native) residue index input_index {array} -- input residue index resindices {array} -- target residue index of input atoms Returns...
5fd414cc147e1fe5c6c51b6c6e655a11b8bec8db
61,122
def array_from_where(process, where): """Get array of scannables from provided parameter""" if where == 'all': return process.pages if where == 'pages': return process.pages if where == 'modules': return process.modules if not where is None: return [module for module ...
9e312cbd2b890ec976ba42f524ee57d501c30efa
61,123
import tqdm def get_tqdm(**kwargs): """ Similar to :func:`get_tqdm_kwargs`, but returns the tqdm object directly. """ return tqdm(**get_tqdm_kwargs(**kwargs))
4905c3196f06b2f490b2dc53a97c698e85da2b4c
61,124
import random def get_rnd_kpts_per_samples(num_batch, num_kpts, nMaps_shuffled): """ This method gets num_batch, num_kpts, nMaps_shuffled and for each example in num_batch, selects as many as 'nMaps_shuffled' random UNIQUE samples in the range [0, num_kpts) and returns them """ # building ...
b61d24b4cd4967b32bc38511413c0bb405290746
61,125
def conv_reduce_sum(x, result_shape, padding, strides): """Sums along the output dimensions in line with an N-D convolution. For example, with a kernel size of 3, padding=`VALID`, and stride of 1, then with respect to each spatial dimension of the convolution (and disregarding class, batch and channel dimensio...
bfc0fa2d84d3658a74486b2f2193ca6f0d8e10a6
61,126
def inside_string(i, j, string_ranges): """Returns true if the range described by i and j is contained within a range in the list string_ranges""" for s, e in string_ranges: if i >= s and j <= e: return True return False
aea2ac8a777914c2e86aea40cf43f4d01b2ef8b0
61,127
import re def clean_txt(txt): """clean txt from e.g. html tags""" cleaned = re.sub(r'<.*?>', '', txt) # remove html cleaned = cleaned.replace('&lt;', '<').replace('&gt;', '>') # retain html code tags cleaned = cleaned.replace('&quot;', '"') cleaned = cleaned.replace('&rsquo;', "'") cleaned = c...
6eb173f7f06794fc2e9220c15b3743fc27e11904
61,128
def rgbd(depth,rgb): """ return 32x32x4 array """ d=misc.imread(depth) c=misc.imread(rgb) r=c[:,:,0] g=c[:,:,1] b=c[:,:,2] img=np.zeros([r.shape[0],r.shape[1],4]) img[:,:,0]=r img[:,:,1]=g img[:,:,2]=b img[:,:,3]=d return img
8224d740cdd32b9b208c2d58c2c669103119f065
61,129
def filter_items(items, *args, **kwargs): """Filters an iterable using lookup parameters :param items : iterable :param args : ``Q`` objects :param kwargs : lookup parameters :rtype : lazy iterable (generator) """ q1 = list(args) if args is not None else [] q2 = [Q(**kwargs)]...
4f2cd17f8f64b063956a15e1fb177fa407e919b2
61,130
def _create_validation_data_loader(img_path, batch_size, img_size, n_cpu): """ Creates a DataLoader for validation. :param img_path: Path to file containing all paths to validation images. :type img_path: str :param batch_size: Size of each image batch :type batch_size: int :param img_size:...
63109318fba9f224e802be8e2296b6bc3c78ac99
61,131
def cast_ext(ext: str) -> str: """Convert ext to a unified form.""" ext = ext.lower() if ext == 'jpeg': ext = 'jpg' return ext
7b4894e035a3b785b017c9794e494ff7b78e7c1b
61,132
import logging def setup_logger(name, log_file, formatter_text): """To setup as many loggers as you want""" handler = logging.FileHandler(log_file) handler.setFormatter(logging.Formatter(formatter_text)) logger = logging.getLogger(name) logger.setLevel(logging.INFO) logger.addHandler(handler...
6f80c4abbc33c20a60e919a3a03bc4d75eae917e
61,133
def filter_reply_msg(top_indices, top_cosine, cosine_cut_off, count_cutoff): """ Filter out responses 1. cosine similarity < cosine_cut_off 2. too short replies (word count <= count_cutoff) 3. replies contain other special characters :type pandas DataFrame: response_df :type float: cosi...
4915c71f64cc2a676a3f7da458a73ff8a165aee0
61,134
import math from eiscat_toolkit import loc2gg def find_coord_alt_2(loc, elRange, elProject, az, alt, range_start=None, accuracy=1): """same as find_coord_alt, but lets you find the proper range using one elevation elRange and then project to another elevation elProject.""" # find starting guess for rang...
bf99399a87770eda65634397b635fceb40291abb
61,136
def create_app(mbtiles=None, cache_config=None): """Initialize the application with a given configuration. mbtiles must be a path to the MBTiles sqlite file. """ app = Flask(__name__) app.config.update({ 'MBTILES_PATH': mbtiles }) app.register_blueprint(frontend) cache.init_app...
46fb9db09d567474ebeaa936f2dcd573a0d1a354
61,137
def get_xaligned_axes(ax, y_distance, height, factor=1., **kwargs): """ :param ax: :param y_distance: negative distance in y direction to the x axis :param height: height of the new axes :param factor: factor for scaling the fig_width_inch of the new axes :param kwargs: kwargs passed to matplot...
768b7bcd93e5c363a80049c76fa0e761ffc940db
61,138
def get_tracing_strat(quarantine_infect_mult, other_infect_mults) -> Stratification: """ Contact tracing stratification to represent those detected actively through screening of first order contacts of symptomatic COVID-19 patients presenting passively. """ tracing_strat = Stratification("tracing",...
a92256fa5fb8bb3629cb590eae2ff6baed59c95d
61,139
def main_add(args): """Add variables main.""" return add_variables(args.directory, args.env_spec, args.vars_to_add, args.default)
ffae73e612874d3ed73102e7ac85dd9202d74fa8
61,141
from typing import Optional def make_range( index: pd.DatetimeIndex, other_index: pd.DatetimeIndex = None ) -> Optional[Range1d]: """Make a 1D range of values from a datetime index or two. Useful to share axis among Bokeh Figures.""" index = tz_index_naively(index) other_index = tz_index_naively(other...
25acbc625cef95b01e5e48010c0af0280bd0f104
61,142
import re def parse_issue_comment(username, body, sha, botname, hooks=[]): """ Parse an issue comment looking for commands that Homu should handle Parameters: username: the username of the user that created the issue comment. This is without the leading @ body: the full body of the com...
c9087b204bfde84d32e8fca21c3186d99436e7ca
61,143
def applyPrecession(ra, dec, epoch=2000.0, mjd=None): """ applyPrecession() applies precesion and nutation to coordinates between two epochs. Accepts RA and dec as inputs. Returns corrected RA and dec (in degrees). Assumes FK5 as the coordinate system units: ra_in (degrees), dec_in (degrees) ...
984c99010190011a93d0e31824f801c80089ff9a
61,144
def oriented_bounds_2D(points, qhull_options='QbB'): """ Find an oriented bounding box for a set of 2D points. Parameters ---------- points: (n,2) float, 2D points Returns ---------- transform: (3,3) float, homogenous 2D transformation matrix to move the input points so...
3585e86d9522822816908c2c5f5a484720ad04ea
61,145
def filter_map(df_map, df_samp, sample_col): """Filtering df_sample to just destination position, then adding values to df_map """ # formatting sample table df_samp = filter_samp(df_samp, sample_col) # formatting mapping table df_map = df_map.drop_duplicates(subset='#SampleID') # joinin...
9f1d2400f06e4e3a6036448052c7ebe4c77f1495
61,146
def low_frequency_accuracy(sent_test_tags, sent_pred_tags, counter): """ sent_test_tags: # [[{'start_idx': 7, 'end_idx': 12, 'text': '東芝キヤリア'}, {'start_idx': 14, 'end_idx': 19, 'text': 'ダイキン工業'}], [{'start_idx': 0, 'end_idx': 1, 'text': '東芝'}, {'start_idx': 27, 'end_idx': 32, 'text': 'ダイキン工...
49d40fd41ace2a25be35d0a2d764bd23b4cad0b8
61,147
def _set_concatenate(sets): """concatenate indexable objects. Parameters ---------- sets : iterable of indexable objects Returns ------- indexable object handles both arrays and tuples of arrays """ def con(set): # if not all(): # raise ValueError('concaten...
36bec5766d636f381d4e399918ca25b989bd752e
61,148
from typing import List from typing import Tuple def count_chunks(alignment: List[Tuple[int, int]]) -> int: """ Find the minimum number of chunks the alignment can be grouped into. """ alignment = sorted(alignment) num_chunks = 0 last_h, last_r = -2, -2 for (h, r) in alignment: if...
41429e2e725b32edadc066ce4a2748cc3933cc50
61,149
def create_basic_vector(num_qubits: int): """Generate list of basic vectors Args: num_qubits (int): number of qubits Returns: np.ndarray: |00...0>, |00...1>, ..., |11...1> """ bs = [] for i in range(0, 2**num_qubits): b = np.zeros((2**num_qubits, 1)) b[i] = 1 ...
2fb39fec815a9ea250dd687eb796f93e5972899f
61,150
def intersection(box1, box2): """Compute pairwise intersection areas between boxes. Args: box1: a float Tensor with [N, 4]. box2: a float Tensor with [M, 4]. Returns: a float tensor with shape [N, M] representing pairwise intersections """ with tf.name_scope('Intersection'): y_min1, x_min1, ...
3eddb5c7aa7e85e233d595569f0d5f2c479f44d8
61,151
def _get_converter(orig, target): """get funtion 'convert_{}_to_{}' when available for coverage """ try: func = getattr(utils, f'convert_{orig}_to_{target}') except AttributeError: func = partial(convert_unit, orig=orig, to=target) return func
5d08c1f13b56720f12ca5d875b13138f3eee4601
61,152
import operator def get(ind, seq, default=no_default): """ Get element in a sequence or dict Provides standard indexing >>> get(1, 'ABC') # Same as 'ABC'[1] 'B' Pass a list to get multiple values >>> get([1, 2], 'ABC') # ('ABC'[1], 'ABC'[2]) ('B', 'C') Works on any value th...
7c98f4f5db3d1b2ccf43ddf3546bc5cd7bfc312a
61,153
from typing import Any from typing import List from typing import Optional def verify_trim(trims: Any) -> List[Optional[int]]: """Basically just to satisfy mypy. My trims should *always* be a tuple.""" return list(trims) if isinstance(trims, tuple) else [None, None]
1c3f738fd0b77388999c5de34d71ead90d39543e
61,154
def get_reference_output_files(reference_files_dict: dict, file_type: str) -> list: """ Returns list of files matching a file_type from reference files Args: reference_files_dict: A validated dict model from reference file_type: a file type string, e.g. vcf, fasta...
7050c39a8116f8874dbc09bcf7ff2908dcd13ff8
61,155
import requests from bs4 import BeautifulSoup import time import random def get_stock_names(code, retry=3): """ 从新浪财经中爬去上市公司的名称以及简称。 需要的输入: code: 股票代码 retry:错误发生之后重新尝试的次数 """ stock_info = {'code': code} URL = "http://vip.stock.finance.sina.com.cn/corp/go.php/vCI_CorpInfo/stockid/%s.pht...
cf1cd00e42bc3ae668d70a4574f0ff3b1769ed3b
61,156
def sanitizeSmarts(smarts, outrxn): """ It works both with the smiles string or a rxn file """ try: try: rxn = AllChem.ReactionFromSmarts(smarts, useSmiles=True) except: rxn = AllChem.ReactionFromSmarts(smarts) smi = AllChem.ReactionToSmiles(rxn) with open...
99a4dbe01c27e9eaf2a5d4486bdbf72de9dde508
61,157
def draw_line_param_abc(line, min_x=0, max_x=100, min_y=0, max_y=100): """draw line a*x + b*y + c = 0, line=[a, b, c]""" a, b, c = line[0], line[1], line[2] pts = [] if a == 0 and b == 0: print('Warning, line parameters error!') return pts if b == 0: pts = [[get_line_ABC_x(...
9f28fb42a29a77a0ed5aa3c321e6f939f7fa1c15
61,158
def close_noscript(tag): """Return a string with each closing parent tags for escaping a noscript""" s = "" if tag.findParent("noscript"): curr = tag.parent while True: s += "</{0}>".format(curr.name) if curr.name == "noscript": break curr ...
8082f609ff4c98059d728eeed8fb1f87a5fda48f
61,159
def rev_comp(seq): """ """ complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'N': 'N'} return "".join(complement[base] for base in seq)[::-1]
f5876955ee1bec0eb393d306870a8c388fce7762
61,160
import click def test_function(ctx): """ Simple single-function test """ config_filename = ctx.obj['config_filename'] config = pywren.wrenconfig.load(config_filename) wrenexec = pywren.default_executor() def hello_world(x): return "Hello world" fut = wrenexec.call_async(hell...
32200dd3b03addcc321c366c62aff4f6e21bf153
61,161
def _pooling(net, stride, operation, use_bounded_activation): """Parses operation and performs the correct pooling operation on net.""" padding = 'SAME' pooling_type, pooling_shape = _operation_to_pooling_info(operation) if use_bounded_activation: net = tf.nn.relu6(net) if pooling_type == 'avg': net =...
5d58ed2bbfca4432dbb2442e7ebbfaf7498df264
61,162
import hashlib def testfunc(res, i): """Return a hash of the index plus the other results.""" m = hashlib.md5() m.update(str(i).encode('utf-8')) for r in res: m.update(r.encode('utf-8')) return m.hexdigest()
f19a38d99bf50c33614134dec0d8184f35b27d60
61,163
def has_group_permission(user, thing, permission, grp_prop, user_grp_prop='groups'): """Convenience function for checking group permissions.""" # If group does not have permission, fail early. if not permission: raise ForbiddenError() # Check if user is a group member and group has permission. model_group...
35326d4a5e49216d6ae5c869df1e196f75ed6ce6
61,164
def clasificar(a1: float, a2: float, a3: float) -> str: """ Retorna 'Equilatero' si el triángulo es equilatero, 'Isóceles' si es isóceles y 'Escaleno' si es escaleno. """ if a1 == a2 and a1 == a3 and a2 == a3: retorno = "Equilatero" elif a1 == a2 or a1 == a3 or a2 == a3: retorno ...
e44104b58ab5fa24ab37831920e4d1c855eb25f3
61,166
def _list_to_html(list_, html=None): """Convert JSON-LD list to HTML.""" if html is None: html = [] if len(list_) == 1: _to_html(list_[0], html) else: html.append('<ul>\n') for item in list_: html.append('<li>') _to_html(item, html) htm...
15c7c4d5174e5d5f6a471bf41debb370b05b176d
61,168
def pretty_print_prime_rules(primes): """Prints pyboolnet a prime dictionary as Boolean rules The output format is of the form: A* = B & C | !D, for example. Parameters ---------- primes : pyboolnet primes dictionary Update rules to print. """ if primes is None: return...
f72f5b9a2c9b3c90c6682e253dffd1d22f78fa0c
61,169
def to_pil_image(pic, mode=None): """Convert a tensor or an ndarray to PIL Image. Args: pic (Tensor or numpy.ndarray): Image(HWC format) to be converted to PIL Image. mode (`PIL.Image mode`_): color space and pixel depth of input data (optional). .. _PIL.Image mode: https://pillow.readthedoc...
10debe47ed2a32565d7aad4c45441890b1cd2eac
61,170
def generate_objective_or_constraint_expr(columns, tokens, variables, result_value_name, group_by, variable_str, data_str, value_str, index_str): """ Generate the model expression for th...
cd19f7b881f77b031c8ab4c844e6167b6190e983
61,172
def norm(im): """Normaliza una imagen de números reales a [0,1]""" return cv2.normalize(im, None, 0.0, 1.0, cv2.NORM_MINMAX)
9da7a5c503dd8bdc191c6c55273e0183157d159a
61,173
def getServerCEASettingsId(nodename, servername): """Returns the Object ID for CEA Settings in a server, or None""" m = "getServerCEASettingsId:" #sop(m,"Entry. nodename=%s servername=%s" % (nodename, servername)) cea_settings_id = AdminConfig.getid( '/Node:%s/Server:%s/CEASettings:/' % ( nodename, serv...
ea7dddd4f4c44216fd1b67705b880dd00059e13b
61,174
def validate_all_blocks_have_trips(rating): """ Validate that all blocks have at least one revenue trip. Exceptions: - RAD/WAD blocks """ previous_block = None has_revenue_trips = False revenue_trips = { trip.trip_id for trip in rating["trp"] if isinstance(trip,...
071adfac3f3ff6c791ac154b826629f3be8b1d97
61,175
import math def param2stroke(param, H, W, meta_brushes): """ param2stroke """ b = param.shape[0] param_list = paddle.split(param, 8, axis=1) x0, y0, w, h, theta = [item.squeeze(-1) for item in param_list[:5]] sin_theta = paddle.sin(math.pi * theta) cos_theta = paddle.cos(math.pi * thet...
81c4260db0ea94a8a05ba3e42385266604bc945c
61,176
def _sort_key(k): """Sort key for common paths. Ensures the correct order for processing, without having to care about offsetting indices. Heavily inspired by the natsort package: Copyright (c) 2012-2016 Seth M. Morton Permission is hereby granted, free of charge, to any person obtaining a copy o...
92c2281458511415ecd547edbb1a8b843ce8bfd8
61,177
def additive_noise(s, snr): """Additive white noise with a given SNR relative to the input signal""" additive_noise = np.random.randn(len(s)) Es = np.std(s) En = np.std(additive_noise) return additive_noise / En * Es * 10**(snr/20)
2426738acf146f72937fd3a05e3d2491c9f4b4b2
61,178
async def events(city: str, state: str, country: str) -> quart.Response: """Returns current weather event.""" player = { "name": "Jeff the player", "city": city, "state": state, "country": country, } if not player: quart.abort(404) return quart.jsonify(player)
d8ba520a85d75b9d6fe73980f112bee37aa6f462
61,179
def optimal_q_u(kzzinv, noise_covar, x_mean, psi_1, psi_2, ns=nt.NumpyLinalg): """ Computes optimal q(u) :param kzzinv: [M*M] :param noise_covar: scalar :param x_mean: [N*D] means of GP mappinf outpot x_t: GP(x_minus_t) -> f_t -> x_t :param psi_1: [N*M] :param psi_2: [N*M*M] :return: u_m...
eb4ae3178faf63f028853688413b41f429322b80
61,181
def leak_nt_base_palette(manager_palette, worker_palette): """ Function to leak the NT base via TEB Based on: https://github.com/FuzzySecurity/PSKernel-Primitives/blob/master/Pointer-Leak.ps1 and https://www.blackhat.com/docs/us-17/wednesday/us-17-Schenk-Taking-Windows-10-Kernel-Exploitation-To-The-Next-Level%E2%...
d88aca2ce85ddfe67bea2b202c40bf6953d42640
61,182
def generate_export(config: Config, fmt: str) -> str: """ Generate a configuration export in the specified format. Args: config (``fica.config.Config``): the config object to export fmt (``str``): the format to export it to Returns: ``str``: the exported config object """ ...
b90be4da10ed41be802bc8cbd2806746cde91b8e
61,183
from typing import Dict def get_pygments_style_colors( style: Style, *, fallbacks: Dict[str, str] ) -> Dict[str, str]: """Get background/foreground colors for given pygments style.""" background = style.background_color text_colors = style.style_for_token(Text) foreground = text_colors["color"] ...
63975fc72e073df98e508eb54ae1cb97bc98c62f
61,184
def leaver_cf_inv_lentz_old(omega, a, s, m, A, n_inv, tol=1.e-10, N_min=0, N_max=np.Inf): """ Legacy function. Same as :meth:`leaver_cf_inv_lentz` except calling :meth:`qnm.contfrac.lentz`. We do not jit this function since lentz is not jitted. It remains here for testing purpo...
2c1eb0bd983e16b38368bdc60377a3da373b646a
61,185
def normalize_ext_data(data): """ Combine and normalize Extension data. Passing a tuple for an item will ignore defaults. """ normlist = ('sources', 'include_dirs', 'library_dirs', 'runtime_library_dirs') data.update({k: normalize(_build_list(k, v)) for k, v in data.items() if k in normlist}) r...
b600509ac3340d180f2429df21c0f126c6309337
61,187