code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def write_to_database(self, connection): <NEW_LINE> <INDENT> for entry in self.entries: <NEW_LINE> <INDENT> insert_network(connection, entry.time, entry.direction, entry.payloadlength, entry.protocol, commit=False) <NEW_LINE> <DEDENT> connection.commit()
Write all entries to the database Inputs: connection: connection to a database Returns: nothing
625941d245492302aab5e467
def findLength(self, A, B): <NEW_LINE> <INDENT> if A is None or len(A) == 0 or B is None or len(B) == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> dp = [[0] * len(B) for i in range(len(A))] <NEW_LINE> for i in range(len(A)): <NEW_LINE> <INDENT> if B[0] == A[i]: <NEW_LINE> <INDENT> dp[i][0] = 1 <NEW_LINE> <DEDENT...
:type A: List[int] :type B: List[int] :rtype: int
625941d2507cdc57c6306e7f
def gen_batches(n, batch_size, min_batch_size=0): <NEW_LINE> <INDENT> start = 0 <NEW_LINE> for _ in range(int(n // batch_size)): <NEW_LINE> <INDENT> end = start + batch_size <NEW_LINE> if end + min_batch_size > n: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> yield slice(start, end) <NEW_LINE> start = end <NEW_LINE>...
Generator to create slices containing batch_size elements, from 0 to n. The last slice may contain less than batch_size elements, when batch_size does not divide n. Parameters ---------- n : int batch_size : int Number of element in each batch min_batch_size : int, default=0 Minimum batch size to produce. Yi...
625941d2f9cc0f698b14079e
def __init__(self, num_sides=6): <NEW_LINE> <INDENT> self.num_sides = num_sides
Asume a six sided die
625941d23eb6a72ae02ec683
def as_json(self): <NEW_LINE> <INDENT> return json.dumps(self.as_dict())
Convert the analysis result object into a json string :rtype: str :return: the data encoded in json
625941d2a8ecb033257d3270
def softmax_loss_naive(W, X, y, reg): <NEW_LINE> <INDENT> loss = 0.0 <NEW_LINE> dW = np.zeros_like(W) <NEW_LINE> N, D=X.shape <NEW_LINE> D, C=W.shape <NEW_LINE> scores=X.dot(W) <NEW_LINE> scores=(scores.T-np.amax(scores,axis=1)).T <NEW_LINE> loss=-np.sum(scores[range(N),y])+np.sum(np.log(np.sum(np.exp(scores),axis=1)))...
Softmax loss function, naive implementation (with loops) Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. Inputs: - W: A numpy array of shape (D, C) containing weights. - X: A numpy array of shape (N, D) containing a minibatch of data. - y: A numpy array of shape (N,) contain...
625941d201c39578d7e74fde
def _get_signature(self, timestamp: int or str): <NEW_LINE> <INDENT> ha = hmac.new(b'd1b964811afb40118a12068ff74a12f4', digestmod=hashlib.sha1) <NEW_LINE> grant_type = self.login_data['grant_type'] <NEW_LINE> client_id = self.login_data['client_id'] <NEW_LINE> source = self.login_data['source'] <NEW_LINE> ha.update(byt...
通过 Hmac 算法计算返回签名 实际是几个固定字符串加时间戳 :param timestamp: 时间戳 :return: 签名
625941d263b5f9789fde7289
def placePointFeature(self, index: int, point: HexPoint, turn: Turn): <NEW_LINE> <INDENT> if len(self.__ownedPointFeatures) == 0: <NEW_LINE> <INDENT> raise ActionError("You have no settlements or cities to place") <NEW_LINE> <DEDENT> if index < 0 or index >= len(self.__ownedPointFeatures): <NEW_LINE> <INDENT> raise Ind...
raises ActionError
625941d2167d2b6e31218d39
def require_admin(func: const.WebSocketCommandHandler) -> const.WebSocketCommandHandler: <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def with_admin(opp, connection, msg): <NEW_LINE> <INDENT> user = connection.user <NEW_LINE> if user is None or not user.is_admin: <NEW_LINE> <INDENT> raise Unauthorized() <NEW_LINE> <DEDE...
Websocket decorator to require user to be an admin.
625941d27b180e01f3dc499f
def test_create_connection(self): <NEW_LINE> <INDENT> conn = Connection() <NEW_LINE> self.assertIsNotNone(conn) <NEW_LINE> conn = Connection(host='http://foohost') <NEW_LINE> self.assertIsNotNone(conn.client) <NEW_LINE> self.assertIsNotNone(conn) <NEW_LINE> self.assertEqual(repr(conn), "Connection<{}>".format(conn.host...
Connection()
625941d25e10d32532c5f0ca
def rip_packet(header, entry): <NEW_LINE> <INDENT> packet = {} <NEW_LINE> packet['header'] = header <NEW_LINE> packet['entry'] = entry <NEW_LINE> return packet
pack header and every entry together
625941d23617ad0b5ed6809b
def build_dfmp2_iter(se, h_phys, eri_mo, **kwargs): <NEW_LINE> <INDENT> ndim = util.iter_depth(se) <NEW_LINE> if ndim == 0: <NEW_LINE> <INDENT> return build_dfrmp2_iter(se, h_phys, eri_mo, **kwargs) <NEW_LINE> <DEDENT> elif ndim == 1: <NEW_LINE> <INDENT> return build_dfump2_iter(se, h_phys, eri_mo, **kwargs) <NEW_LINE>...
Builds a set of auxiliaries representing all (i,j,a) and (a,b,i) diagrams by iterating the current set of auxiliaries according to the eigenvalue form of the Dyson equation. Parameters ---------- se : Aux auxiliaries of previous iteration eri_mo : (2,q,n,n) ndarray density-fitted two-electron repulsion...
625941d2187af65679ca52c2
def draw(self, context): <NEW_LINE> <INDENT> layout = self.layout <NEW_LINE> layout.prop(self, 'sensorName') <NEW_LINE> layout.separator() <NEW_LINE> layout.prop(self, 'categ', text='Sensor category') <NEW_LINE> layout.prop(self, 'sensorType', text='Sensor type') <NEW_LINE> layout.prop(self, 'addLink')
Args: context: Returns:
625941d25fdd1c0f98dc03d7
def setAs(self, value, unit, timestamp=None, annotation=None): <NEW_LINE> <INDENT> self.set(convert(value, unit, self.tag.unit), timestamp, annotation)
Convert a value in the given unit to the tag's native unit
625941d29b70327d1c4e0f79
def removeFirst(self): <NEW_LINE> <INDENT> if self.first is self.last: <NEW_LINE> <INDENT> self.first = self.last = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.first = self.first.next_node
Remove the first Node in the list.
625941d2bf627c535bc13372
def GetUnitName(self) -> str: <NEW_LINE> <INDENT> repr_and_exp: OrderedDict[Any, Any] = OrderedDict() <NEW_LINE> unit_database = self._unit_database <NEW_LINE> for category, (unit, exp) in self._category_to_unit_and_exps.items(): <NEW_LINE> <INDENT> quantity_type = unit_database.GetCategoryQuantityType(category) <NEW_L...
:rtype: str :returns: A description of the unit showing all the containing parts in the category, units and the exponent for each. This differs from the default unit because the default GetUnit will only return the final name of the unit, composing all the available parts into a single exponent (e.g. if...
625941d2a4f1c619b28b01da
def findRepeatSequencesSpacings(message: str) -> dict: <NEW_LINE> <INDENT> message = NONLETTERS_PATTERN.sub('', message.upper()) <NEW_LINE> seqSpacings = {} <NEW_LINE> for seqLen in range(3, 6): <NEW_LINE> <INDENT> for seqStart in range(len(message) - seqLen): <NEW_LINE> <INDENT> seq = message[seqStart:seqStart + seqLe...
Find spacing between repeat sequences Goes through the message and finds any 3- to 5-letter sequences that are repeated. Then counts the number of letters between the repeated sequences. Args: message: String with message to find repeat sequence spacing. Returns: Dictionary with the keys of the sequence and...
625941d215baa723493c4119
def _make_Ray(self, polyhedron, data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> obj = self._Ray_pool.pop() <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> obj = Ray(self) <NEW_LINE> <DEDENT> obj._set_data(polyhedron, data) <NEW_LINE> return obj
Create a new ray object. INPUT: - ``polyhedron`` -- the new polyhedron. - ``data`` -- the V-representation data. OUTPUT: A new :class:`~sage.geometry.polyhedron.representation.Ray` object. EXAMPLES:: sage: p = Polyhedron([(1,2,3),(2/3,3/4,4/5)], rays=[(5/6,6/7,7/8)]) # indirect doctest sage: next(p.ray...
625941d2aad79263cf390be6
def __init__(self, debug_commands=False): <NEW_LINE> <INDENT> root = _retrieveRepositoryRoot(debug_commands) <NEW_LINE> self._git = GitExecutor(root, debug_commands)
Initialize the git subrepo importer object.
625941d291af0d3eaac9bbbd
def insert(self, word): <NEW_LINE> <INDENT> node = self.root <NEW_LINE> for letter in word: <NEW_LINE> <INDENT> child = node.children.get(letter) <NEW_LINE> if not child: <NEW_LINE> <INDENT> child = TrieNode() <NEW_LINE> node.children[letter] = child <NEW_LINE> <DEDENT> node = child <NEW_LINE> <DEDENT> node.isWord = Tr...
Inserts a word into the trie. :type word: str :rtype: void
625941d2293b9510aa2c3439
def load_glove_from_file(glove_filepath): <NEW_LINE> <INDENT> word_to_index = {} <NEW_LINE> embeddings = [] <NEW_LINE> with open(glove_filepath, "r") as fp: <NEW_LINE> <INDENT> for index, line in enumerate(fp): <NEW_LINE> <INDENT> line = line.split(" ") <NEW_LINE> word_to_index[line[0]] = index <NEW_LINE> embedding_i =...
Load the GloVe embeddings Args: glove_filepath (str): path to the glove embeddings file Returns: word_to_index (dict), embeddings (numpy.ndarary)
625941d2adb09d7d5db6c932
def get_predictions(model, text): <NEW_LINE> <INDENT> inputs = tokenizer(text, return_tensors="pt") <NEW_LINE> candidates_by_label = {} <NEW_LINE> with torch.no_grad(): <NEW_LINE> <INDENT> outputs = model(**inputs) <NEW_LINE> logits = outputs[0][0] <NEW_LINE> tokens = [""] + tokenizer.tokenize(text) + [""] <NEW_LINE> f...
Get model predictions of potential spans within the text
625941d244b2445a33932239
def TransformScope(r, *args): <NEW_LINE> <INDENT> if not r: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> if '/' not in r: <NEW_LINE> <INDENT> return r <NEW_LINE> <DEDENT> for scope in args or ('regions', 'zones'): <NEW_LINE> <INDENT> segment = '/' + scope + '/' <NEW_LINE> if segment in r: <NEW_LINE> <INDENT> retur...
Gets the /*args/ suffix from URI r. Args: r: A URI. *args: Optional URI segment names. If not specified then 'regions', 'zones' is assumed. Returns: The URI segment after the first /*args/ in r, the last /-separated component in r if none found. Example: scope('https://abc/foo/projects/bar/zyx', 'pro...
625941d2c4546d3d9de72bd8
def createconnection(self, remoteids): <NEW_LINE> <INDENT> self.prefab.core.run("killall autossh", die=False) <NEW_LINE> self.prefab.system.package.install("autossh") <NEW_LINE> if remoteids.find(",") != -1: <NEW_LINE> <INDENT> prefab = None <NEW_LINE> for item in remoteids.split(","): <NEW_LINE> <INDENT> try: <NEW_LIN...
@param remoteids are the id's of the reflectors e.g. 'ovh3,ovh5:3333'
625941d2435de62698dfddf1
def get_sisapisteiden_lkm(self): <NEW_LINE> <INDENT> import sys <NEW_LINE> kaikki_pisteet = list(self.gridi.shape) <NEW_LINE> sisapisteet = kaikki_pisteet <NEW_LINE> if sisapisteet[0] >=3: <NEW_LINE> <INDENT> sisapisteet[0] = sisapisteet[0] - 2 <NEW_LINE> <DEDENT> if sisapisteet[1] >=3: <NEW_LINE> <INDENT> sisapisteet[...
lasketaan montako sisäpistettä gridissä on esim 5x5x5 gridissä on 3x3x3 sisäpistettä
625941d267a9b606de4a805c
def bsf(graph, visit_node, starting_node=0): <NEW_LINE> <INDENT> visited_edges = set() <NEW_LINE> queue = [] <NEW_LINE> next_nodes = graph[starting_node] <NEW_LINE> visit_node(starting_node) <NEW_LINE> for node in next_nodes: <NEW_LINE> <INDENT> visited_edges.add((starting_node, node)) <NEW_LINE> queue.append(node) <NE...
Performs breadth-first search algorithm on the graph. Note, here we visit edges, so it is OK for us to visit the same node more than once.
625941d24527f215b584c5f9
def inicializaInterface(self): <NEW_LINE> <INDENT> self.aplicacao = JanelaCombate() <NEW_LINE> Interface.log.debug("Inicializado")
Inicializa a janela principal da interface, organizando todos os frames e widgets presentes na primeira página
625941d2d4950a0f3b08c4f2
def sethasparent(self, state, parent_state, value): <NEW_LINE> <INDENT> msg = "This AttributeImpl is not configured to track parents." <NEW_LINE> assert self.trackparent, msg <NEW_LINE> id_ = id(self.parent_token) <NEW_LINE> if value: <NEW_LINE> <INDENT> state.parents[id_] = parent_state <NEW_LINE> <DEDENT> else: <NEW_...
Set a boolean flag on the given item corresponding to whether or not it is attached to a parent object via the attribute represented by this ``InstrumentedAttribute``.
625941d201c39578d7e74fdf
def testPlotting(self): <NEW_LINE> <INDENT> import matplotlib.pyplot as plt <NEW_LINE> plt.switch_backend("agg") <NEW_LINE> ext = ".png" <NEW_LINE> with lsst.utils.tests.getTempFilePath(ext) as filename: <NEW_LINE> <INDENT> figure, axes = self.fluxTable.plot(show=False) <NEW_LINE> figure.savefig(filename) <NEW_LINE> <D...
Test plotting Not easy to test the actual result, but we can test that the API hasn't been broken.
625941d223e79379d52ee706
def collectGarbage(self) -> None: <NEW_LINE> <INDENT> for checker in self._resource_checkers: <NEW_LINE> <INDENT> checker.cleanResources()
Cleans up any resources that are left after a cluster has been removed.
625941d2d18da76e2353267b
def __init__(self): <NEW_LINE> <INDENT> self.registration = ['network', 'netflow'] <NEW_LINE> self.priority = 5 <NEW_LINE> config_location = os.path.join(os.path.dirname(os.path.abspath(__file__)), "mozilla_location.conf") <NEW_LINE> self.dc_code_list = getConfig('dc_code_list', '', config_location).split(',') <NEW_LIN...
this plugin takes a source hostname of form host.private.site.mozilla.com extracts the site, adds it and compares the site to a list of known datacenters or offices and adds that metadata
625941d27c178a314d6ef604
def test_evaluate_model(): <NEW_LINE> <INDENT> print("test_evaluate_model") <NEW_LINE> path = "data/red.csv" <NEW_LINE> data = pd.read_csv(path, sep=',', index_col=0) <NEW_LINE> bins = (2, 6.5, 8) <NEW_LINE> data['quality'] = pd.cut(data['quality'], bins=bins, labels=['bad', 'good']) <NEW_LINE> label_quality = LabelEnc...
test evaluate_model function
625941d24e696a04525c95ef
def _get_mem_hash(self, start_addr, end_addr): <NEW_LINE> <INDENT> data = self._emu.mem_read(start_addr, end_addr - start_addr) <NEW_LINE> m = hashlib.sha1() <NEW_LINE> m.update(data) <NEW_LINE> hex_hash = binascii.hexlify(m.digest()) <NEW_LINE> return hex_hash
calculate sha1 of the binary memory data to check integrity. not including the end_addr
625941d20a366e3fb873e9be
def tip_scratch(delta_z, end_pos, start_pos=None): <NEW_LINE> <INDENT> mo.xy_scanner.Store_Current_Position(True) <NEW_LINE> mo.regulator.Feedback_Loop_Enabled(False) <NEW_LINE> if start_pos is not None: <NEW_LINE> <INDENT> mo.xy_scanner.Target_Position(start_pos) <NEW_LINE> mo.xy_scanner.move() <NEW_LINE> <DEDENT> mo....
Super destructive. Press the tip into the surface, move it, then come back out. Attributes ---------- delta_z : float The depth to ramp in meters. start_pos : tuple or None The position in normalised co-ordinate range(-1, 1) to perform the initial crash at. Set to None (default) to start from the current p...
625941d28da39b475bd65118
def setPoster(self, poster): <NEW_LINE> <INDENT> self._poster = poster
Sets the poster image, which is shown in place of the video before the user presses play.
625941d229b78933be1e584e
def libgl_workaround() -> None: <NEW_LINE> <INDENT> if os.environ.get('QUTE_SKIP_LIBGL_WORKAROUND'): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> libgl = ctypes.util.find_library("GL") <NEW_LINE> if libgl is not None: <NEW_LINE> <INDENT> ctypes.CDLL(libgl, mode=ctypes.RTLD_GLOBAL)
Work around QOpenGLShaderProgram issues, especially for Nvidia. See https://bugs.launchpad.net/ubuntu/+source/python-qt4/+bug/941826
625941d22c8b7c6e89b35964
def __len__(self): <NEW_LINE> <INDENT> return self._fmodule._rank
Return the basis length, i.e. the rank of the free module. NB: the method ``__len__()`` is required for the basis to act as a "frame" in the class :class:`~sage.tensor.modules.comp.Components`. EXAMPLES:: sage: M = FiniteRankFreeModule(ZZ, 3, name='M') sage: e = M.basis('e') sage: e.__len__() 3 s...
625941d2d6c5a102081441ef
def _trail(path): <NEW_LINE> <INDENT> return join(path, "")
Ensure the path has a trailing separator.
625941d299fddb7c1c9de534
def readUID(self): <NEW_LINE> <INDENT> print("ok") <NEW_LINE> uid = bytes(0) <NEW_LINE> i = 0 <NEW_LINE> self.__uid = uid <NEW_LINE> while(self.__srl.inWaiting() == 0): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> byte = bytes(0) <NEW_LINE> line = bytes(0) <NEW_LINE> endFound = False <NEW_LINE> found = -1 <NEW_LINE> wh...
main method to read only UIDs
625941d263d6d428bbe44693
def run( self, *, actual_output: bytes, input_path: Path, expected_output_path: Optional[Path] ) -> bool: <NEW_LINE> <INDENT> return True
with tempfile.TemporaryDirectory() as tempdir: actual_output_path = Path(tempdir) / "actual.out" with open(actual_output_path, "wb") as fh: fh.write(actual_output) # if you use shlex.quote, it fails on Windows. why? command = " ".join( [ self.judge_command, # already quoted...
625941d26fb2d068a760f242
def test_for_existing_email(self): <NEW_LINE> <INDENT> user = json.dumps({ 'name': 'Joy', 'email': 'candy@gmail.com', 'password': 'phaneroo' }) <NEW_LINE> response = self.client.post('/auth/register', data=user) <NEW_LINE> self.assertEqual(response.status_code, 400) <NEW_LINE> self.assertIn('This email Already exists',...
Should check if email exists
625941d276d4e153a657ecd5
def get(): <NEW_LINE> <INDENT> headers = { 'Content-Type': 'application/json', 'Authorization': 'JWT {}'.format(self._get_jwt(user)) } <NEW_LINE> url = '{base_url}/orders/{order_number}/'.format(base_url=self.url, order_number=order_number) <NEW_LINE> return requests.get(url, headers=headers, timeout=self.timeout)
Internal service call to retrieve an order.
625941d2236d856c2ad44980
@cli.command() <NEW_LINE> @click.option('--format', type=click.Choice(['table', 'machine']), default='table', help="Data output format.") <NEW_LINE> @click.argument('sch_f', type=click.File('r')) <NEW_LINE> def parts(format: str, sch_f: TextIO) -> None: <NEW_LINE> <INDENT> parsed = parse_file(sch_f) <NEW_LINE> if not i...
List used parts/libraries in a schematic
625941d22ae34c7f2600d2d5
def get_name(self): <NEW_LINE> <INDENT> return self.name
Return this predictor's name
625941d2462c4b4f79d1d875
def add(self, first_number, second_number): <NEW_LINE> <INDENT> return first_number + second_number
Adds two numbers together Arguments: first_number - Any number second_number - An number
625941d23c8af77a43ae3945
def configure_peripherals(self, power: int = PinConfiguration.DISABLE, pull_ups: int = PinConfiguration.DISABLE, aux: int = PinConfiguration.DISABLE, chip_select: int = PinConfiguration.DISABLE) -> bool: <NEW_LINE> <INDENT> data = 0 <NEW_LINE> data += power <NEW_LINE> data += pull_ups <NEW_LINE> data += aux <NEW_LINE> ...
SPI Configure Peripherial Pins :param power: The Pin Configuration for Power Pins :type power: int. :param pull_ups: The Pin Configuration for Pull Up Pins :type pull_ups: int. :param aux: The Pin Configuration for AUX pin :type aux: int. :param chip_select: The Pin Configuration for Chip Select Pin :type chip_sele...
625941d250812a4eaa59c4c5
def nanne(x, y, nan_nan=False, nan_val=False, val_nan=False): <NEW_LINE> <INDENT> return nan_compare(np.not_equal, x, y, nan_nan=nan_nan, nan_val=nan_val, val_nan=val_nan)
nanne(x, y) is equivalent to (x != y) except that NaN values in either x or y result in False. The following optional arguments may be provided: * nan_nan (default: False) specifies the return value (True or False) for comparisons equivalent to nanne(nan, nan). * nan_val (default: False) specifies the return v...
625941d2099cdd3c635f0dff
def chapter_title(Chapter): <NEW_LINE> <INDENT> html_doc = chapter_html_doc(Chapter) <NEW_LINE> return html_doc.h1.text
chapter title selector
625941d23cc13d1c6d3c751e
def logNegProbAbnormGivenWords(self, doc, epsilon = 0.1, particles = 16, cap = -1): <NEW_LINE> <INDENT> if not isinstance(epsilon,numpy.ndarray): <NEW_LINE> <INDENT> value = epsilon <NEW_LINE> epsilon = numpy.ones(self.sample[0].phi.shape[0], dtype=numpy.float32) <NEW_LINE> epsilon *= value <NEW_LINE> epsilon[0] = 1.0 ...
Returns the probability of the documents current abnormality flags - uses Bayes rule on logNegProbAbnormGivenWords. Does not attempt to calculate the normalising constant, so everything is with proportionality - you can compare flags for a document, but can't compare between different documents. You actually provide ep...
625941d27cff6e4e81117b2a
def test_validate_yang_models(self, sonic_yang_data): <NEW_LINE> <INDENT> test_file = sonic_yang_data['test_file'] <NEW_LINE> syc = sonic_yang_data['syc'] <NEW_LINE> NON_CONFIG_YANG_FILES = 3 <NEW_LINE> jIn = self.readIjsonInput(test_file, 'SAMPLE_CONFIG_DB_JSON') <NEW_LINE> jIn = json.loads(jIn) <NEW_LINE> numTables =...
In this test, we validate yang models a.) by converting the config as per RFC 7951 using YANG Models, b.) by creating data tree using new YANG models and c.) by validating config against YANG models. Successful execution of these steps can be treated as validation of new Yang models.
625941d2004d5f362079a4d7
def clear_contents(self): <NEW_LINE> <INDENT> default_home_id = int(settings.DEFAULT_HOME.lstrip("#")) <NEW_LINE> try: <NEW_LINE> <INDENT> default_home = ObjectDB.objects.get(id=default_home_id) <NEW_LINE> if default_home.dbid == self.dbid: <NEW_LINE> <INDENT> default_home = None <NEW_LINE> <DEDENT> <DEDENT> except Exc...
Moves all objects (players/things) to their home location or to default home.
625941d23d592f4c4ed1d210
def plot_cov_ellipse(cov, pos, nstd=2, ax=None, **kwargs): <NEW_LINE> <INDENT> def eigsorted(cov): <NEW_LINE> <INDENT> vals, vecs = np.linalg.eigh(cov) <NEW_LINE> order = vals.argsort()[::-1] <NEW_LINE> return vals[order], vecs[:,order] <NEW_LINE> <DEDENT> if ax is None: <NEW_LINE> <INDENT> ax = plt.gca() <NEW_LINE> <D...
Plots an `nstd` sigma error ellipse based on the specified covariance matrix (`cov`). Additional keyword arguments are passed on to the ellipse patch artist. Parameters ---------- cov : The 2x2 covariance matrix to base the ellipse on pos : The location of the center of the ellipse. Expects a 2-element ...
625941d299fddb7c1c9de535
def add_aero(self, velocity, cref, rho_ref, acsid=0, sym_xz=0, sym_xy=0, comment=''): <NEW_LINE> <INDENT> aero = AERO(velocity, cref, rho_ref, acsid=acsid, sym_xz=sym_xz, sym_xy=sym_xy, comment=comment) <NEW_LINE> self._add_aero_object(aero) <NEW_LINE> return aero
Creates an AERO card Parameters ---------- velocity : float the airspeed cref : float the aerodynamic chord rho_ref : float FLFACT density scaling factor acsid : int; default=0 aerodyanmic coordinate system sym_xz : int; default=0 xz symmetry flag (+1=symmetry; -1=antisymmetric) sym_xy : int; defau...
625941d24527f215b584c5fa
def predict(self, ids: Sequence[int]) -> (numpy.ndarray, numpy.ndarray): <NEW_LINE> <INDENT> features = self._db.read_features(ids) <NEW_LINE> p_predictions, variances = self.model_.predict(features) <NEW_LINE> n_predictions = 1 - p_predictions <NEW_LINE> predictions = numpy.concatenate([n_predictions, p_predictions], ...
Predicts labels of instances. Notes ----- Unlike in scikit-learn, predictions are always real-valued. Predicted labels for a classification problem are represented by predicted probabilities of each class. Parameters ---------- ids List of IDs of instances to predict labels for. Returns ------- numpy...
625941d2566aa707497f470b
def _pdf_find_urls(bytes, mimetype): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ascii_bytes = b' '.join(re.compile(b'[\x00\x09\x0A\x0D\x20-\x7E]{12,}').findall(bytes)) <NEW_LINE> ascii_bytes = ascii_bytes.replace(b'\x00', b'') <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> urls = [] <NE...
This function finds URLs inside of PDF bytes.
625941d27b25080760e395fd
def _retrieve(self, obj, selector, preserve, countPurged): <NEW_LINE> <INDENT> saved = transaction.savepoint(optimistic=True) <NEW_LINE> vd = self._recursiveRetrieve(obj=obj, selector=selector, preserve=preserve, inplace=False, countPurged=countPurged) <NEW_LINE> try: <NEW_LINE> <INDENT> saved.rollback() <NEW_LINE> <DE...
Retrieve a former state. Puts the returned version into same context as the working copy is (to make attribute access acquirable).
625941d27d847024c06be461
def start(self): <NEW_LINE> <INDENT> return _sync_fft_swig.hwfft_sptr_start(self)
start(hwfft_sptr self) -> bool
625941d2baa26c4b54cb12c3
def test_doubleErrorDoesNotRemoveObserver(self): <NEW_LINE> <INDENT> events = [] <NEW_LINE> errors = [] <NEW_LINE> publisher = log.LogPublisher() <NEW_LINE> class FailingObserver(object): <NEW_LINE> <INDENT> calls = 0 <NEW_LINE> def log(self, msg, **kwargs): <NEW_LINE> <INDENT> self.calls += 1 <NEW_LINE> if self.calls ...
If logging causes an error, make sure that if logging the fact that logging failed also causes an error, the log observer is not removed.
625941d2be8e80087fb20de6
def get_endpoints(self, **kwargs): <NEW_LINE> <INDENT> operation_name = "get_endpoints" <NEW_LINE> params = locals() <NEW_LINE> for key, val in six.iteritems(params['kwargs']): <NEW_LINE> <INDENT> params[key] = val <NEW_LINE> <DEDENT> del params['kwargs'] <NEW_LINE> resource_path = '/v1/endpoints/' <NEW_LINE> resource_...
This API is invoked by the skill to retrieve endpoints connected to the Echo device. :param full_response: Boolean value to check if response should contain headers and status code information. This value had to be passed through keyword arguments, by default the parameter value is set to False. :type full_respo...
625941d256ac1b37e6264371
def get_job_parameter(self, job_parameter_name): <NEW_LINE> <INDENT> if self._has_job() is False: <NEW_LINE> <INDENT> raise Exception(self.JOB_NOT_FOUND) <NEW_LINE> <DEDENT> if job_parameter_name not in self.__json_data[self.JOB_KEY]: <NEW_LINE> <INDENT> raise Exception(job_parameter_name + " field was not found.") <NE...
Get a field :param job_parameter_name: string :return: string
625941d2956e5f7376d71011
def get_pokemon_info(pokemon, language): <NEW_LINE> <INDENT> r = requests.get(url.format('pokemon/{}'.format(pokemon))) <NEW_LINE> if r.status_code != 200: <NEW_LINE> <INDENT> return responses['error'][language] <NEW_LINE> <DEDENT> r_json = r.json() <NEW_LINE> poke_info = dict() <NEW_LINE> poke_info['name'] = r_json['n...
Obtiene información básica de un Pokémon en un idioma determinado
625941d26fb2d068a760f243
def keyy5(): <NEW_LINE> <INDENT> global h, playernvl2,i,j,y,i2,x2,nvl5,playernvl22,x,can5 <NEW_LINE> if(68 in h): <NEW_LINE> <INDENT> if(i<150): <NEW_LINE> <INDENT> can5.delete(x) <NEW_LINE> i = i + 3 <NEW_LINE> x = can5.create_image(400+i,750+j,image=carro) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> can5.delete(x) ...
funcion para mover los jugadores del nivel5
625941d226068e7796caee84
def __init__(self,data_dir,filename_list,batch_size,imshape,num_classes,crop_shape=[0,0,0], if_random_crop=True, if_flip=False, if_bright=False, if_contrast=False, if_whiten=False, num_epochs=0): <NEW_LINE> <INDENT> self.data_dir=data_dir <NEW_LINE> self.filename_list=filename_list <NEW_LINE> self.batch_size=batch_size...
Args: data_dir: string, directory for .tfrecords file. filename: string, filename for .tfrecords file. batch_size: int, output numbers of images for one time. imshape: int_list with lenght 3, [heigth,width,channal] crop_shape: if Ture, return image tensor with shape crop_shape. if_...: process f...
625941d2fbf16365ca6f636b
def __len__( self ): <NEW_LINE> <INDENT> return len( self._sji_data )
Returns number of items
625941d221bff66bcd684af6
def process_major_each_colleage(self, colleage: Colleage): <NEW_LINE> <INDENT> assert isinstance(colleage, Colleage) <NEW_LINE> self.colleage = colleage <NEW_LINE> _res = self.request_major_department_list( year=self.year, term=self.term, col_cd=colleage.col_cd ) <NEW_LINE> _departments = self.parse_departments(raw_htm...
year, term, campus가 정해지고 colleage를 제공받아 단과대별로 전공 정보를 수집합니다. 다음 단계 : process_major_each_department @param colleage 수집할 단과대학입니다.
625941d257b8e32f52483640
def set_county(self, county): <NEW_LINE> <INDENT> self.__county = county
:param county:
625941d2c4546d3d9de72bd9
def test_user_registration(self): <NEW_LINE> <INDENT> response = self.client().post( '/api/v2/auth/register', data=json.dumps(self.user), content_type='application/json') <NEW_LINE> self.assertEquals(response.status_code, 406) <NEW_LINE> response_msg = json.loads(response.data.decode("UTF-8")) <NEW_LINE> self.assertEqu...
test for user registration
625941d229b78933be1e584f
def __init__(self, call_list, name_mapping=None): <NEW_LINE> <INDENT> self.__name_mapping = name_mapping <NEW_LINE> self.__call_list = self.__parse_list(call_list)
@param call_list: a list of expected calls as tuples (INSTANCE, METHOD, VALUE), where INSTANCE is the object, of which a method call is expected, METHOD is the string method name and VALUE is optional and can be the argument, that is expected to be...
625941d2656771135c3eba14
def check_clear_arg(value): <NEW_LINE> <INDENT> if value == '*': <NEW_LINE> <INDENT> return '*' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return int(value) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise argparse.ArgumentTypeError("%s is not an integer or '*'" % value)
Make sure the value passed in with the -c flag is either an integer or star (*)
625941d2a8370b7717052a43
def testPrintLabelResponse(self): <NEW_LINE> <INDENT> pass
Test PrintLabelResponse
625941d2b545ff76a8913fba
def get_drugs(): <NEW_LINE> <INDENT> kind='DRUG_KIND' <NEW_LINE> url = 'https://rxnav.nlm.nih.gov/REST/Ndfrt/allconcepts.json?kind='+kind <NEW_LINE> r = requests.get(url) <NEW_LINE> data = r.json() <NEW_LINE> groupConcepts = data['groupConcepts'] <NEW_LINE> target = open('drugs.txt', 'w') <NEW_LINE> try: <NEW_LINE> <IN...
This function pings for json objects of Drugs kind in the NDRrt database It then prints them on to a txt file for further use
625941d2498bea3a759b9c53
def __str__(self) -> str: <NEW_LINE> <INDENT> name = f"Athena query {self.execution_id!r}" <NEW_LINE> if self.state_reason is not None: <NEW_LINE> <INDENT> return f"{name} {self.state.lower()}: {self.state_reason}" <NEW_LINE> <DEDENT> return f"{name} {self.state.lower()}"
Report query state with its reason.
625941d2e8904600ed9f20d3
def sigmoid(self, sumofvalues): <NEW_LINE> <INDENT> result = 1/(1+math.exp(-sumofvalues)) <NEW_LINE> return result
Executes sigmoid function with the formula (1/(1+e^-sumofvalues)). Takes in a parameter called sumofvalues.
625941d2b5575c28eb68e1a5
def merge_equals(self, data_reducer=None, data_initializer=None): <NEW_LINE> <INDENT> if not self: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> sorted_intervals = sorted(self.all_intervals) <NEW_LINE> merged = [] <NEW_LINE> current_reduced = [None] <NEW_LINE> higher = None <NEW_LINE> def new_series(): <NEW_LINE> <IND...
Finds all intervals with equal ranges and merges them into a single interval. If provided, uses data_reducer and data_initializer with similar semantics to Python's built-in reduce(reducer_func[, initializer]), as follows: If data_reducer is set to a function, combines the data fields of the Intervals with current...
625941d28e71fb1e9831d94d
def storeCING2db(self): <NEW_LINE> <INDENT> nTmessage("Starting storeCING2db using self.entry_list_todo.") <NEW_LINE> if False: <NEW_LINE> <INDENT> nTmessage("Going to use non-default entry_list_todo in storeCING2db") <NEW_LINE> crdb = NrgCingRdb(schema=self.schema_id) <NEW_LINE> self.entry_list_todo = crdb.getPdbIdLis...
Return True on error.
625941d2e64d504609d749e5
def update_count(): <NEW_LINE> <INDENT> return __salt__['cmd.run']('(gcim -namespace root\ccm\clientsdk -query \'Select * from CCM_SoftwareUpdate\' | measure-object).Count', shell='powershell')
Get the number of available updates from ConfigMgr CLI Example:: salt 'os:Windows' sccm.update_count
625941d238b623060ff0af92
def default_revoked_token_callback(): <NEW_LINE> <INDENT> return jsonify({'msg': 'Token has been revoked'}), 401
By default, if a revoked token is used to access a protected endpoint, we return a general error message with a 401 status code
625941d223849d37ff7b3234
def StoreInCache(self, self_links): <NEW_LINE> <INDENT> if platforms.OperatingSystem.Current() == platforms.OperatingSystem.WINDOWS: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> paths = {} <NEW_LINE> collection = None <NEW_LINE> for ref in self_links: <NEW_LINE> <INDENT> if not collection: <NEW_LINE> <INDENT> tr...
Store names of resources listed in cache. Args: self_links: A list of resource instance references Returns: None
625941d25510c4643540f587
def tracepow(exp, num=1, denom=1, coef=None): <NEW_LINE> <INDENT> from .expressions import AffinExp, TracePow_Exp <NEW_LINE> if not isinstance(exp, AffinExp): <NEW_LINE> <INDENT> exp = AffinExp.fromMatrix(exp) <NEW_LINE> <DEDENT> if coef is not None and not isinstance(coef, AffinExp): <NEW_LINE> <INDENT> coef = AffinEx...
Returns a :class:`TracePow_Exp <picos.TracePow_Exp>` object representing the trace of the pth-power of the symmetric matrix ``exp``, where ``exp`` is an :class:`AffinExp <picos.AffinExp>` which we denote by :math:`X`. This can be used to enter constraints of the form :math:`\operatorname{trace} X^p \leq t` with :math:`...
625941d2b830903b967e9aaf
def is_at_in_list(atm, at_list, rname=None): <NEW_LINE> <INDENT> if rname is None: <NEW_LINE> <INDENT> rname = atm.get_parent().get_resname().replace(' ', '') <NEW_LINE> <DEDENT> if rname in at_list: <NEW_LINE> <INDENT> return atm.id in at_list[rname] or atm.id in at_list['*'] <NEW_LINE> <DEDENT> return atm.id in at_li...
Checks if **at is in **at_list in the context of **rname residue
625941d2f548e778e58cd723
def w_func(self, X, d, n): <NEW_LINE> <INDENT> if n == 0: <NEW_LINE> <INDENT> wX = self.w(X, d, 0) <NEW_LINE> if isinstance(self.k, WarpedKernel): <NEW_LINE> <INDENT> wX = self.k.w_func(wX, d, 0) <NEW_LINE> <DEDENT> return wX <NEW_LINE> <DEDENT> elif n == 1: <NEW_LINE> <INDENT> wXn = self.w(X, d, n) <NEW_LINE> if isins...
Evaluate the (possibly recursive) warping function and its derivatives. Parameters ---------- X : array, (`M`,) The points (from dimension `d`) to evaluate the warping function at. d : int The dimension to warp. n : int The derivative order to compute. So far only 0 and 1 are supported.
625941d2377c676e9127234d
def __len__(self): <NEW_LINE> <INDENT> l = int(len(self.img_seg_pairs) / self.batch_size) <NEW_LINE> return l
Denotes the number of batches per epoch
625941d25166f23b2e1a52fe
def mu_law_encode(audio, quantization_channels=256): <NEW_LINE> <INDENT> mu = float(quantization_channels - 1) <NEW_LINE> quantize_space = np.linspace(-1, 1, quantization_channels) <NEW_LINE> quantized = np.sign(audio) * np.log(1 + mu * np.abs(audio)) / np.log(mu + 1) <NEW_LINE> quantized = np.digitize(quantized, quant...
Quantize waveform amplitudes. Reference: https://github.com/vincentherrmann/ pytorch-wavenet/blob/master/audio_data.py
625941d2fb3f5b602dac3839
def sb_matrix(means, n_classes, spc): <NEW_LINE> <INDENT> all_class_mean = means.mean(0) <NEW_LINE> b_matrix = np.zeros((means.shape[1], means.shape[1])) <NEW_LINE> for i in range(n_classes): <NEW_LINE> <INDENT> diff = (means[i, :] - all_class_mean)[:, np.newaxis] <NEW_LINE> diff = spc * np.matmul(diff, diff.T) <NEW_LI...
Calculate between classes scatter matrix :param means: classes mean :type means: array-like (nd-array, matrix, etc) :param n_classes: number of classes in the given data set :type n_classes: int :param spc: number of samples per class :type spc: int :return: between class scatter matrix :rtype: numpy matrix
625941d297e22403b379d13f
def show_schedule(self): <NEW_LINE> <INDENT> url = "https://nba.hupu.com/schedule" <NEW_LINE> r = requests.get(url, headers=self._headers, timeout=6).text <NEW_LINE> result = str(BeautifulSoup(r, 'lxml').find('table', class_="players_table").text).split() <NEW_LINE> schedule = [r for r in result if r not in ["数据统计", "比...
显示赛程
625941d23eb6a72ae02ec685
def test_generate_azure_events_default_and_no_times(self): <NEW_LINE> <INDENT> account = helper.generate_cloud_account(cloud_type="azure") <NEW_LINE> instance = helper.generate_instance(account) <NEW_LINE> events = helper.generate_instance_events(instance, tuple(), cloud_type="azure") <NEW_LINE> self.assertEqual(len(ev...
Assert generation of an azure InstanceEvent.
625941d25fcc89381b1e1865
def findRoute( self, sourceSE, targetSE ): <NEW_LINE> <INDENT> return S_ERROR( 'IMPLEMENT ME' )
Find the appropriate route from point A to B :param sourceSE : source SE :param targetSE : destination SE :returns: S_OK(FTSRoute)
625941d2f8510a7c17cf98a1
def process_names(fnames): <NEW_LINE> <INDENT> split_names = [os.path.splitext(x)[0].split(" ") for x in fnames] <NEW_LINE> metadata = pd.DataFrame(split_names, columns = ["genotype_leaf", "ch1", "ch2", "ch3", "ch4"]) <NEW_LINE> metadata.insert(0, "fname", fnames) <NEW_LINE> for i in range(1, 5): <NEW_LINE> <INDENT> cu...
Extract Metadata from Filenames The files are named in a consistent enough way that we can extract the relevant features automatically. :param fnames: The original names as a list of strings, encoding features for each sample. :return metadata: A pd.DataFrame whose rows are samples and whose columns. >>> raw_pat...
625941d2460517430c394328
def create_sslcert(self, name, common_name, pri, ca): <NEW_LINE> <INDENT> req = {} <NEW_LINE> req.update({"name": name}) <NEW_LINE> req.update({"common_name": common_name}) <NEW_LINE> req.update({"pri": pri}) <NEW_LINE> req.update({"ca": ca}) <NEW_LINE> body = json.dumps(req) <NEW_LINE> url = '{0}/sslcert'.format(self....
修改证书,文档 https://developer.qiniu.com/fusion/api/4246/the-domain-name#11 Args: name: 证书名称 common_name: 相关域名 pri: 证书私钥 ca: 证书内容 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回dict{certID: <CertID>},失败返回{"error": "<errMsg string>"} - ResponseInfo ...
625941d2d268445f265b5013
def expect_header(self, name, value): <NEW_LINE> <INDENT> self.add_expectation(ExpectedHeader(name, value)) <NEW_LINE> return self
Add an expectation that the HTTP response will contain a header with the specified name and value.
625941d2435de62698dfddf2
@cli.group() <NEW_LINE> def webhook_config(): <NEW_LINE> <INDENT> pass
Helpers to create and test webhook configs.
625941d263b5f9789fde728b
def read_names(num_names): <NEW_LINE> <INDENT> pass
:param num_names: the number of names to read :return: prompt the user to enter a name in the specified format: last, first
625941d2293b9510aa2c343a
def generate_object_list_1(spec): <NEW_LINE> <INDENT> names = [name for name in spec['Objects']] <NEW_LINE> descriptions = [spec['Objects'][name] for name in names] <NEW_LINE> objectlist = {} <NEW_LINE> for i in range(len(names)): <NEW_LINE> <INDENT> obj = ModelObject(names[i], descriptions[i]) <NEW_LINE> objectlist[na...
! Function to generate a table (dictionary) of objects, which represents the entities / nodes of the model. This function is used for AdvanceSyn model specification type 1. @param spec Object: ConfigParser object containing the processed model - from modelspec_reader() or specobj_reader() functions. @return: Dictio...
625941d2d7e4931a7ee9e0c3
def get_engine(self): <NEW_LINE> <INDENT> return create_engine(self.connetion_string, listeners=[ForeignKeysListener()], echo=self.debug, echo_pool=self.debug, strategy='plain')
Returns the engine
625941d27d43ff24873a2e46
def __init__(self, **kwargs): <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> self._namespace = ONTOLOGY_NS <NEW_LINE> self._project_id = PROJECT_ID <NEW_LINE> self._name = "Village"
:param kwargs:
625941d25e10d32532c5f0cc
def setUp(self): <NEW_LINE> <INDENT> self.http = HTTPClient("127.0.0.1", 80) <NEW_LINE> self.con = Mock.HTTPConnection() <NEW_LINE> self.http._getconnection = lambda: self.con
Setup the client.
625941d2aad79263cf390be7
def test_b(self): <NEW_LINE> <INDENT> p = subprocess.Popen(['/usr/bin/python3', './lab1b.py'], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) <NEW_LINE> stdout, _ = p.communicate() <NEW_LINE> expected_output = b'How old are you Isaac?\n' <NEW_LINE> error_output = 'output is not correct(HINT: pay...
[Lab 1] - [Investigation 4] - string objects & printing - Test for correct output "How old are you Isaac?": ./lab1b.py
625941d226238365f5f0f014
def dispatch(self, *args, **kwargs): <NEW_LINE> <INDENT> token = kwargs['token'] <NEW_LINE> self.user = ( self.request.user if self.request.user.is_authenticated else None ) <NEW_LINE> self.room = self.get_object_or_404(PokerRoom, token=token) <NEW_LINE> self.poker_round = self.room.get_poker_round() <NEW_LINE> self.me...
Dispatch request.
625941d2097d151d1a222ffe
def glance_exits(room): <NEW_LINE> <INDENT> exits = room.exits <NEW_LINE> if exits: <NEW_LINE> <INDENT> ret = "" <NEW_LINE> for exit in exits: <NEW_LINE> <INDENT> ret += "\n " + exit.key.ljust(20) <NEW_LINE> ret += " (to {}(#{})".format(exit.destination.key, exit.destination.id) <NEW_LINE> <DEDENT> return ret <NEW_LI...
Show the exits in the room. Args: room (Room): the room with exits.
625941d2236d856c2ad44981
def getTimeBaseNum(self, sampleTimeS): <NEW_LINE> <INDENT> time_interval = c_int32() <NEW_LINE> timebases = [None] * self.MAX_TIMEBASES <NEW_LINE> sampleTimenS = sampleTimeS * 1E9 <NEW_LINE> tb = 0 <NEW_LINE> while tb < self.MAX_TIMEBASES: <NEW_LINE> <INDENT> rv = self.lib.ps3000_get_timebase( c_int16(self.handle), c_i...
ps3000 doesn't seem to have published formula like other scopes.
625941d24c3428357757c4cd