code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def int_to_one_hot(arr, n_classes): <NEW_LINE> <INDENT> arr = np.array(arr) <NEW_LINE> assert arr.size > 0, "Cannot hotify empty array" <NEW_LINE> one_hot = np.zeros(arr.shape + (n_classes,)) <NEW_LINE> axes_ranges = [range(arr.shape[i]) for i in range(arr.ndim)] <NEW_LINE> flat_grids = [_.ravel() for _ in np.meshgrid(...
:param arr: N dim array of size i_1, ..., i_N :param n_classes: C :returns: one-hot N+1 dim array of size i_1, ..., i_N, C :rtype: ndarray
625941e9baa26c4b54cb15ba
def collect_garbage(self): <NEW_LINE> <INDENT> timeout = self.optimize_after <NEW_LINE> key = self.get_full_item_key('__gc') <NEW_LINE> next_gc = self.get(key) <NEW_LINE> if not next_gc: <NEW_LINE> <INDENT> next_gc = times.expires_to_timestamp(timeout) <NEW_LINE> self.set(key, next_gc) <NEW_LINE> return False <NEW_LINE...
Collect garbage Checks previous garbage collection timestamp and performs optimization if its time to do so. You should consider lower optimization timeout than default under load. :return: None
625941e9dd821e528d63b645
def __len__(self): <NEW_LINE> <INDENT> return self.index.size
Returns number of rows in table.
625941e9be383301e01b591c
def create_backup_copy(self): <NEW_LINE> <INDENT> shutil.copy2(self.filename, self.filename + '.bak')
Create a backup copy
625941e9a934411ee3751b34
def setSliceWidgetsDims(self): <NEW_LINE> <INDENT> self.c_slice_widget.setImageDimensions( [self.img_dims[0], self.img_dims[2], self.img_dims[1]]) <NEW_LINE> self.s_slice_widget.setImageDimensions( [self.img_dims[1], self.img_dims[2], self.img_dims[0]]) <NEW_LINE> self.t_slice_widget.setImageDimensions( [self.img_dims[...
This passes the correct image dimensions to all slice views to ensure correct behaviour of the cursor and crosshair. Should be executed after each resampling.
625941e9ff9c53063f47c691
def updateActionLayer(self, previousPropositionLayer): <NEW_LINE> <INDENT> allActions = PlanGraphLevel.actions <NEW_LINE> for action in allActions: <NEW_LINE> <INDENT> if previousPropositionLayer.allPrecondsInLayer(action) and True not in [previousPropositionLayer.isMutex(p1, p2) for p1, p2 in exclusiveP...
Updates the action layer given the previous proposition layer (see propositionLayer.py) You should add an action to the layer if its preconditions are in the previous propositions layer, and the preconditions are not pairwise mutex. allAction is the list of all the action (include noOp) in the domain You might want to ...
625941e93317a56b8693a0ec
def as_image(url, **attributes): <NEW_LINE> <INDENT> return as_tag('img', pair=False, src=url, **attributes)
Formats the given URL as an image. >>> as_image('file://localhost/C:/foo.png') u'<img src="file://localhost/C:/foo.png"/>'
625941e9d53ae8145f87a706
def update_entry_acl_cdmi(self, cdmi_acl): <NEW_LINE> <INDENT> cql_string = acl_cdmi_to_cql(cdmi_acl) <NEW_LINE> self.update_entry_acl(cql_string)
"Update entry ACL from a cdmi object (list of dict)
625941e9e64d504609d74ce0
def get_fact_from_parents(fact, entity): <NEW_LINE> <INDENT> while entity.parent: <NEW_LINE> <INDENT> if fact in entity.parent.facts: <NEW_LINE> <INDENT> return entity.parent[fact] <NEW_LINE> <DEDENT> entity = entity.parent
Crawl through this entity's parents and return the first 'fact' it finds.
625941e9c432627299f050e9
def testRPMBuildData(self): <NEW_LINE> <INDENT> dataIdentifier = "RPM" <NEW_LINE> knownDataFile = "rpmbuild_realanomaly_networkIn.csv" <NEW_LINE> expectedResults = {"fn": 48, "fp": 58, "tn": 7130, "tp": 141, "quality": 10720} <NEW_LINE> self._runQualityTest(dataIdentifier, knownDataFile, expectedResults)
RPM Build Caught Anomaly - Network In 7428 rows
625941e921bff66bcd684dee
@pytest.fixture <NEW_LINE> def rollback_sysmodules(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sysmodules = list(sys.modules) <NEW_LINE> yield <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> for modname in list(sys.modules): <NEW_LINE> <INDENT> if modname not in sysmodules: <NEW_LINE> <INDENT> sys.modules.pop(modn...
Rollback sys.modules to before testing to unload modules during tests.
625941e9507cdc57c6307186
def getUnitType(self): <NEW_LINE> <INDENT> return self._units
Returns which of the psychopy coordinate systems are used by the TextBox. Position and size related attributes mush be specified relative to the unit type being used. Valid options are: - pix - norm - cm
625941e9566aa707497f4a02
def get_deviation_anim_curve_fn(self): <NEW_LINE> <INDENT> animFn = self._MFnAnimCurve_deviation <NEW_LINE> if animFn is None: <NEW_LINE> <INDENT> node = self.get_node() <NEW_LINE> if node is None: <NEW_LINE> <INDENT> LOG.warn('Could not get Marker node. self=%r', self) <NEW_LINE> return animFn <NEW_LINE> <DEDENT> plug...
Get the MFnAnimCurve object for the deviation attribute animCurve. .. note:: Returned object is Maya API 1.0. :returns: Maya animCurve function set. :rtype: maya.OpenMayaAnim.MFnAnimCurve or None
625941e9e1aae11d1e74a15c
def idx(self): <NEW_LINE> <INDENT> return column.LinearDataColumn(self.nrows())
Create an index column (analogous to ``numpy.arange(len(table))``).
625941e9283ffb24f3c55d9c
def getjflag(job): <NEW_LINE> <INDENT> return 1 if job['jobstatus'] in ('finished', 'failed', 'cancelled', 'closed') else 0
Returns flag if job in finished state
625941e9090684286d50f18d
def test_straight_flush2(self): <NEW_LINE> <INDENT> hand = [card.Card("club", 10), card.Card("club", 12), card.Card( "club", 9), card.Card("club", 11), card.Card("club", 13)] <NEW_LINE> result = self.judge.judge(hand) <NEW_LINE> self.assertEqual(result, 813)
ストレートフラッシュの判定テスト2
625941e94527f215b584c8f2
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, AirDirection): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941e923849d37ff7b352b
def test_contents_test2(self): <NEW_LINE> <INDENT> M = process_meeting(contents=self.all_commands_test_contents, extraConfig={'writer_map':self.full_writer_map}) <NEW_LINE> results = M.save() <NEW_LINE> for name, output in six.iteritems(results): <NEW_LINE> <INDENT> if isinstance(output, bytes): <NEW_LINE> <INDENT> out...
Ensure that certain input lines do appear in the output. This test ensures that the input to certain commands does appear in the output.
625941e98e71fb1e9831dc47
def gaussian_gpu_v2(sigma, size=None): <NEW_LINE> <INDENT> if not size: <NEW_LINE> <INDENT> size = int(1 + 8 * sigma) <NEW_LINE> <DEDENT> g_gpu = pyopencl.array.empty(queue, size, dtype=numpy.float32, order="C") <NEW_LINE> t0 = time.time() <NEW_LINE> evt = kernels["gaussian"].gaussian(queue, (64,), (64,), g_gpu.data, n...
Calculate a 1D gaussian using pyopencl. This is the same as scipy.signal.gaussian. Only one kernel to @param sigma: width of the gaussian @param size: can be calculated as 1 + 2 * 4sigma
625941e97d43ff24873a3144
def close_connection(self,cid=None,reason=None): <NEW_LINE> <INDENT> self.send_message("peng3dnet:internal.closeconn",{"reason":reason}) <NEW_LINE> self._mark_close = True <NEW_LINE> self._close_reason = reason
Closes the connection to the server due to the optional reason. ``cid`` is a dummy value used for compatibility with server applications. ``reason`` may be a string describing the reason.
625941e9d18da76e2353297c
def mutt_sendmail( tostr, subject, body, attach, content_is_html=False ): <NEW_LINE> <INDENT> decorators.needlinux(mutt_sendmail) <NEW_LINE> shellobj = shell.ShellExec() <NEW_LINE> temp_cwd = os.getcwd() <NEW_LINE> str_att = '' <NEW_LINE> cmdstr = '' <NEW_LINE> if attach == '': <NEW_LINE> <INDENT> if content_is_html is...
Plz notice this function is not recommanded to use. Use SmtpMailer instead. :param exec_cwd: exec working directory. Plz use :param tostr: recipt list, separated by , :param subject: subject :param body: email content :param attach: email attachment :param content_is_html: is htm mode opened :...
625941e9956e5f7376d7130c
def main(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser( description='Controller to handle database creation and dropping' ' commands.', epilog='Under normal circumstances is not used directly.' ' Used in .testr.conf to automate test database creation' ' and dropping processes.') <NEW_LINE> subparsers = parser...
Controller to handle commands ::create: Create test user and database with random names. ::drop: Drop user and database created by previous command.
625941e938b623060ff0b28d
def testV1alpha1VirtualMachineFlavor(self): <NEW_LINE> <INDENT> pass
Test V1alpha1VirtualMachineFlavor
625941e9f8510a7c17cf9ba0
def create_model(self, hyper_parameters): <NEW_LINE> <INDENT> Embeddings = None <NEW_LINE> if self.embedding_type == 'random': <NEW_LINE> <INDENT> from keras_textclassification.base.embedding import RandomEmbedding as Embeddings <NEW_LINE> <DEDENT> elif self.embedding_type == 'bert': <NEW_LINE> <INDENT> from keras_text...
构建神经网络 :param hyper_parameters: json,超参数 :return:
625941e9f7d966606f6aa4aa
def glInitCompressedAtcTextureAMD(): <NEW_LINE> <INDENT> from OpenGL import extensions <NEW_LINE> return extensions.hasGLExtension( _EXTENSION_NAME )
Return boolean indicating whether this extension is available
625941e932920d7e50b28674
def test_node_comparison(self): <NEW_LINE> <INDENT> self.assertEqual(graph.Node(1), graph.Node(1))
Test node comparison
625941e9d7e4931a7ee9e3bf
def run(self, handler=None): <NEW_LINE> <INDENT> status, results = self.__process.run(ProgressHandlerWrapper(handler)) <NEW_LINE> for x in results: <NEW_LINE> <INDENT> if x.has_key('status'): <NEW_LINE> <INDENT> x['status'] = XRootDStatus(x['status']) <NEW_LINE> <DEDENT> <DEDENT> return XRootDStatus(status), results
Run the copy jobs with an optional progress handler. :param handler: a copy progress handler. You can subclass :mod:`XRootD.client.utils.CopyProgressHandler` and implement the three methods (``begin()``, ``progress()`` and ``end()`` ) to get regular progress updates for...
625941e91f5feb6acb0c4fea
def setup_logging(): <NEW_LINE> <INDENT> log = get_simpleline_logger() <NEW_LINE> null_hd = logging.NullHandler() <NEW_LINE> log.addHandler(null_hd)
Set proper logging for a library
625941e991f36d47f21ac997
def _bidirectional_encoder(self, embedded_inputs, src_lengths): <NEW_LINE> <INDENT> encoder_cell_fw = create_rnn_cell(cell_type=self.model_params['encoder_cell_type'], cell_params={"num_units": self.model_params['encoder_cell_units']}, num_layers=self.model_params['encoder_layers'], dp_input_keep_prob=self.model_params...
Creates graph for bi-directional encoder. TODO: add param tensor shapes :param embedded_inputs: :param src_lengths: :return:
625941e926068e7796caf186
def predict_emotion(img,model): <NEW_LINE> <INDENT> mtcnn = MTCNN(keep_all=True) <NEW_LINE> all_boxes = mtcnn.detect(img) <NEW_LINE> good_boxes = [] <NEW_LINE> for index, proba in enumerate(all_boxes[1]): <NEW_LINE> <INDENT> if(proba > 0.9): <NEW_LINE> <INDENT> good_boxes.append(all_boxes[0][index]) <NEW_LINE> <DEDENT>...
Predicting emotions
625941e930dc7b7665901e01
def setUp(self): <NEW_LINE> <INDENT> self.amazon = AmazonAPI( _AMAZON_ACCESS_KEY, _AMAZON_SECRET_KEY, _AMAZON_ASSOC_TAG, CacheReader=cache_reader, CacheWriter=cache_writer, MaxQPS=0.5 )
Set Up. Initialize the Amazon API wrapper. The following values: * AMAZON_ACCESS_KEY * AMAZON_SECRET_KEY * AMAZON_ASSOC_TAG Are imported from a custom file named: 'test_settings.py'
625941e9377c676e91272647
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <...
Returns the model properties as a dict
625941e996565a6dacc8fb6a
def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(ProctortrackBackendProvider, self).__init__(**kwargs) <NEW_LINE> self.session.oauth_uri = '/edx/oauth2/access_token'
Initialize REST backend. client_id: provided by backend service client_secret: provided by backend service
625941e9a8ecb033257d356c
def normalise_vector(vector): <NEW_LINE> <INDENT> magnitude = vector_length(vector) <NEW_LINE> return tuple(i / magnitude for i in vector)
(num, ...) Normalises 'vector' (scales to unit vector)
625941e9eab8aa0e5d26dffa
def move_files(input_items, target_folder, flatten_results, show_progress=False): <NEW_LINE> <INDENT> moved = 0 <NEW_LINE> skipped = 0 <NEW_LINE> errors = 0 <NEW_LINE> if show_progress: <NEW_LINE> <INDENT> i = 1. <NEW_LINE> file_count = len(input_items) <NEW_LINE> status_writer.send_percent(0.0, _('Starting to process....
Moves files.
625941e9d4950a0f3b08c7e9
@transaction.commit_manually <NEW_LINE> def upload_attachment(request, bookid, version=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> book = models.Book.objects.get(url_title__iexact=bookid) <NEW_LINE> <DEDENT> except models.Book.DoesNotExist: <NEW_LINE> <INDENT> return pages.ErrorPage(request, "errors/book_does_n...
Uploades attachments. Used from Upload dialog. @param request: Django Request @param bookid: Book ID @param version: Book version or None
625941e926068e7796caf187
def update_instrument(self,instrument_id,exchange_id,price_tick,multiple,long_rate=0.12,short_rate=0.12): <NEW_LINE> <INDENT> if instrument_id not in self._contracts: <NEW_LINE> <INDENT> self.logger.error("收到未注册的contract的合约更新信息:%s" % instrument_id) <NEW_LINE> return <NEW_LINE> <DEDENT> c = self._contracts[instrument_id...
exchange_id:交易所编号, 用来区分平今/平仓 price_tick:最小变动单位 multiple:合约乘数 long_rate:多头保证金率,原始保证金率,没有意义 short_rate:空头保证金率,原始保证金率,没有意义 没有加锁必要,即便被竞争,数据也应当一样
625941e9ab23a570cc250627
def add(self, value): <NEW_LINE> <INDENT> if self.head is None: <NEW_LINE> <INDENT> self.head = self.tail = Node(value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.tail.next = Node(value) <NEW_LINE> self.tail = self.tail.next <NEW_LINE> <DEDENT> return self.tail
Creates a new node, add it to the tail, and returns the created node
625941e98c3a873295158861
def _clean_up_caches(directory, amount): <NEW_LINE> <INDENT> free = _free_disk_space_for(directory) <NEW_LINE> if amount < free: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> st_dev = os.stat(directory).st_dev <NEW_LINE> caches_to_clean = [x[1]() for x in _cache_cleanup_list] <NEW_LINE> caches = (c for c in caches_to_...
Explicitly cleanup caches based on their priority (if required). :param directory: the directory (of the cache) to be freed up. :param amount: amount of space to reclaim. :raises: InsufficientDiskSpace exception, if we cannot free up enough space after trying all the caches.
625941e90a50d4780f667337
def deprecated(self, version=None, reason=None, stacklevel=2, name=None, doc=None): <NEW_LINE> <INDENT> def decorator(func): <NEW_LINE> <INDENT> message = reason or 'The function "%s" is deprecated' <NEW_LINE> if '%s' in message: <NEW_LINE> <INDENT> message %= func.__name__ <NEW_LINE> <DEDENT> def wrapped(*args, **kwar...
Display a deprecation message only if the version is older than the compatible version.
625941e94f88993c3716c503
def test_generating_dict_to_1(self): <NEW_LINE> <INDENT> part1 = base_objects.Particle() <NEW_LINE> part1.set('pdg_code', 1) <NEW_LINE> part2 = base_objects.Particle() <NEW_LINE> part2.set('pdg_code', 2) <NEW_LINE> part2.set('is_part', False) <NEW_LINE> part3 = base_objects.Particle() <NEW_LINE> part3.set('pdg_code', 3...
Test the dictionary generation routine generate_ref_dict
625941e9cc0a2c11143dd333
def color(r, g, b): <NEW_LINE> <INDENT> return Quantity_Color(r, g, b, Quantity_TOC_RGB)
Create a Quantity_Color from RGB components Parameters ---------- r : float Red component between 0 and 1 g : float Green component between 0 and 1 b : blue Blue component between 0 and 1 Returns ------- Quantity_Color
625941e9d486a94d0b98e5e7
def events(self, since=None, until=None, filters=None, decode=None): <NEW_LINE> <INDENT> if isinstance(since, datetime): <NEW_LINE> <INDENT> since = utils.datetime_to_timestamp(since) <NEW_LINE> <DEDENT> if isinstance(until, datetime): <NEW_LINE> <INDENT> until = utils.datetime_to_timestamp(until) <NEW_LINE> <DEDENT> i...
Get real-time events from the server. Similar to the ``docker events`` command. Args: since (UTC datetime or int): Get events from this point until (UTC datetime or int): Get events until this point filters (dict): Filter the events by event time, container or image decode (bool): If set to true, strea...
625941e955399d3f05588b58
def run_once(self): <NEW_LINE> <INDENT> self.logger.info(_('Begin container sync "once" mode')) <NEW_LINE> begin = time() <NEW_LINE> all_locs = audit_location_generator(self.devices, container_server.DATADIR, '.db', mount_check=self.mount_check, logger=self.logger) <NEW_LINE> for path, device, partition in all_locs: <N...
Runs a single container sync scan.
625941e950485f2cf553d23c
def components(self): <NEW_LINE> <INDENT> if self.a == 0 and self.b == 0: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> aa = abs(self.a) <NEW_LINE> ab = abs(self.b) <NEW_LINE> ac = abs(self.c) <NEW_LINE> if aa >= ab and aa >= ac: <NEW_LINE> <INDENT> components = [[Direction(1), -self.b], [Direction(2), -self.c]] <N...
Return hex-aligned vectors which add up to this one. The return value value will be a list of [direction, distance] lists. There will be between zero and two elements in the list. If there are two, the directions will be adjacent to one another and the first distance will be greater than or equal to the second.
625941e94d74a7450ccd4665
def verify(data, signature, public_key): <NEW_LINE> <INDENT> encrypt(signature, public_key) <NEW_LINE> if data == signature: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
Verify a 256 bit signature using the public key.
625941e9851cf427c661a9ab
def parse_body(self, transport_response): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return json.loads(transport_response.text) <NEW_LINE> <DEDENT> except JSONDecodeError: <NEW_LINE> <INDENT> return {}
Parse the body of the response. Args: transport_response(TransportResponse): The transport response that contains the body of the response. Returns a dictionary representing the response.
625941e94d74a7450ccd4666
def __init__(self): <NEW_LINE> <INDENT> self.data = np.array([]) <NEW_LINE> self.OpenCMISSFaceID = None <NEW_LINE> self.OpenCMISSElements = None
Initialise a new face.
625941e95f7d997b87174f3d
def _human_time(self, interval): <NEW_LINE> <INDENT> if interval < 60.: <NEW_LINE> <INDENT> dt, unit = interval, "seconds" <NEW_LINE> <DEDENT> if interval >= 60.: <NEW_LINE> <INDENT> dt, unit = interval / 60., "minutes" <NEW_LINE> <DEDENT> elif interval >= 3600.: <NEW_LINE> <INDENT> dt, unit = interval / 3600., "hours"...
Return a time interval scaled to human-usable units.
625941e932920d7e50b28675
def learn(self, wordstream, is_spam): <NEW_LINE> <INDENT> if options["Classifier", "use_bigrams"]: <NEW_LINE> <INDENT> wordstream = self._enhance_wordstream(wordstream) <NEW_LINE> <DEDENT> if options["URLRetriever", "x-slurp_urls"]: <NEW_LINE> <INDENT> wordstream = self._add_slurped(wordstream) <NEW_LINE> <DEDENT> self...
Teach the classifier by example. wordstream is a word stream representing a message. If is_spam is True, you're telling the classifier this message is definitely spam, else that it's definitely not spam.
625941e9d58c6744b42580ff
def aStarSearch(problem, heuristic=nullHeuristic): <NEW_LINE> <INDENT> adj = util.PriorityQueue() <NEW_LINE> explored = [] <NEW_LINE> solution = [] <NEW_LINE> start_node = Node(problem.getStartState(), None, None, 0) <NEW_LINE> adj.push(start_node, start_node.path_cost + heuristic(start_node.state, problem)) <NEW_LINE>...
Search the node that has the lowest combined cost and heuristic first.
625941e9656771135c3ebd15
def test_auth_normal_user_cant_view_addtoshowcase_dropdown_dataset_showcase_list(self): <NEW_LINE> <INDENT> user = factories.User() <NEW_LINE> app = self._get_test_app() <NEW_LINE> factories.Dataset(name='my-showcase', type='showcase') <NEW_LINE> factories.Dataset(name='my-dataset') <NEW_LINE> showcase_list_response = ...
A normal (logged in) user can't view the 'Add to showcase' dropdown selector from a datasets showcase list page.
625941e966656f66f7cbc64e
def test_schedule_generation(self): <NEW_LINE> <INDENT> scheduler = DoubleRoundRobinScheduler(8) <NEW_LINE> random.seed(5) <NEW_LINE> self.assertRaises(ScheduleGenerationFailed, scheduler.generate_schedule, try_once=True) <NEW_LINE> random.seed(2) <NEW_LINE> if PY2: <NEW_LINE> <INDENT> expected_schedule = [ [(5, 6), (7...
Test double round-robin schedule generation.
625941e9627d3e7fe0d692f2
def phase2KeyMixing(tk,p1k,pn): <NEW_LINE> <INDENT> ppk = [i for i in p1k] <NEW_LINE> ppk.append( p1k[4] + pn[1]*256 + pn[0] ) <NEW_LINE> ppk[0] = (ppk[0] + S(ppk[5] ^ (tk[1]*256 + tk[0]) )) & 0xFFFF <NEW_LINE> ppk[1] = (ppk[1] + S(ppk[0] ^ (tk[3]*256 + tk[2]) )) & 0xFFFF <NEW_LINE> ppk[2] = (ppk[2] + S(ppk[1] ^ (tk[...
Create a 16 octet key from the phase1Key (p1k) and 2 octets of sequence counter
625941e9a4f1c619b28b04cf
def to_json_str(self): <NEW_LINE> <INDENT> adict = dict(vars(self), sort_keys=True) <NEW_LINE> adict['type'] = self.__class__.__name__ <NEW_LINE> return json.dumps(adict)
Convert data to json string representation. Returns: json representation as string.
625941e9091ae356686673f7
def reset(self, tick): <NEW_LINE> <INDENT> self.tick = tick
Reset time on timer
625941e907f4c71912b11926
def test_create_database(self): <NEW_LINE> <INDENT> self.assertIsNone(self.cli.create_database('new_db_1')) <NEW_LINE> self.assertIsNone(self.cli.create_database('new_db_2')) <NEW_LINE> self.assertEqual( self.cli.get_list_database(), [{'name': 'new_db_1'}, {'name': 'new_db_2'}] )
Test create a database.
625941e90a366e3fb873ecc0
def read_cifar10(filename_queue): <NEW_LINE> <INDENT> class CIFAR10Record(object): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> result = CIFAR10Record() <NEW_LINE> label_bytes = 1 <NEW_LINE> start_at_bytes = 1 <NEW_LINE> result.height = 32 <NEW_LINE> result.width = 32 <NEW_LINE> result.depth = FLAGS.depth <NEW_LINE> im...
Reads and parses examples from CIFAR10 data files. Recommendation: if you want N-way read parallelism, call this function N times. This will give you N independent Readers reading different files & positions within those files, which will give better mixing of examples. Args: filename_queue: A queue of strings wit...
625941e98da39b475bd6541b
@manager.option('repository', default='.', nargs='?', help='repository path') <NEW_LINE> @manager.option('commit', metavar='<sha or branch>', nargs='?', default='HEAD', help='an integer for the accumulator') <NEW_LINE> @manager.option('-s', '--skip-merge-commits', default=False, action="store_true", help='skip merge co...
Check the messages of the commits.
625941e9b545ff76a89142b6
def schedule( self, timer: Timer, cancelable: bool = False, dispatchers: List[T_Dispatcher] = None, decorators: Optional[List[Decorator]] = None, ): <NEW_LINE> <INDENT> def wrapper(func): <NEW_LINE> <INDENT> task = SchedulerTask( func, timer, self.broadcast, self.loop, cancelable, dispatchers, decorators, ) <NEW_LINE> ...
计划一个新任务. Args: timer (Timer): 该定时任务的计时器. cancelable (bool, optional): 能否取消该任务. 默认为 False. dispatchers (List[T_Dispatcher], optional): 该任务要使用的 Dispatchers. 默认为空列表. decorators (Optional[List[Decorator]], optional): 该任务要使用的 Decorators. 默认为空列表. Returns: Callable[T_Callable, T_Callable]: 任务 函数/方法 包装器.
625941e960cbc95b062c69e5
def _should_fetch(self): <NEW_LINE> <INDENT> last_point_date = self.stockpoints[-1].date <NEW_LINE> difference = (today() - last_point_date).days <NEW_LINE> return any([(today() - dt.timedelta(days=x)).weekday() not in (5,6) for x in range(1,difference)])
Checks if there are any weekdays between the last point we have saved and today. It's a better method of determination than just checking if it's currently the weekend or not as it handles long periods of not grabbing data.
625941e921a7993f00bc8199
def clear_history(self): <NEW_LINE> <INDENT> with self._data_lock: <NEW_LINE> <INDENT> self._data.clear()
Clear the cached measurements
625941e9e1aae11d1e74a15d
def get_departments(courses): <NEW_LINE> <INDENT> departments = {} <NEW_LINE> for course in courses: <NEW_LINE> <INDENT> prefix = course[:2] <NEW_LINE> if prefix not in departments: <NEW_LINE> <INDENT> departments[prefix] = [course] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> departments[prefix].append(course) <NEW_L...
Creates a dictionary of departments and courses in those departments. Parameters: ----------- courses (list): All courses formatted LLNNN (LL is a 2 character department code) returns (dict): Departments where the keys are LL and the values are lists of the courses in the departments
625941e9377c676e91272648
def dec_deg_to_dms(dec_deg): <NEW_LINE> <INDENT> mnt, sec = divmod(dec_deg * 3600, 60) <NEW_LINE> deg, mnt = divmod(mnt, 60) <NEW_LINE> return deg, mnt, sec
Convert decimal degrees to degrees minutes seconds :param dec_deg: Coordinate represented as decimal degree (like 49.854276). Use negative values for South/West. :return: Coordinate represented as degrees minutes seconds
625941e94e696a04525c98ef
def set_fuzzy_match(self, fuzzy): <NEW_LINE> <INDENT> self.config_obj[self.config.MAIN][self.config.FUZZY] = fuzzy <NEW_LINE> self.completer.fuzzy_match = fuzzy
Setter for fuzzy matching mode Used by prompt_toolkit's KeyBindingManager. KeyBindingManager expects this function to be callable so we can't use @property and @attrib.setter. Args: * color: A boolean that represents the fuzzy flag. Returns: None.
625941e9eab8aa0e5d26dffb
def render_template_data(self): <NEW_LINE> <INDENT> if not self.private_token: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> self.connect() <NEW_LINE> self.project = self.setup_project() <NEW_LINE> self.mergerequest = self.crawl_mergerequest() <NEW_LINE> logger.info("Write checklist items in the result.") <NEW_LINE...
Renders data from the Gitlab API Returns: data: dict containing keys with the `remote` prefix
625941e9cdde0d52a9e534d8
def rescale_data(self, X, y, sample_weight): <NEW_LINE> <INDENT> n_samples = X.shape[0] <NEW_LINE> sample_weight = sample_weight * np.ones(n_samples) <NEW_LINE> sample_weight = np.sqrt(sample_weight) <NEW_LINE> sw_matrix = sparse.diamatrix((sample_weight, 0), shape=(n_samples, n_samples)) <NEW_LINE> X = sw_matrix * X <...
对带样本权重的数据进行处理,使之处理后的数据与无样本权重的数据一样。
625941e9796e427e537b0a6b
def load_rc(self, path=None, system=False): <NEW_LINE> <INDENT> if os.path.isfile(self.user_rc_path) and not system: <NEW_LINE> <INDENT> path = self.user_rc_path <NEW_LINE> <DEDENT> elif os.path.isfile(self.sys_rc_path): <NEW_LINE> <INDENT> path = self.sys_rc_path <NEW_LINE> <DEDENT> if not path or not os.path.isfile(p...
Load the conda configuration file. If both user and system configuration exists, user will be used.
625941e944b2445a33932534
def _enumerate_mainline(ancestry, graph, tip_revno, tip, backward=True): <NEW_LINE> <INDENT> if ancestry is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if not ancestry: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> mainline = [] <NEW_LINE> cur = tip <NEW_LINE> cur_revno = tip_revno <NEW_LINE> while cu...
Enumerate the mainline revisions for these revisions. :param ancestry: A set of revisions that we care about :param graph: A Graph which lets us find the parents for a revision :param tip_revno: The revision number for the tip revision :param tip: The tip of mainline :param backward: Show oldest versions first when Tr...
625941e9adb09d7d5db6cc2e
def populate(self) -> None: <NEW_LINE> <INDENT> if current_user.is_admin(): <NEW_LINE> <INDENT> self.courier_id.choices = [(0, None)] + [ (u.id, u.username) for u in User.query.order_by("username") ] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.courier_id.choices = [ (0, None), (current_user.id, current_user.user...
Fill in the options for courier for an Order
625941e98a43f66fc4b54502
def get_block_overview(block_representation, coin_symbol='btc', txn_limit=None, txn_offset=None, api_key=None): <NEW_LINE> <INDENT> assert is_valid_coin_symbol(coin_symbol) <NEW_LINE> assert is_valid_block_representation( block_representation=block_representation, coin_symbol=coin_symbol) <NEW_LINE> url = make_url(coin...
Takes a block_representation, coin_symbol and txn_limit and gets an overview of that block, including up to X transaction ids. Note that block_representation may be the block number or block hash
625941e9f9cc0f698b140a99
def construct_mapping(self, node, deep=False): <NEW_LINE> <INDENT> mapping = {} <NEW_LINE> for key_node, value_node in node.value: <NEW_LINE> <INDENT> key = self.construct_object(key_node, deep=deep) <NEW_LINE> value = self.construct_object(value_node, deep=deep) <NEW_LINE> mapping[key] = value <NEW_LINE> <DEDENT> retu...
Use OrderedDict for maps
625941e931939e2706e4d305
def test_cancerchromosomes(self): <NEW_LINE> <INDENT> handle = open('Entrez/elink9.xml') <NEW_LINE> record = Entrez.read(handle) <NEW_LINE> self.assertEqual(record[0]["DbFrom"], "cancerchromosomes") <NEW_LINE> self.assertEqual(record[0]["IdList"], ["2662"])
Test parsing cancerchromosomes links returned by ELink
625941e9e76e3b2f99f3aca5
def _start(self): <NEW_LINE> <INDENT> LOG.info("Opening socket on port %d" % (self._port,)) <NEW_LINE> self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) <NEW_LINE> self._socket.bind(('0.0.0.0', self._port)) <NEW_LINE> self._soc...
@see Component.start()
625941e9aad79263cf390ee9
def _notify_tracim(self, mails: typing.List[DecodedMail], imapc: imapclient.IMAPClient) -> None: <NEW_LINE> <INDENT> logger.debug(self, "Notify tracim about {} new responses".format(len(mails))) <NEW_LINE> while mails: <NEW_LINE> <INDENT> mail = mails.pop() <NEW_LINE> try: <NEW_LINE> <INDENT> method, endpoint, json_bod...
Send http request to tracim endpoint :param mails: list of mails to send :return: none
625941e92c8b7c6e89b35c5f
def build_model(X, y, num_hidden, learning_rate=0.01, num_iterations=50000, verbose=True): <NEW_LINE> <INDENT> model = NN(n_x=2, n_h=num_hidden, n_y=1, learning_rate=learning_rate) <NEW_LINE> cost_history = [] <NEW_LINE> for i in range(0, num_iterations): <NEW_LINE> <INDENT> A2 = model.feedforward(X) <NEW_LINE> cost = ...
an intermediate method to train our model parameters ------------------- X: numpy.ndarray input data y: numpy.ndarray the real label num_hidden: int number of hidden neurons in the layer learning_rate: float hyperparam for gradient descent algorithm num_iterations: int number of passes, each pass us...
625941e9e76e3b2f99f3aca6
def test_name_must_be_capitalized(self): <NEW_LINE> <INDENT> form = self.make_validated_form(name='RODRIGO queiRoz') <NEW_LINE> self.assertEqual('Rodrigo Queiroz', form.cleaned_data['name'])
Name must be capitalized.
625941e95166f23b2e1a55fa
def closeAllPanels(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.debug('In closeAllPanels(%s,%s)' % (self.panel_launcher, self.panels)) <NEW_LINE> if isinstance(self.panel_launcher, ExternalAppAction): <NEW_LINE> <INDENT> self.panel_launcher.kill() <NEW_LINE> <DEDENT> for p in self.panels: <NEW_LINE> <INDENT...
This method replaces killProcess, using taurus.qt.qtgui.util.ExternalAppAction instead!
625941e9fbf16365ca6f666f
def draw_colorbar(self, image): <NEW_LINE> <INDENT> raise NotImplementedError
Draws a range color-bar within the figure
625941e9460517430c39461a
def testCase110(self): <NEW_LINE> <INDENT> global jval <NEW_LINE> global sval <NEW_LINE> global configdata <NEW_LINE> global appname <NEW_LINE> global schemafile <NEW_LINE> branchfile = os.path.abspath(os.path.dirname(__file__))+os.sep+str('branch0.json') <NEW_LINE> schema = { 'phoneNumber':configdata.schema['propertie...
Load and add branch with force.
625941e94a966d76dd5514b5
def parse_backup_id(server, args): <NEW_LINE> <INDENT> if args.backup_id in ("latest", "last"): <NEW_LINE> <INDENT> backup_id = server.get_last_backup_id() <NEW_LINE> <DEDENT> elif args.backup_id in ("oldest", "first"): <NEW_LINE> <INDENT> backup_id = server.get_first_backup_id() <NEW_LINE> <DEDENT> elif args.backup_id...
Parses backup IDs including special words such as latest, oldest, etc. Exit with error if the backup id doesn't exist. :param Server server: server object to search for the required backup :param args: command line arguments namespace :rtype: barman.infofile.LocalBackupInfo
625941e95166f23b2e1a55fb
def plot_latent_images(model, n, digit_size=28): <NEW_LINE> <INDENT> norm = tfp.distributions.Normal(0, 1) <NEW_LINE> grid_x = norm.quantile(np.linspace(0.05, 0.95, n)) <NEW_LINE> grid_y = norm.quantile(np.linspace(0.05, 0.95, n)) <NEW_LINE> image_width = digit_size*n <NEW_LINE> image_height = image_width <NEW_LINE> im...
Plots n x n digit images decoded from the latent space.
625941e9462c4b4f79d1db71
def startegy_word_count(df): <NEW_LINE> <INDENT> strat_wrds = pd.read_csv("data_files/Strategy_Words.csv") <NEW_LINE> strat_wrd_counts = [] <NEW_LINE> for refl in df['Cleaned_Reflection_String']: <NEW_LINE> <INDENT> numSWrd = np.array([]) <NEW_LINE> refl = refl.lower() <NEW_LINE> for wrd in strat_wrds['Strategy_Words']...
strategy_word_count: function to get the total number of task words appearing the reflection Expects: a pandas dataframe with a column entitled 'Cleaned_Reflection_String Returns: the dataframe with a column appended to it containing strategy word counts
625941e926238365f5f0f316
def __get_scan_resources(self, cookie, scanid): <NEW_LINE> <INDENT> print("\n__get_scan_resources: for scan %s.\n" % scanid) <NEW_LINE> u = self.host + "/data/experiments/%s/scans/%s/resources?format=json" % (self.str_session, scanid) <NEW_LINE> r = self.__get_url(u, headers=cookie, verify=False) <NEW_LINE> resources ...
is used by __download_legacy :param cookie: :param scanid: :return:
625941e9442bda511e8be8b3
def __ge__ (self, other): <NEW_LINE> <INDENT> if not isinstance(other, SortedSet): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.issuperset(other)
x.__ge__(y) <==> x>=y
625941e98a349b6b435e8614
def get_py_files(project_path): <NEW_LINE> <INDENT> found_files = [] <NEW_LINE> for root, dir_names, file_names in os.walk(project_path): <NEW_LINE> <INDENT> for file_name in file_names: <NEW_LINE> <INDENT> if PYTHON_EXT.search(file_name): <NEW_LINE> <INDENT> found_files.append(os.path.join(root, file_name)) <NEW_LINE>...
searches for folders found in project_path and lists py files Args: project_path (str): is the root path to start looking for python files in Returns: list: returns full path to the python files found
625941e94c3428357757c7c7
def exploitation_term_fast(self, key): <NEW_LINE> <INDENT> score = self.auc_sum[key] <NEW_LINE> pos = self.use_counts[key] <NEW_LINE> if pos: <NEW_LINE> <INDENT> return score * 2.0 / (pos * (pos + 1.0)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0.0
value 0 to 1.0 to represent quality of key optimized O(1) implementation exploitation_term_slow()
625941e9435de62698dfe0ef
def autobindict(func): <NEW_LINE> <INDENT> def __wrapper(self, source, context): <NEW_LINE> <INDENT> bindings = bindict(source, context) <NEW_LINE> ret = func(self, source, context, bindings) <NEW_LINE> if ret is not None: <NEW_LINE> <INDENT> bindings.update(exclude_internals(ret)) <NEW_LINE> <DEDENT> return bindings <...
Translate typical template arguments into a contextualized version
625941e921bff66bcd684df0
def solv_problems(self, problems): <NEW_LINE> <INDENT> for problem in problems: <NEW_LINE> <INDENT> print("Problem %d/%d:" % (problem.id, len(problems))) <NEW_LINE> print(problem) <NEW_LINE> solutions = problem.solutions() <NEW_LINE> for solution in solutions: <NEW_LINE> <INDENT> print(" Solution %d:" % solution.id) <...
Solve problems manually from console interactive prompt
625941e9090684286d50f18e
def text_types(clusterer, chromosome): <NEW_LINE> <INDENT> results = [] <NEW_LINE> chromosome.text_types = {"FrontPageIntroduction": 1, "FrontPageHeading": 1, "ArticleHeading": 1, "ArticleByline": 1, "ArticleIntroduction": 1, "ArticleText": 1} <NEW_LINE> result = construct_result_tuple(clusterer.cluster(chromosome)) <N...
Test done with article text set to 0.15 :param clusterer: :param chromosome: :return:
625941e93c8af77a43ae3c48
def _case_format(self, occur): <NEW_LINE> <INDENT> if self.occur == 1: <NEW_LINE> <INDENT> self.attr["nma:implicit"] = "true" <NEW_LINE> <DEDENT> ccnt = len(self.children) <NEW_LINE> if ccnt == 0: return "<empty/>%s" <NEW_LINE> if ccnt == 1 or not self.interleave: <NEW_LINE> <INDENT> return self.start_tag("group") + "%...
Return the serialization format for a case node.
625941e9566aa707497f4a04
def update_tenant(self, id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.update_tenant_with_http_info(id, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.update_tenant_with_http_info(id, **kwargs) <NEW...
update_tenant # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_tenant(id, async_req=True) >>> result = thread.get() :param async_req bool :param int id: (required) :param TenantApiModelsEditInputModel body: ...
625941e97d847024c06be762
def android_cpa_needs_204_now(): <NEW_LINE> <INDENT> ua_str = request.headers.get("User-agent", "") <NEW_LINE> user_agent = user_agent_parser.Parse(ua_str) <NEW_LINE> if "Android" not in ua_str: <NEW_LINE> <INDENT> return _android_has_acked_cp_instructions.get(request.remote_addr, False) <NEW_LINE> <DEDENT> if "Dalvik"...
Does this captive portal agent need a 204 right now? We expect the user agents to go through various states before receiving a 204. This is particularly important for Android >= 7.1, which falls back to cellular if it doesn't get a 204 at the right time.
625941e9ec188e330fd5ac37
def __exit__(self, exc_type, exc_value, traceback): <NEW_LINE> <INDENT> with _lock: <NEW_LINE> <INDENT> pass
Compute the duration and call the callback. If there were any exceptions still grab the time and allow the exception to propogate.
625941e963b5f9789fde7588
def int_ceil(float_): <NEW_LINE> <INDENT> return int(math.ceil(float_))
Округлить float в больщую сторону
625941e9090684286d50f18f
def is_element_present(self, locator, element_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.wait.until(EC.presence_of_element_located(locator)), 'There is no element "{}"'.format(element_name) <NEW_LINE> return True <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return False
Looking for element with given locator and check if this element is present :param locator :param element_name: name of element :return: Returns 'True' if the web-element is present, otherwise returns 'False'
625941e9236d856c2ad44c82
def get_queryset(self): <NEW_LINE> <INDENT> manager = self.model.objects <NEW_LINE> anon = self.request.user.is_anonymous() <NEW_LINE> if anon or not hasattr(manager, 'for_user'): <NEW_LINE> <INDENT> return manager.all() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return manager.for_user(self.request.user)
Special behaviour: filter only for non-anonymous users. Anonymous users are taken care of by token permissions.
625941e923849d37ff7b352d
def __send_task_back(self, task): <NEW_LINE> <INDENT> if (not task.is_completed()): <NEW_LINE> <INDENT> self.connector.send_task_back(task)
Delegates the send task back actions to the connector @param task: instance of filerockclient.pathname_operation.PathnameOperation
625941e9be7bc26dc91cda99
def setSelectionAreas (self,before,sel,after): <NEW_LINE> <INDENT> body = self ; w = body.bodyCtrl <NEW_LINE> pos = w.getYScrollPosition() <NEW_LINE> s = w.getAllText() <NEW_LINE> before = before or '' <NEW_LINE> sel = sel or '' <NEW_LINE> after = after or '' <NEW_LINE> w.delete(0,len(s)) <NEW_LINE> w.insert(0,before+s...
Replace the body text by before + sel + after and set the selection so that the sel text is selected.
625941e924f1403a92601004
def conv_block(input_tensor, kernel_size, filters, stage, block, strides=(2, 2), use_bias=True): <NEW_LINE> <INDENT> nb_filter1, nb_filter2, nb_filter3 = filters <NEW_LINE> conv_name_base = 'res' + str(stage) + block + '_branch' <NEW_LINE> bn_name_base = 'bn' + str(stage) + block + '_branch' <NEW_LINE> x = KL.Conv2D( n...
conv_block is the block that has a conv layer at shortcut # Arguments input_tensor: input tensor kernel_size: default 3, the kernel size of middle conv layer at main path filters: list of integers, the nb_filters of 3 conv layer at main path stage: integer, current stage label, used for generating layer...
625941e98c0ade5d55d3ee61