content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import operator def create_judgment_matrix(N,T,layers,v_r=[],actions=[],judgment_type="OPTIMISTIC"): """Creates a functionality map for input into the functionality parameter in the indp function. :param N: An InfrastructureNetwork instance (created in infrastructure.py) :param T: Number of timesteps to o...
cead11f406918ed290e845b4cd33a955783069f1
3,614,036
def vertically_partition_data(X, X_test, A_idx, B_idx): """ Vertically partition feature for party A and B :param X: train feature :param X_test: test feature :param A_idx: feature index of party A :param B_idx: feature index of party B :return: train data for A, B; test data for A, B ...
58a9c3869ca9189af7c3e387cdab988cb283e07f
3,614,037
from typing import Type from typing import Any def type_instantiate(attr_type: Type, **kwargs) -> Any: """ Instantiate a nominated type. """ while hasattr(attr_type, "__origin__"): attr_type = attr_type.__origin__ return attr_type(**kwargs)
a42893824f52ae2bff583014f3e824634e6417e2
3,614,038
import scipy def eval_tau(J, r, chieff, q, chi1, chi2, precomputedroots=None): """ Period of S as it oscillates from S- to S+ and back to S-. Call ---- tau = eval_tau(J,r,chieff,q,chi1,chi2,precomputedroots=None) Parameters ---------- J: float Magnitude of the total angular m...
04eea453e8c124c405a9e801bfba88fc691fba16
3,614,039
def make_change_dep_eval(dep,): """Produce an evaluation function that returns True if any change has happened on any occurence of the given dep""" def change_dep_eval(orig,modif): s1 = get_pairs(orig, dep) s2 = get_pairs(modif, dep) return s1 != s2, bool(s1) return change_dep_eval
0f3799832c24ce1d9021727f2917d5bb3e5ed1a9
3,614,040
from typing import Optional def get_verse_id(book: Book, chapter: int, verse: int) -> int: """ Given the Book enum, chapter number int, and verse number int return the verse id if it exists. :param book: :param chapter: :param verse: :return: the integer verse id for the given book, chapter, ...
f736a39a640c97473d110be214da534e0fc06010
3,614,041
def get_fitness(cell_type,cell_neighbour_types,DELTA,game,game_params): """returns fitness of single cell""" return 1+DELTA*game(cell_type,cell_neighbour_types,*game_params)
bfac50ecbe64911c145a9e6cbc9e872add774cbf
3,614,042
def patch_resource(url, body): """ Patch resource with the given json body :returns: http response data """ timer = Timer() response = Bridge_DAO().patchURL(url, PHEADER, body) log_data = "PATCH %s %s ==status==> %s" % (url, body, response.status) if not response.status == 200: ...
0dc2d2f47fc453d2902bed28158bc27be0f40101
3,614,043
def fetch_core_sketch(X, ss, **kwargs_rg): """ :param X: the tensor of dimension N :param ks: array of size N :param tensor_proj: True: use tensor random projection, otherwise, use normal one :return: [core_sketch:s_n\times s_n ...\times s_n, list of sketches phis, s_n\times I_n] """ ...
e197a823757634a5587d2aac21ad73a2be8266bb
3,614,044
def test_simplify(): """Test simplification of expr according to manual rules""" h1 = LocalSpace("h1") a = OperatorSymbol("a", hs=h1) b = OperatorSymbol("b", hs=h1) c = OperatorSymbol("c", hs=h1) d = OperatorSymbol("d", hs=h1) expr = 2 * (a * b * c - b * c * a) A_ = wc('A', head=Operat...
30e128cda58a4173fccc5f6507e6fd9926703373
3,614,045
import torch def linear_quantize_callback( inp: torch.Tensor, bits: int = 8, decimal: TensorOrInt = 5, channel_index: int = 1, ) -> torch.Tensor: """quantization function with type signature of [QuantizeCallback][qsparse.common.QuantizeCallback]. Args: inp (torch.Tensor): input tensor...
7e40b94c665135b3a95612992280a0902144ec99
3,614,046
from bs4 import BeautifulSoup import re from datetime import datetime def parse_post(content): """ parse response content :param content: string :return: Dict """ # parse content soup = BeautifulSoup(content, 'lxml') # get title mainTitle = soup.find('div', {'id': 'mainTitle'}) ...
352407882081cee1dbfd55a41d3beebe3ccb2bfa
3,614,047
from typing import Optional def get_ocean_token_address( address_file: str, network: Optional[str] = None, web3: Optional[Web3] = None ) -> str: """Returns the Ocean token address for given network or web3 instance Requires either network name or web3 instance. """ addresses = get_contracts_addres...
bf97f5de1e7258a9f8eef9f3c7277bd860f16928
3,614,048
def _get_relevant_items_by_timestamp( dataframe, col_user=DEFAULT_USER_COL, col_item=DEFAULT_ITEM_COL, col_rating=DEFAULT_RATING_COL, col_timestamp=DEFAULT_TIMESTAMP_COL, col_prediction=PREDICTION_COL, k=DEFAULT_K ): """Get relevant items for each customer def...
1ee48e1152d53bcf39017a1d667c2492af96599e
3,614,049
def check_encryption(value): """ check for the --???-encryption argument raise an exception if the given encryption is invalid """ value = value.lower() if value not in ['ssl', 'tls', 'starttls', 'none']: raise ArgumentTypeError(f'{value} is an unknown encryption. Use can use ssl...
bfb6c18de43c7cd8db6529717950231c327b808d
3,614,050
from typing import Union from typing import Dict from typing import Any import typing def FloatSlider( continuous_update: bool = True, description: str = "", description_tooltip: str = None, disabled: bool = False, layout: Union[Dict[str, Any], Element[ipywidgets.widgets.widget_layout.Layout]] = {...
6533130c79d4a3e108f454c94dd1e203272ce3d3
3,614,051
def _apply_feature_constraints(feature, min_value, max_value): """Constrains `feature` to be between `min_value` and `max_value`.""" if min_value is not None: feature = tf.math.maximum(feature, min_value) if max_value is not None: feature = tf.math.minimum(feature, max_value) return feature
85352d537cddf8409b02fdaa97b385dcc8a928c2
3,614,052
def configure_global_stackwise_virtual(device, domain=None): """ Enables global stackwise-virtual on target device Args: device ('obj'): Device object domain ('str'): Stackwise-virtual domain Returns: None Raises: SubCommandFailure """ ...
6f37c07ec94a488b29df909cf5fc826741a43b74
3,614,053
import six import hashlib def run_server(locker, register=True): """Runs tickets server.""" _LOGGER.info('Tickets server starting.') # no __init__ method. # # pylint: disable=W0232 class TicketLockerServer(gssapiprotocol.GSSAPILineServer): """Ticket locker server.""" @utils.e...
ed9ee1f0f8c0be63e9476f16c5fb4ecd26d15871
3,614,055
def verify_incall_state(log, ads, expected_status): """Verify phones in incall state or not. Verify if all phones in the array <ads> are in <expected_status>. Args: log: Log object. ads: Array of Android Device Object. All droid in this array will be tested. expected_status: If Tru...
a20f88770e92a6f61ac5376e3a7827cf3c82c1f2
3,614,056
from typing import Tuple import math def euclidean_distance( point: Tuple[float, float], origin: Tuple[float, float] = None ) -> float: """Calculate euclidean distance from the origin""" if origin is None: return math.sqrt(sum((p ** 2 for p in point))) else: assert len(origin) == len(p...
b248122c6700d90182d68a35a43c7ad47b968667
3,614,058
def perspective_edit(request, perspective_id, response_format='html'): """Perspective edit""" perspective = get_object_or_404(Perspective, pk=perspective_id) # Don't let users delete their last perspective other_perspectives = Perspective.objects.filter( trash=False).exclude(id=perspective_id) ...
353dcb3f963cc3aa82e69b42d83fb0f6d901927d
3,614,059
def _extract_key(obj): """Convert a handle or Event handle into a Database Event ID.""" if isinstance(obj, Event): return obj.id elif isinstance(obj, str): return obj raise TypeError('Must provide an Event or Event handle (string)')
1b4a3fb64d77ddc196238739f483246a7bf67cb1
3,614,060
def convolve_adjoint_filter(x, y, ndim, input_multi_channel=False, output_multi_channel=False, mode='full'): """Convolution adjoint. Args: x (array): input array with shape batch_shape + input_shape if input_multi_channel=False. Otherwise with shape ...
ec8e26c0a199600fec21ce0a400f9685054e0032
3,614,061
def getCompletedJobs(jobs): """ Gets all completed jobs """ completed_jobs = [] for job in jobs: if 'result' in job: completed_jobs.append(job) return completed_jobs
7193cae304fb0498f9fe50f0302e50699d7e96e3
3,614,062
def read_pergene_file(pergene_insertions_file,chrom): """Reading the pergene file , the information per gene , related to where it starts and ends in the genome. Parameters ---------- pergene_insertions_file : str absolute path of the per gene file location chrom : str Name of the ...
e9629c5a9621784be6eb6efbd1e8793f2ac5b67e
3,614,063
import math def gam_a98rgb(rgb): """Convert an array of linear-light a98-rgb in the range 0.0-1.0 to gamma corrected form.""" return [math.copysign(math.pow(abs(val), 256 / 563), val) for val in rgb]
6d2543dc28ac6533067ffe9b0a265ef093416f9e
3,614,064
import socket def conflictBetweenIPv4AndIPv6(): """ Is there a conflict between binding an IPv6 and an IPv4 port? Return True if there is, False if there isn't. This is a temporary workaround until maybe Twisted starts setting C{IPPROTO_IPV6 / IPV6_V6ONLY} on IPv6 sockets. @return: C{True} ...
bef744d6f066e3aafbe7644662d8d87e4b139abb
3,614,065
import copy def unlock_layer(wC, uC, noise=0.0): """ unlock a layer of a scale invariant MERA Args: wC, uC (list): MERA tensors noise (float): amplitude of noise to be added to the new layer Returns: wC, uC (list): new MERA tensors """ wC.append(copy.copy(wC[-1]))...
9bad36a4d31e8411a14fa13d520f13e2d71167b9
3,614,066
def conformal2geodetic(conformal_lat: "ndarray", ell: Ellipsoid = None, deg: bool = True) -> "ndarray": """ converts from conformal latitude to geodetic latitude like Matlab map.geodesy.ConformalLatitudeConverter.inverse() Parameters ---------- conformal_lat : "ndarray" conformal latit...
5a26f3b1cd8b0b43739db2f936a6b42c79bf6e19
3,614,067
def get_frame_subframe(sfn_sf): """ Get the frame and the subframe number from the received bitstring """ sfn_sf_list = [] frame_mask = ~((1<<4) - 1) frame = (sfn_sf & frame_mask) >> 4 sf_mask = ~(((1<<12) - 1) << 4) subframe = (sfn_sf & sf_mask) sfn_sf_list.append(frame) sf...
d623ef8c1fa97dfbd5b5ef2a99e52e045d5dd205
3,614,068
def make_renderer(nodes, use_binary_transport=False): """Creates the pydeck visualization for rendering""" view_state = pydeck.ViewState( offset=[0, 0], latitude=None, longitude=None, bearing=None, pitch=None, zoom=10, ) views = [pydeck.View(type="OrbitVi...
dc6438f4e48d5fc6fcd4eaca46603e1b0d022874
3,614,069
def get_secret_value(secret_name): """ get secret value from AWS Secrets Manager :param secret_name: name of the secret passed :return secret_value: value of the secret passed """ client = session.client(service_name='secretsmanager') secret_value = '' try: get_secret_value_respo...
70af6ce869ad816de15e99259868cc020071c217
3,614,070
import torch def true_positive_fraction(output, target): """True positive fraction of binary segmentation.""" output, target, was_numpy = _convert_to_torch(output, target) result = _true_positives(output, target) / (torch.sum(output) + torch.sum(target)) return _convert_to_scalar(result, was_numpy)
5c6a7f7df36213da5383c8105910e59fee539e97
3,614,071
def backend_parameter(func): """Decorator for parameters reading data from the backend. Errors are handled in a default way. """ def _func_wrapper(self: 'VehicleState', *args, **kwargs): # pylint: disable=protected-access if self._attributes is None: raise ValueError('No dat...
c12baada4759e475eb554eafffc0aff620f049ac
3,614,072
import re def _build_freetext_query(querystring): """ Parses the freetext argument 'nyckelord' in the following ways: 'word1 AND word2' => word1 and word2 '"word1"AND"word2"' => word1 and word2 '"word1 word2"' => word1 and word2 'word1 OR word2' => word1 or word2 '"word1"OR"word2"' => word...
53a717351c85323bf02df47ce87daab8b9497ae4
3,614,073
def get_course_list(only_active=True, sortedby="name"): """ Return a list of courses. By default only active courses. will be ordered by given field. [{id:, name:, title:}, ] """ clist = [] reload_if_needed() for course in COURSES: if only_active: if COURS...
ef0b4ef4606e9d3cb157efb34decb144caf8e8a7
3,614,074
def covars_for_custom_models_simple_training_data_4elements(): """ defines initial covars compatible with custom_models_simple_training_data_4elements above :return: covars (list of tuple) """ covars = [(0.0, -2.0, 2.0)] return covars
f21cfa472c03811758dfb5196594f93f6e8247c6
3,614,075
import six def create(ctxt, name, source_instance_id, description=None): """Creates migration. Raises: MigrationCreateFailed: If there is error during migration creation. InstanceNotReadyForMigration: Migrating instance failed pre-migration validations ...
25402f56013cc5da7d3483200f0ab94532332624
3,614,076
def get_asgi_application(): """ The public interface to Django's ASGI support. Return an ASGI 3 callable. Avoids making django.core.handlers.ASGIHandler a public API, in case the internal implementation changes or moves in the future. """ django.setup(set_prefix=False) return ASGIHandler()
5e3c760f58005ea84a623305661294f5e9724504
3,614,077
from typing import List from typing import Dict from typing import Union def generate_html(d: List[Dict[str, Union[str, bool]]]) -> str: """ Pass in a dict with a list of rows to include in a formatted table. This will return the HTML for the table. :param d: :return: html: HTML formatted tab...
f874c63735443bb3b68355905e59f5efbc5b50af
3,614,078
from typing import List from typing import Union def flip_random_flippable(reconstructed_edges: List[Edge], initial_weight: int) -> Union[int, None]: """ Flips a random flippable edge in the provided solution. Args: initial_weight: - Initial solution weight. reco...
0f7b4ebc5f99487e171d422554871b3d20833f33
3,614,079
import typing def _de_bruijn(k: int, n: int) -> typing.List[int]: """Generate a De Bruijn sequence. This is a piece of mathematical heavy machinery needed for O(1) ctz on integers of bounded size. The algorithm is adapted from chapter 7 of Frank Ruskey's "Combinatorial Generation". Args: ...
bbb86a4f0a7ef03bbce29126cc56e4fb3e41e288
3,614,080
def preprocess_data(x): """Preprocess data. Ensure x is 2d ndarray, and scale so that the mean absolute amplitude of each column is one. :param x: ndarray, shape (n_samples,) or (n_samples, n_features) :returns: float ndarray, shape (n_samples, n_features) """ x = np.array(x, dtype=np.float64)...
1d696d754db5849c7b092b3a70913ebf164b4df2
3,614,082
def left_edge_vertical_ids(shape): """Link IDs of left edge vertical links. Parameters ---------- shape : tuple of int Shape of grid, given as (rows, columns) of nodes. Returns ------- ndarray : Link IDs of left edge vertical links. Length is (rmg.number_of_rows - 1...
9ff1e8caa66b27deae5b2086de5b40a03917a8ad
3,614,083
def guess_dim_transition_linebyline(filename): """get number of histogram bins from transition matrix file (one line per entry!!!)""" #print "Reading...", filename with open(filename,"r") as f: count = 0 for line in f: # skip lines starting with # if not line.startswith("#"): ...
f0cb5bb788195c0b2369d588e2e9d8e9caa3c5f1
3,614,084
from typing import List from typing import Dict def deduplicate(new_data: List[Dict]) -> List[Dict]: """ Checks for duplicates and omits them """ old_data = load_data() data = [] for new in new_data: if all(new['tweet_id'] != old[2] for old in old_data): data.append(new) return...
b648ea4cfc9a8d14e6eff822e56680fdcb1e17eb
3,614,085
def identify_necessary_covariates(dependents, definitions): """Identify covariates necessary to compute `dependents`. This function can be used if only a specific subset of covariates is necessary and not all covariates. See also -------- respy.likelihood._compute_x_beta_for_type_probability ...
08f6db315a1c1281ef2ffae4efc1ccda78f3e95e
3,614,086
def delete_event(current_user, event_id): """ Deleting a User Event from the database if it exists. :param current_user: :param event_id: :return: """ try: int(event_id) except ValueError: return response('failed', 'Please provide a valid Event Id', 400) user_event = ...
eb4977198c87294eb0980932dfd17e572d950bbf
3,614,087
def make_meeting(): """ Generate a new dummy meeting and save it. """ meeting = frappe.get_doc({ "doctype": "Meeting", "title": "Test Meeitng", "status": "Planned", "date": "2017-07-20", "from_time": "09:00", "to_time": "09:30", "minutes": [ { "description": "Test minute 1", "status": "Open",...
047c3ed250e5cda64bea859ddcfd0a3c3a7a8b3c
3,614,089
def test_authorize_scalar_attribute_eq(post_fixtures): """Test authorization rules on a relationship with one object equaling another.""" # Object equals another object Oso.load_str( """ allow(actor: test_app2::User, "read", _: test_app2::Post{created_by: actor, access_level: "private"}); ...
0b3727b4bcc4e3f61d53f3b06228f1e05f7287d1
3,614,091
def load_template(template_file_path): """ Load a Jinja2 template and return it Args: template_file_path (str): path to the Jinja2 template file Returns: Template: contains jinja2 template """ return Template(open(template_file_path).read())
7841065523262a2c049d783df1c06b27c65b3cf6
3,614,092
def template_used(response, template_name): """Asserts a given template was used (with caveats) First off, this is a gross simplification of what the Django assertTemplateUsed() TestCase method does. This does not work as a context manager and it doesn't handle a lot of the pseudo-response cases. ...
f8a878d27c5379b0b2f2fac2a08fbeee91607858
3,614,093
def _sign_trace(s11, s22, s33): """Calculate sign of trace. Sign of 0 is set to 1. Parameters ---------- s11: array_like Component 11 of 3D tensor. s22: array_like Component 22 of 3D tensor. s33: array_like Component 33 of 3D tensor. Returns ------- numpy.nd...
d0557995bd5662e84939536b2e220acf6e0ce460
3,614,094
def read2dlv(filename): """Read LabView 2D array and return as numpy array. Big-endian version. """ if isinstance(filename, str): f = open(filename, 'rb') else: f = filename dims = np.fromstring(f.read(8), dtype=np.dtype('>u4')) ccd_temp = np.fromstring(f.read(), dtype=np.dt...
911a62eac2b43fca607f95aefdd845d7c67877bb
3,614,095
import click def ensure_remote(ctx, param, value): """ Ensure --remote is used. """ # pylint: disable=unused-argument if value and ctx.params.get('remote') == (None, None): raise click.BadParameter('Invalid without "-r" / "--remote" option') return value
d22f8d73e4b5ec57cc18607918775778d09efc67
3,614,096
def edit_draft_service(draft_id): """ Edit a draft service :param draft_id: :return: """ updater_json = validate_and_return_updater_request() update_json = validate_and_return_draft_request() page_questions = get_request_page_questions() draft = DraftService.query.filter( D...
db734fb9bf2b3cdaa9f89162e08875215cd4dfad
3,614,097
def is_lisp_like(view): """ Check for a lisp like file using the current language/syntax setting """ return get_dialect(view) != ''
c6b6f4df062173421b8300bf9e82e1240213f692
3,614,098
from typing import Callable import types import json def _execute(cls, app_engine: AppKernelEngine, provisioner_method: Callable, model_class: Model): """ The main view function for flask routes. :param app_engine: the app engine instance :param provisioner_method: the method on our service object whi...
8b2ffd71bc512afad0657ea5695b7a281cde5f86
3,614,099
import tqdm def get_all_mask_volumes(): """ Purpose: Returns all masks for dataset in a single numpy array of 32 bit floats. Shape will be 259x240x240x155x1 """ all_patient_paths = get_each_hgg_folder() # preallocate empty np array to hold all the masks # dim 0 ...
661e64bdd550f98ae4861384da558981bb2e887e
3,614,100
def prepare_training_data(sessions): """ Convert extracted session into training data :param sessions: list of sessions :return: """ purchase_sessions = [] abandon_sessions = [] for s in sessions: # check that purchase action occurs after add action if Actions.purchase...
41ae799dcc815a1da5b89d6718bad7c0f84b375c
3,614,101
import torch def nx_to_graph_data_obj_simple(G, partial_charge=False): """ Converts nx graph to pytorch geometric Data object. Assume node indices are numbered from 0 to num_nodes - 1. NB: Uses simplified atom and bond features, and represent as indices. NB: possible issues with recapitulating rel...
e080aec34468e4948ca38dd162d864e8dc5dd4ba
3,614,102
def after_replace(func, target=None): """Request `func` be invoked as `func(self, old)` when `model` is about to replace an older version of itself. Alternatively when applied to a collection, request `func(key, old, new)` be invoked. :: @acid.events.after_replace def after_replace(sel...
a1c84c1c6a9cc04bd46c04b68410f33d5a26dd13
3,614,103
def construct_sequence(seq_dict): """Construct RnaSequence from dict of {pos:residue}. seq_dict -- dictionary of {position: residue} Checks whether the first residue is 0. Checks whether all residues between min and max index are present. No checking on validity of residue symbols. """ ...
cb150f3400807dd22ca1044a68f4a62faa279c1c
3,614,105
def _cauchy_ ( self , mu , gamma ) : """Generate Cauchy random numbers - rely on the distribution of the ratio for two Gaussian variables - see https://en.wikipedia.org/wiki/Cauchy_distribution """ g1 = self.gauss ( 0.0 , 1.0 ) while abs ( g1 ) < _fmin : g1 = self.gauss ( 0.0 , 1.0 ) g2 = ...
724afa6a7bf733227ae1fa03614785ba6f622b8c
3,614,106
def get_group_cpu_name(ifamily, category, device): """ Abstract layer to group i3, i5, i7 families. :param ifamily: which series of cpu we want to group :param category: category to make sure the input is processor :param device: device to check :return: grouped device name """ ifamily_...
46b3bf00540e9147f6e4bab3a1431bd8497009a6
3,614,107
def median(values): """Return median value for the list of values. @param values: list of values for processing. @return: median value. """ values.sort() n = int(len(values) / 2) return values[n]
c40b9e0b2cdd2b00ae6692aed2cfe9787bc8f9df
3,614,108
def remove_default_create_options(options): """ Return only non default create options """ _options = options.copy() for opt in IPSET_DEFAULT_CREATE_OPTIONS: if opt in _options and \ IPSET_DEFAULT_CREATE_OPTIONS[opt] == _options[opt]: del _options[opt] return _options
cbfdbbfab149cea698e912db0d3271ddcb97a20e
3,614,109
import numpy def _grid_3d(dx, dy, dz, order): """Generate 3D structured grid.""" # Internal functions def meshgrid(x, y, z, indexing="ij", order=order): X, Y, Z = numpy.meshgrid(x, y, z, indexing=indexing) return X.ravel(order), Y.ravel(order), Z.ravel(order) def mesh_vertices(i, j, k...
4204f54c0629fa17d4f8ffff997cfce735e4307c
3,614,110
def title_keywords(title): """Given a title, returns every author assigned keyword""" q = """ SELECT GROUP_CONCAT(keyword) FROM OriginalKeywords WHERE ArticleID='{t}'""".format(t=title) curr.execute(q) return curr.fetchall()[0][0].split(',')
2560ca23e91f3347c6bbb77c285b5f9a6fac7a75
3,614,111
import torch def collate_fn(batch, transforms): """Collate function to be passed to the PyTorch dataloader. Parameters ---------- batch : list Uncollated batch of size `batch_size`. device : str or torch.device Current working device. transforms : callable Transformati...
89daebd2f58d9a7b83c7bd7c14cdde2ed16d8b3d
3,614,112
def persistence_function_from_model(model, G_interlayer, layer_vec=None, N=None, T=None, Nt=None): """ Returns a function to calculate persistence according to a given multilayer model :param model: network layer topology (temporal, multilevel, multiplex) :param G_interlayer: input graph containing all...
9e3998ac4beb0ed653f6482a550fbde5e6c75eeb
3,614,113
def sanitizer(name): """ Sanitizes a string supposed to be an entity name. That is, invalid characters like slashes are substituted with underscores. :param name: A string representing the name. :returns: The sanitized name. :rtype: str """ return name.replace("/", "_")
f59aa75a40067068c711a4ca01b643c69d43cd0c
3,614,114
def fget_wcs(fitsfile_path): """Get the World coordinate system (wcs) from the fits header for plotting. Parameters ========== fitsfile_path: str The input fits path Return ====== wcs: `astropy.wcs.wcs.WCS` Image coordinates in WCS format """ hdu = fits.getheade...
e85e903a0dc3ff624fa2e1d053f7225932601c8d
3,614,115
def is_repository_setup(): """Indicates if base repository is setup or not. """ return repository_cache.get_value() is not None
0ab19dba941fe5af6359a3ed6b725a751dca3b41
3,614,116
def ISURL(value): """ Checks whether a value is a valid URL. It does not need to be fully qualified, or to include "http://" and "www". It does not follow a standard, but attempts to work similarly to ISURL in Google Sheets, and to return True for text that is likely a URL. Valid protocols include ftp, http,...
e1362d9cfe97b35e935d072da1aa1791acd24371
3,614,117
def transaction_class(cls): """ Return the associated transaction class for given versioned SQLAlchemy declarative class or version class. :: from sqlalchemy_continuum import transaction_class transaction_class(Article) # Transaction class :param cls: SQLAlchemy versioned decla...
054bf2e31b7c4132928192c21317ad898ed13dde
3,614,118
def _GenerateRootGradle(jinja_processor): """Returns the data for the root project's build.gradle.""" variables = {'template_type': 'root'} return jinja_processor.Render(_JINJA_TEMPLATE_PATH, variables)
cfb28ff7fe2dffb1e451bce9e94b51ef17286209
3,614,120
def measure_display_label(src_type): """update label upon modification of Radio Items""" source_label, measure_label = get_source_labels(src_type) source_unit, measure_unit = get_source_units(src_type) return 'Measured %s (%s)' % (measure_label, measure_unit)
70e7ffc3dddc7b92cce79d66985b283d088759f3
3,614,121
def only_choice(values): """Apply the only choice strategy to a Sudoku puzzle The only choice strategy says that if only one box in a unit allows a certain digit, then that box must be assigned that digit. Parameters ---------- values(dict) a dictionary of the form {'box_name': '123456...
c8760594858a48aaa97e62ffbbb2f290bcff4e1f
3,614,122
def get_xml_storage_model(): """ Return the configured xml storage model class using apps.get_model() """ app, model = acs_settings.XML_STORAGE_MODEL.split(".") return apps.get_model( app_label=app, model_name=model )
03285f7c8ad7f781c4a82ac22d86cbbe0291c96b
3,614,123
def _get_deployments_digest_by_uid(uid): """ Get list of deployments for a reference designator; return digests. (See also event_tools.py, get_deployment_events. Supports asset management Deployment tab.) """ results = [] try: # Get vocabulary dictionary once. vocab_dict = get_vocab(...
ab3b689e9b6d47b0bb10a06cfc105f03493a15f4
3,614,124
def layout_arc_with_drc_exclude( cell, layer, drc_layer, center, r, w, theta_start, theta_end, ex=None, **kwargs ): """ Layout arc with drc exclude squares on sharp corners""" dpoly = layout_arc(cell, layer, center, r, w, theta_start, theta_end, ex, **kwargs) dpoly.layout_drc_exclude(cell, drc_layer, ex...
38bfe0f29f0a9e2a4ea3b7ad0ca43fdb5ee6ce5e
3,614,125
def create_fake_user(): """ Generate new user and saves to database """ user = User.objects.create(username=faker.first_name_male()) return user
71e141e6b2f34f4cc1453dffee113117125ce782
3,614,126
def control_brightness(how, level): """Control brightness level.""" _change_brightness(how, level) _send_notification() return 0
624e69d94c4d763699aff93d46482ecaa5c664df
3,614,127
def has_negative_control(cmd): """Return whether a command has negatively controlled qubits.""" return get_control_count(cmd) > 0 and '0' in cmd.control_state
94c5ab2773f946dc6c598e64c91ea7d90ec83b08
3,614,128
def qg8_graph_load(filename: str): """" Load a QG8 graph from file chunk by chunk """ f = qg8_file_open(filename, QG8_MODE_READ) if f is None: return None graph = qg8_graph([]) # create empty graph object i = qg8_file_iterator(f) while qg8_file_has_next(i): # EOF check ...
6c6b2ab78131fb9454c782aade283f59e223400a
3,614,129
def all_reduce(tensor, op=dist.ReduceOp.SUM, group=dist.group.WORLD): """ Reduces the tensor data across all machines in such a way that all get the final result. After the call the returned tensor is going to be bitwise identical in all processes. Arguments: tensor (Tensor): Input of ...
ecdd395272ff314a77b8e765d0f825cf7329fad2
3,614,130
def _get_stock_ledger_entries(filters): """ Get data from Stock Ledger Entries with the following fields: (1) date, (2) item_code, (3) actual_qty, (4) qty_after_transaction, (5) project, (6) stock_uom, (7) item_name :param filters: :return: Stock Ledger Entries """ item_code = filters.ge...
6ed2ce915876b1232c695619c4823db789be0a61
3,614,131
def parse(tokens): """Parses the infix permission ``tokens`` into a postfix instruction list. :param tokens: The token list produced by :func:`~pwh_permissions.tokenise` :type tokens: ``list`` :return: The token list in postfix notation :rtype: ``list`` """ result = [] stack = [] bu...
1e4bc897ec205112004aca56d49606e0726de27a
3,614,132
def roots_legendre_interval(n, a, b): """ Computes the sample points and weights for Gauss-Legendre quadrature on interval `[a, b]`. The sample points are the roots of the n-th degree Legendre polynomial `P_n(x)`. These sample points and weights correctly integrate polynomials of degree `2n - 1...
2e0e09785ec9557dbe4cc1c368d7401c581f947e
3,614,133
from typing import Optional from typing import List from typing import Tuple from pathlib import Path def get_physical_dependencies(obj: str, lib: str, include_self: bool, job: Optional[IBMJob]=None, verbose: bool=False) -> List[Tuple[str, str, str]]: """Get the dependencies for a given physical file object ...
8e358ef3a2b0210668ce1a4c88235c7975005138
3,614,134
def compute_counters(data): """ Returns the number of times a separator is in each line. """ counters = np.zeros((len(data), len(SEPARATORS))) for i, line in enumerate(data): counters[i] = [get_character_count(line, sep) for sep in SEPARATORS] return counters
9c115cad6a543939ca6601183bf31d976abd7a80
3,614,136
def mishActivation(x): """ Mish Activation Function """ return x * tf.math.tanh(tf.math.softplus(x))
d66dd5a2ee371e7937aa69ddf00ffc7481dc0d32
3,614,137
from clawpack.geoclaw import topotools from numpy import array import netCDF4 import xarray def read_netcdf(path, zvar=None, extent='all', coarsen=1, return_topo=True, return_xarray=False, verbose=False): """ :Input: - *path* (str) - Path to the file to read, or url to remote file, ...
9f28f25e7c7f9be856825843421f42a2f37027bf
3,614,139
def quantize(v, unit): """Quantize value `v` to a multiple of `unit`. When `unit` is an integer, the return value will be integer as well, otherwise the function will return a float. Parameters ---------- v : ndarray or number Number to be quantized unit : number The quantiz...
55f3b88d28dc94430cd7741f6f1e2603b208054e
3,614,140
def next(dist, median, d1, d2, p, N): """ INPUT dist: distance matrix median: list of integers for selected vertices d1: list of nearest facility for each vertex d2: list of second nearest facility p: number of facilities to locate N: number of vertices on the nextwork OU...
00bb21f286b29659358c91144567940ba4cbf758
3,614,141
def stop(): """ Stop the currently running recipe. :return: object response One of: ok error message Only present if response is "error" and there is a message to present to the user. """ recipes.stop() return jsonify({...
2c7dd7ff86d373877c9493b2027d0134624428f1
3,614,142
import textwrap def loadings_histograms( pca, feature_labels, n_components='all', bins=50, n_features_to_label=10, max_text_len=35, text_kws={'color': 'white', 'bbox': {'facecolor': 'k', 'alpha': 0.7, 'pad': 1}}, save_fig=None): """Plot histograms of the loadings ...
70e0248b76f543100704445467be7c52f760e16a
3,614,143
import re def password_string(value): """密码输入类型""" if len(value) < 8 or len(value) > 20 or re.match(r'^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$', value) is None: raise ValueError('密码至少包含 数字和英文,长度6-20,不能出现非法字符') return value
e6bfcc473c164cd06e3acd65165f6fb9dcd251cf
3,614,144