code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def inBoxes (p, bboxes): <NEW_LINE> <INDENT> dim = len(p) <NEW_LINE> for box in bboxes: <NEW_LINE> <INDENT> rst = [p[idd] > box[1][idd] or p[idd] < box[0][idd] for idd in range(dim)] <NEW_LINE> s = sum(rst) <NEW_LINE> if (s<1): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False
Check whether point p falls into boxes :param p: :param boxes: [ [several(dim) lowends] [several(dim) highends] ... ] :return: True or False
625941d17b25080760e395ed
def _box_cross_relations_duplicates(self, duplicates: list, childs: list, relation_key: str): <NEW_LINE> <INDENT> new_duplicates = [] <NEW_LINE> self._add_child_to_duplicates(duplicates, childs[0], relation_key) <NEW_LINE> for child in childs[1:]: <NEW_LINE> <INDENT> for dup in duplicates: <NEW_LINE> <INDENT> new_item ...
Generates duplicates for childs of relation with relation_key. Given a list of duplicates, add the first child to all the existing duplicates. Create new duplicates for the other childs. :param duplicates: :param childs: :param relation_key: :return:
625941d18a349b6b435e8308
def _get_tuple_multich(self, name): <NEW_LINE> <INDENT> field = np.array(self[name]) <NEW_LINE> if field.ndim == 1: <NEW_LINE> <INDENT> field = np.repeat([field], self.nch, axis=0) <NEW_LINE> <DEDENT> return field
Get a n-element tuple field in multi-ch format (1 row per ch).
625941d14f88993c3716c1fb
def sensitve_information_disclosure(self,vector,content): <NEW_LINE> <INDENT> if content and vector: <NEW_LINE> <INDENT> vector = vector.strip().lower() <NEW_LINE> content = content.strip().lower() <NEW_LINE> if vector in content: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False
It checks fot the content, if sensitive word exist in the contents, it could be a breach... :param vector: URLS :param content: website page :return: if there is any information disclosed
625941d1baa26c4b54cb12b3
def main(_): <NEW_LINE> <INDENT> return COMPLETE
STEPS to perform
625941d1a4f1c619b28b01cb
def format_data(_): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> temp_map = {} <NEW_LINE> global nodes_map <NEW_LINE> data = open(data_path, mode="r") <NEW_LINE> data2 = open(node_map, mode="w") <NEW_LINE> for line in data: <NEW_LINE> <INDENT> data2.write(line) <NEW_LINE> <DEDENT> pass <NEW_LINE> data2.write('\n') <NEW...
creates a dict of dicts that can be recuresed over by the main function. :param _:
625941d1be7bc26dc91cd793
def __str__(self): <NEW_LINE> <INDENT> return "service %s" % (self.name, )
Return the string representation.
625941d1ac7a0e7691ed425f
def get_recipe_by_yummly_id(self): <NEW_LINE> <INDENT> yummly_id = self.yummly_id <NEW_LINE> params = {'_app_id': YUMMLY_APP_ID, '_app_key': YUMMLY_APP_KEY } <NEW_LINE> recipe_response = requests.get( ("http://api.yummly.com/v1/api/recipe/%s" % yummly_id), params=params).json() <NEW_LINE> self.name = recipe_response.ge...
Uses yummly_id returned from Search to query Yummly API. Converts and stores time, as well as servings, ingredients, attributes, images, and attribution.
625941d19f2886367277aa21
def _setup_data_interpolator(self) -> None: <NEW_LINE> <INDENT> relative_path = os.path.join("src", "simulated_data", "simulated_twitch.csv") <NEW_LINE> absolute_path = os.path.normcase(os.path.join(get_current_file_abs_directory(), os.pardir, os.pardir)) <NEW_LINE> file_path = resource_path(relative_path, base_path=ab...
Set up the function to interpolate data. This function is necessary to handle different sampling periods. This function should only be called once.
625941d11f5feb6acb0c4ce4
def delete_component(self): <NEW_LINE> <INDENT> if not self.container_compo: <NEW_LINE> <INDENT> raise ValueError("Only dynamically created components can be deleted") <NEW_LINE> <DEDENT> if self.name: <NEW_LINE> <INDENT> self.unregister_field(self) <NEW_LINE> <DEDENT> for compo in list(getattr(self, 'components', []))...
Deletes itself. You can call this method on dynamically created components. After it's deletion you can not use this component any longer in the layout.
625941d1d268445f265b5002
def __call__(self): <NEW_LINE> <INDENT> while len(self._guesses) < MAX_GUESSES: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> guess = self.guess() <NEW_LINE> <DEDENT> except ValueError as ve: <NEW_LINE> <INDENT> print(ve) <NEW_LINE> continue <NEW_LINE> <DEDENT> win = self._validate_guess(guess) <NEW_LINE> if win: <NEW_L...
Entry point / game loop, use a loop break/continue, see the tests for the exact win/lose messaging
625941d129b78933be1e583f
def run(self, tweet_count=10000, sleep_between_tweets=15): <NEW_LINE> <INDENT> while(True): <NEW_LINE> <INDENT> self.run_once(tweet_count) <NEW_LINE> time.sleep(sleep_between_tweets*60)
Run indefinitely, sleeping between each tweet.
625941d197e22403b379d12e
def _handle_load_data_infile(self, filename): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> fp = open(filename, 'rb') <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._socket.send(b'') <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise errors.OperationalError( "MySQ...
Handle a LOAD DATA INFILE LOCAL request
625941d16fece00bbac2d8d3
def itkConnectedComponentImageFilterIUL3IUL3_cast(*args): <NEW_LINE> <INDENT> return _itkConnectedComponentImageFilterPython.itkConnectedComponentImageFilterIUL3IUL3_cast(*args)
itkConnectedComponentImageFilterIUL3IUL3_cast(itkLightObject obj) -> itkConnectedComponentImageFilterIUL3IUL3
625941d12eb69b55b151ca44
def _dodots(self, token='', value=None, parts=None, context={}): <NEW_LINE> <INDENT> as_string = token.startswith('{{') <NEW_LINE> if parts[0] not in context and parts[0] not in self._targets: <NEW_LINE> <INDENT> if self._errors: <NEW_LINE> <INDENT> six.raise_from(UnknownContextValue('Unknown context variable \'{}\''.f...
Process a expression - i.e. access to a data item within the context A wrapper around self._resolvedots so that errors are dealt with as requested by the caller Executed at run time only :param token: The full token for error reporting only - remove ?? :param value: The actual value of the first/only part of the nam...
625941d1e64d504609d749d4
def set_default_executor(self, executor): <NEW_LINE> <INDENT> self._executor = executor
Sets the default executor to use with :meth:`run_in_executor`.
625941d156ac1b37e6264362
def test_render_float(self): <NEW_LINE> <INDENT> renderer = XMLRenderer() <NEW_LINE> content = renderer.render({'field': 123.4}, 'application/xml') <NEW_LINE> self.assertXMLContains(content, '<field>123.4</field>')
Test XML rendering.
625941d163f4b57ef00012ab
def divide(self, layout, width, height, dpi_x, dpi_y): <NEW_LINE> <INDENT> raise NotImplementedError
Divide the element into two depending on available space. @param layout: pango layout to write on @param type: Pango.Layout @param width: width of available space for this element @param type: device points @param height: height of available space for this element @param type: device points @param dpi_x: the horizonta...
625941d163f4b57ef00012ac
def deleteMaxHeap(array): <NEW_LINE> <INDENT> heap_end_border = len(array) - 1 <NEW_LINE> while heap_end_border > 0: <NEW_LINE> <INDENT> val = deleteFromMaxHeap(array, heap_end_border) <NEW_LINE> print(f'Deleted Item {val}') <NEW_LINE> heap_end_border -= 1
@Time-Complexity O(n log(n))
625941d15fc7496912cc3b12
def __init__(self, **desc): <NEW_LINE> <INDENT> cls = self.__class__ <NEW_LINE> attrs = self.__class__.attributes() <NEW_LINE> str_attrs = [attr for attr in attrs if isinstance(attr, str)] + [attr[0] for attr in attrs if isinstance(attr, tuple)] <NEW_LINE> for attr in attrs: <NEW_LINE> <INDENT> if isinstance(attr, tupl...
Subclasses should not need to override __init__. Add attributes to __attributes__ instead.
625941d16fb2d068a760f233
def regular_LDPC_code_contructor(self,n_p_q): <NEW_LINE> <INDENT> n = n_p_q[0] <NEW_LINE> p = n_p_q[1] <NEW_LINE> q = n_p_q[2] <NEW_LINE> ratioTest = (n*1.0) / q <NEW_LINE> if ratioTest%1 != 0: <NEW_LINE> <INDENT> print('\nError in regular_LDPC_code_contructor: The ', end='') <NEW_LINE> print('ratio of inputs n/q must ...
This function constructs a LDPC parity check matrix H. The algorithm follows Gallager's approach where we create p submatrices and stack them together. Reference: Turbo Coding for Satellite and Wireless Communications, section 9,3. Note: the matrices computed from this algorithm will never have full rank. (Reference G...
625941d166673b3332b92226
def do(self): <NEW_LINE> <INDENT> if self.count == 0: return False <NEW_LINE> exploit, data, batch = self.requests.popleft() <NEW_LINE> assert callable(exploit), 'Invalid exploit call %s' % exploit <NEW_LINE> if batch is None: self.count -= 1 <NEW_LINE> else: <NEW_LINE> <INDENT> try: nextData = next(batch) <NEW_LINE> e...
@see: IResolve.do
625941d115fb5d323cde0ca5
def multiply_adjacency_matrices(vertices, A, B): <NEW_LINE> <INDENT> result = dict() <NEW_LINE> for u in vertices: <NEW_LINE> <INDENT> for v in vertices: <NEW_LINE> <INDENT> result[(u, v)] = min([ A[(u, x)] + B[(x, v)] for x in vertices ]) <NEW_LINE> <DEDENT> <DEDENT> return result
'Multiply' two adjacency matrices where multiplication and addition are defined as: multiply: add values together add: take the minimum value Since normal multiplication for n x n matrices looks like: C[(i, j]] = sum([ A[(i, k)] * B[(k, j)] for k in range(n) ]) With our new definition of addition and multiplica...
625941d1656771135c3eba04
def get_stat_xplore_measure_data(table_headers, schema_headers, measure_id, field_ids = None, fields_include_total = None, df_schema = None, geog_folder_label = 'Geography (residence-based)', geog_field_label= 'National - Regional - LA - OAs', geog_level_label = 'Local Authority'): <NEW_LINE> <INDENT> body = build_requ...
For an input measure ID and field IDs as well as the labels for the geography folder, field and level to get data for build that dictionary of data to send to the Stat-Xplore table end point to request data. Args: table_headers (dict): The headers to uses for the request to the table endpoint of the Stat-Xplore A...
625941d1596a897236089c54
def propage_hooks_changes(self): <NEW_LINE> <INDENT> pass
Propage a change in the hooks pool
625941d10383005118ecf777
def callfuncstatus(self, sFunc, *args, **kargs): <NEW_LINE> <INDENT> func = getattr(self.VxDLL, sFunc) <NEW_LINE> func.restype = LVSTATUS <NEW_LINE> status = func(*args) <NEW_LINE> if 'bIgnoreError' in kargs: <NEW_LINE> <INDENT> bIgnoreError = kargs['bIgnoreError'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> bIgnoreE...
General function caller which checks for errors in DLL return value
625941d132920d7e50b28365
def orbitals_coul_filename(postfix): <NEW_LINE> <INDENT> return _orbitals_coul_filename_template.format("")
Construct filename for Coulomb tbme basis orbitals. Arguments: postfix (str): ignored Returns: (str) filename
625941d1ab23a570cc250317
def test_endpoint_setter_mixed2(self): <NEW_LINE> <INDENT> assert self.query.endpoint == 'nodes' <NEW_LINE> self.query.endpoint = 'nodes' <NEW_LINE> assert self.query.endpoint == 'nodes' <NEW_LINE> with pytest.raises(InvalidQueryError, match='Mixed endpoints are not supported'): <NEW_LINE> <INDENT> self.query.endpoint ...
Setting the endpoint property twice to different values should raise InvalidQueryError (combination 2).
625941d15f7d997b87174c2d
def _expand(self, current_dir: str, mapping: Dict[str, str]) -> Dict[str, str]: <NEW_LINE> <INDENT> def final_src(src): <NEW_LINE> <INDENT> return os.path.abspath(os.path.expanduser(src)) <NEW_LINE> <DEDENT> def final_dst(dst): <NEW_LINE> <INDENT> return os.path.join(current_dir, dst) <NEW_LINE> <DEDENT> return {final_...
Expands the mapping that the user sees out into a mapping from absolute source to absolute destination.
625941d1bde94217f3682f85
def show_logo(self): <NEW_LINE> <INDENT> pprops = api.portal.get_tool('portal_properties') <NEW_LINE> sprops = pprops.site_properties <NEW_LINE> return getattr(sprops, 'show_header_logo', True)
Return the value of the 'show_header_logo' site property.
625941d1e8904600ed9f20c2
def test_remove_file_no_parser(self): <NEW_LINE> <INDENT> ui = mock_ui() <NEW_LINE> hgcommands.init(ui, self.repo) <NEW_LINE> hgrepo = repository(ui, self.repo) <NEW_LINE> (open(hgrepo.pathto('file.txt'), 'w') .write('line 1\nline 2\n')) <NEW_LINE> hgcommands.addremove(ui, hgrepo) <NEW_LINE> hgcommands.commit(ui, hgrep...
Change by removing a file, without parser
625941d155399d3f0558884a
def keyword_parse(self, mnem, desc): <NEW_LINE> <INDENT> Tree = make_tree() <NEW_LINE> new_desc = [v for i, v in enumerate(desc) if i not in self.duplicate] <NEW_LINE> new_mnem = [v for i, v in enumerate(mnem) if i not in self.duplicate] <NEW_LINE> aliased = 0 <NEW_LINE> print("Alasing with keyword extractor...") <NEW_...
:param mnem: list of mnemonics :param desc: list of descriptions :return: None Find exact labels of mnemonics with descriptions that can be filtered through keyword extractor tree
625941d1e8904600ed9f20c3
def __pos__(self): <NEW_LINE> <INDENT> child = self.__class__() <NEW_LINE> for prop in self.evolvables: <NEW_LINE> <INDENT> setattr(child, prop, getattr(self, prop)) <NEW_LINE> <DEDENT> if len(self.evolvables.keys()) > 0: <NEW_LINE> <INDENT> prop = random.choice(self.evolvables.keys()) <NEW_LINE> a = self.evolvables[pr...
Mutation operator for a single trait. The default behavior is to randomly pick an evolvable, and recalculate it on the specified ranges. Subclasses should override this method to implement more directed mutation behaviour.
625941d107d97122c4178a22
def is_visible(node, displayLayer=True, intermediateObject=True, parentHidden=True, visibility=True): <NEW_LINE> <INDENT> if not cmds.objExists(node): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not cmds.objectType(node, isAType='dagNode'): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if visibility:...
Is `node` visible? Returns whether a node is hidden by one of the following methods: - The node exists (always checked) - The node must be a dagNode (always checked) - The node's visibility is off. - The node is set as intermediate Object. - The node is in a disabled displayLayer. - Whether any of its parent nodes is ...
625941d1f7d966606f6aa19a
def write(memory_location): <NEW_LINE> <INDENT> print( f"Contents of memory location {memory_location} is {memory[memory_location]}." ) <NEW_LINE> return
Prints the contents of the given memory location to the screen
625941d1bd1bec0571d907c4
def show_policy(self, ax, policy=None): <NEW_LINE> <INDENT> if policy is not None: <NEW_LINE> <INDENT> assert len(policy) == len(self.states), 'Policy not compatible with state space dimensions' <NEW_LINE> for s in range(policy.shape[0]): <NEW_LINE> <INDENT> a = policy[s] <NEW_LINE> if self.actions[a].di...
Show a policy on the gridworld interface
625941d116aa5153ce36260d
def test_config_load(self): <NEW_LINE> <INDENT> confdata = prokka_script.load_bulk_prokka_config(CONFIG_FNAME, NULL_LOGGER) <NEW_LINE> self.assertEqual(confdata, CONFDATA)
Loads and parses bulk_prokka config file
625941d1283ffb24f3c55a95
def get_endpoint(region): <NEW_LINE> <INDENT> if not Regions.is_valid_region(region): <NEW_LINE> <INDENT> raise InvalidRegionException(region) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return _urls[region] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise NoEndpointForRegionException(region)
Return the endpoint for a given region identifier. :param region: :raises: NoEndpointForRegionException
625941d18c3a873295158550
def _job_id(resource_uuid: str) -> str: <NEW_LINE> <INDENT> return resource_uuid if "." in resource_uuid else f"{resource_uuid}.0"
Normalize single "ClusterID" and bulk "ClusterID.ProcID" UUIDs to job IDs
625941d132920d7e50b28366
def front_right_cliff_sensor(dc, darkness_entry): <NEW_LINE> <INDENT> front_right_cliff_sensor = new_create.Sensors.cliff_front_right_signal <NEW_LINE> darkness = darkness_entry.get() <NEW_LINE> if front_right_cliff_sensor >= darkness: <NEW_LINE> <INDENT> dc.robot.stop()
Activates the front right cliff sensor, and detects the darkness set by the user
625941d1b57a9660fec33a1a
def unfollow_group(context: Context, data_dict: DataDict) -> None: <NEW_LINE> <INDENT> schema = context.get('schema', ckan.logic.schema.default_follow_group_schema()) <NEW_LINE> _unfollow(context, data_dict, schema, context['model'].UserFollowingGroup)
Stop following a group. :param id: the id or name of the group to stop following :type id: string
625941d13346ee7daa2b2f01
def doublyContractedProduct(self): <NEW_LINE> <INDENT> return _MEDCouplingCorba.MEDCouplingFieldDouble_doublyContractedProduct(self)
doublyContractedProduct(self) -> MEDCouplingFieldDouble 1
625941d1b5575c28eb68e195
def factorize_binary_categories(df): <NEW_LINE> <INDENT> cols =[] <NEW_LINE> for col in df.columns: <NEW_LINE> <INDENT> data_type = df[col].dtype <NEW_LINE> col_unique_len = len(df[col].value_counts()) <NEW_LINE> if col_unique_len <3: <NEW_LINE> <INDENT> if (data_type == 'object'): <NEW_LINE> <INDENT> cols.append(col) ...
This function will factorize every binary "object" within a dataframe. (Null values will be returned as -1)
625941d1f548e778e58cd713
def finishURL(): <NEW_LINE> <INDENT> pass
Finish url
625941d12ae34c7f2600d2c6
def test_cpu_affinity(): <NEW_LINE> <INDENT> def mock_cpu_affinity_handler(self, *args, **kwargs): <NEW_LINE> <INDENT> return [0, 1] <NEW_LINE> <DEDENT> if is_ci_env() or sys.platform.startswith('darwin'): <NEW_LINE> <INDENT> with mock.patch.object(psutil.Process, 'cpu_affinity', create=True, new=mock_cpu_affinity_hand...
Test CPU affinity setting
625941d124f1403a92600cfa
def get_number_of_terms(self): <NEW_LINE> <INDENT> raise NotImplementedError
Returns the number of terms in this ontology.
625941d1377c676e9127233e
def test_is_near_now(): <NEW_LINE> <INDENT> now = datetime.datetime.now(tz=pytz.UTC) <NEW_LINE> assert is_near_now(now) is True <NEW_LINE> later = now + datetime.timedelta(0, 6) <NEW_LINE> assert is_near_now(later) is False <NEW_LINE> earlier = now - datetime.timedelta(0, 6) <NEW_LINE> assert is_near_now(earlier) is Fa...
Test is_near_now for now
625941d1b5575c28eb68e196
def notify_update(self, update): <NEW_LINE> <INDENT> if not isinstance(update, list): <NEW_LINE> <INDENT> update = [update] <NEW_LINE> <DEDENT> self.queue.extend(update) <NEW_LINE> module_groups = self.i3status_thread.config['.module_groups'] <NEW_LINE> groups_to_update = set() <NEW_LINE> for item in update: <NEW_LINE>...
Name or list of names of modules that have updated.
625941d17047854f462a159e
def makeNgsCovMat( nxSubaps, subapDiam, pupilMask, r0, sep, wvl=500e-9, L0=None, l0=None, map_size=501): <NEW_LINE> <INDENT> t = time.time() <NEW_LINE> sep = numpy.array(sep) <NEW_LINE> max_sep = (1+2*nxSubaps)*subapDiam + max(abs(sep)) <NEW_LINE> print("map_size: {}".format(map_size)) <NEW_LINE> print("max_sep: {}".fo...
Calculates the theoretical covariance matrix of SH WFSs through atmospheric turbulence with a given separation Parameters: nxSubaps (int): Number of x sub-apertures in WFS subapDiam (float): Size of each sub-aperture in metres pupilMask (ndarray): Array of 1 and 0 specifying pupil function r0 (float): ...
625941d145492302aab5e459
def iterable_middleware(app): <NEW_LINE> <INDENT> def inner(environ, start_response): <NEW_LINE> <INDENT> rv = app(environ, start_response) <NEW_LINE> class Iterable(object): <NEW_LINE> <INDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(rv) <NEW_LINE> <DEDENT> if hasattr(rv, 'close'): <NEW_LINE> <INDENT> def ...
Guarantee that the app returns an iterable
625941d107f4c71912b11618
def secure_form_remote_tag(**args): <NEW_LINE> <INDENT> id = authentication_token() <NEW_LINE> form_html = form_remote_tag(**args) <NEW_LINE> return '%s\n%s' % (form_html, content_tag('div', hidden_field(token_key, id), style='display: none;'))
Create a form tag (like webhelpers.rails.prototype.form_remote_tag) including a hidden authentication token field.
625941d18e71fb1e9831d93e
def get_metadata(tree): <NEW_LINE> <INDENT> metadata = [] <NEW_LINE> fl_tables = tree.xpath( '//html:table[contains(@class, "field-list")]', namespaces=NS) <NEW_LINE> if len(fl_tables) == 0: <NEW_LINE> <INDENT> return metadata <NEW_LINE> <DEDENT> fl_el = fl_tables[0] <NEW_LINE> for f_el in fl_el.xpath( '//html:tr[conta...
Extracts test case metadata from given html tree.
625941d17d43ff24873a2e36
def saveImage(self, user_id): <NEW_LINE> <INDENT> positions, heights, widths = self.getCompressedSkyline() <NEW_LINE> path = str(Path(__file__).parent) + "/userData/" <NEW_LINE> Path(path + user_id).mkdir(parents=True, exist_ok=True) <NEW_LINE> if len(positions) == 0: <NEW_LINE> <INDENT> plt.bar([0], [0], width=1, alig...
Generates a skyline image and saves it inside ./userData/'user_id'
625941d1167d2b6e31218d2b
def rank(self): <NEW_LINE> <INDENT> return self.__submodule.rank()
Return the rank of this homology group. EXAMPLES:: sage: from sage_modabvar import J0 sage: d = J0(43).homology().decomposition(2) sage: [H.rank() for H in d] [2, 4]
625941d13617ad0b5ed6808d
def try_remove(List, item, is_copy=True): <NEW_LINE> <INDENT> if is_copy: <NEW_LINE> <INDENT> List = deepcopy(List) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> List.remove(item) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return List
Try to remove an item from the List. If failed, return the original List.
625941d15e10d32532c5f0bc
def predict(self, X): <NEW_LINE> <INDENT> return [self._predict(x) for x in X]
:param X: :return: 分类器的分数
625941d1ec188e330fd5a933
def saveWav(path, data, sr): <NEW_LINE> <INDENT> wavfile.write(path, int(sr), data)
Save data to wave file. Parameters ---------- path: str Path to save data: array_like Float wave data For mono data, shape = (nSample,) For multi channel data, shape = (nSample, nChannel) sr: int Sample rate of wave data
625941d1a219f33f34628afe
def createRenderNode(sceneNode): <NEW_LINE> <INDENT> renderNode = sceneNode.RenderNodeClass(sceneNode) <NEW_LINE> updateChildren(renderNode) <NEW_LINE> return renderNode
:type sceneNode: Node :rtype: mcedit2.rendering.rendergraph.RenderNode
625941d1925a0f43d254a00d
def test_extreme_contrast() -> None: <NEW_LINE> <INDENT> original = create_image(6, 1) <NEW_LINE> set_color(original, 0, 0, create_color(0, 0, 0)) <NEW_LINE> set_color(original, 1, 0, create_color(0, 128, 128)) <NEW_LINE> set_color(original, 2, 0, create_color(127, 127, 127)) <NEW_LINE> set_color(original, 3, 0, cr...
Function Name: Test Extreme Contrast Author: Mohamed Kaddour 101140829 tests the the extreme_contrast functions using two sample images >>>test_extreme_contrast() Checking pixel @(0, 0) PASSED ------ Checking pixel @(1, 0) PASSED ------
625941d121bff66bcd684ae7
def acc(val, mag): <NEW_LINE> <INDENT> if val == 0: <NEW_LINE> <INDENT> return mag <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (val / abs(val)) * (0 - mag)
Function to make the force vector. relWindVec is the direction the apparent wind comes *from*. We want to compute the accleration vector in the direction the wind blows to.
625941d1236d856c2ad44971
def update_deadline(self, request, *args, **kwargs): <NEW_LINE> <INDENT> issue_id = self.kwargs.get('issue_id', None) <NEW_LINE> issue = get_object_or_404(Issue, id=issue_id) <NEW_LINE> serializer = IssueDeadlineSerializer(data=self.request.data) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> serializer.updat...
updates an issue's deadline
625941d1293b9510aa2c342b
def train(self, input_fn, steps, monitors=None): <NEW_LINE> <INDENT> return self._train_model(input_fn=input_fn, steps=steps, monitors=monitors)
Trains a model given input builder function. Args: input_fn: Input builder function, returns tuple of dicts or dict and Tensor. steps: number of steps to train model for. monitors: List of `BaseMonitor` subclass instances. Used for callbacks inside the training loop. Returns: Returns s...
625941d13346ee7daa2b2f02
def is_max(self): <NEW_LINE> <INDENT> return self._type == self._max_type
(bool) Returns True iff this tile is a maximum tile.
625941d15f7d997b87174c2e
def test_handle_poison_no_route_unpoison(self): <NEW_LINE> <INDENT> self.setUp() <NEW_LINE> self.test_handle_poison_no_route() <NEW_LINE> h1, h2 = self.h1, self.h2 <NEW_LINE> self.router.handle_route_advertisement( route_dst=h1, port=1, route_latency=1) <NEW_LINE> packet = Packet(dst=h1, src=h2) <NEW_LINE> with self._p...
An "unpoisoned" route should be used again.
625941d12c8b7c6e89b35956
def _registerObjectTypes(self): <NEW_LINE> <INDENT> self._object_factory.register(model.hosts.Host) <NEW_LINE> self._object_factory.register(model.hosts.Interface) <NEW_LINE> self._object_factory.register(model.hosts.Service) <NEW_LINE> self._object_factory.register(model.hosts.HostApplication) <NEW_LINE> self._object_...
Registers in the factory all object types that can be created
625941d163d6d428bbe44685
def load_file(fname, **kwargs): <NEW_LINE> <INDENT> raw_data = np.loadtxt(fname, **kwargs) <NEW_LINE> return datastats.DataStats(raw_data=raw_data)
Create DataStats object from sample data in file. :param fname: file name :param kwargs: pass through kwargs to numpy.loadtext :return: DataStats object
625941d1e76e3b2f99f3a99f
def ringprocesser(new_ring, molecule): <NEW_LINE> <INDENT> for ring in new_ring: <NEW_LINE> <INDENT> size = len(ring) <NEW_LINE> if size > 0: <NEW_LINE> <INDENT> q_position = [0,0,0] <NEW_LINE> if size < 3 or size == 8: <NEW_LINE> <INDENT> molecule.ring_errors.append(ring) <NEW_LINE> <DEDENT> elif size == 3: <NEW_LINE>...
process the a ring that as been identitifyied and defines a q atom with approperate valence and position in space then add them to the ring and atom list
625941d1fff4ab517eb2f5d2
def get_W_shape(self): <NEW_LINE> <INDENT> num_input_channels = self.input_shape[-1] <NEW_LINE> return self.filter_size + (num_input_channels, self.num_filters)
Get the shape of the weight matrix `W`. Returns ------- tuple of int The shape of the weight matrix.
625941d123e79379d52ee6f9
def setCheckOnMap( self, pixmap ): <NEW_LINE> <INDENT> self._checkOnMap = QtGui.QPixmap(pixmap)
Sets the pixmap to be used when rendering a check state in the on state. :param pixmap | <QtGui.QPixmap> || <str> || None
625941d17c178a314d6ef5f6
def magma_free_eval(code, strip=True, columns=0): <NEW_LINE> <INDENT> from six.moves.urllib.parse import urlencode <NEW_LINE> from six.moves import http_client as httplib <NEW_LINE> from xml.dom.minidom import parseString <NEW_LINE> server = "magma.maths.usyd.edu.au" <NEW_LINE> processPath = "/xml/calculator.xml" <NEW_...
Use the free online MAGMA calculator to evaluate the given input code and return the answer as a string. LIMITATIONS: The code must evaluate in at most 20 seconds and there is a limitation on the amount of RAM. EXAMPLES:: sage: magma_free("Factorization(9290348092384)") # optional - internet [ <2, 5>, <2903...
625941d1d99f1b3c44c67723
def get(self, request): <NEW_LINE> <INDENT> resource_urls = [reverse('another-example', kwargs={'num': num}, request=request) for num in range(3)] <NEW_LINE> return {"Some other resources": resource_urls}
Handle GET requests, returning a list of URLs pointing to 3 other views.
625941d1d7e4931a7ee9e0b4
def connect(self): <NEW_LINE> <INDENT> if self.dbh == None: <NEW_LINE> <INDENT> self.dbh = MySQLdb.connect(host=self.db_host, user=self.db_user, passwd=self.db_pass, db=self.db_name, charset='utf8', use_unicode=1)
Connect to the database
625941d1462c4b4f79d1d866
def VQC(weights, x, wires, n_layers=1, types = 1): <NEW_LINE> <INDENT> data_size = len(x) <NEW_LINE> n_wires = len(wires) <NEW_LINE> weights_each_layer = (n_wires*(n_wires+3) - 2*data_size) <NEW_LINE> n_weights_needed = weights_each_layer * n_layers <NEW_LINE> if len(x) > n_wires: <NEW_LINE> <INDENT> raise ValueError(...
Circuits ID = 5, 6 in arXiv:1905.10876 paper :param weights: trainable weights of shape 2*n_layers*n_wires :param 1d x: input, len(x) is <= len(wires) :param wires: list of wires on which the feature map acts :param n_layers: number of repetitions of the first layer
625941d129b78933be1e5840
def loss_function(self, build_network_result, labels): <NEW_LINE> <INDENT> raise NotImplementedError('Must be implemented in derived classes')
Returns the op to measure the loss of the model.
625941d176e4537e8c351809
def insertBlockRules(self): <NEW_LINE> <INDENT> if not self.createBlockRules: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> logging.info("Preparing to create block rules into Rucio...") <NEW_LINE> unsubBlocks = self.getUnsubscribedBlocks.execute() <NEW_LINE> for item in unsubBlocks: <NEW_LINE> <INDENT> if not self.ruc...
Creates a simple replication rule for every single block that is under production in a given site/RSE. Also persist the rule ID in the database.
625941d126238365f5f0f005
def __init__(self, data): <NEW_LINE> <INDENT> self.ca_system_id = None <NEW_LINE> self.ca_pid = None <NEW_LINE> super(ConditionalAccessDescriptor, self).__init__(data)
Constructor Creates the descriptor from the given data by calling ConditionalAccessDescriptor.parse().
625941d1d6c5a102081441e1
def main(dbtype, ldr, custom=None): <NEW_LINE> <INDENT> logger.warning('Starting DB Load Tests') <NEW_LINE> load_duration = [] <NEW_LINE> delete_duration = [] <NEW_LINE> if dbtype == 'mongo': <NEW_LINE> <INDENT> logger.warning('Loading Mongo') <NEW_LINE> logger.info('loading: %s:%d (%d)', ldr.host, ldr.port, ldr.concur...
Main program
625941d14e4d5625662d456c
def get_probability_predictions_of_tf_dataset(self, test_dataset, meta_file_name=None): <NEW_LINE> <INDENT> sess = tf.Session() <NEW_LINE> test_dataset = test_dataset.batch(100) <NEW_LINE> test_iterator = test_dataset.make_initializable_iterator() <NEW_LINE> next_test_batch = test_iterator.get_next() <NEW_LINE> sess.ru...
:param test_dataset: :return:
625941d17c178a314d6ef5f7
def update_address_group(self, group_name, data): <NEW_LINE> <INDENT> api_url = self.urlbase + "api/v2/cmdb/firewall/addrgrp/" + group_name <NEW_LINE> if not self.does_exist(api_url): <NEW_LINE> <INDENT> logging.error('Requested address group "{group_name}" does not exist in Firewall config.'.format( group_name=group_n...
Update address group with provided data :param group_name: Address group being updated :param data: JSON Data with which to upate the address group :return: HTTP Status Code
625941d176d4e153a657ecc7
def test_invalid_email_format(self): <NEW_LINE> <INDENT> response = self.client.post( '/api/v1/hostel/register', data=json.dumps(invalid_email_format), content_type='application/json', headers=self.get_registrar_token()) <NEW_LINE> result = json.loads(response.data.decode()) <NEW_LINE> self.assertEqual(result['message'...
An admin cannot add a student with the wrong email format..
625941d1d53ae8145f87a405
def DP(self, dungeon: List[List[int]]) -> int: <NEW_LINE> <INDENT> def get_min(curr_cell, next_row, next_col): <NEW_LINE> <INDENT> if next_row >= R or next_col >= C: <NEW_LINE> <INDENT> return float('inf') <NEW_LINE> <DEDENT> next_cell = dp[next_row][next_col] <NEW_LINE> return max(1, next_cell - curr_cell) <NEW_LINE> ...
:type dungeon: List[List[int]] :rtype: int
625941d124f1403a92600cfb
def __init__(self, filename_arg): <NEW_LINE> <INDENT> self.filename = filename_arg <NEW_LINE> self.data = importdata(self.filename + '.csv') <NEW_LINE> self.peaks = None <NEW_LINE> self.mean_hr_bpm = None <NEW_LINE> self.voltage_extreme = None <NEW_LINE> self.time_duration = None <NEW_LINE> self.num_beats = None <NEW_L...
this is the initial function :param filename_arg: input the filename for the test_data
625941d1099cdd3c635f0df1
def testHarmonicOscillator(self): <NEW_LINE> <INDENT> dt = 12.34 * np.pi / hp['omega'] <NEW_LINE> num_steps = 3 <NEW_LINE> qs = np.linspace(-95., 95., 31) <NEW_LINE> wf_qs = np.linspace(-93., 93., 29) <NEW_LINE> wfn = 3 <NEW_LINE> herms = np.polynomial.hermite.hermval(np.sqrt(hp['mass'] * hp['omega'] / HBAR) * wf_qs, n...
Check the harmonic oscillator survival amplitude.
625941d14f88993c3716c1fc
def lower_bounds(self, *args): <NEW_LINE> <INDENT> def sa(a, b = self._cplex.variables.get_num() - 1): <NEW_LINE> <INDENT> return list(zip(*CPX_PROC.boundsa_lower(self._env._e, self._cplex._lp, a, b))) <NEW_LINE> <DEDENT> return apply_freeform_two_args("solution.sensitivity.lower_bounds", sa, self._cplex.variables.get_...
Returns the sensitivity of a set of lower bounds. Can be called by four forms. >>> import cplex >>> c = cplex.Cplex() >>> out = c.set_results_stream(None) >>> out = c.set_log_stream(None) >>> c.read("example.mps") >>> c.solve() >>> c.solution.sensitivity.lower_bounds(1) (-1e+20, 17.5) >>> c.solution.sensitivity.lower...
625941d107d97122c4178a23
def get(self, request, format=None): <NEW_LINE> <INDENT> an_apiview = [ 'Uses HTTP methods as function (get, post, put, patch, delete)', 'It is similar to a traditional Django View', 'Gives you the most control over your logic', 'Is mapped manually to URLS', ] <NEW_LINE> return Response({'message': 'Hello!', 'an_apivie...
Returns a list of APIView features.
625941d130bbd722463cbf5c
def __init__(self, num_classes=1, num_filters=32, drop = 0.5, pretrained=False): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.pool = nn.MaxPool2d(2, 2) <NEW_LINE> self.drop = nn.Dropout(drop) <NEW_LINE> self.encoder = models.vgg11(pretrained=pretrained).features <NEW_LINE> self.relu = self.encoder[1] <NEW_LIN...
Easy setup for using pretrained VGG11 features in the encoder part of the network. Uses transposed conv in decoder part.
625941d16e29344779a627a7
def compile_subroutine_body(self, was_constructor, was_method): <NEW_LINE> <INDENT> self.tkx.advance() <NEW_LINE> while self.tkx.get_next_token() == 'var': <NEW_LINE> <INDENT> self.compile_var_dec() <NEW_LINE> <DEDENT> self.vm_writer.write_function(self.subroutine_name, self.subroutine_table.var_count(LOCAL)) <NEW_LINE...
subroutine body Inside declaration
625941d107f4c71912b11619
def present( self, qt_notification: "QWebEngineNotification", *, replaces_id: Optional[int], ) -> int: <NEW_LINE> <INDENT> if replaces_id is None: <NEW_LINE> <INDENT> replaces_id = 0 <NEW_LINE> <DEDENT> actions = [] <NEW_LINE> if self._capabilities.actions: <NEW_LINE> <INDENT> actions = ['default', 'Activate'] <NEW_LIN...
Shows a notification over DBus.
625941d14f88993c3716c1fd
def __str__(self): <NEW_LINE> <INDENT> cols = [ list(map(format_number, col)) for col in self.columns() ] <NEW_LINE> def decimal_pos(n): <NEW_LINE> <INDENT> if '.' in n: <NEW_LINE> <INDENT> return n.index('.') <NEW_LINE> <DEDENT> return len(n) <NEW_LINE> <DEDENT> for col_no, col in enumerate(cols[:]): <NEW_LINE> <INDEN...
'Pretty' formatting of the Matrix44.
625941d199cbb53fe6792d7c
def oracle_invert(self, qi, qo): <NEW_LINE> <INDENT> self.cnot_gate(qi, qo) <NEW_LINE> self.x_gate(qo)
x -> !x oracle function.
625941d1566aa707497f46fd
def avg_data_reader(cross_dict, dcat, dpoa, fname='data/ChodroffGoldenWilson2019_vot_avg.csv'): <NEW_LINE> <INDENT> full = pd.read_csv('data/ChodroffGoldenWilson2019_vot_avg.csv', delimiter = ',', na_filter=False) <NEW_LINE> full['lang'] = full[['family', 'language', 'dialect']].apply(lambda x: '_'.join(x), axis=1) <NE...
reads in data from ChodroffGoldenWilson2019_vot_avg.csv, expected format: family,language,dialect,vot.category,poa2,vot.mu discards languages without all 3 poa per vot.category
625941d1796e427e537b075d
def http_capture_filter(app, callback=lambda request, response: True): <NEW_LINE> <INDENT> def m(environ, start_response): <NEW_LINE> <INDENT> request = Request(environ) <NEW_LINE> response = request.get_response(app) <NEW_LINE> callback(request.copy(), response.copy()) <NEW_LINE> return response(environ, start_respons...
captures request and response and passes off to a callback :rtype: :ref:`wsgi_application` :param app: inner :ref:`wsgi_application` :param callback: function to call
625941d131939e2706e4cfff
def __init__(self, cache=None, collection=None, columns=0, column=0, parameters=None, timeout=None): <NEW_LINE> <INDENT> super(Updater, self).__init__() <NEW_LINE> self.cache = cache <NEW_LINE> self.collection = collection <NEW_LINE> self.columns = columns <NEW_LINE> self.column = column <NEW_LINE> self.parameters = pa...
Updater constructor. Args: cache: The persistent cache object. collection: The resource collection name that (1) uniquely names the table(s) for the parsed resource parameters (2) is the lookup name of the resource URI parser. Resource collection names are unique by definition. Non-resource collection ...
625941d11f5feb6acb0c4ce6
def check_keyup_events(event, ship): <NEW_LINE> <INDENT> if event.key == pygame.K_RIGHT: <NEW_LINE> <INDENT> ship.moving_right = False
Respond to key release
625941d1d8ef3951e32436d4
def inflate(self, radius): <NEW_LINE> <INDENT> r = round(radius / self._cellsize) <NEW_LINE> Y, X = np.meshgrid(np.arange(-r, r+1), np.arange(-r, r+1)) <NEW_LINE> SE = X**2 + Y**2 <= r**2 <NEW_LINE> SE = SE.astype(int) <NEW_LINE> self._grid = sp.binary_dilation(self._grid, SE)
Inflate obstales :param radius: radius of circular structuring element in world units :type radius: float A circular structuring element is created and used to dilate the stored occupancy grid. Successive calls to ``inflate`` will compound the inflation. :seealso: :func:`scipy.ndimage.binary_dilation`
625941d1d10714528d5ffe7b
def delete_network(context, id): <NEW_LINE> <INDENT> LOG.info("delete_network %s for tenant %s" % (id, context.tenant_id)) <NEW_LINE> with context.session.begin(): <NEW_LINE> <INDENT> net = db_api.network_find(context, None, None, None, False, id=id, scope=db_api.ONE) <NEW_LINE> if not net: <NEW_LINE> <INDENT> raise n_...
Delete a network. : param context: neutron api request context : param id: UUID representing the network to delete.
625941d16e29344779a627a8
@task <NEW_LINE> def make_venv(): <NEW_LINE> <INDENT> bootstrap_venv(__here__ / path('env'), 'sideboard') <NEW_LINE> develop_sideboard()
make a virtualenv for the sideboard project
625941d1046cf37aa974cedd
def found_at(self): <NEW_LINE> <INDENT> res = '"' + self.get_uri() + '", using HTTP method ' <NEW_LINE> res += self.get_method() + '. The sent post-data was: "' <NEW_LINE> dc_length = len(str(self.get_dc())) <NEW_LINE> if dc_length > 65: <NEW_LINE> <INDENT> res += '...' + self.get_var() + '=' + self.get_mod_value() + '...
:return: A string representing WHAT was fuzzed.
625941d1e64d504609d749d6
def load_cached_objs_from_file(fname): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> doc, root = xmlutil.load_file(fname, CACHEDOBJ_DOC_ROOT) <NEW_LINE> cobj = Cached_Objlist() <NEW_LINE> conode = root.find("OBJL") <NEW_LINE> if conode is None: <NEW_LINE> <INDENT> raise xmlutil.XMLError("No tree") <NEW_LINE> <DEDENT> co...
Load cached objs text file
625941d1a8ecb033257d3263
def test_get_payments_for_issued_invoice(self): <NEW_LINE> <INDENT> pass
Test case for get_payments_for_issued_invoice Get Payments for issued Invoice. # noqa: E501
625941d156ac1b37e6264364