code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def _get_sha_sign(self, form_dict, parameters, passphrase): <NEW_LINE> <INDENT> form_dict = dict((key.upper(), value) for key, value in form_dict.iteritems()) <NEW_LINE> sha_parameters = sorted(parameters.intersection(form_dict.iterkeys())) <NEW_LINE> sha_parameters = filter(lambda key: form_dict.get(key), sha_paramete...
Add the cryptographic SHA1 signature to the given form dictionary.
625941e38a349b6b435e854e
def translate_location_to_course_locator(self, course_key, published=True): <NEW_LINE> <INDENT> cached = self._get_course_locator_from_cache(course_key, published) <NEW_LINE> if cached: <NEW_LINE> <INDENT> return cached <NEW_LINE> <DEDENT> course_son = self._interpret_location_course_id(course_key) <NEW_LINE> entry = s...
Used when you only need the CourseLocator and not a full BlockUsageLocator. Probably only useful for get_items which wildcards name or category. :param course_key: a CourseKey :param published: a boolean representing whether or not we should return the published or draft version Returns a Courselocator
625941e35fc7496912cc3d59
def test_invalid_server(self): <NEW_LINE> <INDENT> server = Server('fefabef') <NEW_LINE> with self.assertRaises(ServerNotFoundError): <NEW_LINE> <INDENT> services = server.services()
Verify invalid host name throws an exception.
625941e38c3a87329515879a
def restart(self): <NEW_LINE> <INDENT> self.stop() <NEW_LINE> return self.start()
定义重启的接口 :return:
625941e3b7558d58953c52e7
@login_required <NEW_LINE> @user_passes_test(is_coordinator) <NEW_LINE> def coordinator_export_award(request, award_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> award = Award.objects.get(awardid = award_id) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> messages.warning(request, _("Award does not exist")) <NEW_LI...
Function creates an Excel file for an which lists all of its applications award_id - the id of the award to be exported
625941e3925a0f43d254a256
def __init__(self, address=None, duration=None, preparation_time=None, time_windows=None): <NEW_LINE> <INDENT> self._address = None <NEW_LINE> self._duration = None <NEW_LINE> self._preparation_time = None <NEW_LINE> self._time_windows = None <NEW_LINE> self.discriminator = None <NEW_LINE> if address is not None: <NEW_...
Stop - a model defined in Swagger
625941e34a966d76dd5513ee
@contextmanager <NEW_LINE> def en_locale(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> locale.setlocale(locale.LC_TIME, "en_US.UTF-8") <NEW_LINE> <DEDENT> except locale.Error: <NEW_LINE> <INDENT> yield <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> yield <NEW_LINE> <DEDENT> finally: <NEW_LINE>...
A context maanger that temporarily sets the LC_TIME locale to en_US.UTF-8 and then resets it.
625941e3ab23a570cc250561
def affine_transformation(x, y, a, b, c, d, e, f): <NEW_LINE> <INDENT> return x * a + y * b + e, x * c + y * d + f
perform an affine 2d transformation using the given matrix coefficients
625941e3d53ae8145f87a644
def plugin_to_dict(name, p): <NEW_LINE> <INDENT> parameters = [] <NEW_LINE> for param_name in p.parameters.keys(): <NEW_LINE> <INDENT> parameters.append({ 'name': param_name, 'value': stringify_parameter_value(p.parameters[param_name]), 'type': p.parameters_types[param_name].__name__, 'description': p.parameters_desc[p...
Returns a dictionary representation of a plugin in a given state.
625941e34d74a7450ccd459f
def get_live_levels(journey_module_rel): <NEW_LINE> <INDENT> all_levels = Level.objects.filter(module=journey_module_rel.module) <NEW_LINE> active_levels_id = list() <NEW_LINE> for level in all_levels: <NEW_LINE> <INDENT> if level.is_active(): <NEW_LINE> <INDENT> active_levels_id.append(level.id) <NEW_LINE> <DEDENT> <D...
Returns all the live levels linked to a specific module
625941e3a79ad161976cc521
def is_abitoken(s): <NEW_LINE> <INDENT> return s in ABI_ALLTOKENS
True if s is one of the token supported by the ABINIT parser i.e. variable name or unit name.
625941e3796e427e537b09a4
def task(self, coro): <NEW_LINE> <INDENT> @asyncio.coroutine <NEW_LINE> def coro_wrapper(): <NEW_LINE> <INDENT> iterator = iter(coro) <NEW_LINE> value = exception = None <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if exception is None: <NEW_LINE> <INDENT> value = iterator.send(value) <NEW_LINE> ...
Run an asyncio-style coroutine on this clock Futures yielded by the coroutine will be handled by this Clock. In addition to futures, the coroutine may yield real numbers, which are translated to :meth:`sleep`.
625941e3a17c0f6771cbe42b
def test_regular(): <NEW_LINE> <INDENT> nose.tools.ok_(True)
A regular test case
625941e363d6d428bbe448cc
def printout(self): <NEW_LINE> <INDENT> if CYCLE_COST: <NEW_LINE> <INDENT> headings = ["NO", "ARCH", "CIPHER", "DIR", "HASH", "KEYSZ", "CYCLE COST A"] <NEW_LINE> print("Buffer size: {} bytes".format(PACKET_SIZE)) <NEW_LINE> <DEDENT> elif THROUGHPUT: <NEW_LINE> <INDENT> headings = ["NO", "ARCH", "CIPHER", "DIR", "HASH",...
Prints out readable representation of the list. Self.analyze is set to true.
625941e3656771135c3ebc4e
def get_idx(in_files, stop_idx=None, start_idx=None): <NEW_LINE> <INDENT> from nibabel import load <NEW_LINE> img = load(in_files) <NEW_LINE> hdr = img.get_header() <NEW_LINE> nvols = int(hdr.get_data_shape()[3]) <NEW_LINE> if (start_idx == None) or (start_idx < 0) or (start_idx > (nvols - 1)): <NEW_LINE> <INDENT> star...
Method to get the first and the last slice for the functional run. It verifies the user specified first and last slice. If the values are not valid, it calculates and returns the very first and the last slice Parameters ---------- in_file : string (nifti file) Path to input functional run stop_idx : int ...
625941e3187af65679ca54fc
def probe_cert(self, domain, **kwargs): <NEW_LINE> <INDENT> if "host" not in kwargs: <NEW_LINE> <INDENT> host = socket.gethostbyname(domain) <NEW_LINE> logger.debug('%s resolved to %s', domain, host) <NEW_LINE> kwargs["host"] = host <NEW_LINE> <DEDENT> kwargs.setdefault("port", self.PORT) <NEW_LINE> kwargs["name"] = se...
Probe tls-sni-01 challenge certificate. :param unicode domain:
625941e344b2445a3393246f
def test_containers_use_always_image_pull_policy(self): <NEW_LINE> <INDENT> for container in self.object['spec']['template']['spec']['containers']: <NEW_LINE> <INDENT> self.assertEqual("Always", container.get('imagePullPolicy'))
Ensure that all containers use 'Always' as imagePullPolicy.
625941e3cad5886f8bd273b4
def despawn(self): <NEW_LINE> <INDENT> if self.location is not None: <NEW_LINE> <INDENT> for char in self.location.characters: <NEW_LINE> <INDENT> self.remove_cmds(character) <NEW_LINE> <DEDENT> self.location.entities.remove(self) <NEW_LINE> <DEDENT> self.location = None
removes entity from location and frees it for gc
625941e3cad5886f8bd273b5
def plotPrediction(ax, data, prev_mult=1, plot_gp=False): <NEW_LINE> <INDENT> phat = data['pred'].transpose() * prev_mult <NEW_LINE> pctiles = np.percentile(phat, [1, 5, 50, 95, 99], axis=1) <NEW_LINE> pbar = data['data']['cases']/data['data']['N'] * prev_mult <NEW_LINE> pbar = clip_to_range(pbar, phat.index) <NEW_LINE...
Predictive time series plot with (by default) the prediction summarised as [0.01,0.05,0.5,0.95,0.99] quantiles, and observations colour-coded by tail-probability. Parameters ========== ax -- a set of axes on which to plot X -- 1D array-like of times of length n y -- 1D array-like of observed number of cases at each ...
625941e373bcbd0ca4b2c451
def __init__(self, ulog: ULog, min_flight_time_seconds: float = 0.0, in_air_margin_seconds: float = 0.0) -> None: <NEW_LINE> <INDENT> self._ulog = ulog <NEW_LINE> self._min_flight_time_seconds = min_flight_time_seconds <NEW_LINE> self._in_air_margin_seconds = in_air_margin_seconds <NEW_LINE> try: <NEW_LINE> <INDENT> se...
initializes an InAirDetector instance. :param ulog: :param min_flight_time_seconds: set this value to return only airtimes that are at least min_flight_time_seconds long :param in_air_margin_seconds: removes a margin of in_air_margin_seconds from the airtime to avoid ground effects.
625941e34e696a04525c9829
def question(request, question_id): <NEW_LINE> <INDENT> post = get_object_or_404( models.Post, id=question_id, post_type='question', deleted=False ) <NEW_LINE> datum = get_question_data(post.thread) <NEW_LINE> json_string = simplejson.dumps(datum) <NEW_LINE> return HttpResponse(json_string, content_type='application/js...
Gets a single question
625941e3293b9510aa2c366e
def moveup(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> id = int(self.GetFormValue(u"id")) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> id = 0 <NEW_LINE> <DEDENT> if not id: <NEW_LINE> <INDENT> ok = False <NEW_LINE> msgs = _(u"Not found") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ok, msgs = self.context.M...
move pageelement one position up in container redirect to request.url parameter: id, url in request
625941e3bf627c535bc135ab
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, APIStatus): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941e31f5feb6acb0c4f25
def diapreresnet1001_cifar10(classes=10, **kwargs): <NEW_LINE> <INDENT> return get_diapreresnet_cifar(classes=classes, blocks=1001, bottleneck=True, model_name="diapreresnet1001_cifar10", **kwargs)
DIA-PreResNet-1001 model for CIFAR-10 from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. ctx : Context, defau...
625941e3dd821e528d63b582
def simplify (self, name): <NEW_LINE> <INDENT> path = os.path.normpath(os.path.join(self.path, name)) <NEW_LINE> if path[:len(self.cwd)] == self.cwd: <NEW_LINE> <INDENT> return path[len(self.cwd):] <NEW_LINE> <DEDENT> return path
Simplify an path name by removing the current directory if the specified path is in a subdirectory.
625941e3004d5f362079a70d
def move(self,dt=None,num_timesteps=1): <NEW_LINE> <INDENT> if dt is None: <NEW_LINE> <INDENT> dt = self.timestep <NEW_LINE> <DEDENT> num_timesteps = max(1,int(num_timesteps)) <NEW_LINE> x_dot,y_dot,v_dot,heading_dot = self.simulateDynamics(self.accel,self.yaw_rate,dt=dt) <NEW_LINE> self.x_com += dt*num_timesteps*x_dot...
The motion dynamics of the vehicle. Given an input acceleration and wheel- angle this determines how much the vehicle should move, and then resets the vehicles coordinates appropriately.
625941e385dfad0860c3b237
def send(self, value): <NEW_LINE> <INDENT> return self.__call_gen(self.__send, value)
If the generator exits, discard it and call `_handle_exit()`.
625941e3a05bb46b383ecbfa
def fractionToDecimal(numerator, denominator): <NEW_LINE> <INDENT> remain_dict = dict() <NEW_LINE> quotient, remainder = divmod(numerator, denominator) <NEW_LINE> if remainder: <NEW_LINE> <INDENT> num_vec = [str(quotient), '.'] <NEW_LINE> remain_dict[remainder] = len(num_vec) <NEW_LINE> dividend = remainder * 10 <NEW_L...
:type numerator: int :type denominator: int :rtype: str
625941e3aad79263cf390e23
def _draw_vertex_ticks_tikz(tree, context, v2, id_to_location): <NEW_LINE> <INDENT> eps = 1e-8 <NEW_LINE> for node in tree.preorder(): <NEW_LINE> <INDENT> if abs(v2[id(node)]) > eps: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> npos = 0 <NEW_LINE> nneg = 0 <NEW_LINE> nzero = 0 <NEW_LINE> for n in node.get_neighbors...
@param v2: maps node id to valuation for zero crossing ticks
625941e3f9cc0f698b1409d4
def set(self, value: str) -> "ReportTo": <NEW_LINE> <INDENT> self.value = value <NEW_LINE> return self
Set custom value for `Report-To` header :param value: custom header value :type value: str :return: ReportTo class :rtype: ReportTo
625941e3ac7a0e7691ed44a1
def __init__(self,embedder,embedder_params,encoder_layer_params,num_encoder_layers,output_size): <NEW_LINE> <INDENT> dropout = embedder_params['dropout'] <NEW_LINE> super(TransformerDqn, self).__init__() <NEW_LINE> self.embedder = embedder(**embedder_params) <NEW_LINE> self.encoder_layer = nn.TransformerEncoderLayer(**...
:param embedder: module to embed the states :param output_size: number of actions we can choose
625941e3566aa707497f493f
def get_volume_snap(self, array, device_id, snap_name, snap_id): <NEW_LINE> <INDENT> snapshot = None <NEW_LINE> snap_info = self.get_volume_snap_info(array, device_id) <NEW_LINE> if snap_info: <NEW_LINE> <INDENT> if (snap_info.get('snapshotSrcs', None) and bool(snap_info['snapshotSrcs'])): <NEW_LINE> <INDENT> for snap ...
Given a volume snap info, retrieve the snapVx object. :param array: the array serial number :param device_id: the source volume device id :param snap_name: the name of the snapshot :param snap_id: the unique snap id of the snapVX :returns: snapshot dict, or None
625941e356ac1b37e62645a4
def keys(): <NEW_LINE> <INDENT> pass
Return: an iterable such as queue, deque, list
625941e321a7993f00bc80d2
def reset(self): <NEW_LINE> <INDENT> self.ui.txtWorkDir.setText(self._working_dir) <NEW_LINE> self.ui.txtArgs.setPlainText(' '.join(self._arglist))
discard inputs
625941e3a4f1c619b28b040c
def wline(self, line): <NEW_LINE> <INDENT> if DEBUG: <NEW_LINE> <INDENT> print(time.asctime(), ">>>", line) <NEW_LINE> <DEDENT> msg = line + CRLF <NEW_LINE> m = self.pongre.search(line) <NEW_LINE> if m: <NEW_LINE> <INDENT> self.sock.send(msg.encode()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> while self.lastcommand...
Send a line to the hub
625941e39c8ee82313fbbb52
def select_device_id(ap): <NEW_LINE> <INDENT> device=[] <NEW_LINE> try: <NEW_LINE> <INDENT> resp = ap.get(api="PUT API CALL FOR NETWORK DEVICES HERE") <NEW_LINE> status = resp.status_code <NEW_LINE> response_json = resp.json() <NEW_LINE> device = response_json["response"] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT>...
This function returns a network device id that user selected from a list. Exit script if there is no any network device. Parameters ---------- ap (object): apic-em object that defined in apicem.py Return: ------- str: network device id
625941e3adb09d7d5db6cb69
def move(self): <NEW_LINE> <INDENT> if self.direction == 'U': <NEW_LINE> <INDENT> if self.rect.top > 0: <NEW_LINE> <INDENT> self.rect.top -= self.speed <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.live = False <NEW_LINE> <DEDENT> <DEDENT> elif self.direction == 'D': <NEW_LINE> <INDENT> if self.rect.top + self.rec...
子弹的移动
625941e3460517430c394558
def add(self, userfile): <NEW_LINE> <INDENT> if isinstance(userfile, UserFile) and userfile not in self._collection: <NEW_LINE> <INDENT> self._log.debug("Adding UserFile object to collection: " "{0}".format(userfile)) <NEW_LINE> self._collection.append(userfile) <NEW_LINE> <DEDENT> elif isinstance(userfile, list): <NEW...
Add a userfile to the collection. :Args: - userfile (:class:`.UserFile`, list): File to be added to the collection. Must be unique or FileInvalidException will be raised. ``userfile`` can also be a list, all non-unique and non-:class:`.UserFile` objects will be removed with a warning before...
625941e3fbf16365ca6f65a7
def _from_compatible_tensor_list(self, tensor_list): <NEW_LINE> <INDENT> return self._from_components(nest.pack_sequence_as( self._component_specs, tensor_list, expand_composites=True))
Reconstructs a value from a compatible flat list of `tf.Tensor`. Args: tensor_list: A flat list of `tf.Tensor`, compatible with `self._flat_tensor_specs`. (Caller is responsible for ensuring compatibility.) Returns: A value that is compatible with this `TypeSpec`.
625941e310dbd63aa1bd2f7e
def get_object_list(self, request): <NEW_LINE> <INDENT> object_list = super(TenantResource, self).get_object_list(request) <NEW_LINE> accessible_tenants = [g[0] for g in request.user.groups.values_list('name')] <NEW_LINE> return object_list.filter(slug__in=accessible_tenants)
Filters associated tenants
625941e356b00c62f0f14a38
def handle_player_dead_keys(key): <NEW_LINE> <INDENT> key_char = chr(key.c) <NEW_LINE> if key_char == "i": <NEW_LINE> <INDENT> return {'show_inventory': True} <NEW_LINE> <DEDENT> if key.vk == libtcod.KEY_ENTER and key.lalt: <NEW_LINE> <INDENT> return {'fullscreen': True} <NEW_LINE> <DEDENT> elif key.vk == libtcod.KEY_E...
Handle input from keyboard with player is dead.
625941e3bd1bec0571d90a0b
def deg2rad(deg): <NEW_LINE> <INDENT> return deg * np.pi / 180.0
Convert degrees to radians
625941e3090684286d50f0c7
def on_tick(self, sim): <NEW_LINE> <INDENT> self.playback_time += sim.dt <NEW_LINE> i = min(int(self.playback_time / self.dt) + 1, self.traj_len - 1) <NEW_LINE> s = min(1., 1.1 * self.playback_time / self.duration) <NEW_LINE> quat = quat_slerp(self.start_contact.quat, self.end_contact.quat, s) <NEW_LINE> self.foot_targ...
Main function called at each control cycle. Parameters ---------- sim : Simulation Current simulation instance.
625941e376d4e153a657ef0e
def __init__(self, image): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.image = image <NEW_LINE> self.x = 2 * config.CIRCLE_RADIUS <NEW_LINE> self.y = int(config.HEIGHT/2.0) <NEW_LINE> self.radius = config.CIRCLE_RADIUS <NEW_LINE> self.gravity_force = config.GRAVITY / config.BIRD_MASS <NEW_LINE> self.velocity...
:param color: rgb bird color
625941e3fbf16365ca6f65a8
def allow_migrate(self, db, model): <NEW_LINE> <INDENT> if db == self.using: <NEW_LINE> <INDENT> return model._meta.app_label in self.apps <NEW_LINE> <DEDENT> elif model._meta.app_label in self.apps: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return None
Make sure the apps we care about appear in the db
625941e391f36d47f21ac8d2
def __init__(self, name, app_name, wallet_id=0): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.app_name = app_name <NEW_LINE> self.id = dbus.Int64(wallet_id) <NEW_LINE> self._session_bus = dbus.SessionBus() <NEW_LINE> self._connection = self._session_bus.get_object(BUS_NAME, OBJECT_PATH)
Open a session bus and get a proxy object to KWallet.
625941e36aa9bd52df037182
def test_model(self,cobra_model_I,ko_list=[],flux_dict={},description=None): <NEW_LINE> <INDENT> cobra_model = cobra_model_I; <NEW_LINE> for ko in ko_list: <NEW_LINE> <INDENT> cobra_model.reactions.get_by_id(ko).lower_bound = 0.0; <NEW_LINE> cobra_model.reactions.get_by_id(ko).upper_bound = 0.0; <NEW_LINE> <DEDENT> for...
simulate a cobra model
625941e39b70327d1c4e11b3
def derive_orphan_trunk_adapters(self): <NEW_LINE> <INDENT> sea_trunks = [] <NEW_LINE> for sea in self.seas: <NEW_LINE> <INDENT> sea_trunks.append(sea.primary_adpt) <NEW_LINE> sea_trunks.extend(sea.addl_adpts) <NEW_LINE> <DEDENT> orig_trunks = copy.copy(self.trunk_adapters) <NEW_LINE> orphan_trunks = copy.copy(self.tru...
Builds a list of trunk adapters not attached to a SEA.
625941e3d486a94d0b98e523
def random_sample(self, size=None, dtype=float): <NEW_LINE> <INDENT> dtype = _check_and_get_dtype(dtype) <NEW_LINE> out = cupy.empty(size, dtype=dtype) <NEW_LINE> if dtype.char == 'f': <NEW_LINE> <INDENT> func = curand.generateUniform <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> func = curand.generateUniformDouble <NE...
Returns an array of random values over the interval ``[0, 1)``. .. seealso:: :func:`cupy.random.random_sample` for full documentation, :meth:`numpy.random.RandomState.random_sample`
625941e332920d7e50b285b0
def build_from_content_template(inner_file, inner_dict, outer_file, outer_dict, output_file): <NEW_LINE> <INDENT> with open(inner_file) as fi: <NEW_LINE> <INDENT> inner_template = Template(fi.read()) <NEW_LINE> <DEDENT> with open(outer_file) as fi: <NEW_LINE> <INDENT> outer_template = Template(fi.read()) <NEW_LINE> <DE...
Uses secondary template to build the content of the primary template. Based on the pattern used in the blog posts and Project Euler stuff. inner_file - the file location of the inner template file inner_dict - the dictionary to be used in the jinja render statement outer_file - the file location of the outer template ...
625941e3ff9c53063f47c5ce
def test_get_action_url_pattern_change_handler(self): <NEW_LINE> <INDENT> self.assertEqual( self.helper.get_action_url_pattern('change_handler'), r'^omniforms/omniform/change_handler/(?P<instance_pk>[-\w]+)/(?P<related_object_id>[\d]+)/$' )
The method should return the correct regex
625941e32ae34c7f2600d50d
def fit(self, A, O, nb_epoch=10): <NEW_LINE> <INDENT> self.setup(A, O) <NEW_LINE> loss_list = [] <NEW_LINE> global_loss_list = [] <NEW_LINE> for i in range(nb_epoch): <NEW_LINE> <INDENT> indices = self.sample_indices() <NEW_LINE> loss = self.partial_fit(indices) <NEW_LINE> loss_list.append(loss) <NEW_LINE> global_loss ...
run training :param A: adjacency matrix, dense or sparse matrix :param O: constraint matrix, dense or sparse matrix :return: list of training loss
625941e34a966d76dd5513ef
def captain_win_loss_by_toss(df_match_info, df_bat, captain=''): <NEW_LINE> <INDENT> cap = df_bat[(df_bat['captain'] == True) & (df_bat['innings_name'].str.contains('Thames Ditton CC'))][['player_name', 'match_id']] <NEW_LINE> cap.columns = ['captain_name', 'match_id'] <NEW_LINE> df_mi = df_match_info.merge(cap, how='l...
Return some basic stats around the toss
625941e38e71fb1e9831db84
def get_final_metrics(self, raw_data = False, convert_to_string = True): <NEW_LINE> <INDENT> self.convert_to_string = convert_to_string <NEW_LINE> assert self.replication_counter == self.replication_num, "ERROR: Didn't finish all replications. Please call this function in a proper place in your code ..." <NEW_LINE> if ...
This function returns the final metrics collected at the end of pre-defined number of replications Parameters ---------- :arg raw_data: boolean if True return the full collected value array for each metric. If false mean and std_dev will be calculated and returned. :arg convert_to_string if True the mean and std valu...
625941e3d8ef3951e324391a
def __init__(self, WL, T): <NEW_LINE> <INDENT> self.T = T <NEW_LINE> self.WL = WL <NEW_LINE> self.h = [None for i in range(T)] <NEW_LINE> self.w = np.zeros(T)
Parameters ---------- WL : the class of the base weak learner T : the number of base learners to learn
625941e38a349b6b435e854f
def post_request(self, uri, stream): <NEW_LINE> <INDENT> req = urllib2.Request(uri, stream, headers=self.headers) <NEW_LINE> return req
Generate a POST request to be used with urlopen.
625941e3d164cc617578312c
def _process_tasks(self): <NEW_LINE> <INDENT> self.logger.info('Fetching tasks') <NEW_LINE> try: <NEW_LINE> <INDENT> for _ in xrange(self._max_tasks_per_period): <NEW_LINE> <INDENT> task = self._task_queue.get(block=False) <NEW_LINE> if task is None: <NEW_LINE> <INDENT> self._state = PoolWorker.STOPPED <NEW_LINE> self....
Fetch tasks from task queue if available and pass them for processing This task is run periodically (because SimpleQueue does not provide callbacks and/or asynchronous interface) and fetched tasks from task queue. Task format is described above.
625941e35fdd1c0f98dc0611
def add_convm(self, eid, pconvm, ta1, film_node=0, cntmdot=0, ta2=None, mdot=1.0, comment=''): <NEW_LINE> <INDENT> boundary_condition = CONVM(eid, pconvm, ta1, film_node=film_node, cntmdot=cntmdot, ta2=ta2, mdot=mdot, comment=comment) <NEW_LINE> self._add_thermal_bc_object(boundary_condition, boundary_condition.eid) <N...
Creates a CONVM card Parameters ---------- eid : int element id (CHBDYP) pconid : int property ID (PCONVM) mid : int Material ID ta1 : int ambient point for convection ta2 : int; default=None None : ta1 ambient point for convection film_node : int; default=0 cntmdot : int; default=0 control...
625941e35166f23b2e1a5535
def wait_for(self): <NEW_LINE> <INDENT> self.thread.join() <NEW_LINE> self.logger.debug('Thread %s terminated.', self.__class__.__name__)
Waits for this task's thread to terminate.
625941e376e4537e8c351a52
def generate_release(token, gh, args): <NEW_LINE> <INDENT> _ldd_summary = {} <NEW_LINE> _pds4_alpha_version = convert_pds4_version_to_alpha(args.pds4_version) <NEW_LINE> _config = load_config() <NEW_LINE> for _repo in gh.repositories_by(args.github_org): <NEW_LINE> <INDENT> logger.info(f'checking {_repo.name}') <NEW_LI...
Get Discipline Repos from Org. Loop through repos in Github org to determine if it is a discipline LDD
625941e3e8904600ed9f230f
def create_kml(tag_dictionary, output_file): <NEW_LINE> <INDENT> kml = simplekml.Kml() <NEW_LINE> for tag, value in tag_dictionary.items(): <NEW_LINE> <INDENT> longitude = value["longitude"] <NEW_LINE> latitude = value["latitude"] <NEW_LINE> date_time = value["date_time"] <NEW_LINE> signal_strength = value["signal_stre...
Created a new KML file from a list of geo tags
625941e30c0af96317bb85c4
def get_courses(self, subject): <NEW_LINE> <INDENT> return list(self.subjects[subject].keys( ))
Returns a list of courses for a given subject
625941e3a8ecb033257d34a8
def test_failed_form_validation_without_user(self): <NEW_LINE> <INDENT> form = AnswerForm(self.params, question=self.question) <NEW_LINE> self.assertFalse(form.is_valid())
Test failed form validation of user does not present.
625941e3046cf37aa974d120
def higher_rainfall_avg(cityOne,cityTwo,weather_filename): <NEW_LINE> <INDENT> openFile = open(weather_filename,"r") <NEW_LINE> cityOneTotal = 0 <NEW_LINE> cityTwoTotal = 0 <NEW_LINE> counter1 = 0 <NEW_LINE> counter2 = 0 <NEW_LINE> for i in openFile: <NEW_LINE> <INDENT> split = i.rstrip().split(",") <NEW_LINE> citySpli...
Gets the city with the highest rain fall through avereaging.
625941e31d351010ab855ef7
def is_Press_Finger(self): <NEW_LINE> <INDENT> logger.debug("Is_Press_Finger started") <NEW_LINE> response_packet = self.generic_Command(0x00,"IS_PRESS_FINGER") <NEW_LINE> if(response_packet.response == 0x30): <NEW_LINE> <INDENT> logger.debug("Is_Press_Finger ended") <NEW_LINE> return response_packet.parameter <NEW_LIN...
Checks wether or not there is a finger on the scanner. @return 0 if there is a finger pressing the scanner and NoN-zero otherwise. @raises ValueError if receives a invalid response code.
625941e30fa83653e4657395
def print_status(text, linefeed=2): <NEW_LINE> <INDENT> text = f'{next(SPINNER)} {text}' <NEW_LINE> screen_width = shutil.get_terminal_size((80, 0))[0] <NEW_LINE> print(text + ' ' * (screen_width-(len(text)+1)) + '\b' * (screen_width -1) + '\n' * linefeed, end='')
output status line
625941e30a50d4780f667272
def get_hands(path): <NEW_LINE> <INDENT> with open(path) as f: <NEW_LINE> <INDENT> rounds = [line.strip('\n') for line in f.readlines()] <NEW_LINE> <DEDENT> return rounds
Return the contents of the file found at path into a list with the new line character stripped.
625941e31f037a2d8b9465da
def dt(): <NEW_LINE> <INDENT> dt = datetime.datetime.now() <NEW_LINE> _date_time = dt.strftime("%Y-%m-%d %H:%M:%S") <NEW_LINE> _date = dt.strftime("%Y-%m-%d") <NEW_LINE> _time = dt.strftime("%H:%M:%S") <NEW_LINE> return _date_time, _date, _time
日期函数
625941e316aa5153ce362855
def get_stacked_cpu_metrics(metrics, hide_idle=True): <NEW_LINE> <INDENT> stacked_metrics = deepcopy(metrics) <NEW_LINE> for m in stacked_metrics: <NEW_LINE> <INDENT> match = CPU_NUMBER_RE.match(m["name"]) <NEW_LINE> m["stack"] = int(match.group("number")) <NEW_LINE> if hide_idle and m["name"].endswith("idle"): <NEW_LI...
Get metrics with the ``stack`` attribute added. :param list metrics: The metrics to stack. :param bool hide_idle: (optional) Hide CPU idle. :rtype: :py:class:`list` Each CPU will be added to a stack group equal to that CPU's number. CPU idle metrics are hidden by default. ``metrics`` is not modified by this function...
625941e350812a4eaa59c6fb
def filter_candidates(candidates, transaction_db, min_support): <NEW_LINE> <INDENT> n = dict([(c, 0) for c in candidates]) <NEW_LINE> for t in transaction_db: <NEW_LINE> <INDENT> for c in candidates: <NEW_LINE> <INDENT> if c.issubset(t): <NEW_LINE> <INDENT> n[c] += 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> l = frozenset(...
Filtrates all candidates that not reach the minimum support required in the given transaction database :param candidates: set of k-size sets :param transaction_db: database of transactions :param min_support: minimum support to validate candidates :return: sub-set of candidates such that candidates have more support ...
625941e345492302aab5e6a4
def get_schema_forbidden(self, type='read'): <NEW_LINE> <INDENT> exclude = [] <NEW_LINE> try: <NEW_LINE> <INDENT> exclude.extend(self.schema.Meta.exclude) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> if type == 'write': <NEW_LINE> <INDENT> fields = self.schema().fields <NEW_LI...
Get fields that can't be modified, either for a 'read' operation (trying to access or search on a field) or a 'write' operation (trying to update a field). Args: type (str): 'read' or 'write'.
625941e3d10714528d6000c4
def test_establish_not_complete_without_close_token(self): <NEW_LINE> <INDENT> (channel_token, cust_state, com, com_proof) = self.bolt.bidirectional_establish_customer_generate_proof(self.channel_token, self.cust_state) <NEW_LINE> pay_token = self.bolt.bidirectional_establish_merchant_issue_pay_token(self.channel_state...
Test that missing close token prevents the customer from establishing
625941e33cc13d1c6d3c7755
def parse_dims(self, dims, obj): <NEW_LINE> <INDENT> def _parse_dim_(cf_arg): <NEW_LINE> <INDENT> if cf_arg in obj.dims: <NEW_LINE> <INDENT> return cf_arg <NEW_LINE> <DEDENT> dim = self.search_dim(obj, cf_arg) <NEW_LINE> if not dim: <NEW_LINE> <INDENT> raise XoaCFError(f"Invalid argument for dimension: {cf_arg}") <NEW_...
Convert from generic dim names to specialized names Parameters ---------- dims: str, tuple, list, dict obj: xarray.Dataset, xarray.DataArray Return ------ Same type as dims
625941e3a4f1c619b28b040d
def _Struct(module, parsed_struct): <NEW_LINE> <INDENT> struct = mojom.Struct(module=module) <NEW_LINE> struct.mojom_name = parsed_struct.mojom_name <NEW_LINE> struct.native_only = parsed_struct.body is None <NEW_LINE> struct.spec = 'x:' + module.GetNamespacePrefix() + struct.mojom_name <NEW_LINE> module.kinds[struct.s...
Args: module: {mojom.Module} Module currently being constructed. parsed_struct: {ast.Struct} Parsed struct. Returns: {mojom.Struct} AST struct.
625941e3dc8b845886cb5913
def distribute_model(self): <NEW_LINE> <INDENT> if self.args.num_gpus > 1: <NEW_LINE> <INDENT> self.resnet.cuda(0) <NEW_LINE> self.resnet = torch.nn.DataParallel(self.resnet, device_ids=[i for i in range(0, self.args.num_gpus)]) <NEW_LINE> self.transformers.cuda(0)
Distributes the CNNs over multiple GPUs. :return: Nothing
625941e338b623060ff0b1ca
def get_builds_for_repo(self, repo_id): <NEW_LINE> <INDENT> url = "%s/repo/%s/builds" % (TRAVIS_API_URL, repo_id) <NEW_LINE> payload = {"limit": 5} <NEW_LINE> r = requests.get(url, params=payload, headers=self.headers) <NEW_LINE> r.raise_for_status() <NEW_LINE> response = r.json() <NEW_LINE> result = [] <NEW_LINE> for ...
Returns the latest builds for the specified repository
625941e321bff66bcd684d2c
def make_sparse(self, sparseness_ratio=0.4): <NEW_LINE> <INDENT> sparseness = int(len(self.data) * sparseness_ratio) <NEW_LINE> removed = set() <NEW_LINE> while len(removed) < sparseness: <NEW_LINE> <INDENT> for cell in self.data.keys(): <NEW_LINE> <INDENT> if len(self.data[cell]) == 1: <NEW_LINE> <INDENT> nb = self.da...
Remove sparseness_ratio percentage of dead end cells Args: sparseness_ratio (float): percentage of dead end cell to remove
625941e36aa9bd52df037183
def object(self): <NEW_LINE> <INDENT> return QObject()
QObject QDeclarativeProperty.object()
625941e38c0ade5d55d3ed9b
@typemap <NEW_LINE> def to_sequence_like(x, dynamic_axes_like, name=''): <NEW_LINE> <INDENT> from cntk.cntk_py import to_sequence_like <NEW_LINE> x = sanitize_input(x) <NEW_LINE> dynamic_axes_like = sanitize_input(dynamic_axes_like) <NEW_LINE> return to_sequence_like(x, dynamic_axes_like, name)
This function converts 'x' to a sequence using the most significant static axis [0] as the sequence axis. The length of the sequences are obtained from the 'dynamic_axes_like' operand. Args: x: the tensor (or its name) which is converted to a sequence dynamic_axes_like: Tensor operand used to obtain the length...
625941e3004d5f362079a70e
def derivative(func, x, h=0.001): <NEW_LINE> <INDENT> return (func(x + h) - func(x - h)) /(2 * h)
author: Collins C. Chinedu <kolyneschinedu@gmail.com> approximates the derivative of a scalarn function at a point x using centered divided difference params: func -> scalar function of the basic form 'f(x)' x -> a point x at which to calculate the derivative h -> step value (making this s...
625941e3099cdd3c635f1036
def save_error(storage_helper, params, request, msg): <NEW_LINE> <INDENT> clear_analysis_files(storage_helper, params.tmp_dir, params.bucket, True) <NEW_LINE> request.description = msg <NEW_LINE> request.in_error = True <NEW_LINE> request.processed = True <NEW_LINE> request.save()
Utility function to clear files and update analysis request object :param storage_helper: minio storage helper :param params: a StaticAnalysisParams instance :param request: an AnalysisRequest instance :param msg: message to set as a description
625941e33317a56b8693a02c
def findKthLargest(self, nums, k): <NEW_LINE> <INDENT> minHeap = [] <NEW_LINE> for num in nums: <NEW_LINE> <INDENT> if len(minHeap) < k: <NEW_LINE> <INDENT> heapq.heappush(minHeap, num) <NEW_LINE> <DEDENT> elif num < minHeap[0]: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> elif num > minHeap[0]: <NEW_LINE> <INDENT>...
:type nums: List[int] :type k: int :rtype: int
625941e3f9cc0f698b1409d5
def trimquants(self, col: str, inf: float, sup: float): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.df = self._trimquants(col, inf, sup) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.err(e, self.trimquants, "Can not trim quantiles")
Remove superior and inferior quantiles from the dataframe :param col: column name :type col: str :param inf: inferior quantile :type inf: float :param sup: superior quantile :type sup: float :example: ``ds.trimquants("Col 1", 0.01, 0.99)``
625941e32c8b7c6e89b35b9b
def update_tags(self, genome, asset=None, tag=None, data=None): <NEW_LINE> <INDENT> if _check_insert_data(genome, str, "genome"): <NEW_LINE> <INDENT> _safe_setdef(self[CFG_GENOMES_KEY], genome, PXAM()) <NEW_LINE> if _check_insert_data(asset, str, "asset"): <NEW_LINE> <INDENT> _safe_setdef(self[CFG_GENOMES_KEY][genome],...
Updates the genomes in RefGenConf object at any level. If a requested genome-asset-tag mapping is missing, it will be created :param str genome: genome to be added/updated :param str asset: asset to be added/updated :param str tag: tag to be added/updated :param Mapping data: data to be added/updated :return RefGenConf...
625941e3d4950a0f3b08c726
def test_created_token_no_user(self): <NEW_LINE> <INDENT> payload = { 'email': 'test@email.com', 'password': 'testpass', } <NEW_LINE> res = self.client.post(TOKEN_URL, payload) <NEW_LINE> self.assertNotIn('token', res.data) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
Test that token is not created if user does not exist.
625941e331939e2706e4d241
def get_fk_relationship(self, column, fk): <NEW_LINE> <INDENT> table_side = 'm' <NEW_LINE> relation_side = 'n' <NEW_LINE> if self.test_column_uniqueness(column) is True: <NEW_LINE> <INDENT> table_side = '1' <NEW_LINE> <DEDENT> if self.test_column_uniqueness(fk.column) is True: <NEW_LINE> <INDENT> relation_side = '1' <N...
Return a string to describe the foreign key relationship
625941e307d97122c4178c71
def testRegionWithTolerance(self): <NEW_LINE> <INDENT> region1 = ZoneCluster([self.zones[0]]) <NEW_LINE> region2 = ZoneCluster([self.zones[1]]) <NEW_LINE> self.assertFalse(overlaps(region1, region2)) <NEW_LINE> self.assertFalse(overlaps(region2, region1)) <NEW_LINE> self.assertTrue(overlaps(region1, region2, 10)) <NEW_...
Test support for tolerance thresholds
625941e3ac7a0e7691ed44a2
@api.route('/currency', methods=['GET']) <NEW_LINE> @auto.doc(groups="public") <NEW_LINE> def currency(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> curr_db = get_curr_db() <NEW_LINE> <DEDENT> except InternalError as e: <NEW_LINE> <INDENT> api_logger.error(e.args) <NEW_LINE> abort(500) <NEW_LINE> <DEDENT> currency_li...
Return list of supported currencies. Input ----- Return ----- currency - array of supported currencies
625941e3498bea3a759b9e8b
def valid_length(self, phrase): <NEW_LINE> <INDENT> if len(phrase) < 4 or len(phrase) > 30: <NEW_LINE> <INDENT> return False
Method to validate length of string
625941e363b5f9789fde74c3
def _load_kernel_modules(self): <NEW_LINE> <INDENT> if not path.isdir(W1ThermSensor.BASE_DIRECTORY): <NEW_LINE> <INDENT> system("modprobe w1-gpio_pin") <NEW_LINE> system("modprobe w1-therm") <NEW_LINE> <DEDENT> for i in range(self.RETRY_ATTEMPS): <NEW_LINE> <INDENT> if path.isdir(W1ThermSensor.BASE_DIRECTORY): <NEW_LIN...
Load kernel modules needed by the temperature sensor if they are not already loaded. If the base directory then does not exist an exception is raised an the kernel module loading should be treated as failed. :raises KernelModuleLoadError: if the kernel module could not be loaded properly
625941e34a966d76dd5513f0
def forward(self, g_list, d=None): <NEW_LINE> <INDENT> for i, g in enumerate(g_list): <NEW_LINE> <INDENT> src = g.number_of_nodes() - 1 <NEW_LINE> possible_dests = range(src) <NEW_LINE> src_embed_expand = g.nodes[src].data['hv'].expand(src, -1) <NEW_LINE> possible_dests_embed = g.nodes[possible_dests].data['hv'] <NEW_L...
For each g in g_list, add an edge (src, dest) if (src, dst) does not exist. The src is just the latest node in g. Initialize edge features if new edges are added. During training, dst is passed rather than chosen and the log P of the action is recorded. During inference, dst is sampled from a Categorical distribution...
625941e34c3428357757c703
def get_bs_cat_cancel(df_policy, idx_df): <NEW_LINE> <INDENT> cat_cancel = get_bs_cat(df_policy, idx_df, 'Cancellation') <NEW_LINE> cat_cancel = np.where(cat_cancel == 'Y', 1, 0) <NEW_LINE> return(cat_cancel)
In: DataFrame(df_policy), Any(idx_df), Out: Series(cat_cancel), Description: get whether the policy has previous policy
625941e37d43ff24873a3080
def _pre_launch_validation( username, esh_driver, identity_uuid, boot_source, size): <NEW_LINE> <INDENT> identity = CoreIdentity.objects.get(uuid=identity_uuid) <NEW_LINE> check_quota(username, identity_uuid, size, include_networking=True) <NEW_LINE> check_application_threshold(username, identity_uuid, size, boot_sourc...
Used BEFORE launching a volume/instance .. Raise exceptions here to be dealt with by the caller.
625941e330bbd722463cc1a5
def render_to_json(**jsonargs): <NEW_LINE> <INDENT> def outer(f): <NEW_LINE> <INDENT> @wraps(f) <NEW_LINE> def inner_json(request, *args, **kwargs): <NEW_LINE> <INDENT> result = f(request, *args, **kwargs) <NEW_LINE> r = HttpResponse(content_type='application/json') <NEW_LINE> if result: <NEW_LINE> <INDENT> indent = js...
Renders a JSON response with a given returned instance. Assumes json.dumps() can handle the result. The default output uses an indent of 4. @render_to_json() def a_view(request, arg1, argN): ... return {'x': range(4)} @render_to_json(indent=2) def a_view2(request): ... return [1, 2, 3]
625941e3796e427e537b09a6
def mouse(theWindowName, theButton, theQuery): <NEW_LINE> <INDENT> print('This is wrapper function to help code autocompletion.')
Query the mouse for events in a particular button in a particular window. This function behave exactly like `cvui.mouse(int theButton, int theQuery)`, with the difference that queries are targeted at a particular mouse button in a particular window instead. Parameters ---------- theWindowName: str name of the ...
625941e363d6d428bbe448ce
def read_memory(self, weights=None, idx=None): <NEW_LINE> <INDENT> if weights is None: <NEW_LINE> <INDENT> weights = torch.zeros(1, self.memory.size(0)).cuda() <NEW_LINE> weights[0, idx] = 1 <NEW_LINE> <DEDENT> self.addressing.append(weights[0].data) <NEW_LINE> read = torch.mm(weights, self.memory) <NEW_LINE> return re...
Read from memory (w X M)
625941e3097d151d1a223235
def store_cache(self, cache_file_name): <NEW_LINE> <INDENT> dir_name = os.path.dirname(cache_file_name) <NEW_LINE> if not os.path.isdir(dir_name): <NEW_LINE> <INDENT> os.makedirs(dir_name) <NEW_LINE> <DEDENT> with open(cache_file_name, "w") as json_file: <NEW_LINE> <INDENT> lines_data = [] <NEW_LINE> for line in self.p...
Cache the current track
625941e3bd1bec0571d90a0c
def get_parsed_args(): <NEW_LINE> <INDENT> parser, parser_deployer, parser_switches, parser_all = get_args(parser_args=True) <NEW_LINE> args = parser.parse_args() <NEW_LINE> if hasattr(args, 'deployer'): <NEW_LINE> <INDENT> _check_deployer(args, parser_deployer) <NEW_LINE> <DEDENT> if hasattr(args, 'switches'): <NEW_LI...
Get parsed 'gen' command arguments
625941e357b8e32f5248387b
def getNeighbor(self, parent_dungeon, direction: tuple): <NEW_LINE> <INDENT> x = self.pos[0] + direction[0] <NEW_LINE> y = self.pos[1] + direction[1] <NEW_LINE> return parent_dungeon[(x, y)]
Returns neighbor cell inside parent_dungeon in the given direciton.
625941e3167d2b6e31218f72
@moa.args.argument('-t', '--title', help='A title for this job') <NEW_LINE> @moa.args.forceable <NEW_LINE> @moa.args.commandName('map!') <NEW_LINE> def createMapX(job, args): <NEW_LINE> <INDENT> _createAdhocJob(job, args, 'map', [ ( 'process', _get_bash_history_file() ), ('input', None), ('output', None), ])
create an adhoc moa 'map' job This command is exactly the same as `moa map` but uses the Moa local (or user) bash history instead.
625941e34f88993c3716c441