code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def get_nu_pdt(asize, Z, grain_type): <NEW_LINE> <INDENT> EA = get_EA(asize, Z+1, grain_type) <NEW_LINE> Emin = get_Emin(asize, Z) <NEW_LINE> hnu_pdt = EA + Emin <NEW_LINE> nu_pdt = hnu_pdt / hplanck <NEW_LINE> del EA, Emin, hnu_pdt <NEW_LINE> return nu_pdt
When Z<0, the -Z attached electrons occupy energy levels above the valence band. The photodetachment threshold energy is given by equation 18 (WD01).
625941e4d18da76e235328e0
def edSetInPort(self): <NEW_LINE> <INDENT> return _pilot.OutputDataStreamPort_edSetInPort(self)
edSetInPort(OutputDataStreamPort self) -> std::set< YACS::ENGINE::InPort *,std::less< YACS::ENGINE::InPort * >,std::allocator< YACS::ENGINE::InPort * > >
625941e44d74a7450ccd45ca
def draw_triangle(border_color, fill_color, f, l): <NEW_LINE> <INDENT> lesser_angles = l <NEW_LINE> color(border_color, fill_color) <NEW_LINE> begin_fill() <NEW_LINE> down() <NEW_LINE> for _ in range(0, 3): <NEW_LINE> <INDENT> forward(f) <NEW_LINE> left(lesser_angles) <NEW_LINE> <DEDENT> end_fill() <NEW_LINE> up()
Draw a right triangle.
625941e4f7d966606f6aa40e
def _allowed_to_proceed(self, verbose): <NEW_LINE> <INDENT> def _display(msg, paths): <NEW_LINE> <INDENT> if not paths: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> logger.info(msg) <NEW_LINE> with indent_log(): <NEW_LINE> <INDENT> for path in sorted(compact(paths)): <NEW_LINE> <INDENT> logger.info(path) <NEW_LINE> <...
Display which files would be deleted and prompt for confirmation
625941e47d43ff24873a30a9
def test_neg_remove_with_no_parameters(self): <NEW_LINE> <INDENT> with pytest.raises(TypeError) as typeError: <NEW_LINE> <INDENT> self.as_connection.remove() <NEW_LINE> <DEDENT> assert "Required argument 'key' (pos 1) not found" in str( typeError.value)
Invoke remove() without any mandatory parameters.
625941e429b78933be1e5aac
def rectangleArea(height, width): <NEW_LINE> <INDENT> return height * width
Calculating the area of the rectangle and returning the value.
625941e45510c4643540f7df
def load_config(self, schema): <NEW_LINE> <INDENT> partial_config = {} <NEW_LINE> for key_name, sub_schema in iter_schema(schema): <NEW_LINE> <INDENT> environment_key = self._prefix + "_".join(key_name) <NEW_LINE> raw_value = os.environ.get(environment_key) <NEW_LINE> coerced_value = coerce_value(raw_value, sub_schema)...
Load configuration values for this schema.
625941e4b7558d58953c5311
def put(self, request, pk=None): <NEW_LINE> <INDENT> return Response({'method': 'PUT'})
handles updating an item
625941e415fb5d323cde0f1a
def project_with_homography(matrix, model_points, model_line_segment, rgb_image): <NEW_LINE> <INDENT> assert matrix.shape == (3, 4) <NEW_LINE> assert model_points.shape[1] == 2 <NEW_LINE> assert model_line_segment.shape[1] == 2 <NEW_LINE> N = model_points.shape[0] <NEW_LINE> image_points = np.zeros((N, 2)) <NEW_LINE> f...
:param matrix: 3*4 projection matrix :param model_points: N x 2 matrix, model world coordinate in meter :param model_line_segment: int segment index, start from 0 :param rgb_image: an RGB image :return: RGB image with model lines
625941e431939e2706e4d26a
def getNodePosition(mazeNodes, node): <NEW_LINE> <INDENT> for element in mazeNodes: <NEW_LINE> <INDENT> for inside in element: <NEW_LINE> <INDENT> if inside.number == node: <NEW_LINE> <INDENT> return inside.position
Returns the node position in the maze map [row, column]
625941e4adb09d7d5db6cb92
def __repr__(self): <NEW_LINE> <INDENT> return f"DimensionlessParticle(mass={self.mass}, charge={self.charge})"
Return a string representation of a |DimensionlessParticle|. Examples -------- >>> dimensionless_particle = DimensionlessParticle(mass=1.45, charge=1.23) >>> repr(dimensionless_particle) 'DimensionlessParticle(mass=1.45, charge=1.23)'
625941e4b5575c28eb68e409
def tableCellColumnSpan(self): <NEW_LINE> <INDENT> return 0
tableCellColumnSpan(self) -> int
625941e43c8af77a43ae3baa
def get_bn_modules(model: nn.Module) -> List[nn.Module]: <NEW_LINE> <INDENT> bn_layers = [ m for m in model.modules() if m.training and isinstance(m, BN_MODULE_TYPES) ] <NEW_LINE> return bn_layers
Find all BatchNorm (BN) modules that are in training mode. See fvcore.precise_bn.BN_MODULE_TYPES for a list of all modules that are included in this search. Args: model (nn.Module): a model possibly containing BN modules. Returns: list[nn.Module]: all BN modules in the model.
625941e4b57a9660fec33c8f
def reduce_stock_sale(reduce_set, username, now_time, user_level): <NEW_LINE> <INDENT> sale_id = now_time + user_level <NEW_LINE> total = 0 <NEW_LINE> return_set = { 'sale_id': sale_id, 'time': now_time } <NEW_LINE> try: <NEW_LINE> <INDENT> sale_list = {} <NEW_LINE> for key in reduce_set: <NEW_LINE> <INDENT> goods_id =...
销售-减少库存,添加销售库记录 返回: { 'status': 'success'/'fail', 'list': {0:{id, name, quantity, price, tot_price}, 1:.....} 'total': 总额, 'sale_id': 销售单号, 'time': now_time, 'username': 用户名 }
625941e44c3428357757c72b
def __init__(self, action=None, application=None, description=None, disabled=None, dst_list=None, name=None, src_list=None, uri=None): <NEW_LINE> <INDENT> self._action = None <NEW_LINE> self._application = None <NEW_LINE> self._description = None <NEW_LINE> self._disabled = None <NEW_LINE> self._dst_list = None <NEW_LI...
SecRuleResponse - a model defined in Swagger
625941e47c178a314d6ef86b
def idea(self, hmm): <NEW_LINE> <INDENT> pass
what if we just make everything fully abstract and so everything is just a stack of operations. Or I mean we should keep better structure over stuff but ALSO keep something like that so that every single contribution (extra text, text filtered out, text edited...) can be taken out/changed or whatever, after the fact. O...
625941e48c3a8732951587c5
def objs_touching_point(self, x, y): <NEW_LINE> <INDENT> raise NotImplementedError(msg_abstract)
Returns a container with known objects touching point (x, y) Useful for mouse pick
625941e49b70327d1c4e11dd
def sections(self): <NEW_LINE> <INDENT> return self._ordered_subsections.copy()
Get the subections of this object
625941e4d486a94d0b98e54c
def _parse_header(self, metadata): <NEW_LINE> <INDENT> lines = metadata.rstrip().splitlines() <NEW_LINE> if len(lines) != self.header_size: <NEW_LINE> <INDENT> raise ValueError("expected {} header lines, found {}".format(self.header_size, len(lines))) <NEW_LINE> <DEDENT> lines = [line.rstrip() for line in lines] <NEW_L...
Parses header text and return a dictionary. Raises ValueError for any errors encountered.
625941e4956e5f7376d71271
def Generate(test_runs, manifests): <NEW_LINE> <INDENT> tmpl_args = [] <NEW_LINE> for test_run_id, test_run in enumerate(test_runs): <NEW_LINE> <INDENT> logging.info('Generating report for: %s.', test_run) <NEW_LINE> test_run.CleanUpTestResults() <NEW_LINE> test_run.SuppressTestResults(manifests) <NEW_LINE> groups = {}...
Generate HTML report from provided test runs. Args: test_runs: DejaGnuTestRun objects list. manifests: Manifest object list that will drive test result suppression. Returns: String to which the HTML report was rendered.
625941e4d268445f265b5274
def widget_to_matrix_coords(self, x, y): <NEW_LINE> <INDENT> return y // self.cell_size, x // self.cell_size
Given pixel ccordinates, return coordinates of corresponding cell Returns (row, column)
625941e4ec188e330fd5ab9d
def make_heartbeat_response(heartbeat_id=0): <NEW_LINE> <INDENT> payload = bytearray(struct.pack('<B', heartbeat_id)) <NEW_LINE> message = HibikeMessage(MESSAGE_TYPES["HeartBeatResponse"], payload) <NEW_LINE> return message
Makes and returns HeartBeat message.
625941e4956e5f7376d71272
def save_models(self): <NEW_LINE> <INDENT> obj = self.new_obj <NEW_LINE> obj.save() <NEW_LINE> if obj.course_org is not None: <NEW_LINE> <INDENT> course_org = obj.course_org <NEW_LINE> course_org.course_nums = Courseinfo.objects.filter(course_org=course_org).count() <NEW_LINE> course_org.save()
在保存课程时,修改机构的课程总数
625941e415fb5d323cde0f1b
def test_resume(self): <NEW_LINE> <INDENT> game = self.start_game() <NEW_LINE> start = self.master.get_time() <NEW_LINE> self.master.admin('Server: pause') <NEW_LINE> sleep(7) <NEW_LINE> self.assertAdminVetoable(self.master, 'resume', 'Fake Human Player (Fake_Master) is resuming the game.') <NEW_LINE> self.wait_for_act...
Players can resume a paused game.
625941e4bf627c535bc135d5
def jql(self, jql, fields='*all', start=0, limit=None, expand=None): <NEW_LINE> <INDENT> params = {} <NEW_LINE> if start is not None: <NEW_LINE> <INDENT> params['startAt'] = int(start) <NEW_LINE> <DEDENT> if limit is not None: <NEW_LINE> <INDENT> params['maxResults'] = int(limit) <NEW_LINE> <DEDENT> if fields is not No...
Get issues from jql search result with all related fields :param jql: :param fields: list of fields, for example: ['priority', 'summary', 'customfield_10007'] :param start: OPTIONAL: The start point of the collection to return. Default: 0. :param limit: OPTIONAL: The limit of the number of issues to return, this may be...
625941e4377c676e912725ad
def get_random_data(annotation_line, input_shape, max_boxes=50, jitter=.3, hue=.1, sat=1.5, val=1.5): <NEW_LINE> <INDENT> line = annotation_line.split() <NEW_LINE> image = Image.open(line[0]) <NEW_LINE> iw, ih = image.size <NEW_LINE> h, w = input_shape <NEW_LINE> box = np.array([np.array(list(map(int, box.split(','))))...
random preprocessing for real-time data augmentation
625941e4e76e3b2f99f3ac0b
def eraseMem(self, EraseCal=False): <NEW_LINE> <INDENT> if not isinstance(EraseCal, bool): <NEW_LINE> <INDENT> raise LabJackException("EraseCal must be a Boolean value (True or False).") <NEW_LINE> <DEDENT> if EraseCal: <NEW_LINE> <INDENT> command = [ 0 ] * 8 <NEW_LINE> command[1] = 0xF8 <NEW_LINE> command[2] = 0x01 <N...
Name: U6.eraseMem(EraseCal=False) Args: EraseCal, set to True to erase the calibration memory. Desc: The U6 uses flash memory that must be erased before writing. Please read section 5.2.8 of the user's guide before you do something you may regret. >>> myU6 = U6() >>> myU6.eraseMem() NOTE: Do not call this f...
625941e4b57a9660fec33c90
def click_categories_delete_button(self): <NEW_LINE> <INDENT> is_clicked = None <NEW_LINE> try: <NEW_LINE> <INDENT> self.logger.info('Start: click categories delete button') <NEW_LINE> self._system_admin_page.click_categories_delete_button() <NEW_LINE> is_clicked = True <NEW_LINE> <DEDENT> except WebDriverException as ...
Returning click categories delete button Implementing logging for click categories delete button functionality :return: True/False
625941e4566aa707497f4969
def differentiator(delta): <NEW_LINE> <INDENT> def _differentiator(fin): <NEW_LINE> <INDENT> def fout(x, diff): <NEW_LINE> <INDENT> if sum(diff) == 0: <NEW_LINE> <INDENT> out = as_array(fin(x)) <NEW_LINE> return out <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> diff_axis = np.argmax(diff) <NEW_LINE> x_plus_dx = np.copy...
Decorator that makes a function differentiable. The derivatives of the function are approximated by finite differences. The function must take a single (N, D) array of positions as input. The returned function takes a single (N, D) array of positions and a (D,) array derivative specification. Parameters ---------- del...
625941e4bf627c535bc135d6
def create_entity(self, entity_json, update_identifier=None, token=None): <NEW_LINE> <INDENT> if not token: <NEW_LINE> <INDENT> token = self.do_auth() <NEW_LINE> if not token: <NEW_LINE> <INDENT> raise Exception('create_entity was unable to authenticate') <NEW_LINE> <DEDENT> <DEDENT> if update_identifier: <NEW_LINE> <I...
create_entity(entity_json) calls to /entities/ endpoint entity_json: [str] currently formatted request body in EIQ-json for new entity returns: [python object] parsed json response from api
625941e43c8af77a43ae3bab
def evaluate_actions(self, inp, timesteps, actions): <NEW_LINE> <INDENT> dist, values = self.get_dist_and_state_value(inp, timesteps) <NEW_LINE> action_log_probs = dist.log_prob(self.make_tensor(actions)) <NEW_LINE> if len(action_log_probs.shape) == 2: <NEW_LINE> <INDENT> action_log_probs = action_log_probs.sum(-1) <NE...
Evaluates the given actions for the given input for training, returning the log-probs/values/entropy
625941e40a366e3fb873ec24
def get_dataset_report_html_template(**kwargs): <NEW_LINE> <INDENT> return _get_template(os.path.join(ROOT_DIR, 'template_reports', 'dataset_report_template.tmpl.html'), **kwargs)
Returns html template (string) for dataset report page (page de garde)
625941e4fff4ab517eb2f844
def get_latest_snapshot(self, refresh_if_old=False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> snap = TaskSnapshot.objects.filter(task=self).latest('date') <NEW_LINE> if refresh_if_old and (datetime.now() - snap.date) > timedelta(hours=1): <NEW_LINE> <INDENT> snap = self.snapshot() <NEW_LINE> <DEDENT> ...
Returns the most recent snapshot of the Task. If no snapshots found, returns None.
625941e4c432627299f0504f
def average_edge_length(m,max_iter=1): <NEW_LINE> <INDENT> return lib_py_gel.average_edge_length(m.obj)
Returns the average edge length.
625941e46e29344779a62a16
def check_play_button(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets, mouse_x, mouse_y): <NEW_LINE> <INDENT> button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y) <NEW_LINE> if button_clicked and not stats.game_active: <NEW_LINE> <INDENT> start_game(ai_settings, screen, stats, sb, ship, a...
玩家单击Play按钮后开始游戏
625941e476d4e153a657ef38
def set_block(self,width_1=10.0,angle_u=60.0,angle_v=60.0): <NEW_LINE> <INDENT> angle_u_rad=angle_u*pi/180.0 <NEW_LINE> angle_v_rad=angle_v*pi/180.0 <NEW_LINE> x_dummy,f1_max=self.F1_axis_ini.calc_highest_point() <NEW_LINE> x_dummy,f1_min=self.F1_axis_ini.calc_lowest_point() <NEW_LINE> axis_1_length=abs(f1_max-f1_min) ...
sets the angle-nomogram of the block
625941e407d97122c4178c9b
def replace_api_secret_key_with_http_info(self, api_key_id, api_version, **kwargs): <NEW_LINE> <INDENT> all_params = ['api_key_id', 'api_version'] <NEW_LINE> all_params.append('async_req') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.appen...
Generate an API Secret Key # noqa: E501 Generate a new API secret key. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_api_secret_key_with_http_info(api_key_id, api_version, async_req=True) >>> result = th...
625941e473bcbd0ca4b2c47b
def remove(self, node): <NEW_LINE> <INDENT> if not self.valid_node(node): <NEW_LINE> <INDENT> raise ValueError('MongoTree::remove:> node used for the node ' 'argument is not valid.') <NEW_LINE> <DEDENT> for child in node['children']: <NEW_LINE> <INDENT> child = self.db.treefoo.find_one({'_id': child}) <NEW_LINE> if not...
Remove a node from the tree. If it has children, remove those, too. Arguments: node (dict): A dict representing a node.
625941e4d8ef3951e3243944
def calculateProbability(x, mean, cov, isNaive = False): <NEW_LINE> <INDENT> d = len(x) <NEW_LINE> stdev = math.fabs(np.linalg.det(cov)) <NEW_LINE> n = 1 / ((math.sqrt(2*math.pi)**d * stdev)) <NEW_LINE> temp = np.dot(x - mean[0] , np.linalg.inv(cov)) <NEW_LINE> exponentnum = math.fabs(np.dot(temp, np.transpose(x - mean...
calculate the probability density function of Fx. input: x: test case mean:array of means for the x's type cov: array of covariance matrix of x's type isNaive: if true, is naive bayes's operation, otherwise, full bayes Output: the pdf
625941e4b830903b967e9d0d
def do_update(self, arg): <NEW_LINE> <INDENT> if arg == "": <NEW_LINE> <INDENT> print('** class name missing **') <NEW_LINE> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> model_name, model_id, attr, value = arg.split(' ') <NEW_LINE> models.storage.update(model_name, model_id, attr, value) <NEW_LINE> models.storag...
Updates an instance based on the class name and id by adding or updating attribute (save the change into the JSON file) Usage: update <class name> <id> <attribute name> "<attribute value>"
625941e41f037a2d8b946603
def tls(force=False): <NEW_LINE> <INDENT> def middleware(conn): <NEW_LINE> <INDENT> if force or conn.has_extn('STARTTLS'): <NEW_LINE> <INDENT> conn.starttls() <NEW_LINE> conn.ehlo() <NEW_LINE> <DEDENT> <DEDENT> return middleware
Middleware implementing TLS for SMTP connections. By default this is not forced- TLS is only used if STARTTLS is available. If the *force* parameter is set to True, it will not query the server for TLS features before upgrading to TLS.
625941e4dd821e528d63b5ac
def create_volume(self, volume): <NEW_LINE> <INDENT> volume_name = self._translate_volume_name(volume['name']) <NEW_LINE> volume_size = float( volume['size'] * zte_pub.ZTE_SIZE * zte_pub.ZTE_SIZE) <NEW_LINE> self._create_volume(volume_name, volume_size)
Create a new volume.
625941e4099cdd3c635f105f
def largestDivisibleSubset(self, nums): <NEW_LINE> <INDENT> if len(nums) < 2: <NEW_LINE> <INDENT> return nums <NEW_LINE> <DEDENT> nums.sort() <NEW_LINE> dp = [1 for _ in range(len(nums))] <NEW_LINE> res = [] <NEW_LINE> parent = [-1 for _ in range(len(nums))] <NEW_LINE> for j in range(1, len(nums)): <NEW_LINE> <INDENT> ...
:type nums: List[int] :rtype: List[int]
625941e4a8ecb033257d34d2
def master_inhibit(self, state=True): <NEW_LINE> <INDENT> if state: <NEW_LINE> <INDENT> param = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> param = 1 <NEW_LINE> <DEDENT> ph = dict(message=make_msg(228, [param]), request_code=228, bytes_expected=0, bytes_sent=1, type_returned=bool, user_message='modify_master_inhibi...
Change master inhibit state. Parameters ---------- state : bool State to change the coin validator too. Raises ------ UserWarning -- If the state is not True or False. -- If self.serial_object.isOpen() is False.
625941e45166f23b2e1a555f
def sortColors(self, nums): <NEW_LINE> <INDENT> if nums is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> p_r, p_b = 0, len(nums) - 1 <NEW_LINE> curr = 0 <NEW_LINE> while curr <= p_b: <NEW_LINE> <INDENT> if nums[curr] == 0: <NEW_LINE> <INDENT> nums[curr], nums[p_r] = nums[p_r], nums[curr] <NEW_LINE> p_r += 1 <NEW...
:type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
625941e40c0af96317bb85ee
def toggle_styles(self,*style_names): <NEW_LINE> <INDENT> self._style_classes ^= set(style_names) <NEW_LINE> self.restyle()
Toggle some style classes and restyle the part
625941e41d351010ab855f21
def filter_paired_dataset_indices_by_size(src_sizes, tgt_sizes, indices, max_sizes): <NEW_LINE> <INDENT> if max_sizes is None: <NEW_LINE> <INDENT> return indices, [] <NEW_LINE> <DEDENT> if type(max_sizes) in (int, float): <NEW_LINE> <INDENT> max_src_size, max_tgt_size = max_sizes, max_sizes <NEW_LINE> <DEDENT> else: <N...
Filter a list of sample indices. Remove those that are longer than specified in max_sizes. Args: indices (np.array): original array of sample indices max_sizes (int or list[int] or tuple[int]): max sample size, can be defined separately for src and tgt (then list or tuple) Returns: np.array: f...
625941e444b2445a3393249a
def __and__(self, other): <NEW_LINE> <INDENT> if self.upper < other.lower or other.upper < self.lower: <NEW_LINE> <INDENT> return self.__class__((0, 0)) <NEW_LINE> <DEDENT> lower = max(self.lower, other.lower) <NEW_LINE> upper = min(self.upper, other.upper) <NEW_LINE> return self.__class__( [lower, upper], lower_inc=lo...
Define the intersection operator
625941e4baa26c4b54cb1522
def __cmp__(self, other): <NEW_LINE> <INDENT> return NotImplemented
Return negative if self < other, zero if self == other, positive if self > other.
625941e40fa83653e46573bf
def new_url(**kwargs): <NEW_LINE> <INDENT> url_base = "/axapi/v3/gslb/ip-list/{gslb-ip-list-obj-name}" <NEW_LINE> f_dict = {} <NEW_LINE> f_dict["gslb-ip-list-obj-name"] = "" <NEW_LINE> return url_base.format(**f_dict)
Return the URL for creating a resource
625941e456ac1b37e62645ce
def assert_approx_equal(actual,desired,significant=7,err_msg='',verbose=True): <NEW_LINE> <INDENT> __tracebackhide__ = True <NEW_LINE> import numpy as np <NEW_LINE> (actual, desired) = map(float, (actual, desired)) <NEW_LINE> if desired == actual: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> with np.errstate(invalid=...
Raises an AssertionError if two items are not equal up to significant digits. .. note:: It is recommended to use one of `assert_allclose`, `assert_array_almost_equal_nulp` or `assert_array_max_ulp` instead of this function for more consistent floating point comparisons. Given two numbers...
625941e450485f2cf553d1a2
def setup_app(command, conf, vars): <NEW_LINE> <INDENT> if not pylons.test.pylonsapp: <NEW_LINE> <INDENT> load_environment(conf.global_conf, conf.local_conf) <NEW_LINE> <DEDENT> db_conn = connect(conf) <NEW_LINE> db_conn.register([User]) <NEW_LINE> users_collection = db_conn[conf['mongo.db']].users <NEW_LINE> _ = unico...
Place any commands to setup quotehi here
625941e48e05c05ec3eea77e
def distribute(items, ticks): <NEW_LINE> <INDENT> assert type(items) == list <NEW_LINE> assert type(ticks) == int <NEW_LINE> assert ticks > 0 <NEW_LINE> i = 0 <NEW_LINE> items_per_bucket = math.ceil(len(items) / ticks) <NEW_LINE> buckets = [ [] for _ in range(ticks) ] <NEW_LINE> for j, item in enumerate(items): <NEW_LI...
`distribute(items, ticks)` Groups the items over the specified number of ticks so that they're evenly distributed @param : items : items to group together into buckets @param : ticks : the number of groups/buckets to group items into @return : list : a list of lists, with some items grouped into each individual lis...
625941e4d164cc6175783156
def format(self, data): <NEW_LINE> <INDENT> format_specification = self._construct_format_specification( self.expanded_pattern() ) <NEW_LINE> return self._PLAIN_PLACEHOLDER_REGEX.sub( functools.partial(self._format, data=data), format_specification )
Return a path formatted by applying *data* to this template. Raise :py:class:`~lucidity.error.FormatError` if *data* does not supply enough information to fill the template fields.
625941e4ab23a570cc25058d
def delete_role(self, role_id): <NEW_LINE> <INDENT> resp, body = self.delete('OS-KSADM/roles/%s' % role_id) <NEW_LINE> self.expected_success(204, resp.status) <NEW_LINE> return rest_client.ResponseBody(resp, body)
Delete a role. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v2-ext/index.html#delete-a-role
625941e41d351010ab855f22
def create_vrf_and_assign_interfaces(self, count, start=1): <NEW_LINE> <INDENT> for i in range(count): <NEW_LINE> <INDENT> vrf_id = i + start <NEW_LINE> pg_if = self.pg_if_by_vrf_id[vrf_id][0] <NEW_LINE> dest_addr = pg_if.local_ip6n <NEW_LINE> dest_addr_len = 64 <NEW_LINE> self.vapi.ip_table_add_del(is_ipv6=1, is_add=1...
Create required number of FIB tables / VRFs, put 3 pg-ip6 interfaces to every FIB table / VRF. :param int count: Number of FIB tables / VRFs to be created. :param int start: Starting number of the FIB table / VRF ID. (Default value = 1)
625941e4a05bb46b383ecc25
def run(): <NEW_LINE> <INDENT> os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' <NEW_LINE> from django.conf import settings <NEW_LINE> try: <NEW_LINE> <INDENT> from django import setup <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> setup() <NEW_LINE...
Run tests with Django setup.
625941e4e76e3b2f99f3ac0c
def start_anonymous_external_test(self): <NEW_LINE> <INDENT> url = self.address + "/api/v4/sessions" <NEW_LINE> res = self._request(url, method='POST') <NEW_LINE> result = res['result'] <NEW_LINE> session = Session(self, result['session']) <NEW_LINE> session.data_signature = result['signature'] <NEW_LINE> return sessio...
:rtype: (Session,Master,str)
625941e44f88993c3716c46a
def update(): <NEW_LINE> <INDENT> update_code() <NEW_LINE> update_env() <NEW_LINE> symlink() <NEW_LINE> permissions()
Copies your project and updates environment and symlink
625941e450812a4eaa59c724
def is_suspicious(self) -> bool: <NEW_LINE> <INDENT> return self.score >= self.suspicious_threshold
Check if the Result's score is high enough to be flagged as suspicious
625941e4ec188e330fd5ab9e
def __call__(self, outputs, output_symbols, label): <NEW_LINE> <INDENT> outputs = torch.stack(outputs) <NEW_LINE> seq_len, batch_size, label_size = outputs.shape <NEW_LINE> outputs = outputs.transpose(0,1) <NEW_LINE> outputs = outputs.transpose(1,2) <NEW_LINE> label = label[:,1:] <NEW_LINE> if label.shape[1] != seq_len...
outputs: (seq_len, batch_size, label_size) label: (batch_size, seq_len)
625941e47b25080760e3985e
def change_ring(self, base_ring=None, names=None, sparse=False, order=None): <NEW_LINE> <INDENT> if base_ring is None: <NEW_LINE> <INDENT> base_ring = self.base_ring() <NEW_LINE> <DEDENT> if names is None: <NEW_LINE> <INDENT> names = self.variable_names() <NEW_LINE> <DEDENT> if self._n == 1: <NEW_LINE> <INDENT> return ...
EXAMPLES:: sage: R = LaurentPolynomialRing(QQ,2,'x') sage: R.change_ring(ZZ) Multivariate Laurent Polynomial Ring in x0, x1 over Integer Ring
625941e48e05c05ec3eea77f
def test_activity_to_support(self): <NEW_LINE> <INDENT> duty_cycle = 0.75 <NEW_LINE> activity_phases = [0, 0.5, -1.0, -0.5] <NEW_LINE> support_phases = configs.activity_to_support_phases( activity_phases, duty_cycle ) <NEW_LINE> print('A->S:', support_phases) <NEW_LINE> self.assertEqual(support_phases[0], -0.25) <NEW_L...
:return:
625941e4851cf427c661a913
def save_link_info_json(json_dict): <NEW_LINE> <INDENT> current_path = os.path.dirname(os.path.abspath(__file__)) <NEW_LINE> relative_path = "../../data/json/" <NEW_LINE> json_folder_path = os.path.join(current_path, relative_path) <NEW_LINE> if not os.path.exists(json_folder_path): <NEW_LINE> <INDENT> os.makedirs(json...
Create a folder and output a JSON file of nearby traffic information :param json_dict: a json data of compelete query :return:
625941e4004d5f362079a738
def gen_binder_url(fname, binder_conf, gallery_conf): <NEW_LINE> <INDENT> fpath_prefix = binder_conf.get('filepath_prefix') <NEW_LINE> link_base = binder_conf.get('notebooks_dir') <NEW_LINE> relative_link = os.path.relpath(fname, gallery_conf['src_dir']) <NEW_LINE> path_link = os.path.join( link_base, replace_py_ipynb(...
Generate a Binder URL according to the configuration in conf.py. Parameters ---------- fname: str The path to the `.py` file for which a Binder badge will be generated. binder_conf: dict | None The Binder configuration dictionary. See `gen_binder_rst` for details. Returns ------- binder_url : str A URL th...
625941e44527f215b584c85a
def add_schedule(self, name, activation_date, day_period='one_time', final_action='ALERT_FAILURE', activated=True, minute_period='one_time', day_mask=None, repeat_until_date=None, comment=None): <NEW_LINE> <INDENT> json = { 'name': name, 'activation_date': activation_date, 'day_period': day_period, 'day_mask': day_mask...
Add a schedule to an existing task. :param str name: name for this schedule :param int activation_date: when to start this task. Activation date should be a UTC time represented in milliseconds. :param str day_period: when this task should be run. Valid options: 'one_time', 'daily', 'weekly', 'monthly', 'yearl...
625941e4187af65679ca5527
def add_include(self, module_spec): <NEW_LINE> <INDENT> assert self.can_include <NEW_LINE> if module_spec.name in self.includes: <NEW_LINE> <INDENT> raise ThriftCompilerError( 'Cannot include module "%s" in "%s". ' 'The name is already taken.' % (module_spec.name, self.path) ) <NEW_LINE> <DEDENT> self.includes[module_s...
Adds a module as an included module. :param module_spec: ModuleSpec of the included module.
625941e44a966d76dd55141a
def close(self): <NEW_LINE> <INDENT> logger.info("producer close incomplete - skipping") <NEW_LINE> print("producer close- skipping") <NEW_LINE> self.producer.flush()
Prepares the producer for exit by cleaning up the producer
625941e4287bf620b61d3e68
def twoSum(self, numbers, target): <NEW_LINE> <INDENT> for idx, n1 in enumerate(numbers, 1): <NEW_LINE> <INDENT> if n1 > target: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> start, end = idx, len(numbers) <NEW_LINE> while start < end: <NEW_LINE> <INDENT> mid = start + (end-start)//2 <NEW_LINE> if numbers[mid] + n1 > ...
:type numbers: List[int] :type target: int :rtype: List[int]
625941e4be8e80087fb21044
def get_votation_ids(year=None): <NEW_LINE> <INDENT> params = dict( sz=10000, utformat='iddump' ) <NEW_LINE> if year: params['rm'] = votation_year(year) <NEW_LINE> r = requests.get('{0}/voteringlista/'.format(API_URL), params=params) <NEW_LINE> return r.text.split(',')
Returns a list of votation ids for the given year or current year if none passed. Arguments: year: A year that corresponds to the votation year format Returns: A list of votation ids
625941e4462c4b4f79d1dad6
def bbox_nms(bbox, threshold, mode='union'): <NEW_LINE> <INDENT> scores = bbox[:, 0] <NEW_LINE> x1 = bbox[:, 1] <NEW_LINE> y1 = bbox[:, 2] <NEW_LINE> x2 = bbox[:, 3] <NEW_LINE> y2 = bbox[:, 4] <NEW_LINE> areas = (x2 - x1 + 1) * (y2 - y1 + 1) <NEW_LINE> order = scores.argsort()[::-1] <NEW_LINE> keep = [] <NEW_LINE> whil...
Non Maximum Suppression with different mode. Parameters ---------- bbox : numpy.ndarray, m x n, m >= 5 threshold : float, threshold to suppress overlapped face mode : str, optional ['union', 'min'] Returns: ------- list of int, indexes to keep
625941e4796e427e537b09d0
def genLogname(directory, tag): <NEW_LINE> <INDENT> return "%s/%s.log"%(directory, tag)
standardizes the naming convention for log files NOTE: interactiveQueue has a logger named "iQ" and all QueueItems and Tasks can access this logger by referencing it through the logging module. what's more, they can route their own output into multiple log files by adding Handlers to the child loggers returns a...
625941e40a366e3fb873ec25
def _onCustomTree(self, ev=None): <NEW_LINE> <INDENT> msg = strings.messages[self, 'loadCustomTree'] <NEW_LINE> dlg = wx.FileDialog(wx.GetApp().GetTopWindow(), message=msg, style=wx.FD_OPEN) <NEW_LINE> if dlg.ShowModal() != wx.ID_OK: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> choice = self.__treeChoice <NEW_LINE...
Called when the user pushes the *load custom tree* button. Prompts the user to choose a file, then calls :meth:`__loadTree`.
625941e4c432627299f05050
def getTackExt(self): <NEW_LINE> <INDENT> tackExt = None <NEW_LINE> for x509 in self.x509List[::-1]: <NEW_LINE> <INDENT> tlsCert = TlsCertificate(x509.bytes) <NEW_LINE> if tlsCert.tackExt: <NEW_LINE> <INDENT> if tackExt: <NEW_LINE> <INDENT> raise SyntaxError("Multiple TACK Extensions") <NEW_LINE> <DEDENT> else: <NEW_LI...
Get the TACK and/or Break Sigs from a TACK Cert in the chain.
625941e40c0af96317bb85ef
@app.route('/daniel', methods=['POST']) <NEW_LINE> def daniel(): <NEW_LINE> <INDENT> msg = Message.parse(request) <NEW_LINE> logging.debug(msg) <NEW_LINE> if msg.user_name == "slackbot": <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> bot = Daniel(msg) <NEW_LINE> return bot.say()
Daniel is a BOT, who reacts with calling his name 1) yo you: daniel yo daniel: yo 2) echo you: daniel echo HelloWorld daniel: HelloWorld
625941e43346ee7daa2b3176
def nearest_neighbours(p, old_projects): <NEW_LINE> <INDENT> threshold = 5 <NEW_LINE> return sorted(old_projects, key=lambda proj: proximity(p, proj[0]), reverse=True)[:threshold]
INPUT: p - a project vector, oldprojects - a list of tuples (project vector, software choice) [here software choice is a number in {1, 2, 3} representing the choice of software. OUTPUT: a list of the projects in oldprojects which most closely resemble our project of interest. NOTES: We can add a variable called thresho...
625941e47d43ff24873a30aa
def _field(self, *keys) -> Any: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> d = self._node <NEW_LINE> for key in keys: <NEW_LINE> <INDENT> d = d[key] <NEW_LINE> <DEDENT> return d <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> d = self._full_metadata <NEW_LINE> for key in keys: <NEW_LINE> <INDENT> d = d[key] ...
Lookups given fields in _node, and if not found in _full_metadata. Raises KeyError if not found anywhere.
625941e4f7d966606f6aa410
def _authenticate(self, conf, login, password): <NEW_LINE> <INDENT> if not password: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> entry = False <NEW_LINE> try: <NEW_LINE> <INDENT> filter = filter_format(conf['ldap_filter'], (login,)) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> _logger.warning('Cou...
Authenticate a user against the specified LDAP server. In order to prevent an unintended 'unauthenticated authentication', which is an anonymous bind with a valid dn and a blank password, check for empty passwords explicitely (:rfc:`4513#section-6.3.1`) :param dict conf: LDAP configuration :param login: username :para...
625941e4d10714528d6000ef
def tennisSet(score1, score2): <NEW_LINE> <INDENT> winner = max(score1, score2) <NEW_LINE> loser = min(score1, score2) <NEW_LINE> return (winner == 6 and loser < 5) or (winner == 7 and 5 <= loser <= 6)
In tennis, a set is finished when one of the players wins 6 games and the other one wins less than 5, or, if both players win at least 5 games, until one of the players wins 7 games. Determine if it is possible for a tennis set to be finished with the score score1 : score2.
625941e4de87d2750b86019e
def dateSelection3(self): <NEW_LINE> <INDENT> self.YearSpinBox11 = Spinbox(self.second, from_ = 2019, to = 2020, textvariable = self.SelectedYear11, wrap = TRUE, state = 'readonly', width = 7 ) <NEW_LINE> self.MonthSpinBox11 = Spinbox(self.second, values = tuple( self.DaysInMonth.keys() )[1:], textvariable = self.Sel...
'if self.MonthSpinBox is not None:
625941e401c39578d7e75243
def global_water_balance(self, *args, **kwargs): <NEW_LINE> <INDENT> return _cmf_core.NeumannBoundary_list_global_water_balance(self, *args, **kwargs)
global_water_balance(NeumannBoundary_list self, Time t) -> real real global_water_balance(cmf::math::Time t) const Returns the sum of the water balances of the nodes .. math:: \sigma_{global} = \sum_{i=0}^N{\sum_{j=0}^{C_i}{q_{ij}(t)}} . Replaces slow Python code like:
625941e4656771135c3ebc7b
def remove_listener(self, event_name: str, listener: Callable): <NEW_LINE> <INDENT> if event_name not in self.__listeners: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for priority, listeners in self.__listeners[event_name].items(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> key = listeners.index(listener) <NEW_LIN...
Removes an event listener from the specified events. :param event_name: The event to remove a listener from :param listener: The listener to remove
625941e4b545ff76a891421d
def lasso_coordinate_descent_step(i, feature_matrix, output, weights, l1_penalty): <NEW_LINE> <INDENT> prediction = predict_output(feature_matrix, weights) <NEW_LINE> ro_i = sum(feature_matrix[:,i]*(output - prediction + weights[i]*feature_matrix[:,i])) <NEW_LINE> if i == 0: <NEW_LINE> <INDENT> new_weight_i = ro_i <NEW...
Lasso Coordinate Descent Step. Returns new weight for feature[i] by calculating the residual of the model without feature[i] and setting it equal to ro_i. If ro_i is between -l1_penalty/2 and +l1_penalty/2 then the new weight will be set to 0, otherwise it will be set equal to ro_i plus/minus l1_penalty/2 (lambda). ...
625941e4eab8aa0e5d26df61
def one_hot(self, x): <NEW_LINE> <INDENT> y = torch.zeros(4, 10) <NEW_LINE> for i in range(4): <NEW_LINE> <INDENT> index = int(x[i]) <NEW_LINE> y[i][index] = 1 <NEW_LINE> <DEDENT> return y
以onehot形式做标签 :param x: :return:
625941e4be7bc26dc91cda00
def load_path2gt(paths_file, config): <NEW_LINE> <INDENT> paths = list() <NEW_LINE> path2gt = dict() <NEW_LINE> path2onehot = dict() <NEW_LINE> pf = open(paths_file) <NEW_LINE> for path in pf.readlines(): <NEW_LINE> <INDENT> path = path.rstrip('\n') <NEW_LINE> paths.append(path) <NEW_LINE> label = path2gt_datasets(path...
Given the path, construct the ground truth vectors. This function heavily relies on path2gt_datasets(.), where the relation between the path and ground truth are defined.
625941e445492302aab5e6cf
def __check_response_for_bluedart_error(self): <NEW_LINE> <INDENT> pass
This checks the response for general bluedart errors that aren't related to any one WSDL.
625941e4a8ecb033257d34d3
def save_envelope_to_blockchain(envelope): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> call_ledger_api("post", "/ledger/envelopes", json.loads(envelope.toc)) <NEW_LINE> <DEDENT> except APIError as error: <NEW_LINE> <INDENT> raise APIError("Failed to save envelope to blockchain. " + str(error))
save the given envelope on the blockchain by calling the ledger service
625941e492d797404e304593
def test_rejects_non_integer_value(self): <NEW_LINE> <INDENT> self.assertRaises(ValueError, self.linkedlist.insert_sorted, "4") <NEW_LINE> self.assertRaises(ValueError, self.linkedlist.insert_sorted, 1.5)
Tests non integer value is rejected and an error is raised
625941e43617ad0b5ed682fe
def BlockPath(block_name): <NEW_LINE> <INDENT> idef = scriptcontext.doc.InstanceDefinitions.Find(block_name, True) <NEW_LINE> if not idef: raise ValueError("%s does not exist in InstanceDefinitionsTable"%block_name) <NEW_LINE> return idef.SourceArchive
Returns path to the source of a linked or embedded block definition. A linked or embedded block definition is a block definition that was inserted from an external file. Parameters: block_name = name of an existing block definition Returns: path to the linked block on success Example: import rhinoscriptsyntax as ...
625941e4956e5f7376d71273
def test_get_mailing_list_member(self): <NEW_LINE> <INDENT> member = SpokeMailingListMember(self.org_name, self.list_address) <NEW_LINE> result = member.get(self.list_member)['data'] <NEW_LINE> list_name, list_domain = self.list_address.split('@') <NEW_LINE> rdn = '%s=%s' % (self.list_key, list_name) <NEW_LINE> contain...
Retrieve mailing list member; retrieve list member object.
625941e4d268445f265b5276
def reverseList(self, head): <NEW_LINE> <INDENT> prev = None <NEW_LINE> curr = head <NEW_LINE> if curr == None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> while curr != None: <NEW_LINE> <INDENT> temp = curr.next <NEW_LINE> curr.next = prev <NEW_LINE> prev = curr <NEW_LINE> curr = temp <NEW_LINE> <DEDENT> return pre...
:type head: ListNode :rtype: ListNode
625941e491f36d47f21ac8fe
def tsp_force_brute(g, progress_bar=False): <NEW_LINE> <INDENT> pp = itertools.permutations(range(1, len(g))) <NEW_LINE> poids_min = math.inf <NEW_LINE> meilleur_ch = (0,) <NEW_LINE> if progress_bar: <NEW_LINE> <INDENT> pp = tqdm(pp) <NEW_LINE> <DEDENT> for ch in pp: <NEW_LINE> <INDENT> ch = (0,) + ch <NEW_LINE> poids ...
entrée: g: graphe complet non orienté sous forme de matrice d'adjacence symétrique sortie: un cycle hamiltonien de poids minimal, commençant par le sommet 0 remarque: génération de toutes les permutations commençant par 0 donc deux fois trop de cycles hamiltoniens (chaque cycle apparaît deux fois, une fois par sens de ...
625941e40a50d4780f66729d
def mBM5poly(vol, pars): <NEW_LINE> <INDENT> a = pars[0] <NEW_LINE> b = pars[1] <NEW_LINE> c = pars[2] <NEW_LINE> d = pars[3] <NEW_LINE> e = pars[4] <NEW_LINE> n = 1 <NEW_LINE> VV = np.power(vol, -1 / 3) <NEW_LINE> E = a + b * VV + c * VV ** 2 + d * VV ** 3 + e * VV ** 4 <NEW_LINE> return E
modified BM5 EOS, Shang SL comput mater sci, 2010: 1040-1048, original expressions.
625941e47c178a314d6ef86e
def request_id_to_key(request_id): <NEW_LINE> <INDENT> return ndb.Key(TaskRequest, request_id ^ task_pack.TASK_REQUEST_KEY_ID_MASK)
Converts a request id into a TaskRequest key. Note that this function does NOT accept a task id. This functions is primarily meant for limiting queries to a task creation range.
625941e407d97122c4178c9c
def run(self): <NEW_LINE> <INDENT> logger.info("loading projects") <NEW_LINE> self._load_projects() <NEW_LINE> while not self._quit: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> time.sleep(self.LOOP_INTERVAL) <NEW_LINE> self._update_projects() <NEW_LINE> self._check_task_done() <NEW_LINE> self._check_request() <NEW_LIN...
Start scheduler loop
625941e499fddb7c1c9de797
def predict(X): <NEW_LINE> <INDENT> pass
Predicts a value of from the surrogate model for the given independent values in X. X: list The input values for which the predicted output is requested. Returns the predicted output value.
625941e4956e5f7376d71274
def RemoveChildren(self, devices): <NEW_LINE> <INDENT> if self.minor is None: <NEW_LINE> <INDENT> base.ThrowError("drbd%d: can't attach to drbd8 during RemoveChildren", self._aminor) <NEW_LINE> <DEDENT> info = self._GetShowInfo(self.minor) <NEW_LINE> if "local_dev" not in info: <NEW_LINE> <INDENT> return <NEW_LINE> <DE...
Detach the drbd device from local storage. @type devices: list of L{BlockDev} @param devices: a list of exactly two L{BlockDev} objects; the first denotes the data device, the second the meta device for this DRBD device
625941e45510c4643540f7e2
def show_landmarks(image, heatmap, gt_landmarks, gt_heatmap): <NEW_LINE> <INDENT> pred_landmarks = [] <NEW_LINE> pred_landmarks, _ = get_preds_fromhm(torch.from_numpy(heatmap).unsqueeze(0)) <NEW_LINE> pred_landmarks = pred_landmarks.squeeze()*4 <NEW_LINE> heatmap = np.max(gt_heatmap, axis=0) <NEW_LINE> heatmap = heatma...
Show image with pred_landmarks
625941e415baa723493c4380
def rgetKEffChol(self): <NEW_LINE> <INDENT> return _core.CGPCholCache_rgetKEffChol(self)
rgetKEffChol(CGPCholCache self) -> MatrixXdChol & Parameters ---------- self: limix::CGPCholCache *
625941e4bd1bec0571d90a37
@register_model <NEW_LINE> def regnety_040(pretrained=False, **kwargs): <NEW_LINE> <INDENT> return _regnet('regnety_040', pretrained, **kwargs)
RegNetY-4.0GF
625941e40fa83653e46573c0