code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def set_api_endpoints(self, endpoints): <NEW_LINE> <INDENT> endpoints = sorted(endpoints) <NEW_LINE> for relation in self.relations: <NEW_LINE> <INDENT> relation.to_publish['api-endpoints'] = endpoints | Send the list of API endpoint URLs to which workers should connect. | 625941f357b8e32f52483a87 |
def getOutputFilesNames(molname, workdir): <NEW_LINE> <INDENT> pdbFile = os.path.join(workdir, molname+'.pdb') <NEW_LINE> outFile = os.path.join(workdir,'out') <NEW_LINE> return pdbFile, outFile | Generate output BOSS file names (PDB, OUT file)
Parameters
----------
molname : str
Molecule name
workdir : str
Working folder
Returns
-------
pdbFile : str
PDB file name
outFile : str
OUT file name | 625941f38e05c05ec3eea962 |
def set_network_bias_layer(self): <NEW_LINE> <INDENT> assert len(self.core_list[-1]) == len(self.loihi_snn_dimension) - 1 <NEW_LINE> neuron_prototype = nx.CompartmentPrototype( compartmentCurrentDecay=2 ** 12 ) <NEW_LINE> self.network_bias_layer = self.net.createCompartmentGroup(size=0) <NEW_LINE> for core in self.core... | Setup Network Bias Layer | 625941f3379a373c97cfb12f |
def degree_sequence(G): <NEW_LINE> <INDENT> return [degree(G, v) for v in nodes(G)] | Return the degree sequence of G.
The degree sequence of a graph is the sequence of degrees of the nodes
in the graph.
Parameters
----------
G : NetworkX graph
An undirected graph.
Returns
-------
list
The degree sequence of the graph.
Examples
--------
>>> G = nx.path_graph(3) # Path on 3 nodes
>>> nx.degre... | 625941f35fdd1c0f98dc081d |
def __init__(self, board, predecessor, move): <NEW_LINE> <INDENT> self.board = board <NEW_LINE> self.predecessor = predecessor <NEW_LINE> self.move = move <NEW_LINE> self.num_moves = 0 <NEW_LINE> if self.predecessor != None: <NEW_LINE> <INDENT> self.num_moves = predecessor.num_moves + 1 | a constructor for a State object
inputs: parameter board that stores a reference to the State object,
parameter predessor that stores a reference to the State object,
parameter move that stores a string representing the move that was
needed to transition from the predecessor state to this state | 625941f3adb09d7d5db6cd74 |
def recipe_image_file_path(instance, file_name): <NEW_LINE> <INDENT> ext = file_name.split('.')[-1] <NEW_LINE> filename = f'{uuid.uuid4()}.{ext}' <NEW_LINE> return os.path.join('uploads/recipe/', filename) | generate file path to new recipe image | 625941f37c178a314d6efa52 |
def valid_jumps(self, square, opponents): <NEW_LINE> <INDENT> jumps = [] <NEW_LINE> if self.get_square(square) in ("bm", "bk", "wk"): <NEW_LINE> <INDENT> if self.jump_room_exists(square, "SE"): <NEW_LINE> <INDENT> diag_offs = 4 if (square//4) % 2 else 5 <NEW_LINE> if self.get_square(square+diag_offs) in opponents: <NEW... | Find all legal jumps for the piece on square
Return the list of all legal jumps the piece on square. | 625941f3004d5f362079a916 |
def addOrModifyDowntimeCache( self, downtimeID = None, element = None, name = None, startDate = None, endDate = None, severity = None, description = None, link = None, dateEffective = None, lastCheckTime = None, meta = None ): <NEW_LINE> <INDENT> meta = { 'onlyUniqueKeys' : True } <NEW_LINE> return self._query( 'addOrM... | Adds or updates-if-duplicated to DowntimeCache. Using `downtimeID` to query
the database, decides whether to insert or update the table.
:Parameters:
**downtimeID** - `string`
unique id for the downtime
**element** - `string`
valid element in the topology ( Site, Resource, Node )
**name** - `string`
... | 625941f3d4950a0f3b08c92e |
def rename(self, name, new_name): <NEW_LINE> <INDENT> pass | rename a group | 625941f37047854f462a19ea |
def _index(self): <NEW_LINE> <INDENT> if self.y + 1 >= self.size[0]: <NEW_LINE> <INDENT> self.display = self.display[1:] + [u" " * self.size[1]] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.y += 1 | Move the cursor down one row in the same column. If the cursor is at
the last row, create a new row at the bottom. | 625941f36fece00bbac2dd2e |
def from_string(self, s): <NEW_LINE> <INDENT> record = Record() <NEW_LINE> tokenizer = ConfigParseTokenizer() <NEW_LINE> blocks = tokenizer.text_to_blocks(s) <NEW_LINE> tokens = tokenizer.blocks_to_tokens(blocks) <NEW_LINE> for token in tokens: <NEW_LINE> <INDENT> if token.type == ConfigParseToken.NAME: <NEW_LINE> <IND... | . | 625941f39b70327d1c4e13c0 |
def dic(image, dic_angle, dic_phase, dic_split): <NEW_LINE> <INDENT> x = (_fft.fftshift((_numpy.arange(image.shape[0])-image.shape[0]/2.+0.5) / float(image.shape[0]))[_numpy.newaxis, :]) <NEW_LINE> y = (_fft.fftshift((_numpy.arange(image.shape[1])-image.shape[1]/2.+0.5) / float(image.shape[1]))[:, _numpy.newaxis]) <NEW... | Differential interference contrast | 625941f3ab23a570cc250770 |
def _recv_int(self,value): <NEW_LINE> <INDENT> return struct.unpack(self.board.int_type,value)[0] | Recieve an int in binary format, returning as python int. | 625941f3fb3f5b602dac3c82 |
def sql_for_columns(self, qn, connection): <NEW_LINE> <INDENT> db_type = self.field.db_type(connection=connection) <NEW_LINE> if self.table_alias: <NEW_LINE> <INDENT> lhs = '%s.%s' % (qn(self.table_alias), qn(self.col_name)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> lhs = qn(self.col_name) <NEW_LINE> <DEDENT> retur... | Taken from WhereNode.sql_for_columns | 625941f3e5267d203edce27d |
def get_seconds(seconds): <NEW_LINE> <INDENT> return (seconds%3600)%60 | Return the number of seconds that have alpsed since midnight as seen on a clock with given number of seconds.
>>>get_seconds(3800)
20
>>>get_seconds(700)
40 | 625941f355399d3f05588ca1 |
def test_create_session_without_authentication(self): <NEW_LINE> <INDENT> with patch.object(self.fake_auth_plugin, 'authenticate', return_value=None) as mock_method: <NEW_LINE> <INDENT> session = mock_method() <NEW_LINE> <DEDENT> self.assertEquals(session, None) | Create a session with authentication failure should succeed
| 625941f3293b9510aa2c3878 |
def main(dfile): <NEW_LINE> <INDENT> trans_table = str.maketrans('abcdefghijklmuvwxyznopqrst', 'uvwxyznopqrstabcdefghijklm', '\n') <NEW_LINE> with open(dfile, 'r') as dfld: <NEW_LINE> <INDENT> for l in dfld: <NEW_LINE> <INDENT> print(l.translate(trans_table)) <NEW_LINE> <DEDENT> <DEDENT> return 0 | Try to solve it
@param dfile: data file path
@type of dfile: str | 625941f3435de62698dfe235 |
def propmerge(into, data_from): <NEW_LINE> <INDENT> newprops = copy.deepcopy(into) <NEW_LINE> for prop, propval in six.iteritems(data_from): <NEW_LINE> <INDENT> if prop not in newprops: <NEW_LINE> <INDENT> newprops[prop] = propval <NEW_LINE> continue <NEW_LINE> <DEDENT> new_sp = newprops[prop] <NEW_LINE> for subprop, s... | Merge JSON schema requirements into a dictionary | 625941f34428ac0f6e5bade0 |
def write( self, dataframe, path, filetype="parquet", gzip=False, partition_by=None, suffix=None, drop_partitions=False, **pandas_kwargs, ): <NEW_LINE> <INDENT> warn_tsv_deprecation(filetype=filetype) <NEW_LINE> def _serialize(data): <NEW_LINE> <INDENT> if filetype in ["tsv", "dsv"]: <NEW_LINE> <INDENT> params = {"inde... | Saves data in a given format
:param dataframe: input pandas.DataFrame
:param path: path-like
:param filetype: output format: parquet|dsv|jsonlines
:param gzip: should the output be gzipped: dsv|jsonlines
:param partition_by: optional, list of columns to partition the output
:param suffix: optional, suffix to use for ou... | 625941f3a8ecb033257d36b3 |
def get_default_message(self): <NEW_LINE> <INDENT> return self.title | Use the title of the video as the default message for a fact. | 625941f3851cf427c661aaf2 |
def getKubernetesCloudProvider(self) -> Optional[str]: <NEW_LINE> <INDENT> return 'aws' | Use the "aws" Kubernetes cloud provider when setting up Kubernetes. | 625941f356b00c62f0f14c46 |
def transform_quaternion_stamped(self, new_frame_id, quat_stamped): <NEW_LINE> <INDENT> return self.transformer.transform_quaternion_stamped(new_frame_id, quat_stamped, self.get_robot_state()) | Transforms a quaternion into new_frame_id according to the current state in the diff.
**Args:**
**new_frame_id (string):** new frame id
**quat_stamped (geometry_msgs.msg.QuaternionStamped):** quaternion stamped (current frame is defined by
header)
**Returns:**
A geometry_msgs.msg.QuaternionSt... | 625941f350485f2cf553d384 |
def gen_direct_message(with_source=False): <NEW_LINE> <INDENT> projs = get_rows() <NEW_LINE> proj_idx = choose_idx([r["title"] for r in projs]) <NEW_LINE> proj = projs[proj_idx] <NEW_LINE> title = proj.get("title", "__title__") <NEW_LINE> demo_url = proj.get("demo_url", "") <NEW_LINE> message = f"Hey check out {title} ... | single project text to send to a buddy in a DM | 625941f3d7e4931a7ee9e508 |
def get_prod(self): <NEW_LINE> <INDENT> return self._prod | Getter | 625941f30a50d4780f667480 |
def upgrade_validate_with(self, force=False): <NEW_LINE> <INDENT> if not self.is_cib_sane(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> validator = self.cib_elem.get("validate-with") <NEW_LINE> if force or not validator or re.match("0[.]6", validator): <NEW_LINE> <INDENT> return ext_cmd("cibadmin --upgrade --... | Upgrade the CIB.
Requires the force argument to be set if
validate-with is configured to anything other than
0.6. | 625941f34c3428357757c90c |
def __init__(self, beta, gf_struct, n_iw=1025, n_tau=10001, n_l=30, delta_interface = False): <NEW_LINE> <INDENT> gf_struct = fix_gf_struct_type(gf_struct) <NEW_LINE> SolverCore.__init__(self, beta=beta, gf_struct=gf_struct, n_iw=n_iw, n_tau=n_tau, n_l=n_l, delta_interface = delta_interface) <NEW_LINE> mesh = MeshImFre... | Initialise the solver.
Parameters
----------
beta : scalar
Inverse temperature.
gf_struct : list of pairs [ (str,int), ...]
Structure of the Green's functions. It must be a
list of pairs, each containing the name of the
Green's function block and its linear size.
... | 625941f35f7d997b87175086 |
def is_sublist(needle, haystack): <NEW_LINE> <INDENT> ln = len(needle) <NEW_LINE> lh = len(haystack) <NEW_LINE> for pos in range(lh - ln + 1): <NEW_LINE> <INDENT> if needle == haystack[pos:pos+ln]: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False | True if needle is a sublist of haystack, False otherwise.
Could be more efficient with Boyer-Moore-Horspool but our needles
are usually ngrams (ie. short), so this is a O(nm) implementation. | 625941f360cbc95b062c6b2c |
def test_init(): <NEW_LINE> <INDENT> Drivetrain() | Test the creation of a Drivetrain | 625941f350485f2cf553d385 |
def matrix_skew_x(angle): <NEW_LINE> <INDENT> return ((1.0, math.tan(angle), 0.0), (0.0, 1.0, 0.0)) | Create a transform matrix to skew along X axis by `angle`.
Args:
angle: Angle in radians to skew.
Returns:
A transform matrix as 2x3 tuple | 625941f38a43f66fc4b54647 |
def set_Email(self, value): <NEW_LINE> <INDENT> super(DonateToProjectInputSet, self)._set_input('Email', value) | Set the value of the Email input for this Choreo. ((required, string) The email address of the person who is making the donation.) | 625941f3498bea3a759ba096 |
def delete_application(self, app): <NEW_LINE> <INDENT> if isinstance(app, dict): app = app['id'] <NEW_LINE> self.request('DELETE', '/applications/{0}'.format(app)) | Delete an application with ID *app*. | 625941f37cff6e4e81117f6e |
def stuff_only(func): <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def wrapper(*args, **kwargs): <NEW_LINE> <INDENT> user_id = session.get('user_id', False) <NEW_LINE> if user_id is False: <NEW_LINE> <INDENT> return 'Access Deny', 403 <NEW_LINE> <DEDENT> user = app.db.user.find_one({'_id': user_id}) <NEW_LINE> if not us... | Декоратор - "только для персонала" | 625941f363f4b57ef00016f0 |
def __iter__(self): <NEW_LINE> <INDENT> return iter(self.clusters) | Iterate over clusters | 625941f315baa723493c4563 |
def test__get_or_create_uuid(self): <NEW_LINE> <INDENT> sessionise = preprocessing.Sessionise(self._df, 'unique_id', 'date') <NEW_LINE> sessionise._add_session_boundaries() <NEW_LINE> df = sessionise.df <NEW_LINE> df.loc[:, 'session_uuid'] = df.apply( lambda row: sessionise._get_or_create_uuid(row), axis=1 ) <NEW_LINE>... | Tests `_get_or_create_uuid` function with known cases. | 625941f33d592f4c4ed1d646 |
def _set_Jac(self, M, Jac, mpidx, mnidx, jacpidx, jacnidx): <NEW_LINE> <INDENT> np.put(M.data, mpidx + self._mbase, np.take(Jac, jacpidx)) <NEW_LINE> self._mbase += len(mpidx) <NEW_LINE> np.put(M.data, mnidx + self._mbase, -np.take(Jac, jacnidx)) <NEW_LINE> self._mbase += len(mnidx) | Set current contributions of Jac into M (in coo format) | 625941f301c39578d7e75424 |
def make_color_table(args): <NEW_LINE> <INDENT> black = "0 0 0" <NEW_LINE> saturation = 1.0 <NEW_LINE> brightness = 1.0 <NEW_LINE> angle_delta = 1.0 / (args.num_colors - 1) <NEW_LINE> hues = [i * angle_delta for i in range(args.num_colors - 1)] <NEW_LINE> hsb = [f'{hue:.2f} {saturation:.2f} {brightness:.2f}' for hue i... | make a table of N colors in HSB.
The first color will be black, the rest will be evenly-spaced hues | 625941f3283ffb24f3c55ee3 |
def reuse(scope): <NEW_LINE> <INDENT> warnings.warn( "The `reuse()` function has been renamed to `reuse_variables()`, " "`reuse()` will be removed in the coming version (0.4.1)", FutureWarning) <NEW_LINE> return reuse_variables(scope) | (Deprecated) Alias of :func:`reuse_variables`. | 625941f323849d37ff7b3673 |
def get_related_locations(self): <NEW_LINE> <INDENT> locs = [] <NEW_LINE> try: <NEW_LINE> <INDENT> if self.check_related_locations(): <NEW_LINE> <INDENT> for loc in self.__data['relatedLocations']['primaryLocations']: <NEW_LINE> <INDENT> type = loc['facilityType'] <NEW_LINE> loc_id = loc['links']['self']['href'].split(... | Returns the related locations of the entertainment | 625941f32c8b7c6e89b35da4 |
def getModifiers(self, node): <NEW_LINE> <INDENT> modifiers = self.predecessors(node) <NEW_LINE> modifiers.sort() <NEW_LINE> return modifiers | return immediate predecessorts of node. The returned list is sorted by node span. | 625941f357b8e32f52483a88 |
def parse_movie(request, name, year=None): <NEW_LINE> <INDENT> return HttpResponse(json.dumps(TmdbMovieParser(unicode(name), int(year)).get_info())) | :param year: int
:param name: str
:type request: HttpRequest | 625941f30c0af96317bb87d0 |
def filter_word_test1(M): <NEW_LINE> <INDENT> filename = '/home/class_test/sasa/RG_word_sims.tsv' <NEW_LINE> indices = M.index.values <NEW_LINE> out = open('RG_word_sims.filtered.tsv', 'w') <NEW_LINE> with open(filename) as f: <NEW_LINE> <INDENT> for line in f: <NEW_LINE> <INDENT> w1,w2,_ = line.strip().split() <NEW_LI... | Create a new word similarity file that only contains words in M | 625941f330bbd722463cc3b2 |
def opponent(self, player): <NEW_LINE> <INDENT> if player == '1': <NEW_LINE> <INDENT> return '2' <NEW_LINE> <DEDENT> if player == '2': <NEW_LINE> <INDENT> return '1' | Returns who has the next turn | 625941f3d6c5a10208144639 |
def test_run_42270_kwargs_to_args(self): <NEW_LINE> <INDENT> def test_func(arg1, arg2, arg3, *args, **kwargs): <NEW_LINE> <INDENT> return {"args": [arg1, arg2, arg3] + list(args), "kwargs": kwargs} <NEW_LINE> <DEDENT> with patch.dict(module.__salt__, {CMD: test_func}), patch.dict( module.__opts__, {"use_superseded": ["... | Test module.run filling in args with kwargs with the same name. | 625941f33539df3088e2e934 |
def parse_year_from_description(description, separator, year_position): <NEW_LINE> <INDENT> from datetime import date <NEW_LINE> today = date.today() <NEW_LINE> current_year = today.year <NEW_LINE> data = description.split(separator) <NEW_LINE> year = type_of_value(data[int(year_position)]) <NEW_LINE> if isinstance(yea... | Parse year from virus description
:param description: The description string that will be parsed
:param separator: What separator is used
:param year_position: The position is the year information
:return: | 625941f321a7993f00bc82e5 |
def minimize(self, loss_fn, x, optim_state): <NEW_LINE> <INDENT> grads = self._compute_gradients(loss_fn, x) <NEW_LINE> return self._apply_gradients(grads, x, optim_state) | Analogous to tf.Optimizer.minimize
:param loss_fn: tf Tensor, representing the loss to minimize
:param x: list of Tensor, analogous to tf.Optimizer's var_list
:param optim_state: A possibly nested dict, containing any optimizer state.
Returns:
new_x: list of Tensor, updated version of `x`
new_optim_state: dict, u... | 625941f3ff9c53063f47c7d9 |
def add_newlines(self: logging.Logger, num_newlines=1) -> None: <NEW_LINE> <INDENT> self.removeHandler(self.base_handler) <NEW_LINE> self.addHandler(self.newline_handler) <NEW_LINE> for _ in range(num_newlines): <NEW_LINE> <INDENT> self.info('') <NEW_LINE> <DEDENT> self.removeHandler(self.newline_handler) <NEW_LINE> se... | Add newlines to a logger object
Args:
num_newlines (int, optional): Number of new lines. Defaults to 1. | 625941f3236d856c2ad44dcc |
def register_admin(self, data): <NEW_LINE> <INDENT> return self.client.post('/api/v1/auth/register', data=json.dumps(data), content_type='application/json') | This method register admin | 625941f3287bf620b61d4049 |
def get_queue(queue_name): <NEW_LINE> <INDENT> return sqs.get_queue_by_name(QueueName=queue_name) | Get an aws SQS object by name.
See: http://boto3.readthedocs.io/en/latest/reference/services/sqs.html#queue
:param queue_name:
:return: | 625941f33617ad0b5ed684df |
def open(self, path): <NEW_LINE> <INDENT> import subprocess <NEW_LINE> if not path.endswith('.sublime-project'): <NEW_LINE> <INDENT> path += '.sublime-project' <NEW_LINE> <DEDENT> executable_path = sublime.executable_path() <NEW_LINE> if sublime.platform() == 'osx': <NEW_LINE> <INDENT> app_path = executable_path[:execu... | Open project from file name. | 625941f36fb2d068a760f690 |
def __init__(__self__, *, arn: Optional[pulumi.Input[str]] = None, description: Optional[pulumi.Input[str]] = None, member_definitions: Optional[pulumi.Input[Sequence[pulumi.Input['WorkteamMemberDefinitionArgs']]]] = None, notification_configuration: Optional[pulumi.Input['WorkteamNotificationConfigurationArgs']] = Non... | Input properties used for looking up and filtering Workteam resources.
:param pulumi.Input[str] arn: The Amazon Resource Name (ARN) assigned by AWS to this Workteam.
:param pulumi.Input[str] description: A description of the work team.
:param pulumi.Input[Sequence[pulumi.Input['WorkteamMemberDefinitionArgs']]] member_d... | 625941f3dc8b845886cb5b20 |
def containVirus(self, isInfected): <NEW_LINE> <INDENT> grid = isInfected <NEW_LINE> res = 0 <NEW_LINE> self.aaaa = {} <NEW_LINE> while True: <NEW_LINE> <INDENT> lst = self.findRegions(grid) <NEW_LINE> if not lst: return res <NEW_LINE> for i, j in lst: <NEW_LINE> <INDENT> for ii, jj in [(i + 1, j), (i - 1, j), (i, j + ... | :type isInfected: List[List[int]]
:rtype: int | 625941f33617ad0b5ed684e0 |
def try_update_cache_file(self, filename, update_dict): <NEW_LINE> <INDENT> FILE_LOCK_TIMEOUT = 3 <NEW_LINE> self.logger.info("Num new geocodings: %d" % len(update_dict)) <NEW_LINE> try: <NEW_LINE> <INDENT> ExclusiveCacheFile.new_or_update(filename, update_dict, FILE_LOCK_TIMEOUT) <NEW_LINE> <DEDENT> except LockExcepti... | Updates cache file with new geocodings.
Gives up if can't open the cache file exclusively in 3 seconds. | 625941f35166f23b2e1a5742 |
def test_submit_edit_intervention_point_with_intervention_point_urls(self): <NEW_LINE> <INDENT> intervention_point = self.create_test_intervention_point(name="old_name") <NEW_LINE> intervention_point_id = intervention_point.id <NEW_LINE> track1 = self.create_test_track(name="track1") <NEW_LINE> track2 = self.create_tes... | Tests that submit_edit_intervention_point does not change DB count
but does change InterventionPoint attribute, edits the existing
InterventionPointUrl, and creates a new InterventionPointUrl | 625941f3a05bb46b383ece05 |
def create(self, request): <NEW_LINE> <INDENT> serializer = BasicModuleSerializer(data=request.data) <NEW_LINE> if serializer.is_valid(raise_exception=True): <NEW_LINE> <INDENT> exists = BasicModule.objects.filter( name=serializer.validated_data['name']).exists() <NEW_LINE> if exists: raise DBIntegrityException( serial... | create new entry
:param request: rest framework request
:return: new entry | 625941f3b5575c28eb68e5ef |
def test_distributions1(): <NEW_LINE> <INDENT> dist = distributions(alphabets=1).example() <NEW_LINE> assert dist.alphabet == ((0, 1),) | A test for the distributions strategy. | 625941f32ae34c7f2600d719 |
def to_string(self, use_long=False): <NEW_LINE> <INDENT> if use_long: <NEW_LINE> <INDENT> return u"{0} ([{1:.2f}, {2:.2f}, {3:.2f}])".format(self.name, self.position.x, self.position.y, self.position.z) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.name | Describes this system as a string.
Args:
use_long: If true, also includes the system position
Returns:
A string representing this system | 625941f3796e427e537b0bb4 |
def update(self, d): <NEW_LINE> <INDENT> self.kwargs.update(d) | Update contents of the context after init | 625941f35fc7496912cc3f67 |
def predict_labels(self, dists, k=1): <NEW_LINE> <INDENT> num_test = dists.shape[0] <NEW_LINE> y_pred = np.zeros(num_test) <NEW_LINE> for i in range(num_test): <NEW_LINE> <INDENT> indices = np.argsort(dists[i])[:k] <NEW_LINE> closest_y = self.y_train[indices] <NEW_LINE> values, counts = np.unique(closest_y, return_coun... | Given a matrix of distances between test points and training points,
predict a label for each test point.
Inputs:
- dists: A numpy array of shape (num_test, num_train) where dists[i, j]
gives the distance betwen the ith test point and the jth training point.
Returns:
- y: A numpy array of shape (num_test,) containi... | 625941f3462c4b4f79d1dcb9 |
def open_pool(self, minconns: int = 1, maxconns: Optional[int] = None) -> None: <NEW_LINE> <INDENT> if self.pool.closed: <NEW_LINE> <INDENT> maxconns = maxconns if maxconns is not None else minconns <NEW_LINE> self.pool = ThreadedConnectionPool( minconns, maxconns, host=self.config.DATABASE_HOST, user=self.config.DATAB... | Initialises and opens a connection pool to the PostgreSQL database
(psycopg2.pool.ThreadedConnectionPool).
'minconn' new connections are created immediately. The connection pool
will support a maximum of about 'maxconn' connections.
Args:
minconns: minimum amount of available connections in the pool,
... | 625941f33346ee7daa2b335b |
def linear_system_solver_th(vector_a, vector_b, r): <NEW_LINE> <INDENT> Y = [r[0]] <NEW_LINE> N = len(vector_a) <NEW_LINE> L, D = thomas_algorithm(vector_a, vector_b) <NEW_LINE> Z = [r[0]/D[0]] <NEW_LINE> for i in range(1, N): <NEW_LINE> <INDENT> yi = r[i] - L[i - 1] * Y[i - 1] <NEW_LINE> Y.append(yi) <NEW_LIN... | Esta função resolve um sistema linear tridiagonal Ax = r
Arguments:
vector_a {[array]} -- diagonal princial de A
vector_b {[array]} -- subdiagonal de A
r {[array]} -- array com os resultados
Returns:
{[array]} -- array com os valores de x | 625941f324f1403a9260114a |
@tags(['python', 'blog', 'jabba']) <NEW_LINE> def step_00b(): <NEW_LINE> <INDENT> url = 'https://pythonadventures.wordpress.com/' <NEW_LINE> print('#', url) <NEW_LINE> open_url(url) | (00b) Python Adventures (open blog) | 625941f3796e427e537b0bb5 |
def calc_mtd(daily_prices, monthly_prices): <NEW_LINE> <INDENT> if len(monthly_prices) == 1: <NEW_LINE> <INDENT> return daily_prices[-1] / daily_prices[0] - 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return daily_prices[-1] / monthly_prices[-2] - 1 | Calculates mtd return of a price series.
Use daily_prices if prices are only available from same month
else use monthly_prices | 625941f34f88993c3716c64a |
def _list(key, **attrs): <NEW_LINE> <INDENT> if hasattr(key, 'key'): <NEW_LINE> <INDENT> return key <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return List(key, **attrs) | Initializes a new List or passes one through.
a_list = _list("foo@bar.com", name="Foo")
same_list = _list(a_list)
new_list = _list("bar@bar.com")
key = Either a String List key or a List.
Returns a List. | 625941f37cff6e4e81117f6f |
def pop(self): <NEW_LINE> <INDENT> if self.stack: <NEW_LINE> <INDENT> if self.stack[-1] == self.minStack[-1]: <NEW_LINE> <INDENT> self.minStack.pop() <NEW_LINE> <DEDENT> self.stack.pop() | :rtype: void | 625941f307d97122c4178e84 |
def TakeDamage(self, damage): <NEW_LINE> <INDENT> super().TakeDamage(damage) <NEW_LINE> self.health -= damage <NEW_LINE> print("{0} took {1} damage, and has {2} health remaining".format(self.name, damage, self.health)) | Damages this unit.
Parameters
----------
damage: int
Amount of damage this unit will take
Value must be non negative
Raises
------
ValueError
If the value of damage is negative
TypeError
If there is not one parameter passed
If damage is not an int | 625941f37b180e01f3dc4dd9 |
def build(self, input_shape): <NEW_LINE> <INDENT> self.hidden_layers = [ ActivationLayer(self._num_units, trainable=self._trainable, activation=self._activation, name='activation_layer_{}'.format(self._feature_num)) ] <NEW_LINE> if not self._shallow: <NEW_LINE> <INDENT> self._h1 = tf.keras.layers.Dense(64, activation='... | Builds the feature net layers. | 625941f3711fe17d82542947 |
def load(self): <NEW_LINE> <INDENT> logger.warning(self.STAT_FILEPATH) <NEW_LINE> with open(self.STAT_FILEPATH, "r") as f: <NEW_LINE> <INDENT> self.stats = json.load(f) <NEW_LINE> <DEDENT> with open(self.RECORD_FILEPATH, "r") as f: <NEW_LINE> <INDENT> self.records = json.load(f) | Load stats from file as json. | 625941f3aad79263cf391034 |
def redraw_messages(self): <NEW_LINE> <INDENT> height, width = self.win_messages.getmaxyx() <NEW_LINE> self.win_messages.clear() <NEW_LINE> start = max(len(self.message_buffer) - height, 0) <NEW_LINE> for x in range(min(height, len(self.message_buffer))): <NEW_LINE> <INDENT> message = self.message_buffer[start] <NEW_LI... | Redraws all messages in the message window | 625941f329b78933be1e5c8e |
def tidy_plot(xmin, xmax, ymin, ymax, center = False, title = None, xlabel = None, ylabel = None): <NEW_LINE> <INDENT> plt.ion() <NEW_LINE> plt.figure(facecolor="white") <NEW_LINE> ax = plt.subplot() <NEW_LINE> if center: <NEW_LINE> <INDENT> ax.spines['left'].set_position('zero') <NEW_LINE> ax.spines['right'].set_color... | Set up axes for plotting
xmin, xmax, ymin, ymax = (float) plot extents
Return matplotlib axes | 625941f3d268445f265b5459 |
@app.route('/logout') <NEW_LINE> def logout(): <NEW_LINE> <INDENT> if 'username' in login_session: <NEW_LINE> <INDENT> gdisconnect() <NEW_LINE> del login_session['google_id'] <NEW_LINE> del login_session['access_token'] <NEW_LINE> del login_session['username'] <NEW_LINE> del login_session['email'] <NEW_LINE> del login_... | Log out the currently connected user. | 625941f3eab8aa0e5d26e144 |
def focal_loss_binary(y_true, y_pred): <NEW_LINE> <INDENT> gamma = 2.0 <NEW_LINE> alpha = 0.25 <NEW_LINE> pt_1 = tf.where(tf.equal(y_true, 1), y_pred, tf.ones_like(y_pred)) <NEW_LINE> pt_0 = tf.where(tf.equal(y_true, 0), y_pred, tf.zeros_like(y_pred)) <NEW_LINE> epsilon = K.epsilon() <NEW_LINE> pt_1 = K.clip(pt_1, epsi... | Binary cross-entropy focal loss
| 625941f3e64d504609d74e29 |
def test_fits_writeread_recarray(self): <NEW_LINE> <INDENT> random.seed(seed=12345) <NEW_LINE> nside_coverage = 32 <NEW_LINE> nside_map = 64 <NEW_LINE> nRand = 1000 <NEW_LINE> ra = np.random.random(nRand) * 360.0 <NEW_LINE> dec = np.random.random(nRand) * 180.0 - 90.0 <NEW_LINE> self.test_dir = tempfile.mkdtemp(dir='./... | Test fits recarray writing and reading. | 625941f3851cf427c661aaf3 |
def test(self): <NEW_LINE> <INDENT> self.compare_outputs() | should correctly use before and ignore controllers | 625941f3fbf16365ca6f67bb |
def test_create_room_name_is_alpha(self): <NEW_LINE> <INDENT> new_room = self.amity.create_room("Office","J3322%&*!)") <NEW_LINE> self.assertEqual(new_room, "\x1b[31mThe room name needs to be made up of L-E-T-T-E-R-S.") | This tests that the name of the room is alphabetical input. | 625941f344b2445a3393267b |
def verify_email_token( token: bytes, ip_address: str, user_agent: str, session_token: str, email_address: str, session_cookie_key: bytes, match_returned_items: Sequence = ("ipa", "ema"), ttl_seconds: int = 900, reqid: Union[int, str] = None, ) -> bool: <NEW_LINE> <INDENT> decrypted_token = decrypt_message( token, sess... | This verifies the token returned by the user.
By default, it requires that the token be returned no more than 15 minutes
after it's been issued. It also tries to match the specified items in
``match_returned_items`` to the current values provided as args::
'ipa' -> ip_address
'usa' -> user_agent
'stk' -> ... | 625941f382261d6c526aba93 |
def __init__(self): <NEW_LINE> <INDENT> self.nlay = 3 <NEW_LINE> self.thickness = [2.5, 0.3 ,4.0] <NEW_LINE> self.nindx = [3.3, 3.4, 3.3] <NEW_LINE> self.wavelength = 1.5 <NEW_LINE> self.nig = 10.0 <NEW_LINE> self.nreff = 0.0 <NEW_LINE> self.nieff = 0.0 | input parameters from file | 625941f3ac7a0e7691ed46aa |
def splinesamples2psd(freqs, samples, seglen, verbose=False): <NEW_LINE> <INDENT> nfreq = len(freqs) <NEW_LINE> nsamp = len(samples) <NEW_LINE> psds = np.empty((nsamp, nfreq), dtype=float) <NEW_LINE> for ind, sample in enumerate(samples): <NEW_LINE> <INDENT> if verbose: <NEW_LINE> <INDENT> print('spline sample %d'%ind)... | return the spline's contribution to the PSD estimate at freqs for each sample | 625941f3d4950a0f3b08c930 |
def test_transferFrom_reverts(hkdai, accounts): <NEW_LINE> <INDENT> with pytest.reverts("Insufficient allowance"): <NEW_LINE> <INDENT> hkdai.transferFrom(accounts[0], accounts[2], "1 ether", {'from': accounts[1]}) <NEW_LINE> <DEDENT> with pytest.reverts("Insufficient allowance"): <NEW_LINE> <INDENT> hkdai.transferFrom(... | transferFrom should revert | 625941f3bd1bec0571d90c19 |
def list_array_drives(self): <NEW_LINE> <INDENT> print('\n[*] Drives on the array.') <NEW_LINE> list_drives = self.array.list_drives() <NEW_LINE> return list_drives | List all drives on the array. | 625941f324f1403a9260114b |
def create_coefficient_matrix(size, k): <NEW_LINE> <INDENT> m = np.zeros([size, size]) <NEW_LINE> populate_first_and_last_row_identities(m) <NEW_LINE> populate_btcs_coefficients(m, k) <NEW_LINE> return m | Returns a matrix having dimensions size*size populated with the
coefficients to solve BTCS | 625941f3925a0f43d254a467 |
def __init__(self, outFile): <NEW_LINE> <INDENT> self.outFile = open(outFile, 'wt') <NEW_LINE> self.count = 0 | Opens the output file and gets ready to write into it.
| 625941f37047854f462a19ec |
def fit_text(X, Y, input_seq_max_length=None, target_seq_max_length=None): <NEW_LINE> <INDENT> if input_seq_max_length is None: <NEW_LINE> <INDENT> input_seq_max_length = MAX_INPUT_SEQ_LENGTH <NEW_LINE> <DEDENT> if target_seq_max_length is None: <NEW_LINE> <INDENT> target_seq_max_length = MAX_TARGET_SEQ_LENGTH <NEW_LIN... | Create a config dict | 625941f34d74a7450ccd47b0 |
def get_hierarchy_id(self): <NEW_LINE> <INDENT> return self._catalog_id | Gets the Id of this hierarchy. | 625941f3442bda511e8be9f9 |
def get_random_proxy_from_web(self, schema='https'): <NEW_LINE> <INDENT> proxy = None <NEW_LINE> url = self.proxy_url <NEW_LINE> try: <NEW_LINE> <INDENT> response = requests.get(url=url) <NEW_LINE> if response and response.status_code == 200: <NEW_LINE> <INDENT> re = json.loads(response.text) <NEW_LINE> if 'error' in r... | 从代理池中获取ua
:params schema: https or http
:params proxy_url: 代理池地址
:return: id, proxy | 625941f399cbb53fe67931ce |
def flush_prop_cache(): <NEW_LINE> <INDENT> global _PROP_CACHE <NEW_LINE> _PROP_CACHE = defaultdict(dict) | Clear property cache | 625941f332920d7e50b287bf |
def test_convert_units(): <NEW_LINE> <INDENT> cosmo = md.Cosmology(H0=70.0, Omega_dm0=0.3-0.045, Omega_b0=0.045) <NEW_LINE> utils.convert_units(1.0, 'radians', 'degrees') <NEW_LINE> utils.convert_units(1.0, 'arcmin', 'arcsec') <NEW_LINE> utils.convert_units(1.0, 'Mpc', 'kpc') <NEW_LINE> utils.convert_units(1.0, 'Mpc', ... | Test the wrapper function to convert units. Corner cases should be tested in the
individual functions. This function should test one case for all supported conversions
and the error handling. | 625941f3a8370b7717052e87 |
def get_states(self): <NEW_LINE> <INDENT> return [xb.numeric_state for xb in self.xb] | Return the numeric states (0,1,2) of all cross-bridges | 625941f3dd821e528d63b78e |
@when('we create an application with a declaration') <NEW_LINE> def step_impl(context, **_kwargs): <NEW_LINE> <INDENT> use_fixture(fixtures.cs_beacon_declare_client, context) <NEW_LINE> context.response = context.beacon_declare_client.create(config=json.loads(context.text)) | step impl | 625941f371ff763f4b549c81 |
def execute(self, query): <NEW_LINE> <INDENT> conn = self.engine.connect() <NEW_LINE> conn.execute("commit") <NEW_LINE> try: <NEW_LINE> <INDENT> conn.execute(query) <NEW_LINE> <DEDENT> except ProgrammingError as e: <NEW_LINE> <INDENT> print(e) <NEW_LINE> <DEDENT> except OperationalError as e: <NEW_LINE> <INDENT> print(... | Executes a query on the database. | 625941f3fb3f5b602dac3c84 |
def _compute_gradient_list(f, xs, delta): <NEW_LINE> <INDENT> xs = list(map(ops.convert_to_tensor, xs)) <NEW_LINE> xs_dtypes = [x.dtype for x in xs] <NEW_LINE> f_temp = _prepare(f, xs_dtypes) <NEW_LINE> y = f_temp(*xs) <NEW_LINE> return zip(*[_compute_gradient(f, y.shape, dtypes.as_dtype(y.dtype), xs, i, delta) for i i... | Compute gradients for a list of x values. | 625941f3ff9c53063f47c7da |
def add_delay(self, delay_us): <NEW_LINE> <INDENT> next_cb = self.__current_address + self._DMA_CONTROL_BLOCK_SIZE <NEW_LINE> if next_cb > self._phys_memory.get_size(): <NEW_LINE> <INDENT> raise MemoryError("Out of allocated memory.") <NEW_LINE> <DEDENT> next1 = self._phys_memory.get_bus_address() + next_cb <NEW_LINE> ... | Add delay at the current position.
:param delay_us: delay in us. | 625941f3004d5f362079a919 |
def _get_icon_rect(self, opt, text_rect): <NEW_LINE> <INDENT> icon_size = opt.iconSize <NEW_LINE> if not icon_size.isValid(): <NEW_LINE> <INDENT> icon_extent = self.pixelMetric(QStyle.PM_SmallIconSize) <NEW_LINE> icon_size = QSize(icon_extent, icon_extent) <NEW_LINE> <DEDENT> icon_mode = (QIcon.Normal if opt.state & QS... | Get a QRect for the icon to draw.
Args:
opt: QStyleOptionTab
text_rect: The QRect for the text.
Return:
A QRect. | 625941f385dfad0860c3b447 |
def totient_phi_2(m: int): <NEW_LINE> <INDENT> if m < 1: <NEW_LINE> <INDENT> raise ValueError('The given number is not positive.') <NEW_LINE> <DEDENT> if not isinstance(m, int): <NEW_LINE> <INDENT> raise ValueError('The given number is not an integer') <NEW_LINE> <DEDENT> if m == 1: <NEW_LINE> <INDENT> return 1 <NEW_LI... | Problem 37: Calculate Euler's totient function phi(m) (improved).
Parameters
----------
m : int
A positive integer number
Returns
-------
int
The totient of the given number
Raises
------
ValueError
If the given number is not a positive integer | 625941f3442bda511e8be9fa |
def file_to_letter_array(myFile): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(myFile, 'r') as f: <NEW_LINE> <INDENT> return [letter for line in f for word in line.translate(line.maketrans("", "", string.punctuation)).lower().split() for letter in list(word)] <NEW_LINE> <DEDENT> <DEDENT> except Exception as e... | Reads a file and returns an array of the letters. | 625941f38c0ade5d55d3efab |
def __ne__(self, other: 'SourceMetaData') -> bool: <NEW_LINE> <INDENT> return not self == other | Return `true` when self and other are not equal, false otherwise. | 625941f3435de62698dfe237 |
def build_command(command, *arguments): <NEW_LINE> <INDENT> arguments = [arg for arg in arguments if arg is not None] <NEW_LINE> command = '*%(num_params)d\r\n$%(len_command)d\r\n%(command)s\r\n' % { 'num_params': len(arguments) + 1, 'len_command': len(command), 'command': command } <NEW_LINE> for i in range(len(argume... | Build a redis command using RESP | 625941f38a43f66fc4b54648 |
def get_PoolManager(): <NEW_LINE> <INDENT> if myproxy: <NEW_LINE> <INDENT> return urllib3.ProxyManager(myproxy, num_pools=1, headers=myheaders) <NEW_LINE> <DEDENT> return urllib3.PoolManager(num_pools=1, headers=myheaders) | Creates a pool manager with proxy support, if applicable
:return: ProxyManager if https_proxy is defined, else PoolManager. | 625941f34428ac0f6e5bade2 |
def createGroup(group): <NEW_LINE> <INDENT> pass | Args:
group:
Returns: | 625941f35fcc89381b1e1cae |
def get_class_parent(self, im_class): <NEW_LINE> <INDENT> func = self._method.__func__ <NEW_LINE> name = func.__name__ <NEW_LINE> doc = func.__doc__ <NEW_LINE> @wraps(func, assigned=self._wrappers) <NEW_LINE> def wrapper(*args, **kwargs): <NEW_LINE> <INDENT> return func(im_class, *args, **kwargs) <NEW_LINE> <DEDENT> pa... | Determine the parent method using the class context.
Args:
im_class: The method's class instance.
Returns:
A tuple:
- The wrapped method.
- The parent method or `None` if it was not found.
- The original documentation of the method or `None` if there is no
documentation on the inheriting met... | 625941f376d4e153a657f11d |
def unmute_reactions(self): <NEW_LINE> <INDENT> self._mute_reactions(False) | Unmute thread reactions. | 625941f3a17c0f6771cbe639 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.