content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def plot_histogram(ax,values,bins,colors='r',log=False,xminmax=None): """ plot 1 histogram """ #print (type(values)) ax.hist(values, histtype="bar", bins=bins,color=colors,log=log, alpha=0.8, density=False, range=xminmax) # Add a small annotation. # ax.annotate('Annotation', ...
d11e89c005275a176fd00d0e2ac5173ee8f490b1
21,358
def build_model(): """Build the model. Returns ------- tensorflow.keras.Model The model. """ input_x = tf.keras.Input( shape=(30,), name='input_x' ) # shape does not include the batch size. layer1 = tf.keras.layers.Dense(5, activation=tf.keras.activations.tanh) lay...
81e2ee2533903beaa4a087613e63ea383d8a746b
21,359
import torch def evaluate_generator(generator, backbone_pool, lookup_table, CONFIG, device, val=True): """ Evaluate kendetall and hardware constraint loss of generator """ total_loss = 0 evaluate_metric = {"gen_macs":[], "true_macs":[]} for mac in range(CONFIG.low_macs, CONFIG.high_macs, 10):...
53941e29cae9a89c46ce598291638d7df28db4ff
21,360
def getCameras(): """Return a list of cameras in the current maya scene.""" return cmds.listRelatives(cmds.ls(type='camera'), p=True)
a3a6f202250f92c1cab46df92c78b53b15fd5cae
21,362
import re def convert_quotes(text): """ Convert quotes in *text* into HTML curly quote entities. >>> print(convert_quotes('"Isn\\'t this fun?"')) &#8220;Isn&#8217;t this fun?&#8221; """ punct_class = r"""[!"#\$\%'()*+,-.\/:;<=>?\@\[\\\]\^_`{|}~]""" # Special case if the very first chara...
82b5cabc2f4b77f5c39ab785c02e04ff4ca4f517
21,363
import warnings def time_shift(signal, n_samples_shift, circular_shift=True, keepdims=False): """Shift a signal in the time domain by n samples. This function will perform a circular shift by default, inherently assuming that the signal is periodic. Use the option `circular_shift=False` to pad with nan va...
f5017a5b9988ff5dc10e49b1f2d4127293564607
21,364
def get_avgerr(l1_cols_train,l2_cols_train,own_cols_xgb,own_cols_svm,own_cols_bay,own_cols_adab,own_cols_lass,df_train,df_test,experiment,fold_num=0): """ Use mae as an evaluation metric and extract the appropiate columns to calculate the metric Parameters ---------- l1_cols_train : list l...
74bfe9ce91f04a2ce3955098f9d1145c5c60ef4a
21,365
from operator import and_ def get_repository_metadata_by_changeset_revision( trans, id, changeset_revision ): """Get metadata for a specified repository change set from the database.""" # Make sure there are no duplicate records, and return the single unique record for the changeset_revision. Duplicate recor...
33f5da869f8fde08e2f83d7a60a708e4848664a1
21,366
import pickle import gc def generate_encounter_time(t_impact=0.495*u.Gyr, graph=False): """Generate fiducial model at t_impact after the impact""" # impact parameters M = 5e6*u.Msun rs = 10*u.pc # impact parameters Tenc = 0.01*u.Gyr dt = 0.05*u.Myr # potential parameters...
0871e3b6f09e9bf1154182a3d0a24713a90f2fbb
21,367
def get_census_centroid(census_tract_id): """ Gets a pair of decimal coordinates representing the geographic center (centroid) of the requested census tract. :param census_tract_id: :return: """ global _cached_centroids if census_tract_id in _cached_centroids: return _cached_centroid...
ba3dde30ce9bd3eab96f8419580edfda051c5564
21,368
def configure_context(args: Namespace, layout: Layout, stop_event: Event) -> Context: """Creates the application context, manages state""" context = Context(args.file) context.layout = layout sensors = Sensors(context, stop_event) context.sensors = sensors listener = KeyListener(context.on_key, ...
b24ee704939cf3f02774b6fe3c9399042247500a
21,369
def offsetEndpoint(points, distance, beginning=True): """ Pull back end point of way in order to create VISSIM intersection. Input: list of nodes, distance, beginning or end of link Output: transformed list of nodes """ if beginning: a = np.array(points[1], dtype='float') b =...
a6733d5670221fbd14b527d63430ebd94e022a5a
21,370
def _remove_parenthesis(word): """ Examples -------- >>> _remove_parenthesis('(ROMS)') 'ROMS' """ try: return word[word.index("(") + 1 : word.rindex(")")] except ValueError: return word
f47cce7985196b1a9a12284e888b4097b26c32f4
21,371
def check_closed(f): """Decorator that checks if connection/cursor is closed.""" def g(self, *args, **kwargs): if self.closed: raise exceptions.Error(f"{self.__class__.__name__} already closed") return f(self, *args, **kwargs) return g
fcb7f8399ae759d644e47b6f8e8a6b887d9315fc
21,372
def get_box_filter(b: float, b_list: np.ndarray, width: float) -> np.ndarray: """ Returns the values of a box function filter centered on b, with specified width. """ return np.heaviside(width/2-np.abs(b_list-b), 1)
2885133af9f179fa5238d4fc054abfd48f317709
21,373
def search(ra=None, dec=None, radius=None, columns=None, offset=None, limit=None, orderby=None): """Creates a query for the carpyncho database, you can specify""" query = CarpynchoQuery(ra, dec, radius, columns, offset, limit, orderby) return query
aad189695ef93e44aa455635dae2791843f7d174
21,374
def repetitions(seq: str) -> int: """ [Easy] https://cses.fi/problemset/task/1069/ [Solution] https://cses.fi/paste/659d805082c50ec1219667/ You are given a DNA sequence: a string consisting of characters A, C, G, and T. Your task is to find the longest repetition in the sequence. This is a ma...
4dde2ec4a6cd6b13a54c2eafe4e8db0d87381faa
21,375
def measure(data, basis, gaussian=0, poisson=0): """Function computes the dot product <x,phi> for a given measurement basis phi Args: - data (n-size, numpy 1D array): the initial, uncompressed data - basis (nxm numpy 2D array): the measurement basis Returns: - A m-sized numpy 1D ar...
0a25ea52a67441972b65cdad7c76cb772ec6bc6d
21,377
def getUserByMail(email): """Get User by mailt.""" try: user = db_session.query(User).filter_by(email=email).one() return user except Exception: return None
423d5dc969d43e0f4a1aafc51b5a05671a1fc3e1
21,378
def parse_headers(headers, data): """ Given a header structure and some data, parse the data as headers. """ return {k: f(v) for (k, (f, _), _), v in zip(headers, data)}
456c2ab2d2f7832076a7263be8815b9abeec56dd
21,379
def dataset_parser(value, A): """Parse an ImageNet record from a serialized string Tensor.""" # return value[:A.shape[0]], value[A.shape[0]:] return value[:A.shape[0]], value
0b07b6eec9e3e23f470970c489ad83c416d650e7
21,380
def default_csv_file(): """ default name for csv files """ return 'data.csv'
e0a1267e1e8e463d435f3116e970132c4eab949d
21,381
def download(object_client, project_id, datasets_path): """Download the contents of file from the object store. Parameters ---------- object_client : faculty.clients.object.ObjectClient project_id : uuid.UUID datasets_path : str The target path to download to in the object store Re...
91da7409b4cc518d87b6502e193a4174c045be0e
21,383
from pathlib import Path from typing import Any def get_assets_of_dataset( db: Session = Depends(deps.get_db), dataset_id: int = Path(..., example="12"), offset: int = 0, limit: int = settings.DEFAULT_LIMIT, keyword: str = Query(None), viz_client: VizClient = Depends(deps.get_viz_client), ...
344095c94884059ed37662521f346d6c03bb4c7f
21,384
def check_rule(body, obj, obj_string, rule, only_body): """ Compare the argument with a rule. """ if only_body: # Compare only the body of the rule to the argument retval = (body == rule[2:]) else: retval = ((body == rule[2:]) and (obj == obj_string)) return retval
9237da310ebcc30f623211e659ac2247efb36f69
21,385
from warnings import warn def pdm_auto_arima(df, target_column, time_column, frequency_data, epochs_to_forecast = 12, d=1, D=0, seasonal=True, m =12, ...
d5dd6d8ddf01358cde26f9e467e410419290da2e
21,386
def get_lines(filename): """ Returns a list of lines of a file. Parameters filename : str, name of control file """ with open(filename, "r") as f: lines = f.readlines() return lines
1307b169733b50517b26ecbf0414ca3396475360
21,387
def _check_socket_state(realsock, waitfor="rw", timeout=0.0): """ <Purpose> Checks if the given socket would block on a send() or recv(). In the case of a listening socket, read_will_block equates to accept_will_block. <Arguments> realsock: A real socket.socket() object to check for...
f4f493f03a2cd824a2bdc343f9367611011558eb
21,388
def str_to_pauli_term(pauli_str: str, qubit_labels=None): """ Convert a string into a pyquil.paulis.PauliTerm. >>> str_to_pauli_term('XY', []) :param str pauli_str: The input string, made of of 'I', 'X', 'Y' or 'Z' :param set qubit_labels: The integer labels for the qubits in the string, given in ...
3a5be0f84006979f9b7dbb6ed436e98e7554cf68
21,389
from typing import Type def _GetNextPartialIdentifierToken(start_token): """Returns the first token having identifier as substring after a token. Searches each token after the start to see if it contains an identifier. If found, token is returned. If no identifier is found returns None. Search is abandoned w...
e486ba1f5e9ee1b2d6c01aa5aa9d5d5270e0db10
21,390
def _challenge_transaction(client_account): """ Generate the challenge transaction for a client account. This is used in `GET <auth>`, as per SEP 10. Returns the XDR encoding of that transaction. """ builder = Builder.challenge_tx( server_secret=settings.STELLAR_ACCOUNT_SEED, cli...
a1762788077d7e9403c7e5d3b94e78cca11f0ce8
21,391
def mapCtoD(sys_c, t=(0, 1), f0=0.): """Map a MIMO continuous-time to an equiv. SIMO discrete-time system. The criterion for equivalence is that the sampled pulse response of the CT system must be identical to the impulse response of the DT system. i.e. If ``yc`` is the output of the CT system with an ...
6aa83119efcad68b1fdf3a0cbc5467c53d2a30bb
21,392
def normalize_type(type: str) -> str: """Normalize DataTransfer's type strings. https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer-getdata 'text' -> 'text/plain' 'url' -> 'text/uri-list' """ if type == 'text': return 'text/plain' elif type == 'url': return 'tex...
887c532218a7775ea55c6a39953ec244183af455
21,393
def _parity(N, j): """Private function to calculate the parity of the quantum system. """ if j == 0.5: pi = np.identity(N) - np.sqrt((N - 1) * N * (N + 1) / 2) * _lambda_f(N) return pi / N elif j > 0.5: mult = np.int32(2 * j + 1) matrix = np.zeros((mult, mult)) fo...
5afc399cc6f303ba35d7e7c6b6b039130fcd1b17
21,394
def get_log(id): """Returns the log for the given ansible play. This works on both live and finished plays. .. :quickref: Play; Returns the log for the given ansible play :param id: play id **Example Request**: .. sourcecode:: http GET /api/v2/plays/345835/log HTTP/1.1 **Exampl...
7a67f7b9d89df39824e566fcb11083be9d3f76e8
21,395
def filterLinesByCommentStr(lines, comment_str='#'): """ Filter all lines from a file.readlines output which begins with one of the symbols in the comment_str. """ comment_line_idx = [] for i, line in enumerate(lines): if line[0] in comment_str: comment_line_idx.append(i) ...
8a6ce56187afc2368ec81d11c38fe7af2eacb14f
21,396
def assemble_result_from_graph(type_spec, binding, output_map): """Assembles a result stamped into a `tf.Graph` given type signature/binding. This method does roughly the opposite of `capture_result_from_graph`, in that whereas `capture_result_from_graph` starts with a single structured object made up of tenso...
a25b4d935dfcb62acad15da5aeafee390b03a38c
21,397
def parse(peaker): # type: (Peaker[Token]) -> Node """Parse the docstring. Args: peaker: A Peaker filled with the lexed tokens of the docstring. Raises: ParserException: If there is anything malformed with the docstring, or if anything goes wrong with parsing. #...
abd8b495281c159f070a890a392d7a80da740fa4
21,398
import ctypes def sphrec(r, colat, lon): """ Convert from spherical coordinates to rectangular coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sphrec_c.html :param r: Distance of a point from the origin. :type r: float :param colat: Angle of the point from the positive Z...
d633b26cd6776d13b6d0e66a9366676c8b8ac962
21,400
import json def counter_endpoint( event=None, context=None ): """ API endpoint that returns the total number of UFO sightings. An example request might look like: .. sourcecode:: http GET www.x.com/counter HTTP/1.1 Host: example.com Accept: application/json, text/javascript ...
e492253f36736c112dcafc15d0e5c30cf27d5560
21,401
def search_trie(result, trie): """ trie search """ if result.is_null(): return [] # output ret_vals = [] for token_str in result: ret_vals += trie.find(token_str) if result.has_memory(): ret_vals = [ one_string for one_string in ret_vals if resu...
75ad08db7962b47ea6402e866cf4a7a9861037c9
21,402
def get_nb_entry(path_to_notes: str = None, nb_name: str = None, show_index: bool = True) -> str: """Returns the entry of a notebook. This entry is to be used for the link to the notebook from the table of contents and from the navigators. Depending on the value of the...
ec216cae586d2746af80ca88a428c6b907ad5240
21,403
def get_label_encoder(config): """Gets a label encoder given the label type from the config Args: config (ModelConfig): A model configuration Returns: LabelEncoder: The appropriate LabelEncoder object for the given config """ return LABEL_MAP[config.label_type](config)
8c7d6e9058af81c94cde039030fed12c4a65b8e6
21,404
def get_lesson_comment_by_sender_user_id(): """ { "page": "Long", "size": "Long", "sender_user_id": "Long" } """ domain = request.args.to_dict() return lesson_comment_service.get_lesson_comment_by_sender_user_id(domain)
7a20e44af39e2efc5cb83eedd9dfb74124a2777f
21,405
def _inertia_grouping(stf): """Grouping function for class inertia. """ if hasattr(stf[2], 'inertia_constant'): return True else: return False
a7689324ccabf601bf8beaec4c1826e8df25880b
21,406
def parse_input(raw_input: str) -> nx.DiGraph: """Parses Day 12 puzzle input.""" graph = nx.DiGraph() graph.add_nodes_from([START, END]) for line in raw_input.strip().splitlines(): edge = line.split('-') for candidate in [edge, list(reversed(edge))]: if candidate[0] == END: ...
1c38124fed386829d712041074cc76c891981498
21,407
def zonal_mode_extract(infield, mode_keep, low_pass = False): """ Subfunction to extract or swipe out zonal modes (mode_keep) of (y, x) data. Assumes here that the data is periodic in axis = 1 (in the x-direction) with the end point missing If mode_keep = 0 then this is just the zonal averaged field I...
a73015ac000668d11dd97ef0c8f435181fb0b9f7
21,408
import pickle def clone(): """Clone model PUT /models Parameters: { "model_name": <model_name_to_clone>, "new_model_name": <name_for_new_model> } Returns: - {"model_names": <list_of_model_names_in_session>} """ request_json = request.get_json() name = request...
49aaf81371f197858e4347efdfa04136e3342dc7
21,409
def GetFlagFromDest(dest): """Returns a conventional flag name given a dest name.""" return '--' + dest.replace('_', '-')
021ab8bca05afbb2325d865a299a2af7c3b939c9
21,410
def get_rst_export_elements( file_environment, environment, module_name, module_path_name, skip_data_value=False, skip_attribute_value=False, rst_elements=None ): """Return :term:`reStructuredText` from exported elements within *file_environment*. *environment* is the full :term:`Javascript` enviro...
4b3a055e47b7c859216b26ec50bf21bcec3af076
21,411
def ganache_url(host='127.0.0.1', port='7445'): """Return URL for Ganache test server.""" return f"http://{host}:{port}"
9de6e2c26c0e1235a14c8dd28040fcdfb8a36a7f
21,412
def to_news_detail_list_by_period(uni_id_list: list, start: str, end: str) -> list: """ 根据统一社会信用代码列表,获取企业在给定日期范围的新闻详情列表,使用串行 :param end: :param start: :param uni_id_list: :return: """ detail_list = [] for uni_id in ...
27493cc0f50a443cea69be74cd2bb1c494e1687f
21,413
from typing import List def positions_to_df(positions: List[alp_api.entity.Asset]) -> pd.DataFrame: """Generate a df from alpaca api assests Parameters ---------- positions : List[alp_api.entity.Asset] List of alpaca trade assets Returns ------- pd.DataFrame Processed dat...
5f77f4862f0244ba66e3d99e8a34e2dd8a56d91d
21,414
import requests from bs4 import BeautifulSoup def get_all_pages(date): """For the specific date, get all page URLs.""" r = requests.get(URL, params={"search": date}) soup = BeautifulSoup(r.text, "html.parser") return [ f"https://www.courts.phila.gov/{url}" for url in set([a["href"] fo...
f74e2167498fa8eb95e81c07c49a79b690adfcb2
21,415
from typing import List def boundary_condition( outer_bc_geometry: List[float], inner_bc_geometry: List[float], bc_num: List[int], T_end: float, ): """ Generate BC points for outer and inner boundaries """ x_l, x_r, y_d, y_u = outer_bc_geometry xc_l, xc_r, yc_d, yc_u = inner_bc_geo...
5941e213a7c48e39b79969d70b9a53a52207272f
21,416
def extractInfiniteNovelTranslations(item): """ # Infinite Novel Translations """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None tagmap = [ ('Ascendance of a Bookworm', 'Ascend...
0b31fcb764840242869eb3aa224b5f04d28beff8
21,417
def fill_diagonal(matrix, value, k=0, unpadded_dim=None): """ Returns a matrix identical to `matrix` except that the `k'th` diagonal has been overwritten with the value `value`. Args: matrix: Matrix whose diagonal to fill. value: The value to fill the diagonal with. k: The diagonal to fill. unpa...
d3dddf35b70788d832b6df119de8ba2760bb7fa7
21,418
from typing import Optional from typing import Callable import functools def container_model(*, model: type, caption: str, icon: Optional[str]) -> Callable: """ ``container_model`` is an object that keeps together many different properties defined by the plugin and allows developers to build user interfac...
e06ad5ab45f75fcc02550497e290fb8c07193645
21,420
def ward_quick(G, feature, verbose = 0): """ Agglomerative function based on a topology-defining graph and a feature matrix. Parameters ---------- G graph instance, topology-defining graph feature: array of shape (G.V,dim_feature): some vectorial information related to th...
a5c4e847bf6c70acfee1b5d5466b5310d40b528d
21,421
def conv3x3(in_planes, out_planes, stride=1, output_padding=0): """3x3 convolution transpose with padding""" return nn.ConvTranspose2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, output_padding=output_padding, ...
00c9b5123eaf408a1c4432b962739ec519851a59
21,422
def unwrap(func): """ Returns the object wrapped by decorators. """ def _is_wrapped(f): return hasattr(f, '__wrapped__') unwrapped_f = func while (_is_wrapped(unwrapped_f)): unwrapped_f = unwrapped_f.__wrapped__ return unwrapped_f
17aa0c8cc91578fd1187784ad0396ed91c5ec9b8
21,423
def get_payload_from_scopes(scopes): """ Get a dict to be used in JWT payload. Just merge this dict with the JWT payload. :type roles list[rest_jwt_permission.scopes.Scope] :return dictionary to be merged with the JWT payload :rtype dict """ return { get_setting("JWT_PAYLOAD_SCO...
d2192d2eef5cf6e5cc28d2125bef94c438075884
21,424
from typing import Dict def missing_keys_4(data: Dict, lprint=print, eprint=print): """ Add keys: _max_eval_all_epoch, _max_seen_train, _max_seen_eval, _finished_experiment """ if "_finished_experiment" not in data: lprint(f"Add keys _finished_experiment ...") max_eval = -1 for k1, v...
ad8d3f7c19dd4eefa0db465dd52b5e8dc8f0bd1e
21,425
def translate(txt): """Takes a plain czech text as an input and returns its phonetic transcription.""" txt = txt.lower() txt = simple_replacement(txt) txt = regex_replacement(txt) txt = chain_replacement(txt) txt = grind(txt) return txt
a7f35b7be14dfed0d9a4e68e2e3113d97f2468cb
21,426
def struct_getfield_longlong(ffitype, addr, offset): """ Return the field of type ``ffitype`` at ``addr+offset``, casted to lltype.LongLong. """ value = _struct_getfield(lltype.SignedLongLong, addr, offset) return value
24ff5e6b35de48bccf810bb9b723852f1ab16fb6
21,427
def subscribe(request): """View to subscribe the logged in user to a channel""" if request.method == "POST": channels = set() users = set() for key in request.POST: if key.startswith("youtube-"): channel_id = key[8:] if models.YoutubeChannel.ob...
6ee833eb6536f7958f74f274a776b31fab7051dc
21,428
from typing import OrderedDict import json def eval_accuracies(hypotheses, references, sources=None, filename=None, mode='dev'): """An unofficial evalutation helper. Arguments: hypotheses: A mapping from instance id to predicted sequences. references: A mapping from instance id to ground trut...
ede152bb51fcb53574eec0dfb84b6ca971289d5d
21,430
from datetime import datetime def perform_login(db: Session, user: FidesopsUser) -> ClientDetail: """Performs a login by updating the FidesopsUser instance and creating and returning an associated ClientDetail.""" client: ClientDetail = user.client if not client: logger.info("Creating client ...
013875ba1ca30615690d8d477e1246174bdc6279
21,431
def _bytestring_to_textstring(bytestring: str, number_of_registers: int = 16) -> str: """Convert a bytestring to a text string. Each 16-bit register in the slave are interpreted as two characters (1 byte = 8 bits). For example 16 consecutive registers can hold 32 characters (32 bytes). Not much of con...
474ac26b8fb3e454ce2747300c42b86df988ecc8
21,433
import numpy def sigma_XH(elem,Teff=4500.,M_H=0.,SNR=100.,dr=None): """ NAME: sigma_XH PURPOSE: return uncertainty in a given element at specified effective temperature, metallicity and signal to noise ratio (functional form taken from Holtzman et al 2015) INPUT: ele...
186974970505b21cb9978c8afcfbee1a9c0bf17c
21,434
from typing import Callable def lazy_load_command(import_path: str) -> Callable: """Create a lazy loader for command""" _, _, name = import_path.rpartition('.') def command(*args, **kwargs): func = import_string(import_path) return func(*args, **kwargs) command.__name__ = name # typ...
273e482412a079e5a59b84422ee409df7b3a7a1c
21,435
def tlam(func, tup): """Split tuple into arguments """ return func(*tup)
0e3a9b93b36795e6c11631f8c8852aba59724f88
21,436
from typing import Counter def sax_df_reformat(sax_data, sax_dict, meter_data, space_btw_saxseq=3): """"Function to format a SAX timeseries original data for SAX heatmap plotting.""" counts_nb = Counter(sax_dict[meter_data]) # Sort the counter dictionnary per value # source: https://stackoverflow.com...
6e241979d673910da2acfd522d1c32a3f1d815a8
21,437
def filter_not_t(func): """ Transformation for Sequence.filter_not :param func: filter_not function :return: transformation """ return Transformation( "filter_not({0})".format(name(func)), partial(filterfalse, func), {ExecutionStrategies.PARALLEL}, )
af548f7cfa60f5b598ad3527d8eaabca09aed4e6
21,438
def get_task_by_id(id): """Return task by its ID""" return TaskJson.json_by_id(id)
c1b1a4137cdab853e7d6c02167b914367120972a
21,439
def priority(floors, elevator): """Priority for a State.""" priority = 3 - elevator for i, floor in enumerate(floors): priority += (3 - i) * len(floor) return priority
b65abac24fb85f50425f2adfd4d98786b41c9a2d
21,440
from typing import Union from typing import List def get_user_groups(user_id: Union[int, str]) -> List[UserSerializer]: """ 获取指定 User 的全部 Groups Args: user_id: 指定 User 的 {login} 或 {id} Returns: Group 列表, 语雀这里将 Group 均视作 User. """ uri = f'/users/{user_id}/groups' method = ...
de02631693c6b31c566f93ee4cdc96bee3db024a
21,441
def user_news_list(): """ 新闻列表 :return: """ user = g.user page = request.args.get("page") try: page = int(page) except Exception as e: current_app.logger.error(e) page = 1 # 查询 news_list = [] current_page = 1 total_page = 1 try: pagin...
adc202bfdbf2c2e2d7d60c949fdad028a56b63c0
21,442
def unificate_link(link): """Process whitespace, make first letter upper.""" link = process_link_whitespace(link) if len(link) < 2: return link.upper() else: return link[0].upper() + link[1:]
4d9a5a4a88141f2a8e6400186c607615470cabde
21,443
def compute_vel_acc( robo, symo, antRj, antPj, forced=False, gravity=True, floating=False ): """Internal function. Computes speeds and accelerations usitn Parameters ========== robo : Robot Instance of robot description container symo : symbolmgr.SymbolManager Instance of symbol...
474729b9329ee21d4bcfffb33916d8d85a21ea62
21,444
def _sample_n_k(n, k): """Sample k distinct elements uniformly from range(n)""" if not 0 <= k <= n: raise ValueError("Sample larger than population or is negative") if 3 * k >= n: return np.random.choice(n, k, replace=False) else: result = np.random.choice(n, 2 * k) sele...
3aad3ed36590655ef079a4d39745d6c59ec499a8
21,445
def _all_usage_keys(descriptors, aside_types): """ Return a set of all usage_ids for the `descriptors` and for as all asides in `aside_types` for those descriptors. """ usage_ids = set() for descriptor in descriptors: usage_ids.add(descriptor.scope_ids.usage_id) for aside_type i...
75652e9468e6a61763b407bf11d644b1d08dd38c
21,446
def svn_client_invoke_get_commit_log2(*args): """svn_client_invoke_get_commit_log2(svn_client_get_commit_log2_t _obj, apr_array_header_t commit_items, void * baton, apr_pool_t pool) -> svn_error_t""" return _client.svn_client_invoke_get_commit_log2(*args)
fe7652c7e1573c3d688ddde40630b9b24e5bb48c
21,447
def round_extent(extent, cellsize): """Increases the extent until all sides lie on a coordinate divisible by cellsize.""" xmin, ymin, xmax, ymax = extent xmin = np.floor(xmin / cellsize) * cellsize ymin = np.floor(ymin / cellsize) * cellsize xmax = np.ceil(xmax / cellsize) * cellsize ymax = ...
384cf262f5dd206b0755623ce6d859e4f82efa86
21,448
def add_numbers(): """Add two numbers server side, ridiculous but well...""" #a = request.args.get('a', 0, type=str)#input from html a = request.args.get('a') print(a) result = chatbot.main(a) print("Result: ", result) #input from html returned=a #return jsonify(returned); retur...
d0e670ea0fc7bff33d5419316f5ebddf12cecea0
21,449
import re def _parse_stack_info(line, re_obj, crash_obj, line_num): """ :param line: line string :param re_obj: re compiled object :param crash_obj: CrashInfo object :return: crash_obj, re_obj, complete:Bool """ if re_obj is None: re_obj = re.compile(_match_stack_item_re()) com...
b360ef9c6d96092f59952fec90fdc41b2463c780
21,450
import math def Orbiter(pos,POS,veloc,MASS,mass): """ Find the new position and velocity of an Orbiter Parameters ---------- pos : list Position vector of the orbiter. POS : list Position vector of the centre object. veloc : list Velocity of the orbiter. MASS :...
8d6c08fc1a7fa1165550e13944c1dbda414e6e62
21,451
def build_heading(win, readonly=False): """Generate heading text for screen """ if not win.parent().albumdata['artist'] or not win.parent().albumdata['titel']: text = 'Opvoeren nieuw {}'.format(TYPETXT[win.parent().albumtype]) else: wintext = win.heading.text() newtext = '' ...
133f4111171ab0bd04bed82455ced9aa9dcc010b
21,452
def GetTraceValue(): """Return a value to be used for the trace header.""" # Token to be used to route service request traces. trace_token = properties.VALUES.core.trace_token.Get() # Username to which service request traces should be sent. trace_email = properties.VALUES.core.trace_email.Get() # Enable/dis...
67c1fc9d0602ca25c02dd088e1abba1ad951022f
21,453
from typing import Optional from typing import Union from typing import Tuple def sql( where: str, parameters: Optional[Parameters] = None ) -> Union[str, Tuple[str, Parameters]]: """ Return a SQL query, usable for querying the TransitMaster database. If provided, parameters are returned duplicated, ...
22ca2194f355deaa4fc55b458c1f1a013ab2902e
21,455
def clip(a, a_min, a_max): """Clips the values of an array to a given interval. Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of ``[0, 1]`` is specified, values smaller than 0 become 0, and values larger than 1 become 1. Args: ...
0394b68329c48198ade9a3131c6c26940f09a154
21,456
def hole_eigenvalue_residual( energy: floatarray, particle: "CoreShellParticle" ) -> float: """This function returns the residual of the hole energy level eigenvalue equation. Used with root-finding methods to calculate the lowest energy state. Parameters ---------- energy : float, eV ...
500033e927c29595c67d2e2327ebe1ae6d39cfd0
21,457
def open_raster(filename): """Take a file path as a string and return a gdal datasource object""" # register all of the GDAL drivers gdal.AllRegister() # open the image img = gdal.Open(filename, GA_ReadOnly) if img is None: print 'Could not open %s' % filename sys.exit(1) el...
b1c002be50b59e74a327943af8613b11cddf9b88
21,458
def reduce2latlon_seasonal( mv, season=seasonsyr, region=None, vid=None, exclude_axes=[], seasons=seasonsyr ): """as reduce2lat_seasonal, but both lat and lon axes are retained. Axis names (ids) may be listed in exclude_axes, to exclude them from the averaging process. """ # backwards compatibility with...
7f101ce4ac5d4382d287901607c455b4d922f847
21,459
def GetFreshAccessTokenIfEnabled(account=None, scopes=None, min_expiry_duration='1h', allow_account_impersonation=True): """Returns a fresh access token of the given account or the active account. Same as GetAccessTo...
7716b44802d84aac1952e936166f3414459cbc4b
21,460
def unicode_to_xes(uni): """Convert unicode characters to our ASCII representation of patterns.""" uni = uni.replace(INVISIBLE_CRAP, '') return ''.join(BOXES[c] for c in uni)
4c6eebcf562804340ef683eec84e28002202d833
21,461
def AvailableSteps(): """(read-only) Number of Steps available in cap bank to be switched ON.""" return lib.Capacitors_Get_AvailableSteps()
210f1316beafcdef266858490411bb9f737cb3de
21,462
import re def modify_list(result, guess, answer): """ Print all the key in dict. Arguments: result -- a list of the show pattern word. guess -- the letter of user's guess. answer -- the answer of word Returns: result -- the list of word after modified. """ guess ...
9384ecd09659c55808a859dd613641ccac46c760
21,463
def f(p, snm, sfs): """ p: proportion of all SNP's on the X chromosome [float, 0<p<1] snm: standard neutral model spectrum (optimally scaled) sfs: observed SFS """ # modify sfs fs = modify(p, sfs) # return sum of squared deviations of modified SFS with snm spectrum: return np.sum( ...
b7d3c8ef188a5126fe7b817c78949fb9feec5b62
21,464
def get_N_intransit(tdur, cadence): """Estimates number of in-transit points for transits in a light curve. Parameters ---------- tdur: float Full transit duration cadence: float Cadence/integration time for light curve Returns ------- n_intransit: int Number of...
d126b5590a8997b8695c1a86360421f2bf4b8357
21,465