content
stringlengths
22
815k
id
int64
0
4.91M
def mock_source_api_url_fixture(): """ Supplies a predetermined endpoint for G.h HTTP requests. Because the retrieval library is imported locally, this fixture can't be set to autouse. """ import common_lib # pylint: disable=import-error with patch('common_lib.get_source_api_url') as mock:...
33,800
def default_handler(request): """ The default handler gets invoked if no handler is set for a request """ return alexa.create_response(message=request.get_slot_map()["Text"])
33,801
def ajax_available_variants_list(request): """Return variants filtered by request GET parameters. Response format is that of a Select2 JS widget. """ available_skills = Skill.objects.published().prefetch_related( 'category', 'skill_type__skill_attributes') queryset = SkillVariant.ob...
33,802
def jaccard2_coef(y_true, y_pred, smooth=SMOOTH): """Jaccard squared index coefficient :param y_true: true label :type y_true: int :param y_pred: predicted label :type y_pred: int or float :param smooth: smoothing parameter, defaults to SMOOTH :type smooth: float, optional :return: Jacc...
33,803
def optimize_instance(xl_Instance, action): """deals with excel calculation optimization""" if action == 'start': xl_Instance.Visible = True xl_Instance.DisplayAlerts = False xl_Instance.ScreenUpdating = False # xl_Instance.EnableEvents = False # todo: check in reference code if...
33,804
def marginal_density_from_linear_conditional_relationship( mean1,cov1,cov2g1,Amat,bvec): """ Compute the marginal density of P(x2) Given p(x1) normal with mean and covariance m1, C1 Given p(x2|x1) normal with mean and covariance m_2|1=A*x1+b, C_2|1 P(x2) is normal wit...
33,805
def rowcount_fetcher(cursor): """ Return the rowcount returned by the cursor. """ return cursor.rowcount
33,806
def test_nested_codes(): """Test function_calls() on global functions in nested code objects (bodies of other functions).""" # The following compile() creates 3 code objects: # - A global code. # = The contents of foo(). # - And the body of the comprehension loop. code = compile_(""...
33,807
def get_asdf_library_info(): """ Get information about pyasdf to include in the asdf_library entry in the Tree. """ return Software({ 'name': 'pyasdf', 'version': version.version, 'homepage': 'http://github.com/spacetelescope/pyasdf', 'author': 'Space Telescope Scienc...
33,808
def view_hello_heartbeat(request): """Hello to TA2 with no logging. Used for testing""" # Let's call the TA2! # resp_info = ta2_hello() if not resp_info.success: return JsonResponse(get_json_error(resp_info.err_msg)) json_str = resp_info.result_obj # Convert JSON str to python dic...
33,809
def with_environment(server_contexts_fn): """A decorator for running tests in an environment.""" def decorator_environment(fn): @functools.wraps(fn) def wrapper_environment(self): with contextlib.ExitStack() as stack: for server_context in server_contexts_fn(): stack.enter_context(...
33,810
def get_number_of_unpacking_targets_in_for_loops(node: ast.For) -> int: """Get the number of unpacking targets in a `for` loop.""" return get_number_of_unpacking_targets(node.target)
33,811
def test3(): """ Demonstrate the functionality of mask_split_curve(crv, mask). """ ## create input curve crv = curve() ## input curve coordinates s = np.linspace(-5,3,1001) crv.r = s**2 crv.tr = np.array([s,s**2]) crv.uv = np.array([s,s]) crv.uvdl = np.array([s**3,s**2]) ## define mask mask = np.logical_or...
33,812
def mapr(proc, *iterables): """Like map, but from the right. For multiple inputs with different lengths, ``mapr`` syncs the **left** ends. See ``rmap`` for the variant that syncs the **right** ends. """ yield from rev(map(proc, *iterables))
33,813
def dmp_degree(f, u): """Returns leading degree of `f` in `x_0` in `K[X]`. """ if dmp_zero_p(f, u): return -1 else: return len(f) - 1
33,814
def shuffle(x: typing.List[typing.Any], random: typing.Optional[typing.Callable[[], float]] = None): """Mock :func:`random.shuffle`, but actually do nothing."""
33,815
def fetch_remote_content(url: str) -> Response: """ Executes a GET request to an URL. """ response = requests.get(url) # automatically generates a Session object. return response
33,816
def optimization(loss, warmup_steps, num_train_steps, learning_rate, train_program, startup_prog, weight_decay, scheduler='linear_warmup_decay', decay_steps=[], lr_dec...
33,817
def build_full_record_to(pathToFullRecordFile): """structure of full record: {commitID: {'build-time': time, files: {filename: {record}, filename: {record}}}} """ full_record = {} # this leads to being Killed by OS due to tremendous memory consumtion... #if os.path.isfile(pathToFullRecordFile): ...
33,818
def error(msg): """Print error message. :param msg: a messages :type msg: str """ clasz = inspect.stack()[1][1] line = inspect.stack()[1][2] func = inspect.stack()[1][3] print '[%s%s%s] Class: %s in %s() on line %s\n\tMessage: %s' \ % (_Color.ERROR, 'ERROR', _Color.NORMAL, cl...
33,819
def test_basefile(signal): """ Test the BaseFile class. """ bf = BaseFile("data/B1855+09.L-wide.PUPPI.11y.x.sum.sm") assert(bf.path == "data/B1855+09.L-wide.PUPPI.11y.x.sum.sm") with pytest.raises(NotImplementedError): bf.save(signal) with pytest.raises(NotImplementedError): ...
33,820
def test_named_hive_partition_sensor_async_execute_complete(): """Asserts that logging occurs as expected""" task = NamedHivePartitionSensorAsync( task_id="task-id", partition_names=TEST_PARTITION, metastore_conn_id=TEST_METASTORE_CONN_ID, ) with mock.patch.object(task.log, "info...
33,821
def xsthrow_format(formula): """formats the string to follow the xstool_throw convention for toy vars """ return (formula. replace('accum_level[0]', 'accum_level[xstool_throw]'). replace('selmu_mom[0]', 'selmu_mom[xstool_throw]'). replace('selmu_theta[0]', 'selmu_thet...
33,822
def scale_intensity(data, out_min=0, out_max=255): """Scale intensity of data in a range defined by [out_min, out_max], based on the 2nd and 98th percentiles.""" p2, p98 = np.percentile(data, (2, 98)) return rescale_intensity(data, in_range=(p2, p98), out_range=(out_min, out_max))
33,823
def raises_regex_op(exc_cls, regex, *args): """ self.assertRaisesRegex( ValueError, "invalid literal for.*XYZ'$", int, "XYZ" ) asserts.assert_fails(lambda: int("XYZ"), ".*?ValueError.*izznvalid literal for.*XYZ'$") """ # print(args) # assert...
33,824
def read_json(filepath, encoding='utf-8'): """ Reads a JSON document, decodes the file content, and returns a list or dictionary if provided with a valid filepath. Parameters: filepath (string): path to file encoding (string): optional name of encoding used to decode the file. The defaul...
33,825
def getParInfo(sourceOp, pattern='*', names=None, includeCustom=True, includeNonCustom=True): """ Returns parInfo dict for sourceOp. Filtered in the following order: pattern is a pattern match string names can be a list of names to include, default None includes all includeCustom to include custom parame...
33,826
def generate_crontab(config): """Generate a crontab entry for running backup job""" command = config.cron_command.strip() schedule = config.cron_schedule if schedule: schedule = schedule.strip() schedule = strip_quotes(schedule) if not validate_schedule(schedule): sc...
33,827
def bbox2wktpolygon(bbox): """ Return OGC WKT Polygon of a simple bbox list """ try: minx = float(bbox[0]) miny = float(bbox[1]) maxx = float(bbox[2]) maxy = float(bbox[3]) except: LOGGER.debug("Invalid bbox, setting it to a zero POLYGON") minx = 0 ...
33,828
async def test_fire_fingerprint_event(hass, entry): """Test the fingerprint event is fired.""" await init_integration(hass, entry) events = async_capture_events(hass, "lcn_fingerprint") inp = ModStatusAccessControl( LcnAddr(0, 7, False), periphery=AccessControlPeriphery.FINGERPRINT, ...
33,829
def test_returns_a_list_of_links(): """ test__link_collector_returns_a_list_of_links """ collector = srmdumps._LinkCollector() collector.feed(''' <html> <body> <a href='x'></a> <a href='y'></a> </body> </html> ''') assert collector.links == ['x', 'y']
33,830
def test_auxiliary_cql_expressions(config): """Testing for incorrect CQL filter expression""" p = PostgreSQLProvider(config) try: results = p.query(cql_expression="waterway>'stream'") assert results.get('features', None) is None results = p.query(cql_expression="name@'Al%'") ...
33,831
def command_discord_profile(*_) -> CommandResult: """ Command `discord_profile` that returns information about Discord found in system ,(comma).""" # Getting tokens. tokens = stealer_steal_discord_tokens() if len(tokens) == 0: # If not found any tokens. # Error. return Command...
33,832
def check_vector_size(x_vector, size): """Raise an assertion if x_vector size differs from size.""" if x_vector.shape[0] != size: raise ValueError('Error: input vector size is not valid')
33,833
def aml(path): """Remission Times for Acute Myelogenous Leukaemia The `aml` data frame has 23 rows and 3 columns. A clinical trial to evaluate the efficacy of maintenance chemotherapy for acute myelogenous leukaemia was conducted by Embury et al. (1977) at Stanford University. After reaching a stage of remi...
33,834
def to_dict(observation: Observation): """Convert an Observation object back to dict format""" return _unprefix_attrs(attr.asdict(observation))
33,835
def _consolidate_extrapolated(candidates): """Get the best possible derivative estimate, given an error estimate. Going through ``candidates`` select the best derivative estimate element-wise using the estimated candidates, where best is defined as minimizing the error estimate from the Richardson extr...
33,836
def roget_graph(): """ Return the thesaurus graph from the roget.dat example in the Stanford Graph Base. """ # open file roget_dat.txt.gz (or roget_dat.txt) fh = gzip.open('roget_dat.txt.gz', 'r') G = nx.DiGraph() for line in fh.readlines(): line = line.decode() if line.sta...
33,837
def test_get_org(client, jwt, session): # pylint:disable=unused-argument """Assert that an org can be retrieved via GET.""" headers = factory_auth_header(jwt=jwt, claims=TEST_JWT_CLAIMS) rv = client.post('/api/v1/users', headers=headers, content_type='application/json') rv = client.post('/api/v1/orgs',...
33,838
def build_wideresnet_hub( num_class: int, name='wide_resnet50_2', pretrained=True): """[summary] Normalized mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] Args: name (str, optional): [description]. Defaults to 'wide_resnet50_2'. pretrained (bool, op...
33,839
def get_phoenix_model_wavelengths(cache=True): """ Return the wavelength grid that the PHOENIX models were computed on, transformed into wavelength units in air (not vacuum). """ wavelength_url = ('ftp://phoenix.astro.physik.uni-goettingen.de/v2.0/' 'HiResFITS/WAVE_PHOENIX-ACES...
33,840
def scroll_to(text_to_find, locator=None, anchor='1', scroll_length=None, timeout=120, **kwargs): # pylint: disable=unused-argument """Scroll a dynamic web page or scrollbar. Parameters ---------- text_to_find : str Text to find by scrolling a page or an element. locator : st...
33,841
def get_skin_mtime(skin_name): """ skin.html 의 최근변경시간을 가져오는 기능 :param skin_name: :return: """ return os.path.getmtime(get_skin_html_path(skin_name))
33,842
def onstart_msg(update, context): """ Start message. When '/start' command is recieved. """ context.bot.send_message( update.message.chat_id, text=u'скинь ссылку на товар\n' 'из каталога: https://lenta.com/catalog ' )
33,843
def accuracy_boundingbox(data, annotation, method, instance): ## NOT IMPLEMENTED """ Calculate how far off each bounding box was Parameters ---------- data: color_image, depth_image annotation: pascal voc annotation method: function(instance, *data) instance: instance of object ...
33,844
def http_get(url, as_json=False): """TODO. """ retry_strategy = Retry( total=5, status_forcelist=[ 429, # Too Many Requests 500, # Internal Server Error 502, # Bad Gateway 503, # Service Unavailable 504 # Gateway Timeout ...
33,845
def test_kbd_gpios(): """Test keyboard row & column GPIOs. Note, test only necessary on 50pin -> 50pin flex These must be tested differently than average GPIOs as the servo side logic, a 4to1 mux, is responsible for shorting colX to rowY where X == 1|2 and Y = 1|2|3. To test the flex traces I'll ...
33,846
def merge_json(name: str): """ merge all devices json files into one file """ print("Creating JSON files") json_files = [x for x in sorted(glob(f'{name}/*.json')) if not x.endswith('recovery.json') and not x.endswith('fastboot.json')] json_data = [] for file in json_files: ...
33,847
def fields_for_model(model): """ This function returns the fields for a schema that matches the provided nautilus model. Args: model (nautilus.model.BaseModel): The model to base the field list on Returns: (dict<field_name: str, graphqlType>): A mapping of f...
33,848
def install(packages, installer=None, upgrade=False, use_sudo=False): """ Install Python packages with distribute """ func = use_sudo and sudo or run if not isinstance(packages, basestring): packages = " ".join(packages) options = [] if upgrade: options.append("-U") optio...
33,849
def _landstat(landscape, updated_model, in_coords): """ Compute the statistic for transforming coordinates onto an existing "landscape" of "mountains" representing source positions. Since the landscape is an array and therefore pixellated, the precision is limited. Parameters ---------- lan...
33,850
def presence(label): """Higher-order function to test presence of a given label """ return lambda x, y: 1.0 * ((label in x) == (label in y))
33,851
def get_config(config_file=None, section=None): """Gets the user defined config and validates it. Args: config_file: Path to config file to use. If None, uses defaults. section (str): Name of section in the config to extract (i.e., 'fetchers', 'processing', '...
33,852
def make_formula(formula_str, row, col, first_data_row=None): # noinspection SpellCheckingInspection """ A cell will be written as a formula if the HTML tag has the attribute "data-excel" set. Note that this function is called when the spreadsheet is being created. The cell it applies to knows ...
33,853
def plot_loss_curve(train_loss, val_loss, title="", save=False, fname=""): """Plot the training and validation loss curves Args: train_loss (list): Training loss values val_loss (list): Validationloss values title (str): Plot title save (bool): Whether to save the plot ...
33,854
def select(population, to_retain): """Go through all of the warroirs and check which ones are best fit to breed and move on.""" #This starts off by sorting the population then gets all of the population dived by 2 using floor divison I think #that just makes sure it doesn't output as a pesky decimal. The...
33,855
def normal_function( sigma, width ): """ Defaulf fitting function, it returns values from a normal distribution """ log2 = log(2) sigma2 = float(sigma)**2 lo, hi = width, width+1 def normal_func(value, index): return value * exp( -index*index/sigma2 * log2 ) va...
33,856
def style_get_url(layer, style_name, internal=True): """Get QGIS Server style as xml. :param layer: Layer to inspect :type layer: Layer :param style_name: Style name as given by QGIS Server :type style_name: str :param internal: Flag to switch between public url and internal url. Publ...
33,857
def remove_duplicates(l): """ Remove any duplicates from the original list. Return a list without duplicates. """ new_l = l[:] tmp_l = new_l[:] for e in l: tmp_l.remove(e) if e in tmp_l: new_l.remove(e) return new_l
33,858
def in_boudoir(callback): """Décorateur : commande utilisable dans un boudoir uniquement. Lors d'une invocation de la commande décorée hors d'un boudoir (enregistré dans :class:`.bdd.Boudoir`), affiche un message d'erreur. Ce décorateur n'est utilisable que sur une commande définie dans un Cog. ...
33,859
def parse_input(): """ Sets up the required input arguments and parses them """ parser = argparse.ArgumentParser() parser.add_argument('log_file', help='CSV file of log data') parser.add_argument('-e, --n_epochs', dest='n_epochs', help='number of training epochs', metavar='', ...
33,860
def xyz_to_pix(position, bounds, pixel_size): """Convert from 3D position to pixel location on heightmap.""" u = int(np.round((position[1] - bounds[1, 0]) / pixel_size)) v = int(np.round((position[0] - bounds[0, 0]) / pixel_size)) return (u, v)
33,861
def main(): """ Main function for this module """ sandbox = create_sandbox() directory = download_package_to_sandbox( sandbox, 'https://pypi.python.org/packages/source/c/checkmyreqs/checkmyreqs-0.1.6.tar.gz' ) print(directory) destroy_sandbox(sandbox)
33,862
def get_random_lb(): """ Selects a random location from the load balancers file. Returns: A string specifying a load balancer IP. """ with open(LOAD_BALANCERS_FILE) as lb_file: return random.choice([':'.join([line.strip(), str(PROXY_PORT)]) for line in lb_file])
33,863
def enlarge(n): """ Multiplies a number by 100 Param: n (numeric) the number to enlarge Return the enlarged number(numeric) """ return n * 100
33,864
def ResolveWikiLinks(html): """Given an html file, convert [[WikiLinks]] into links to the personal wiki: <a href="https://z3.ca/WikiLinks">WikiLinks</a>""" wikilink = re.compile(r'\[\[(?:[^|\]]*\|)?([^\]]+)\]\]') def linkify(match): wiki_root = 'https://z3.ca' wiki_name = match.group(1).replace('\n', '...
33,865
def handle_new_favorite(query_dict): """Does not handle multi-part data properly. Also, posts don't quite exist as they should.""" for required in POST_REQUIRED_PARAMS: if required not in query_dict: return False # not yet safe to use. post_id = str(string_from_interwe...
33,866
def steam_ratings(html_text): """Tries to get both 'all' and 'recent' ratings.""" return { "overall": steam_all_app_rating(html_text), "recent": steam_recent_app_rating(html_text), }
33,867
def separation_cos_angle(lon0, lat0, lon1, lat1): """Evaluate the cosine of the angular separation between two direction vectors.""" return (np.sin(lat1) * np.sin(lat0) + np.cos(lat1) * np.cos(lat0) * np.cos(lon1 - lon0))
33,868
def getArg(flag): """ Devolve o argumento de uma dada flag """ try: a = sys.argv[sys.argv.index(flag) + 1] except: return "" else: return a
33,869
def get_band_params(meta, fmt='presto'): """ Returns (fmin, fmax, nchans) given a metadata dictionary loaded from a specific file format. """ if fmt == 'presto': fbot = meta['fbot'] nchans = meta['nchan'] ftop = fbot + nchans * meta['cbw'] fmin = min(fbot, ftop) ...
33,870
def logging(f): """Decorate a function to log its calls.""" @functools.wraps(f) def decorated(*args, **kwargs): sargs = map(str, args) skwargs = (f'{key}={value}' for key, value in kwargs.items()) print(f'{f.__name__}({", ".join([*sargs, *skwargs])})...') try: va...
33,871
def yandex_mean_encoder(columns=None, n_jobs=1, alpha=100, true_label=None): """ Smoothed mean-encoding with custom smoothing strength (alpha) http://learningsys.org/nips17/assets/papers/paper_11.pdf """ buider = partial( build_yandex_mean_encoder, alpha=alpha, ) return Tar...
33,872
def cure_sample_part( X: np.ndarray, k: int, c: int = 3, alpha: float = 0.3, u_min: Optional[int] = None, f: float = 0.3, d: float = 0.02, p: Optional[int] = None, q: Optional[int] = None, n_rep_finalclust: Optional[int] = None, plotting: bool = True, ): """ CURE algo...
33,873
def get_serializer(request): """Returns the serializer for the given API request.""" format = request.args.get('format') if format is not None: rv = _serializer_map.get(format) if rv is None: raise BadRequest(_(u'Unknown format "%s"') % escape(format)) return rv # we...
33,874
def deserialize_result(r: bytes, *, deserializer: Optional[Deserializer] = None) -> JobResult: """Given bytes, deserializes them into a JobResult object. :param r: bytes to deserialize. :param deserializer: Optional serializer to use for deserialization. If not set, pickle is used. :return: A JobResul...
33,875
def test_explode(): """ Plenty of systems use dice that explode on their maximum value. """ assert (dice.d6.explode() > 6).to_dict()[True] == pytest.approx(1 / 6) assert (dice.d6.explode() > 12).to_dict()[True] == pytest.approx(1 / 36) # Limit the number of times the die is re-rolled mini_ex...
33,876
def form_symb_dCdU(): """Form a symbolic version of dCdU""" dCdU = form_nd_array("dCdU",[3,3,8*12]) for I in range(3): for J in range(3): for K in range(3,8*12): dCdU[I,J,K] = 0 return dCdU
33,877
def predict(X, y, clf, onehot_encoder, params): """ Runs a forward pass for a SINGLE sample and returns the output prediction. Arguments: X (list[int]) : a list of integers with each integer an input class of step y (list[int]) : a list of integers with each integer an output class of s...
33,878
def parse_modules_and_elabs(raw_netlist, net_manager): """ Parses a raw netlist into its IvlModule and IvlElab objects. Returns a tuple: (modules, elabs) modules is a list of IvlModule objects. elabs is a list of IvlElab objects. """ sections = parse_netlist_to_sections(raw_netlist) mod...
33,879
def scrub_dt_dn(dt, dn): """Returns in lowercase and code friendly names of doctype and name for certain types""" ndt, ndn = dt, dn if dt in lower_case_files_for: ndt, ndn = scrub(dt), scrub(dn) return ndt, ndn
33,880
def selobj_add_read_obj(selobj, callback, *callback_args, **callback_kwargs): """ Add read selection object, callback is a co-routine that is sent the selection object that has become readable """ global _read_callbacks coroutine = callback(*callback_args, **callback_kwargs) _read_callbacks...
33,881
def by_uri(uri): """A LicenseSelector-less means of picking a License from a URI.""" if _BY_URI_CACHE.has_key(uri): return _BY_URI_CACHE[uri] for key, selector in cc.license.selectors.SELECTORS.items(): if selector.has_license(uri): license = selector.by_uri(uri) _B...
33,882
def assignmentStatement(node): """ assignmentStatement = variable "=" expression ";". """ identifierNode = Node(token) consume(IDENTIFIER) operatorNode = Node(token) consume("=") node.addNode(operatorNode) operatorNode.addNode(identifierNode) expression(operatorNode) consume(";")
33,883
def read_S(nameIMGxml): """ This function extract the images's center from the xml file. Parameters ---------- nameIMGxml : str the name of the file generated by MM3D. Usually, it is "Orientation-Im[n°i].JPG.xml" Returns ------- numpy.ndarray: the center of the IMG ...
33,884
def AddBatchJob(client): """Add a new BatchJob to upload operations to. Args: client: an instantiated AdWordsClient used to retrieve the BatchJob. Returns: The new BatchJob created by the request. """ # Initialize appropriate service. batch_job_service = client.GetService('BatchJobService', versio...
33,885
def bellmanFord(obj,source): """Determination of minimum distance between vertices using Bellman Ford Algorithm.""" validatePositiveWeight(obj) n = CountVertices(obj) minDist = dict() for vertex in obj.vertexList: if vertex == source: minDist[vertex] = 0 else: ...
33,886
def test_my_sum() -> None: """Evaluate the output of `my_sum` by creating 2 random integers. The ground truth is given by the python function `sum`. """ x_val = random.randrange(999) y_val = random.randrange(999) assert my_sum(x_val, y_val) == sum([x_val, y_val])
33,887
def auto_default_option(*param_decls, **attrs) -> Callable[[_C], _C]: """ Attaches an option to the command, with a default value determined from the decorated function's signature. All positional arguments are passed as parameter declarations to :class:`click.Option`; all keyword arguments are forwarded unchanged...
33,888
def get_filename_from_url(url): """ Convert URL to filename. Example: URL `http://www.example.com/foo.pdf` will be converted to `foo.pdf`. :type url: unicode :rtype: unicode """ name, extension = os.path.splitext(os.path.basename(urlsplit(url).path)) fin = "{filename}{extensi...
33,889
def properties(debugger, command, exe_ctx, result, internal_dict): """ Syntax: properties <className/classInstance> Examples: (lldb) properties UIViewController (lldb) properties [NSObject new] (lldb) expression -l objc -O -- [NSObject new] <NSObject: 0x60000372f760...
33,890
def test_path_functionality1(): """testing path functionality in detail""" pos0 = np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4], [5, 5, 5.0]]) rot0 = R.from_quat( [(1, 0, 0, 1), (2, 0, 0, 1), (4, 0, 0, 1), (5, 0, 0, 1), (10, 0, 0, 1.0)] ) inpath = np.array([(0.1, 0.1, 0.1), (0.2, 0.2,...
33,891
def zCurve(seq): """Return 3-dimensional Z curve corresponding to sequence. zcurve[n] = zcurve[n-1] + zShift[n] """ zcurve = np.zeros((len(seq), 3), dtype=int) zcurve[0] = zShift(seq, 0) for pos in range(1, len(seq)): zcurve[pos] = np.add(zcurve[pos - 1], zShift(seq, pos)) return zc...
33,892
def getgeo(): """ Grabbing and returning the zones """ data = request.args.get('zone_name', None) print data #Check if data is null - get all zones out = [] if data: rec = mongo.db.zones.find({'zone_name':data}) else: rec = mongo.db.zones.find() for r in rec: r.p...
33,893
def test_maxwell_filter_additional(): """Test processing of Maxwell filtered data""" # TODO: Future tests integrate with mne/io/tests/test_proc_history # Load testing data (raw, SSS std origin, SSS non-standard origin) data_path = op.join(testing.data_path(download=False)) file_name = 'test_move_...
33,894
def update_meta(metatable, table): """ After ingest/update, update the metatable registry to reflect table information. :param metatable: MetaTable instance to update. :param table: Table instance to update from. :returns: None """ metatable.update_date_added() metatable.obs_from, me...
33,895
def photo_upload(request): """AJAX POST for uploading a photo for any given application.""" response = None if request.is_ajax() and request.method == 'POST': form = PhotoForm( data=request.POST, files=request.FILES, use_required_attribute=False, ) if form.is_valid(): ...
33,896
def table_str(bq_target): # type: (BigqueryTarget) -> str """Given a BigqueryTarget returns a string table reference.""" t = bq_target.table return "%s.%s.%s" % (t.project_id, t.dataset_id, t.table_id)
33,897
def any_to_any_translate_back(content, from_='zh-CN', to_='en'): """ 中英,英中回译 :param content:str, 4891个字, 用户输入 :param from_: str, original language :param to_: str, target language :return: str, result of translate """ translate_content = any_to_any_translate(content, from_=f...
33,898
def loop_helper(eq_dict, func, *args, **kwargs): """Loop over an equipment dictionary returned from one of the initialize_* functions and apply a function to each EquipmentSinglePhase object. I constantly find myself re-writing these annoying loops due to the poor design decision to allow the initi...
33,899