content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_rect_from_column_threshold(column, **kwargs): """ Input: single column containing a chamber, e.g. from get_column Return the column, but cropped at the "dead end" of the chamber, and also the length to which other columns will be cropped if not already found. Call with "maxheight" kwarg when alr...
c5e7a44ea42eadcfcbee9702911d6748db6810f4
70,000
import itk def range(imageOrFilter): """Return the range of values in a image of in the output image of a filter The minimum and maximum values are returned in a tuple: (min, max) range() take care of updating the pipeline """ img = output(imageOrFilter) img.UpdateOutputInformation() img....
5c3ec056208b0829cc081dc88faca28b59760481
70,001
def encodeTime(t): """ Calls the time2integer function by unpacking the list or tuple provided Args: date (tuple): year, month, day Returns: int: the number of seconds since the start of the epoch 1st January 1970 """ return time2integer(t[0],t[1],t[2])
4318f52a65d4ec360e58918cb93177a330610252
70,002
def create_model(config, num_classes=2): """Create a model, starting with a pre-trained checkpoint.""" model_kwargs = dict( config=config.model, n_classes=num_classes, ) model_def = modeling.BertForSequenceClassification.partial(**model_kwargs) if config.init_checkpoint: initial_params = impor...
bac802fc18655260b62cbeec22c059be266f0b00
70,003
def tango_to_katcp_text(text): """Convert Tango description text to KATCP compatible text. Description strings from Tango devices have latin-1 encoding, but KATCP expects utf-8. This is only in Python 2, not Python 3. """ if future.utils.PY2: decoded = text.decode(encoding='latin-1') ...
b5a316534e5f91e24414f103fd7b28a923ec5ffa
70,004
from typing import Optional from datetime import datetime from typing import Union def validate_datetime( value: object, allow_null: bool = False, minimum: Optional[datetime.datetime] = None, maximum: Optional[datetime.datetime] = None, extra_error_msg: str = None, ) -> Union[datetime.datetime, No...
86d5e7db54338cc3f2372e275e6d0490aea14400
70,005
import os def xml_path_completion(xml_path): """ Takes in a local xml path and returns a full path. if @xml_path is absolute, do nothing if @xml_path is not absolute, load xml that is shipped by the package """ if xml_path.startswith("/"): full_path = xml_path else: ...
a5d92d0e21f200b82dfcf7e75d6031c6e1466187
70,006
def get_volume_type(ctxt, id, expected_fields=None): """Retrieves single volume type by id.""" if id is None: msg = _("id cannot be None") raise exception.InvalidVolumeType(reason=msg) if ctxt is None: ctxt = context.get_admin_context() return db.volume_type_get(ctxt, id, expec...
10449cc5cf852237be5d7dda9c7d3c324e212178
70,007
def diag(v): """ @param v: the vector to put in the diagonal @type v: cvxopt dense matrix @return: diagonal matrix @rtype: cvxopt dense matrix """ result = co.matrix(0.0, (v.size[0], v.size[0])) for i, x in enumerate(v): result[i, i] = x return result
649962a4dff2c9722ed0b8b088d143d0b9238a41
70,008
def calculate_unitary(programs, symbol_names, symbol_values): """Calculate the unitary matrix for the given circuits. >>> qubit = cirq.GridQubit(0, 0) >>> symbol = sympy.Symbol('alpha') >>> my_circuit = cirq.Circuit(cirq.H(qubit) ** symbol) >>> tensor_circuit = tfq.convert_to_tensor([my_circuit]) ...
bd4d65e94e79d33d3cc06e1a28af284cc6b82afa
70,009
import struct def nano_get_key(path, key_mask, debug=False): """ derive and obtain master key from nano :param path: derivation path :param key_mask: which parts of key to return :param debug: dump transission in hex :return: a tuple (uncompressed pub key, priv key, chaincode) as specified in ...
78c57b43326eb3afaf126802f499522290c9c428
70,010
def build_network(settings): """ Build a Pandana network from CSV files """ logger.info('building pandana network') network_settings_file = settings['network_settings_file'] if not network_settings_file: logger.error("Please specify 'network_settings_file' in settings") return ...
278da24bc0e94b09fc329390032e517b2dc98b3f
70,011
import os def get_chunk_mos_Resnet(): """ Extract frame features from Resnet50 of individual chunks and stored in Numpy npy files :return: Dictionary containing video id, full MOS, chunk1 MOS, chunk2 MOS, chunk3 MOS """ chunk_mos_dict = dict() ugc_mos_file = r'C:\vq_datasets\ugc_mo...
89d482e0e024063187826ff3adf77d0e0624a8d9
70,012
def parse_args(args): """Parse command line arguments. Returns list of (data) files that need to be processed -- /unless/ the -A (--generate-all) option is passed, in which case superfluous data files are ignored... """ global add_legend, output_file, title_str, type, verbose global generate_all prog = args[...
7e080b1f5c0ed894099b1354ea0498470663a0bd
70,013
def get_enrichment_plots(enrichment_results, identifier, args): """ This function generates a scatter plot with enriched terms (y-axis) and their adjusted pvalues (x-axis) :param dataframe enrichment_results: dataframe with the enrichment data to plot (see enrichment functions for format) :param str id...
b918217c10a5dc91e675e5e236d173682f13a4a8
70,014
import io def load_img(img_path): """This Function loads the image, corrects the channels (in case if it is not a 4D image file) and returns the dimensions of the file with a boolean of whether it is a RGB file""" img = io.imread(img_path) img, use_RGB = correct_channels(img) if img.shape[-1]==3: ...
7cff625728bfe4d02da46637439bce773ae7ebe5
70,015
import os def getFrameLabels(states, nFrames, **kw): """ Given a DataFrame with states, call pickFrames to create a DataFrame with nFrames per state containing the state information, filename and imgFile (the name of the file to be used when writing an image) Args: - states: DataFrame contain...
a835e3879fc55f5984d446295ad99e4a5f697475
70,016
from typing import Union from typing import List def _validate_batch_seed_values( batch: Batch, seed_values: Union[dict, List[dict]] ) -> Union[str, List[str]]: """Validate that seed values line up with the first N columns in a batch. Also construct an appropiate seed string based on the values in the bat...
491e93a081af22924fb787ee1e7af875386ea6c0
70,017
from skimage.external import tifffile def pts_to_img(pts, shape, path): """Saves a set of points into a binary image Parameters ---------- pts: an (N, D) array with N D-dimensional points shape: a tuple describing the overall shape of the image path: path to save the output tiff image Re...
a5f06bbd9c54d653398235c9e6f863694faa8340
70,018
def create_network_settings(neutron, network): """ Returns a NetworkSettings object :param neutron: the neutron client :param network: a SNAPS-OO Network domain object :return: """ return NetworkSettings( name=network.name, network_type=network.type, subnet_settings=create_su...
142ab27fc9dea838796434ded990f6db5c5e02e5
70,019
def add_sensorgroup_filter_by_sensor(query, value): """Adds an sensorgroup-specific filter to a query. Filters results by sensor id if supplied value is an integer. Filters results by sensor UUID if supplied value is a UUID. Otherwise attempts to filter results by name :param query: Initial query ...
9aa9bc6a42cb58c98c15de66b3ce1a29432865fd
70,020
def user_feedback_articles(users): """API-endpoint for requesting user_feedback for articles, 'user_id' must be one or more ids separated by comma.""" return jsonify(db.get_user_feedback_articles(users))
af9b762f59ed85fa7fdd9a9bb09757eb11abd5d4
70,021
def encode_frame(frame): """ Encodes an APRS frame-as-dict as a KISS frame. :param frame: APRS frame-as-dict to encode. :type frame: dict :return: KISS-encoded APRS frame. :rtype: str """ enc_frame = ''.join([ encode_callsign(create_callsign(frame['destination'])), enco...
8431abe37cad2650043793519bea6ac9b86cdfeb
70,022
import re def sanitize(text, new_value=''): """ Removes HTML tags that can be executed, used to download from or link to external resources. """ # if input type is anything but string, return as-is # not enforcing type in parameters since we don't want this to fail with a non string type if n...
e3fda4b348a4e32fb6a5cd3f82c44555f374d264
70,023
import glob def png2fea(dir_name): """ Loads all *.png images from directory dir_name into a dictionary. Keys are the file names and values and 2D numpy arrays with corresponding grayscale images """ features = {} for f in glob(dir_name + '/*.png'): print('Processing file: ', f) ...
885406384ed810a6677c400e956eb1ce1947c2a0
70,024
import sys def art_to_url(tid, artifacts, repo, bucket): """Given an list of artifacts from a task object, return tuple of names and urls""" if "/" not in repo: raise RuntimeError(f"Expecting slash sep. repo. owner and name: '{repo}'") result = [] # N/B: Structure comes from query in get_raw_t...
10a6840ced9689b24507e2391b7f8a4cadd1aead
70,025
import datetime import calendar def getWeekday(year, month, day): """ input: integers year, month, day output: name of the weekday on that date as a string """ date = datetime.date(year, month, day) return calendar.day_name[date.weekday()]
ca5164b6d7243033f57c3a803301ff3c3ec13d29
70,026
def delete(event, context): """ Delete a given scheduled scrape. """ cloudwatch_events = boto3.client("events") rule_name = event["pathParameters"]["rule_name"] rules = cloudwatch_events.list_rules(NamePrefix=rule_name)["Rules"] if len(rules) != 1: if len(rules) == 0: res...
4425e5d9f0be50eaf4b7d915b88c0838c9056d99
70,027
def main(args=None): """Console script for osna.""" return 0
09202d5e071798d90800122cc0ba5f1e55dd81f5
70,028
def load_velodyne_points(filename): """Load 3D point cloud from KITTI file format (adapted from https://github.com/hunse/kitti) """ points = np.fromfile(filename, dtype=np.float32).reshape(-1, 4) points[:, 3] = 1.0 # homogeneous return points
2114e7db090fb5d2d14dd5ac5402b8fef1139c12
70,029
def rivers_with_station(stations): """Creates a list of rivers with at least 1 station""" rivers = [] for i in stations: if i.name != None: if i.river not in rivers: rivers.append(i.river) return rivers
f935e97dca96a94d7d3e839b9b5178b701799e08
70,030
def tree_leaves(root, follow=is_seqcont, children=iter): """Lists tree leaves.""" return list(itree_leaves(root, follow, children))
cd5046bc3fd4e6a5f073cfdaa39e9c47b703065f
70,031
def build_joint_test_es_senseval_gloss_corpus(_basepath,verbose=True): """ Given filepath to base folder of semseval 3 spanish corpus containing the xml.gz files Parses corpus and generates joint context-gloss pairs from wordnet glosses """ _dict_fileref = find_files(_basepath,'MiniDir.xml') _tes...
201d3dade2cdc6364a0f2f5854ce751ae54ac111
70,032
def get_download_cache_dir() -> str: """Returns full path to download cache directory.""" if cache_dir: return cache_dir return join(config_dir, 'cache')
d85624369189d43c8c22eedac81c6d0d289b8057
70,033
def _extract_script_class(module): """Return the subclass of decu.Script found in module.""" for obj in module.__dict__.values(): if isinstance(obj, type) and decu.Script in obj.__bases__: return obj
3e186880531cc6ecc8787ad420edfb65b2faefd1
70,034
import random def create_person_json() -> dict: """ This method returns a new person in JSON format. The age and gender are chosen randomly. The name is created using a third-party lib, based on the person gender. """ age = random.randint(18, 90) gender = "female" if random.choice([True, F...
4956e2c13099b34854ec1190879eae4e96436362
70,035
def weightsP1D(k, m, dx): """ Computes the m+1 weights of P Arguments: k (int): Order of accuracy m (int): Number of cells dx (float): Step size Returns: :obj:`ndarray` containing weights of P """ G = grad1D(k, m, dx) b = np.append(np.insert(np.zeros((m, 1)), ...
11fc31d536c61c946df897071e71d3d6e3960785
70,036
def mutation_remove_audioobject_exampleofwork(audioobject_identifier: str, work_identifier: str): """Returns a mutation for removing that a AudioObject is an example of a work (https://schema.org/exampleOfWork). Arguments: audio_object_identifier: The unique identifier of the AudioObject. w...
006383e8a2e9d95554a3b68c433d13403f479806
70,037
def init_data(rand: bool = False) -> list: """Prepare the training data. Return the training data as a list with the last element in each sample being that sample's label. """ if not rand: result = [ [0.5, 0.4, 0], [0.8, 0.3, 0], [0.3, 0.8, 0], ...
23eb0089c9e4daf468171ad07fc33fb73befcbd0
70,038
def second_half(dayinput): """ second half solver: """ lines = dayinput.split('\n') result = None return result
e90ff0be6170541c2cbfb1727cc86d4ef2855474
70,039
def config_section_data(): """Produce the default configuration section for app.config, when called by `resilient-circuits config [-c|-u]` """ config_data = u"""[fn_create_webex_meeting] # this may also be the conference id for the developer sandbox webex_email= webex_password= webex_site= webex_site...
5e5a1ca7e3402ab177c5805404beb8baed318aaf
70,040
def generate_token() -> str: """Generate an random, secure, URL-safe token.""" return token_urlsafe()
ab6c99786ad42126c3b5299f13c24f03d449fe31
70,041
import os def create_key_bindings(editor): """ Create custom key bindings. This starts with the key bindings, defined by `prompt-toolkit`, but adds the ones which are specific for the editor. """ kb = KeyBindings() # Filters. @Condition def vi_buffer_focussed(): app = get...
75f8a6ff1e4049b15326581830d0d41c40890052
70,042
from typing import List import inspect def get_function_parameters_list(func) -> List[str]: """ Get parameter list of function `func`. Parameters ---------- func : Callable A function to get parameter list. Returns ------- List[str] Parameter list Examples --...
bff2ec37a5564b87e48abf964d0d42a55f809a16
70,043
def lazylist(fn): """A decorator to wrap function return values in `LazyList`""" def wrapped(*args, **kwargs): return LazyList(fn(*args, **kwargs)) return wrapped
acc3d464d23eaedea049b4c59615e414c6877c9d
70,044
def are_compatible_imgs(one_img, another_img): """Return true if one_img and another_img have the same shape. False otherwise. If both are nibabel.Nifti1Image will also check for affine matrices. Parameters ---------- one_img: nibabel.Nifti1Image or np.ndarray another_img: nibabel.Nifti1Im...
100b2101a46547d802b8567c361fa828f5a94787
70,045
import json def generate_api_queries(input_container_sas_url,file_list_sas_urls,request_name_base, caller,additional_args={},image_path_prefixes=None): """ Generate .json-formatted API input from input parameters. file_list_sas_urls is a list of SAS URLs to individual file lists ...
fc8bb3d6a2e93b003c6d9330b93d19f2d4f27c4a
70,046
def get_mesh_from_vertex(vertex): """ Returns corresponding mesh of the given vertex :param vertex: str :return: str """ return get_shape_from_component(vertex, 'vtx')
bee7c1223b9df1349b7fd1bcde7c77e8fd387f7f
70,047
def checkout_counter(request): """Expose the number of items in checkout.""" checkout = get_checkout_from_request(request) return {'checkout_counter': checkout.quantity}
d23f1b3cbd76c81d8b070c0a16073ad018d3e5a0
70,048
def get_vrt_driver(): """ Convenience function to get the VRT driver. """ return gdal.GetDriverByName("VRT")
f7cfeb6d5a71aa6f40ab30573049208b15e31646
70,049
def getSectionText(cd, sectionLabel=None ): """ """ markups = cd.getSectionMarkups(sectionLabel, returnSentenceNumbers=False) txt = " ".join([m.getText() for m in markups]) return txt
d4bcaa109f5774bd3f5a9abb5a11829061b0ca8f
70,050
def preprocessor(url, published): """ Given a url(a web url or a file object), the preprocessor identifies the type of the url and generates news article data and/or twitter data. :returns: Returns newsObject, tweeter object and error object """ news, tweet, error = None, None, None ...
7a6f8cfa84a2c2b2d2a9bbafa6954a6d8b2d2e50
70,051
def make_serializable(data): """Ensure data is serializable.""" if is_serializable(data): return data # if numpy array convert to list try: return data.tolist() except AttributeError: pass except Exception as e: logger.debug('{} exception ({}): {}'.format(type(e)...
e8b22715b114c0012dceade304b8a10e667d0b9a
70,052
def execute_device_action_command(client: MobileIronCoreClient, action: str) -> str: """ Returns results for a MobileIron Device Action :type client: ``MobileIronCoreClient`` :param client: MobileIron client to use :type action: ``str`` :pa...
b397c6b1f3a32ff364e2e19e09615836e4ca4e18
70,053
def search(coordinates): """Search for closest known locations to these coordinates. :param coordinates: A list of tuples of (latitude, longitude) coordinates. :type coordinates: list[tuple] """ gd = GeocodeData() return gd.query(coordinates)
c8c8883913b369b41cebd311331bc960befc8d93
70,054
def sfl_trhph_chloride(V_R1, V_R2, V_R3, T): """ Description: OOI Level 2 Vent Fluid Chloride Concentration TRHPHCC data product, which is calculated using data from the Temperature Resistivity Probe (TRHPH) instrument. Implemented by: 2013-05-01: Christopher Wingard. Init...
4c8f1ddcc9b99b1bf7d3e95f7dd929a267db145d
70,055
def retention_policy_get( database, name, user=None, password=None, host=None, port=None ): """ Get an existing retention policy. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retenti...
0c4e1ad31831d54d23a6860be7e3b4f0b1bbaf38
70,056
import os def setup_iterables(path): """ Sets up the iterables to work with and populates them with the data located at *path* """ abs_path = os.path.join(c.PRE_PATH, path) if_time_scn_ch = [[[channel] for channel in range(c.N_CHAN)] for scenario in range(c.N_SCN)] #...
eca5459986f12032067f08756ee84badd709520a
70,057
import torch def run_episode(env, Q, n_action): """ Run a episode given Q-values @param env: OpenAI Gym environment @param Q: Q-values @param n_action: action space @return: resulting states, actions and rewards for the entire episode """ state = env.reset() rewards = [] action...
0ab96c3d2c768befccebab5bc1af6b37f976594c
70,058
def json(value): """Safe jsonify filter.""" uncleaned = jsonlib.dumps(value) clean = bleach.clean(uncleaned) return mark_safe(clean)
56c5fafc2b33fa1f19f741b1c45a8405f05bf427
70,059
def resampleImage(image,resamplingfactor,conserve=True): """Resample an image by `resamplingfactor`. Parameters ---------- image : 2D array The 2D image array to be resampled. npix must be odd-valued. resamplingfactor : float The factor by which the the image sampling (number of p...
0d997c9a98ebc4e71d17a550d3e8b825b581271e
70,060
def _create_export_movie_task(videoid, movie, nfo_settings): """Create a task for a movie""" # Reset NFO export to false if we never want movies nfo name = '{title} ({year})'.format(title=movie['title'], year=movie['year']) return [_create_export_item_task(name, FOLDER_MOVIES, videoid, name, name, ...
45aa37affbc28ce068862c7af373f687d0a01543
70,061
import importlib def load_attr(name): """Load an attribute in format path.to.module:attribute.""" module_name, attr_name = name.split(":") module = importlib.import_module(module_name) attr = getattr(module, attr_name) return attr
90d7ecbf35a52d1b1ee3e9aeeb1e4263baf055a2
70,062
import html def layout(): """Main layout for the open requests tab.""" if is_logged_in(): user = get_current_user() else: return html.Div([html.Br(), html.H1("You must be logged in to do this")]) requests = user.get_requests_as_mentee() # type: List[Request] if not requests: ...
ae105868377cf4bb626e6ce8214c74289c2b0e09
70,063
import sys def get_worker(step, name, opts): """ Instantiate a worker. This is a factory function that instantiates a worker for a pipeline step, and passes any extra arguments to the worker constructor. Args: step (str): the pipeline step name. name (str): the name of the cl...
0218a14e0a32f9041345ac259782efcd94d0f8b2
70,064
def iou3d_7dof_box_pairwise(boxes1_length, boxes1_height, boxes1_width, boxes1_center, boxes1_rotation_z_radians, boxes2_length, boxes2_height, boxes2_width, boxes2_center, boxes2_rotation_z_radians): """Computes pairwise intersection...
285d2846835bd489c5f85c778177245b1765c465
70,065
def load(as_pandas=None): """ Load the Longley data and return a Dataset class. Parameters ---------- as_pandas : bool Flag indicating whether to return pandas DataFrames and Series or numpy recarrays and arrays. If True, returns pandas. Returns ------- Dataset instanc...
3e4781ba7c33d9588758e298db81690803228bae
70,066
def margin_of_error(samples): """Computes the margin of error for a set of samples. """ return critical_value(samples) * mean_standard_error(samples)
578cc66e482e5b7878ea2c38d4e792553aefc872
70,067
def borrarTarea(request,id): """ Eliminación de tareas y redirección a Tablero Utiliza metodo POST con id de tarea. En html hay un Modal de confirmación. """ if request.method=="POST": Tarea.objects.filter(id=id).delete() return redirect(to="Tablero")
46c46ffb64ebcace343a4edd743074eaf1811bd3
70,068
import math def onnx_rename_weights(onx): """ Renames ONNX initialiers to make sure their name follows the alphabetical order. The model is modified inplace. This function calls :func:`onnx_rename_names <mlprodict.onnx_tools.onnx_manipulations.onnx_rename_names>`. :param onx: ONNX model ...
7452011b7adc723af4262818ba369e349f66bcaf
70,069
def dp_make_weight(egg_weights, target_weight, memo={}): """ Find number of eggs to bring back, using the smallest number of eggs. Assumes there is an infinite supply of eggs of each weight, and there is always a egg of value 1. Parameters: egg_weights - tuple of integers, available egg weights sor...
8546ab2dd0394d2864c23a47ea14614df83ec2f7
70,070
def switch_player (who_play): """ Function for switch the player @type whoPlay: TypeOfPlayers @param whoPlay: The current player @rtype: TypeOfPlayers @return: Return the new user who play """ if (who_play == TypeOfPlayers.PLAYER): who_play = TypeOfPlayers.COMPUTER else: who_play ...
df8d87f8b13f4a8bcb79281b6d94ac2bb22c3c6f
70,071
def get_impact_dates(previous_model, updated_model, impact_date=None, start=None, end=None, periods=None): """ Compute start/end periods and an index, often for impacts of data updates Parameters ---------- previous_model : MLEModel Model used to compute default start/e...
b2e6966e0fe2213e504e913d8cd64dbe84fa815b
70,072
def FindMinCover(points, L, S, format='slash'): """ Find minimal binary interval cover which covers all points, under the constraints given by L and S :param points: collection of IPv4 IPs in string notation e.g. 10.0.0.1 :param L: maximum number of binary intervals :param S: maximum length of a bin...
bca3e1ae12dfc6da516dca123891f03bc5ea6dbb
70,073
from typing import Dict from typing import List def create_event_search( p: Process, search_data: Dict = {}, criteria: Dict = {}, fields: List = ["*"], query: str = None, time_range: Dict = {}, rows=1000, start: int = 0, ) -> Dict: """Perform an event search. Without anything ...
9256b5bb7dae24809b0820e88eed406ee8c14ce1
70,074
def sinh(x): """ Hyperbolic sine """ if isinstance(x, UncertainFunction): mcpts = np.sinh(x._mcpts) return UncertainFunction(mcpts) else: return np.sinh(x)
f3d1f1ec78420b90f8fcc5298547d0c8230e4d74
70,075
def unwrap_value(metadata, attr, default=None): """Gets a value like dict.get() with unwrapping it.""" data = metadata.get(attr) if data is None: return default return data[0]
fee5f12f0fba86e221fe722b5829a50706ccd5dc
70,076
def lookup_A_dns_record_for_ip(sought_ip): """search all DNS records in all domains for an A entry for the IP address""" # IP must match by exact string domains = get_list_of_domains() for domain in domains: records = get_domain_record_list(domain["id"]) for record in records: ...
47501e87a0f6936c5cd177b79b3fbef96014a8d3
70,077
def _get_requirements(requirements_file): # pylint: disable=g-doc-args """Returns a list of dependencies for setup() from requirements.txt. Currently a requirements.txt is being used to specify dependencies. In order to avoid specifying it in two places, we're going to use that file as the source of truth. ...
b1c78333ac42f577c98e3d99c05bf491eb6a888e
70,078
def format_replication_collection(body: Json) -> Json: """Format replication collection data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result: Json = {} if "planVersion" in body: result["plan_version"] = body["planVersion"] if "isRe...
f9f0f05541bb653b262305ec9d8ba875325551f7
70,079
def CreateSQLiteObject(dbname): """ 创建SQLite :param dbname: :return: """ if _SQLInstance.instance: _SQLInstance.instance.close() _SQLInstance.instance = SQLiteMgr(dbname) return _SQLInstance.instance
3375468237007b6d4f4ae899486e6a8829cf5899
70,080
async def validate_input(hass: core.HomeAssistant, data): """Validate the user input allows us to connect. Data has the keys from DATA_SCHEMA with values provided by the user. """ spm = SunPowerMonitor(data["host"]) name = "PVS {}".format(data["host"]) try: response = await hass.async_...
0b3603f188f2d9cdb98304d909981a95bfbbd6ae
70,081
import os def parse_row(row, csv_path): """ :param row: :param csv_path: :return: Parse a row of the CSV master file. """ table = row["table"] inputs_dir = os.path.join(csv_path, row["path"]) project_flag = True if int(row["project_input"]) else False project_is_tx = True if i...
afdabc7dd28f15d7a50e4e81af3434dbed588c80
70,082
def tap_imol_inv_time(ref): """tap imol inverse tapping for imol inverse model Args: - ref(ModelBlock2): reference to ModelBlock2 containing all info Returns: - tapping(tuple): tuple consisting of predict and fit tappings """ if ref.mdl['inv']['recurrent']: tap_pre_inv = tappi...
8c99c7664b78e3c657cc4df5515600df4e0cabdc
70,083
async def async_restore_arrangement(connection, name, window_id=None): """ Restore a window arrangement. """ request = _alloc_request() request.saved_arrangement_request.name = name request.saved_arrangement_request.action = iterm2.api_pb2.SavedArrangementRequest.Action.Value( "RESTORE")...
ec638717bff8560028be641b45c94efd5b2ea843
70,084
def _expected_rule_table(sorted_rules): """Build a table of the expected ACLSwitch output. :param sorted_rules: List of time enforced ACL rules sorted by time. :return: The formatted table. """ table = PrettyTable(["Rule ID", "Rule Time"]) for entry in sorted_rules: table.add_row([entry...
263b8b7413e7447be5bb7d990a90d6efe97ecedc
70,085
def production_env_KO_eval(input_file, model, universal, output_optknock, output_cons_prod): """ Do production envelope analysis on mutants with reaction knockouts Given the output of Optknock analysis, it evaluate the solutions by calculating the production envelope of the model variant with the r...
8a4f39211d2a8ae9c742c519a8c37b8f75ad62a0
70,086
def df_from(url, extension=None): """Load data from URL""" if extension is None: extension = url.split(".")[-1] if extension not in "csv tsv xls xlsx msgpack".split(): extension = "csv" if url.startswith("http:") or url.startswith("https:") or url.startswith("ftp:"): f = ...
2023a9cdc54e1484537b63f6f97fa7b335468472
70,087
def plot_behavioral_index_as_frac_of_courtship( exp, bnames, colors, show_points=True ): """ Parameters ---------- bnames : list of string Should always be in the following order ['tap', 'ori', 'sci'] """ fig, ax = plt.subplots() num_behaviors = len(bnames) n...
4584cc2ba4c3c22949d4c39eb4ef6789a7a5290b
70,088
def tonemapping_operator_simple(RGB): """ Performs given *RGB* array tonemapping using the simple method: :math:`\\cfrac{RGB}{RGB + 1}`. Parameters ---------- RGB : array_like *RGB* array to perform tonemapping onto. Returns ------- ndarray Tonemapped *RGB* array. ...
0e35769eeb1d52661d20977eb458c9c63eccbf88
70,089
def generate_hmackey(i, r, sr): """ 生成 hMac 密钥 :param i :param r :param sr :return: """ hmac_key = sha256_encrypt(i)[8: 12] + sha256_encrypt(r)[8: 16] + sha256_encrypt(sr)[8:12] return hmac_key
fa95c01ba36a4d06b8df5fb4e70ccc44e7a383ea
70,090
def get_frames(cmds): """ 添加命令列表中的粒子坐标到时序列 :param cmds: 命令列表 :return: 时序列 """ frame_list = [] seq_duration = get_max_frame(cmds) dx = seq_duration - len(frame_list) if dx >= 0: for i in range(0, dx + 1): frame_list.append([]) for cmd in cmds: index = ...
e251f285ea6739540251d6d74959b37e00f235ee
70,091
import inspect def update_index_check( index_name: str = None, doc_type: str = None, doc_uuid: str = None, index_params: dict = None, user: dict = None ): """ update an index if doesn't already exist""" log_.debug( "function : %s", inspect.stack()[0][3] ) log_.debug( "locals() : \n%s", pformat(loca...
5c17e8041bec2c6f55cfd909c34520069368e343
70,092
def getTimestamp(self): """Get timestamp (sec)""" return self.seconds + self.picoseconds*1e-12
0c913fdcd9a3ce07e31a416208a8488bd41cea81
70,093
def lazymap(func, seq): """ Lazy equivalent for the map builtin function. lazymap returns a LazyTuple whose contents are computed on demand by applying *func* to seq[i], where i is the index that's being accessed. """ if isinstance(seq, LazySequence): if seq.isTerminating(): ...
9ea778644800d6684b7f43f6983804870b509c98
70,094
from typing import List from typing import Optional def TcxTrackList(filename: str) -> List[tp.TrackPoint]: """Create a List[tp.TrackPoint] which maybe empty if no trkpt's found""" # Create a list of TrackPoints track: List[tp.TrackPoint] = [] elem: et.Element tree = et.parse(filename) root: ...
e90c6fb2341a16953017c2200e2e611f126cc784
70,095
import torch def logsumexp(tensor: torch.Tensor, dim: int = -1, keepdim: bool = False) -> torch.Tensor: """ A numerically stable computation of logsumexp. This is mathematically equivalent to `tensor.exp().sum(dim, keep=keepdim).log()`. This function is typically used for summing lo...
bd32459f6db3bcb38e9be3874478c2775271456c
70,096
def get_offers_formset(): """Helper method that returns a Django formset for a dynamic amount of FruitOffers.""" return modelformset_factory(FruitOffer, form=OfferForm, extra=1)
405e87956b2d65e03855a6eb6e99bb7c05713201
70,097
from pathlib import Path from typing import Optional def choose_file(root_dir: Path) -> Optional[Path]: """ Interactive loop to choose a file """ def _format(root_dir: Path, entry: str) -> str: f = root_dir / entry if f.is_dir(): return entry return f'{entry}\t({hum...
e0f77829053d7dcba5ea348d6c33e5cd2a13819e
70,098
def variable(name, shape, init= 'rand', initializers= { 'zero': tf.initializers.zeros() , 'unit': tf.initializers.ones() , 'rand': tf.glorot_uniform_initializer() }): """wraps `tf.get_variable` to provide initializer based on usage""" return tf.get_variable...
2094cf7240045c4da9953b8732265a278eee10aa
70,099