code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
@permission_required("core.manage_shop") <NEW_LINE> @require_POST <NEW_LINE> def edit_product_data(request, product_id, template_name="manage/product/data.html"): <NEW_LINE> <INDENT> product = lfs_get_object_or_404(Product, pk=product_id) <NEW_LINE> products = _get_filtered_products_for_product_view(request) <NEW_LINE>... | Edits the product with given.
| 625941c6442bda511e8be44d |
def stop(self, report=0): <NEW_LINE> <INDENT> self._t1 = self._timer() <NEW_LINE> if self._verbose: printf("[{self._name}] stop = {self._t1}") <NEW_LINE> if report: self.report(force=1) | set the stop time of a timer | 625941c632920d7e50b28202 |
def copy_matching_files(paths_by_patient_id, copy_dir): <NEW_LINE> <INDENT> t1 = time.time() <NEW_LINE> potential_duplicates = [] <NEW_LINE> _make_dir(os.getcwd() + '/' + copy_dir) <NEW_LINE> for patient_id in paths_by_patient_id: <NEW_LINE> <INDENT> if len(paths_by_patient_id[patient_id]) == 0: <NEW_LINE> <INDENT> con... | Write matching files to new directory. | 625941c657b8e32f524834cd |
def spkt_welch_density(arr, coeff): <NEW_LINE> <INDENT> b = ctypes.c_void_p(0) <NEW_LINE> error_code = ctypes.c_int(0) <NEW_LINE> error_message = ctypes.create_string_buffer(KHIVA_ERROR_LENGTH) <NEW_LINE> KhivaLibrary().c_khiva_library.spkt_welch_density(ctypes.pointer(arr.arr_reference), ctypes.pointer(ctypes.c_int(co... | Estimates the cross power spectral density of the time series array at different frequencies. To do so, the
time series is first shifted from the time domain to the frequency domain.
Welch's method computes an estimate of the power spectral density by dividing the data into overlapping
segments, computing a modified p... | 625941c6956e5f7376d70ea1 |
def reboot_node(self, node): <NEW_LINE> <INDENT> params = {'method': 'voxel.devices.power', 'device_id': node.id, 'power_action': 'reboot'} <NEW_LINE> return self._getstatus(self.connection.request('/', params=params).object) | Reboot the node by passing in the node object | 625941c6be383301e01b54bb |
def pick_value_from_field(point, point_values): <NEW_LINE> <INDENT> offsets = numpy.array([q - point for q, v in point_values]) <NEW_LINE> sq_distances = numpy.sum(offsets * offsets, axis=1) <NEW_LINE> sqweights = 1.0 / (sq_distances + 1) <NEW_LINE> sqweights /= numpy.sum(sqweights) <NEW_LINE> values = numpy.array([x[1... | Return (value, error) sampled from supplied array of (point, value).
Given a number of points in space, which have values associated with them -
'point_values'; return a best guess for what the value might be at the
supplied 'point'.
Note that values are expected to be numpy.array's.
Usage example:
Sample based... | 625941c6be8e80087fb20c77 |
def current_session(self): <NEW_LINE> <INDENT> resource_type = 'sessions' <NEW_LINE> session = self.cimi_search(resource_type) <NEW_LINE> if session and session.count > 0: <NEW_LINE> <INDENT> return session.sessions[0].get('id') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None | Returns current user session or None.
:return: Current user session.
:rtype: str | 625941c6596a897236089af5 |
def getCurrentData(self): <NEW_LINE> <INDENT> return self.reader.read() | Get the current data.
Get the current data returned from the reader's read() method. | 625941c6236d856c2ad4480c |
def sample(self, batch_size: int): <NEW_LINE> <INDENT> batch = [] <NEW_LINE> tree_idx = np.zeros((batch_size,), dtype=np.int32) <NEW_LINE> sample_weights = np.zeros((batch_size,), dtype=np.float32) <NEW_LINE> priority_segment = self.tree.total_priority / batch_size <NEW_LINE> p_min = (self.tree.min_priority + self.min_... | 1. Sample a minibatch of k size
2. Divide the range [0, priority_total] k ranges.
3. Uniformly sample a value from each range
4. Search in the sumtree, retrieve the experience where priority score corresponds to sample values
5. IS (importance-sampling) weights for each minibatch element | 625941c6435de62698dfdc7f |
def remove(name=None, pkgs=None, **kwargs): <NEW_LINE> <INDENT> pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0] <NEW_LINE> old = list_pkgs() <NEW_LINE> targets = [x for x in pkg_params if x in old] <NEW_LINE> if not targets: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> cmd = '/opt/csw/bin/pkguti... | Remove a package and all its dependencies which are not in use by other
packages.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict co... | 625941c685dfad0860c3ae8d |
def test_write_file(self): <NEW_LINE> <INDENT> self.assertTrue(write_file(self.f_path, "w")) | Function: test_write_file
Description: Test writing to a file.
Arguments: | 625941c6c4546d3d9de72a66 |
def execute_action(self, name, params, sg_publish_data): <NEW_LINE> <INDENT> app = self.parent <NEW_LINE> app.log_debug( "Execute action called for action %s. " "Parameters: %s. Publish Data: %s" % (name, params, sg_publish_data) ) <NEW_LINE> try: <NEW_LINE> <INDENT> if name == CLIP_ACTION: <NEW_LINE> <INDENT> self._im... | Execute a given action. The data sent to this be method will
represent one of the actions enumerated by the generate_actions method.
:param name: Action name string representing one of the items returned by generate_actions.
:param params: Params data, as specified by generate_actions.
:param sg_publish_data: ShotGrid... | 625941c645492302aab5e2f5 |
def story_id_file_ooxmlautomationid_get(self, id, ooxml_automation_id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> return self.story_id_file_ooxmlautomationid_get_with_http_info(id, ooxml_automation_id, **kwargs) | story_id_file_ooxmlautomationid_get # noqa: E501
Get updated story as open office xml file (e.g., .pptx, .docx, .xlsx) # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.story_id_file_ooxmlautomationid_get(id, ooxml_... | 625941c68e7ae83300e4afff |
def print(self): <NEW_LINE> <INDENT> table = table_centered(self.screen, ['Primary', 'Secondary', 'Action'], self.items) <NEW_LINE> table.refresh() | print interface to window | 625941c699cbb53fe6792c1a |
def evaluate_numerical_attribute(self, feat, Y): <NEW_LINE> <INDENT> classes=np.unique(Y) <NEW_LINE> return split,mingain,Xlidx,Xridx | Evaluates the numerical attribute for all possible split points for
possible feature selection
Input:
---------
feat: a contiuous feature
Y: labels
Returns:
----------
v: splitting threshold
score: splitting score
Xlidx: Index of examples belonging to left child node
Xridx: Index of examples belonging to right child ... | 625941c6a4f1c619b28b006f |
def update_current_frame(self, increment) -> bool: <NEW_LINE> <INDENT> animation: dict = self._Animation <NEW_LINE> get = self.get_boolean_var <NEW_LINE> is_forwards = animation["forward"] <NEW_LINE> is_pingpong = get("pingpong-animation").get() <NEW_LINE> if not is_pingpong: <NEW_LINE> <INDENT> is_forwards = True <NEW... | Increments current animation frame.
:return: True. | 625941c6fb3f5b602dac36c5 |
def getCpuStepping(self): <NEW_LINE> <INDENT> if self.lCpuRevision is None: <NEW_LINE> <INDENT> return 0; <NEW_LINE> <DEDENT> return (self.lCpuRevision & 0xff); | Returns the CPU stepping for a x86 or amd64 testboxes. | 625941c666656f66f7cbc1dd |
def do_with_submit(self, func, iterables, *args, **kwargs): <NEW_LINE> <INDENT> threads = kwargs.get('threads', None) or 1 <NEW_LINE> with con.ThreadPoolExecutor(max_workers=int(threads)) as executor: <NEW_LINE> <INDENT> for item in iterables: <NEW_LINE> <INDENT> executor.submit(func, item, *args) | Args:
func: function name to execute
iterables: iterables list to execute with given function
Returns: | 625941c62c8b7c6e89b357f4 |
@command('unshare', [], '') <NEW_LINE> def unshare(ui, repo): <NEW_LINE> <INDENT> if repo.sharedpath == repo.path: <NEW_LINE> <INDENT> raise util.Abort(_("this is not a shared repo")) <NEW_LINE> <DEDENT> destlock = lock = None <NEW_LINE> lock = repo.lock() <NEW_LINE> try: <NEW_LINE> <INDENT> destlock = hg.copystore(ui,... | convert a shared repository to a normal one
Copy the store data to the repo and remove the sharedpath data. | 625941c615baa723493c3fa8 |
def preview_anon_tree_started(self): <NEW_LINE> <INDENT> pass | Status messages when previewing an anonymized tree should be
placed here. | 625941c6dc8b845886cb5567 |
def test_increment_relay_recent_measurement_attempt( controller, router_status, server_descriptor ): <NEW_LINE> <INDENT> now = datetime.utcnow() <NEW_LINE> relay = Relay("A" * 40, controller, timestamp=now) <NEW_LINE> assert 0 == relay.relay_recent_measurement_attempt_count <NEW_LINE> with freeze_time("2020-02-29 10:00... | Test that incrementing the measurement attempts do not go on forever
And instead it only counts the number of attempts in the last days. | 625941c6004d5f362079a367 |
def redirect(self): <NEW_LINE> <INDENT> raise NotImplementedError('Subclass should implement function "redirect"') | Expects a HTTP-redirect request | 625941c6293b9510aa2c32cb |
def send(self, cmd, timeout, wait_for_string): <NEW_LINE> <INDENT> return self.target_device.send(cmd, timeout=timeout, wait_for_string=wait_for_string) | Send command to the target device. | 625941c694891a1f4081badc |
def test_get_tasks_raise_error(): <NEW_LINE> <INDENT> event_data = EventData(task_path=_paths['task'], vol_path=_paths['vol']) <NEW_LINE> with pytest.raises(PyEventError): <NEW_LINE> <INDENT> event_data.get_tasks(start=42, end='2017-07-31 12:00') <NEW_LINE> <DEDENT> with pytest.raises(PyEventError): <NEW_LINE> <INDENT>... | raise an error when a bad date is passed in
| 625941c644b2445a339320ca |
def execute_selection(self, select_str): <NEW_LINE> <INDENT> results = None <NEW_LINE> try: <NEW_LINE> <INDENT> conn = psycopg2.connect(dbname=self.database_name, host=self.database_ip, user=self.database_user, password=self.database_password) <NEW_LINE> with conn.cursor() as cur: <NEW_LINE> <INDENT> cur.execute(select... | Executes the SQL Select statement on the database and return the
results. | 625941c6cb5e8a47e48b7adf |
def periodic_call(self): <NEW_LINE> <INDENT> if self.process_incoming(): <NEW_LINE> <INDENT> self.root.after(100, self.periodic_call) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.btnRun.config(state=NORMAL) | determine when to unlock the run button | 625941c67b25080760e3948d |
def test_get_project_with_parents_as_list_with_invalid_id(self): <NEW_LINE> <INDENT> self.get('/projects/%(project_id)s?parents_as_list' % { 'project_id': None}, expected_status=http_client.NOT_FOUND) <NEW_LINE> self.get('/projects/%(project_id)s?parents_as_list' % { 'project_id': uuid.uuid4().hex}, expected_status=htt... | Call ``GET /projects/{project_id}?parents_as_list``. | 625941c60fa83653e4656fef |
def start_game(stats, aliens, bullets, ai_settings, screen, ship): <NEW_LINE> <INDENT> pygame.mouse.set_visible(False) <NEW_LINE> stats.reset_stats() <NEW_LINE> stats.game_active = True <NEW_LINE> aliens.empty() <NEW_LINE> bullets.empty() <NEW_LINE> create_fleet(ai_settings, screen, ship, aliens) <NEW_LINE> ship.center... | 开始新游戏 | 625941c6711fe17d825423a1 |
def write_all( as_all, stream_in, stream_out, function, *args ): <NEW_LINE> <INDENT> if as_all: <NEW_LINE> <INDENT> write( function( stream_in.read(), *args ), stream_out ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> map_write( stream_in, stream_out, function, *args ) | If as_all, print function(*args) on the whole stream,
else, print it for each line. | 625941c67b180e01f3dc4833 |
def sample_delay(self, *args, **kwargs): <NEW_LINE> <INDENT> return _channelcoding_swig.binary_symmetric_channel_sptr_sample_delay(self, *args, **kwargs) | sample_delay(binary_symmetric_channel_sptr self, int which) -> unsigned int | 625941c623849d37ff7b30c3 |
def GetRDFValueType(self): <NEW_LINE> <INDENT> result = self.attribute_type <NEW_LINE> for field_name in self.field_names: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = result.type_infos.get(field_name).type <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise AttributeError("Invalid attribute %... | Returns this attribute's RDFValue class. | 625941c630dc7b766590199b |
def makeLc2HHH(name, LcMassWin, LcPT, LcVtxChi2Ndof, LcBpvdira, LcBpvdls, LcdaughterPT, LcdaughterP, LcdaughterTrkChi2, LcdaughterTrkGhostProb, LcdaughterBpvIpChi2, LcdaughterProtonProbNNp, LcdaughterKaonProbNNk, LcdaughterPionProbNNpi, ) : <NEW_LINE> <INDENT> _LcotherCuts = "( (ADMASS('Lambda_c+')<%(LcMassWin)s) | (A... | Create and return a Lambda_c+/Xi_c+ -> p K- pi+ | 625941c69b70327d1c4e0e08 |
def test_configurable_test_state_changes(): <NEW_LINE> <INDENT> mock_name = "cheese_shop" <NEW_LINE> mock_comment = "I'm afraid we're fresh out of Red Leicester sir." <NEW_LINE> mock_changes = { "testing": {"old": "Unchanged", "new": "Something pretended to change"} } <NEW_LINE> with patch.dict(test.__opts__, {"test": ... | Test test.configurable_test_state with permutations of changes and with
comment | 625941c6460517430c3941bb |
def calculate_city_id_completion(assessment): <NEW_LINE> <INDENT> print("recalculate_city_id_completion.Start.") <NEW_LINE> cidqs_total = len(AssessmentCityIDQuestion.objects.filter(assessment=assessment)) <NEW_LINE> cidqs_answered = 0 <NEW_LINE> for cidq in AssessmentCityIDQuestion.objects.filter(assessment=assessment... | Recalculates city id degree of copmpletion
:param assessment:
:return: | 625941c663b5f9789fde7119 |
def p_if_break_continue(p): <NEW_LINE> <INDENT> pass | if_break_continue : IF LPAREN condition RPAREN instruction_statement_break_continue
| IF LPAREN condition RPAREN instruction_statement_break_continue else_break_continue | 625941c626068e7796caed10 |
def test17(self): <NEW_LINE> <INDENT> a, b = to_dates('201102') <NEW_LINE> self.assertEqual(a, datetime(2011, 2, 1, 0, 0, 0)) <NEW_LINE> self.assertEqual(b, datetime(2011, 2, 28, 23, 59, 59)) | Non leap year | 625941c66fb2d068a760f0cf |
def p_conditional_and_expression_not_name(self, p): <NEW_LINE> <INDENT> if len(p) == 2: <NEW_LINE> <INDENT> p[0] = p[1] <NEW_LINE> <DEDENT> elif len(p) == 4: <NEW_LINE> <INDENT> if p[1].type == "": <NEW_LINE> <INDENT> entry = symbol_table.get_entry(p[1].value) <NEW_LINE> if entry: <NEW_LINE> <INDENT> p[1].type = entry[... | conditional_and_expression_not_name : inclusive_or_expression_not_name
| conditional_and_expression_not_name AND inclusive_or_expression
| name AND inclusive_or_expression | 625941c6167d2b6e31218bc9 |
def disable(self): <NEW_LINE> <INDENT> self.stopSmooth() <NEW_LINE> self.detachNode() <NEW_LINE> DistributedSmoothNode.disable(self) | This method is called when the object is removed from the
scene, for instance because it left the zone. It is balanced
against generate(): for each generate(), there will be a
corresponding disable(). Everything that was done in
generate() or announceGenerate() should be undone in disable().
After a disable(), the o... | 625941c6bde94217f3682e25 |
def _set_magnetfams_ordering(self, value): <NEW_LINE> <INDENT> if not isinstance(value, tuple): <NEW_LINE> <INDENT> raise TypeError("Value must be a tuple.") <NEW_LINE> <DEDENT> for item in value: <NEW_LINE> <INDENT> if not isinstance(item, str): <NEW_LINE> <INDENT> raise TypeError("List elements must be strings.") <NE... | Set magnetfams_ordering_svd property. | 625941c6ac7a0e7691ed4102 |
def login(self, request, user): <NEW_LINE> <INDENT> return login(request, user) | Sign a user in. | 625941c6d164cc6175782d81 |
def saveConfig(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> hwctool.settings.config.parser.set("Form", "autotwitch", str( self.view.cb_autoTwitch.isChecked())) <NEW_LINE> hwctool.settings.config.parser.set("Form", "autonightbot", str( self.view.cb_autoNightbot.isChecked())) <NEW_LINE> configFile = open(hwctool.s... | Save the settings to the config file. | 625941c626068e7796caed11 |
def combine(Food1, Food2): <NEW_LINE> <INDENT> comboDict = { 'name':Food1.name + ' & ' + Food2.name, 'type':Food1.type, 'freq':0, 'cal':Food1.cal + Food2.cal, 'protein':Food1.protein + Food2.protein, 'carb':Food1.carb + Food2.carb, 'fiber':Food1.fiber + Food2.fiber, 'netCarb':Food1.netCarb + Food2.netCarb, 'fat':Food1.... | Combines 2 foods into 1. Adds together any common ingredients, and
macronutrients.
Dependencies: None
Input is 2 Food class objects.
Output is a new Food class object. | 625941c6cc40096d61595984 |
@parallelize <NEW_LINE> def bvh2egg(bvh_path, dst_path=None, scale=1.0): <NEW_LINE> <INDENT> with open(bvh_path) as file_handle: <NEW_LINE> <INDENT> mocap = BvhTree(file_handle.read()) <NEW_LINE> <DEDENT> coords_up = '<CoordinateSystem> { Z-up }\n' <NEW_LINE> comment = '<Comment> {{ Converted from {0} }}\n'.format(os.p... | Converts a BVH file into the Panda3D egg animation file format.
When passing keyword arguments, keywords must be used!
:param bvh_path: File path(s) for BVH source.
:type bvh_path: str|list
:param dst_path: File or folder path for destination Panda3D Egg file.
:type dst_path: str
:param scale: Scale factor for root tr... | 625941c6bde94217f3682e26 |
def complete(self, force=False): <NEW_LINE> <INDENT> self._gather(force=force) <NEW_LINE> self._cleanup(force=force) | Download the results of this experiment back to the local machine. Raises a RuntimeError
unless all SLURM jobs started by the experiment have completed (set [force] to True to
override this check).
:param force: If true, download all current remote data regardless of job status.
:return: None | 625941c60a366e3fb873e84d |
def generate_rtt_url(start_time=None): <NEW_LINE> <INDENT> URL_REAL_TIME_TRAINS = "http://www.realtimetrains.co.uk/search/advanced/STPLNAR/{yyyy}/{mm}/{dd}/{hhhh1}-{hhhh2}?stp=WVS&show=all&order=actual" <NEW_LINE> if start_time is None: <NEW_LINE> <INDENT> start_time = datetime.now() <NEW_LINE> <DEDENT> year = start_ti... | Create a Realtime Trains detailed listing URL from a specified start time. The generated URL will look for movements that are expected for 24 hours following the input start time.
Args:
start_time (datetime): The start time. Defaults to None, which is latar set as the current time.
Returns:
str: A URL for a ... | 625941c6d486a94d0b98e179 |
def add_withdraw_request(self, withdraw): <NEW_LINE> <INDENT> twitch_usernameID = self.get_user(withdraw.twitch_username)[0] <NEW_LINE> twitch_channelID = self.get_channel(withdraw.twitch_channel)[0] <NEW_LINE> self.db.execute("INSERT INTO withdraws (userID, channelID, address, amount, active, datetimeStart) VALUES (?,... | Adds a withdraw to the database
Parameters:
withdraw: The deposit to add | 625941c6aad79263cf390a73 |
def main(): <NEW_LINE> <INDENT> v = [4,2,3,1] <NEW_LINE> selection_sort(v) <NEW_LINE> print(v) | type an unsorted vector | 625941c6f9cc0f698b140630 |
def _fill_tril(mat, rng, symmetric=False): <NEW_LINE> <INDENT> dim = mat.shape[0] <NEW_LINE> if dim == 1: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if dim <= 4: <NEW_LINE> <INDENT> mat[1, 0] = rng.randint(2, dtype=np.int8) <NEW_LINE> if symmetric: <NEW_LINE> <INDENT> mat[0, 1] = mat[1, 0] <NEW_LINE> <DEDENT> if di... | Add symmetric random ints to off diagonals | 625941c6d7e4931a7ee9df51 |
def test_syndome_LUT(self): <NEW_LINE> <INDENT> syns = [] <NEW_LINE> errvecs = golay._make_3bit_errors() <NEW_LINE> for errvec in errvecs: <NEW_LINE> <INDENT> syn = tuple( numpy.mod(numpy.dot(errvec, golay.DEFAULT_H.T), 2) ) <NEW_LINE> syns.append(syn) <NEW_LINE> <DEDENT> self.assertEqual(set(syns),set(golay.DEFAULT_SY... | default syndrome lookup table should have all syndromes as keys
also tests other things | 625941c64a966d76dd551042 |
def convert_time(period, unit): <NEW_LINE> <INDENT> year_pattern = re.compile("year", flags=re.I) <NEW_LINE> month_pattern = re.compile("month", flags=re.I) <NEW_LINE> if re.search(year_pattern, unit) != None: <NEW_LINE> <INDENT> day_count = sum([float(Fraction(quantity)) * 365 for quantity in period.split()]) <NEW_LIN... | In: A period of time as a number and the unit of that number, as in:
("7 1/2", "years")
Out: A timedelta object of the input time period. | 625941c68a349b6b435e81a7 |
def draw(self, screen): <NEW_LINE> <INDENT> self.screen.blit(self.image, self.rect) | 在指定位置绘制外星人 | 625941c6711fe17d825423a2 |
def collect_non_report_files(args, discovered_files): <NEW_LINE> <INDENT> excl_paths = exclude_paths(args) <NEW_LINE> abs_root = os.path.abspath(args.root) <NEW_LINE> non_report_files = [] <NEW_LINE> for root, dirs, files in os.walk(args.root): <NEW_LINE> <INDENT> dirs[:] = filter_dirs(root, dirs, excl_paths) <NEW_LINE... | Collects the source files that have no coverage reports.
| 625941c61d351010ab855b50 |
@exc_handler <NEW_LINE> def get_user_interface(dire, fName): <NEW_LINE> <INDENT> fName = find_file(dire, fName) <NEW_LINE> builder = Gtk.Builder() <NEW_LINE> builder.add_from_file(fName) <NEW_LINE> return builder | Get a "Gtk Builder" after parsing a file containing a GtkBuilder UI
definition and merges it with the current contents of builder.
@param : dire (directory path)
@param : fName (file name)
@return : builder | 625941c6a219f33f3462899f |
def evalRPN(self, tokens): <NEW_LINE> <INDENT> operators = "+-*/" <NEW_LINE> stack = [] <NEW_LINE> for i in tokens: <NEW_LINE> <INDENT> if i not in operators: <NEW_LINE> <INDENT> stack.append(int(i)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if i == "+": <NEW_LINE> <INDENT> a, b = stack.pop(), stack.pop() <NEW_LINE... | :type tokens: List[str]
:rtype: int | 625941c630c21e258bdfa4d0 |
def create_strs(): <NEW_LINE> <INDENT> c_chars = get_chars() <NEW_LINE> strs = ' %s ' % ' '.join(c_chars) <NEW_LINE> font = ImageFont.truetype(font_type, font_size) <NEW_LINE> font_width, font_height = font.getsize(strs) <NEW_LINE> draw.text(((width - font_width) / 3, (height - font_height) / 3), strs, font=font, fill=... | 绘制验证码字符 | 625941c629b78933be1e56e2 |
def GetOperationsHistory(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') | Missing associated documentation comment in .proto file. | 625941c6a05bb46b383ec857 |
@link(dim=1, dependencies={robot: link.match}) <NEW_LINE> def robot_analysis(vector, this, robot=0): <NEW_LINE> <INDENT> rbt = vector[0] <NEW_LINE> matches = {k[0]: year.match_attributes( rbt, k[0], v) for k, v in robot.items()} <NEW_LINE> example = matches[list(robot.keys())[0][0]] <NEW_LINE> def is_sortable(pair): <N... | Do individual performance metrics on da robot. Year-specific | 625941c696565a6dacc8f700 |
def test_that_when_deleting_a_thing_type_fails_the_delete_thing_type_method_returns_error(self): <NEW_LINE> <INDENT> self.conn.delete_thing_type.side_effect = ClientError(error_content, 'delete_thing_type') <NEW_LINE> result = boto_iot.delete_thing_type(thingTypeName=thing_type_name, **conn_parameters) <NEW_LINE> self.... | tests False when delete thing type fails | 625941c61b99ca400220aae5 |
def _crop_idx(self,start=None,end=None,samples=None): <NEW_LINE> <INDENT> assert (start is not None) + (end is not None) + (samples is not None) == 2 <NEW_LINE> if start is None: <NEW_LINE> <INDENT> if samples is None: <NEW_LINE> <INDENT> start=0 <NEW_LINE> start_idx=0 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <IND... | Internal function to calculate crop indexes
If interval required is not contained in TimeMatrix, returns None | 625941c6ad47b63b2c509fb3 |
def on_connect(self, connection, token): <NEW_LINE> <INDENT> logging.info('New connection from %s:%s on connection %d.' % ( 'ADDRESS', 'PORT', connection.id)) <NEW_LINE> player = characters.Player(name='Player-%d' % connection.id, connection=connection) <NEW_LINE> player = Story.get().on_player_connect(player) <NEW_LIN... | Server reported a new connection. | 625941c68da39b475bd64fa6 |
def stop(self): <NEW_LINE> <INDENT> if not self.isRunning(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.__mutex.lock() <NEW_LINE> self.__abort = True <NEW_LINE> self.__mutex.unlock() <NEW_LINE> self.wait() | Public slot to stop the installation procedure. | 625941c6627d3e7fe0d68e83 |
def searchMatrix2(self, matrix, target): <NEW_LINE> <INDENT> if len(matrix) == 0 or len(matrix[0]) == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> l = 0 <NEW_LINE> h = len(matrix) - 1 <NEW_LINE> while l < h: <NEW_LINE> <INDENT> m = (l + h) // 2 <NEW_LINE> if matrix[m][0] == target: <NEW_LINE> <INDENT> return... | :type matrix: List[List[int]]
:type target: int
:rtype: bool | 625941c6d99f1b3c44c675c4 |
def slugify(text): <NEW_LINE> <INDENT> slug = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore') <NEW_LINE> slug = slug.decode('utf-8').lower().replace(' ', '-') <NEW_LINE> slug = ''.join(c for c in slug if c in _SLUG_CHARS) <NEW_LINE> return slug[:_SLUG_SIZE] | Returns the slug of a string (that can be used in an URL for example. | 625941c6fb3f5b602dac36c6 |
def ifelse(num): <NEW_LINE> <INDENT> if ((num % 2) == 0) and (num >= 2) and (num <= 5): <NEW_LINE> <INDENT> return "Not Weird" <NEW_LINE> <DEDENT> if ((num % 2) == 0) and (num >= 6) and (num <= 20): <NEW_LINE> <INDENT> return "Weird" <NEW_LINE> <DEDENT> if ((num % 2) == 0) and (num > 20): <NEW_LINE> <INDENT> return "No... | Handle different if-else Statements | 625941c66aa9bd52df036dd8 |
@cli.command() <NEW_LINE> @click.option('-i', '--input-fp', required=True, type=click.Path(exists=True, dir_okay=False), help='The input BIOM table') <NEW_LINE> @click.option('-o', '--output-fp', default=None, type=click.Path(writable=True), help='An output file-path', required=False) <NEW_LINE> @click.option('-n', '--... | Dump the first bit of a table.
Example usage:
Print out the upper left corner of a BIOM table to standard out:
$ biom head -i table.biom | 625941c68e05c05ec3eea3a8 |
def get_route(self, route_id, source_id): <NEW_LINE> <INDENT> route = self.get(route_id) <NEW_LINE> if route is None: <NEW_LINE> <INDENT> route = Route(route_id, source_id) <NEW_LINE> self[route_id] = route <NEW_LINE> <DEDENT> return route | (add and) get route with given route_id
Parameters
----------
route_id : int
source_id : int
Returns
-------
route | 625941c6be7bc26dc91cd636 |
def test_list_bucket_names_no_buckets(): <NEW_LINE> <INDENT> with pytest.raises(AttributeError): <NEW_LINE> <INDENT> set(el for el in list_bucket_names({None})) | Test when buckets are None. | 625941c6d58c6744b4257c94 |
def get_profile(self, profile): <NEW_LINE> <INDENT> return self.profiles_dir + profile + ".json" | Gets the profile from the config | 625941c657b8e32f524834ce |
def parse_command_for_scantree(self, cmd: typing.List[str]) -> typing.List[str]: <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description="parse scantree options") <NEW_LINE> parser.add_argument('--ignore', type=str, default=None) <NEW_LINE> parser.add_argument('--path', type=str, default=None) <NEW_LINE> (args... | Given the user choice for --ignore get the corresponding value | 625941c6a8ecb033257d3102 |
def get_capabilities_by_ext(self, strict_type_matching: bool = False) -> Dict[str, Dict[Type, Dict[str, Parser]]]: <NEW_LINE> <INDENT> check_var(strict_type_matching, var_types=bool, var_name='strict_matching') <NEW_LINE> res = dict() <NEW_LINE> for ext in self.get_all_supported_exts_for_type(type_to_match=JOKER, stric... | For all extensions that are supported,
lists all types that can be parsed from this extension.
For each type, provide the list of parsers supported. The order is "most pertinent first"
This method is for monitoring and debug, so we prefer to not rely on the cache, but rather on the query engine.
That will ensure consi... | 625941c6a4f1c619b28b0070 |
def addCommonOptions(self, cmdconf): <NEW_LINE> <INDENT> self.add_option("--proxy", dest = "proxy", default = False, help = "Use the given proxy. Skip Grid proxy creation and myproxy delegation.") <NEW_LINE> if cmdconf['requiresTaskOption']: <NEW_LINE> <INDENT> self.add_option("-d", "--dir", dest = "task", default = No... | cmdconf: the command configuration from the ClientMapping | 625941c6d58c6744b4257c95 |
def __exit__(self, exc_type, exc_val, exc_tb): <NEW_LINE> <INDENT> self.close() | Context manager exit point. | 625941c6442bda511e8be44e |
def _message_received(self, msg, headers): <NEW_LINE> <INDENT> result = None <NEW_LINE> response_headers = {} <NEW_LINE> ts = get_ion_ts() <NEW_LINE> response_headers['msg-rcvd'] = ts <NEW_LINE> try: <NEW_LINE> <INDENT> result, new_response_headers = ResponseEndpointUnit._message_received(self, msg, headers) <NEW_LINE>... | Internal _message_received override.
We need to be able to detect IonExceptions raised in the Interceptor stacks as well as in the actual
call to the op we're routing into. This override will handle the return value being sent to the caller. | 625941c6097d151d1a222e8f |
def __rshift__(self, other): <NEW_LINE> <INDENT> return self.result >> other | bitwise operation: result = future >> other | 625941c644b2445a339320cb |
def get_image_pixels(image)->Tuple[int, int]: <NEW_LINE> <INDENT> return image.shape[0], image.shape[1] | 画像のピクセル数を指定する
:param image:
:return: | 625941c682261d6c526ab4d2 |
def net_input(self, X): <NEW_LINE> <INDENT> return np.dot(X, self.w_[1:]) + self.w_[0] | Caculate net input | 625941c6b7558d58953c4f4b |
def check_exclusive_variables(premise_tokens, excl_var_dict): <NEW_LINE> <INDENT> for var in excl_var_dict.keys(): <NEW_LINE> <INDENT> for token in premise_tokens: <NEW_LINE> <INDENT> if is_valid_variable(token, excl_var_dict[var]): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return False | Check whether exclusive variables match any tokens in the sentence. | 625941c68a43f66fc4b5409b |
def factor_ma_fall(sdf, n=(5,10,20,30,60), strict=True): <NEW_LINE> <INDENT> rdf = ma(sdf, n) <NEW_LINE> name_list = [] <NEW_LINE> for ma_n in n: <NEW_LINE> <INDENT> col_name = 'MA_'+str(ma_n)+'_FALL' <NEW_LINE> rdf[col_name] = wave(rdf['MA_'+str(ma_n)], strict) <NEW_LINE> rdf[col_name] = rdf[col_name].map(lambda x: Tr... | factor_ma_fall(sdf, n=[5,10,20,30,60], strict=True):
计算给定一组天数到均线是否都呈下降趋势,若都下降,则为1,反之则为0
Input:
sdf: (DataFrame): 按时间升序排好到股票数据,至少包括['close']
n: (list of int): 要计算的移动平均线的时间窗,如[5,10,...]
strict: (boolean): True为严格下降,走平为0;Flase为宽松条件,下降途中走平也认为在下降
Output:
(series): MA线组下降信号 | 625941c62ae34c7f2600d166 |
def __call__(self): <NEW_LINE> <INDENT> return SecondaryAuthTokenContext(self._version, ) | Constructs a SecondaryAuthTokenContext
:returns: twilio.rest.accounts.v1.secondary_auth_token.SecondaryAuthTokenContext
:rtype: twilio.rest.accounts.v1.secondary_auth_token.SecondaryAuthTokenContext | 625941c6b57a9660fec338b8 |
def cleanbeam(self, npix, fov, pulse=ehc.PULSE_DEFAULT): <NEW_LINE> <INDENT> im = ehtim.image.make_square(self, npix, fov, pulse=pulse) <NEW_LINE> beamparams = self.fit_beam() <NEW_LINE> im = im.add_gauss(1.0, beamparams) <NEW_LINE> return im | Make an image of the observation clean beam.
Args:
npix (int): The pixel size of the square output image.
fov (float): The field of view of the square output image in radians.
pulse (function): The function convolved with the pixel values for continuous image.
Returns:
(Image): an Image object with th... | 625941c632920d7e50b28204 |
def __init__(self, created=None, subscription_id=None, organization_id=None, invoice_id=None, state=None, period=None, start=None, stop=None, usage_type=None): <NEW_LINE> <INDENT> self.swagger_types = { 'created': 'datetime', 'subscription_id': 'str', 'organization_id': 'str', 'invoice_id': 'str', 'state': 'str', 'peri... | Period - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition. | 625941c6ad47b63b2c509fb4 |
def test_get_repo_from_url(): <NEW_LINE> <INDENT> from pygameweb.project.gh_releases import get_repo_from_url <NEW_LINE> url = "https://github.com/pygame/pygame/" <NEW_LINE> assert get_repo_from_url(url) == "pygame/pygame" <NEW_LINE> url = "https://github.com/pygame/pygame" <NEW_LINE> assert get_repo_from_url(url) == "... | gets the github repo from the url.
| 625941c6be8e80087fb20c79 |
def vectorize_0_1(func): <NEW_LINE> <INDENT> @jit(float_[:, ::1](float_[:, :, :, ::1]), nopython=True, nogil=True) <NEW_LINE> def aggregate_0_1(array): <NEW_LINE> <INDENT> m, n, _, _ = array.shape <NEW_LINE> result = np.empty((m, n), dtype=float__) <NEW_LINE> for i in range(m): <NEW_LINE> <INDENT> for j in range(n): <N... | vectorize `func` along 0, 1 axes | 625941c6046cf37aa974cd7e |
def plot_matrix_mixed(A, **kwargs): <NEW_LINE> <INDENT> fig, ax = plt.subplots(1, 1) <NEW_LINE> petsc_mat = A.M.handle <NEW_LINE> total_size = petsc_mat.getSize() <NEW_LINE> f0_size = A.M[0, 0].handle.getSize() <NEW_LINE> Mij = PETSc.Mat() <NEW_LINE> petsc_mat.convert("aij", Mij) <NEW_LINE> n, m = total_size <NEW_LINE>... | Provides a plot of a mixed matrix. | 625941c6462c4b4f79d1d705 |
def run(self): <NEW_LINE> <INDENT> self.login() <NEW_LINE> while True: <NEW_LINE> <INDENT> logging.info("Searching through the following subreddits: {}".format(self.subreddits)) <NEW_LINE> for subreddit in self.subreddits: <NEW_LINE> <INDENT> logging.info("Searching {}".format(subreddit)) <NEW_LINE> self.process_commen... | The main loop, which runs once every 15 minutes.
Looks through self.subreddits and replies to any (new) flagged comments. | 625941c6236d856c2ad4480e |
def sort_schedule_fn(*cmps): <NEW_LINE> <INDENT> dependence = make_dependence_cmp() <NEW_LINE> cmps = (dependence,) + cmps <NEW_LINE> def schedule(fgraph): <NEW_LINE> <INDENT> return sort_apply_nodes(fgraph.inputs, fgraph.outputs, cmps) <NEW_LINE> <DEDENT> return schedule | Make a schedule function from comparators
See also:
sort_apply_nodes | 625941c65fdd1c0f98dc0268 |
def check_case_code(self, indexstr, ustr): <NEW_LINE> <INDENT> ret = None <NEW_LINE> if ustr and len(ustr): <NEW_LINE> <INDENT> if public.is_include_specialchar(u'()', ustr): <NEW_LINE> <INDENT> ret = u"包含半角括号" <NEW_LINE> <DEDENT> <DEDENT> return ret | 案号 校验
不可为空 | 625941c60c0af96317bb821d |
def validate(self, data): <NEW_LINE> <INDENT> error_list = [] <NEW_LINE> start_date = data.get('arrival_date', datetime_object(self.instance.arrival_date) if self.instance else None) <NEW_LINE> end_date = data.get('departure_date', datetime_object(self.instance.departure_date) if self.instance else None) <NEW_LINE> if ... | Validate on the Reservation Serializer data
:param instance: instance of Reservation serializer data
:return: Exception if validation fails else return validated data | 625941c667a9b606de4a7eef |
def all_uuids(self): <NEW_LINE> <INDENT> return super().all_uuids() + self.kid_uuids + self.parent_uuids | Returns a list of unique UUIDs associated with this entity | 625941c6627d3e7fe0d68e84 |
def writeExcelTable(table, fileName, header=True, colsToWrite=None, adapt_column_widths=False): <NEW_LINE> <INDENT> wb = Workbook() <NEW_LINE> ws = wb.active <NEW_LINE> if header is True: <NEW_LINE> <INDENT> headerRow = _get_table_header_output(table, colsToWrite) <NEW_LINE> ws.append(headerRow) <NEW_LINE> <DEDENT> for... | write table to xls file | 625941c6fb3f5b602dac36c7 |
def view(self): <NEW_LINE> <INDENT> most_recent = most_recent_id = None <NEW_LINE> timestamp_idx = self.db.FIELD_MAP['timestamp'] <NEW_LINE> for record in self.db.data: <NEW_LINE> <INDENT> timestamp = record[timestamp_idx] <NEW_LINE> if most_recent is None or timestamp > most_recent: <NEW_LINE> <INDENT> most_recent = t... | View the most recently added book | 625941c6c432627299f04c7a |
def __setitem__(self, url, result): <NEW_LINE> <INDENT> path = self.urt_to_path(url) <NEW_LINE> timestamp = datetime.utcnow() <NEW_LINE> record = {'result': Binary(zlib.compress(pickle.dumps((result)))), 'timestamp': timestamp} <NEW_LINE> self.db.webpage.update({'_id': path}, {'$set': record}, upsert=True) | 此方法在MongoDBCache属性值发生变化时自动调用
将result写入文件中
webpage表中存在三个字段名,_id表示url路径,result表示网页的源代码内容,timestamp表示时间戳
:param url: 地址
:param result: 需要写入的数据
:return: | 625941c65e10d32532c5ef5c |
def get_wilson_B(conformation, **kwargs): <NEW_LINE> <INDENT> if 'ibonds' in kwargs and 'iangles' in kwargs and 'idihedrals' in kwargs: <NEW_LINE> <INDENT> ibonds = kwargs['ibonds'] <NEW_LINE> iangles = kwargs['iangles'] <NEW_LINE> idihedrals = kwargs['idihedrals'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ibonds, ... | Calculate the Wilson B matrix, which collects the derivatives of the
redundant internal coordinates w/r/t the cartesian coordinates.
.. math::
B_{ij} = rac{\partial q_i}{\partial x_j}
where :math:`q_i` are the internal coorindates and the :math:`x_j` are
the Cartesian displacement coordinates of the atoms.
BUT... | 625941c666656f66f7cbc1df |
def find_invalid_chars(self, text, context_size=20): <NEW_LINE> <INDENT> result = defaultdict(list) <NEW_LINE> for idx, char in enumerate(text): <NEW_LINE> <INDENT> if char not in self.alphabet: <NEW_LINE> <INDENT> start = max(0, idx-context_size) <NEW_LINE> end = min(len(text), idx+context_size) <NEW_LINE> result[ch... | Find invalid characters in text and store information about
the findings.
Parameters
----------
context_size: int
How many characters to return as the context. | 625941c62c8b7c6e89b357f6 |
def _default_convert_value(self, value: Any) -> Any: <NEW_LINE> <INDENT> if isinstance(value, models.Manager): <NEW_LINE> <INDENT> value = ", ".join([str(element) for element in value.all()]) <NEW_LINE> <DEDENT> elif hasattr(value, "__call__"): <NEW_LINE> <INDENT> value = value() <NEW_LINE> <DEDENT> return value | Default value converter. | 625941c67047854f462a1440 |
def _synchronize_position(self, date): <NEW_LINE> <INDENT> current_date = date or clock.current_date <NEW_LINE> next_date = get_next_date(current_date).strftime('%Y%m%d') <NEW_LINE> def _update_date(key, value): <NEW_LINE> <INDENT> value.date = next_date <NEW_LINE> for position in value.positions.itervalues(): <NEW_LIN... | 同步昨结算持仓信息 | 625941c63539df3088e2e380 |
def _taken_names(): <NEW_LINE> <INDENT> return [e.name for e in _MENU.entries] + RESV_NAMES | Returns a list of names already taken by menu entries. | 625941c6004d5f362079a369 |
def computeValueFromQValues(self, state): <NEW_LINE> <INDENT> action = self.computeActionFromQValues(state) <NEW_LINE> return self.getQValue(state, action) if action else 0.0 | Returns max_action Q(state,action)
where the max is over legal actions. Note that if
there are no legal actions, which is the case at the
terminal state, you should return a value of 0.0. | 625941c6ff9c53063f47c229 |
def __str__(self): <NEW_LINE> <INDENT> s = '' <NEW_LINE> for key, value in self.weights.items(): <NEW_LINE> <INDENT> X, Y = key <NEW_LINE> if isinstance(X, tuple): <NEW_LINE> <INDENT> s += 'phi(%s,%s) = 1 : w = %f\n' % ('&'.join(X), Y, value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s += 'phi(%s,%s) = 1 : w = %f\n... | Pretty prints the weights vector on std output.
May crash if vector is too wide/full | 625941c6d6c5a1020814407f |
@mxcube.route("/mxcube/api/v0.1/sampleview/centring", methods=['GET']) <NEW_LINE> def get_centring_positions(): <NEW_LINE> <INDENT> aux = {} <NEW_LINE> for pos in mxcube.diffractometer.savedCentredPos: <NEW_LINE> <INDENT> aux.update({pos['posId']: pos}) <NEW_LINE> pos_x, pos_y = mxcube.diffractometer.motor_positions_to... | Retrieve all the stored centred positions.
:response Content-type: application/json, the stored centred positions.
:statuscode: 200: no error
:statuscode: 409: error | 625941c6a8370b77170528d6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.