code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def _initialize(self, param_load_from=None, *args, **kwargs): <NEW_LINE> <INDENT> if param_load_from is None: <NEW_LINE> <INDENT> param_load_from = self.config.dataset_param_load_from <NEW_LINE> <DEDENT> if os.path.exists(param_load_from): <NEW_LINE> <INDENT> with open(param_load_from, 'rb') as f: <NEW_LINE> <INDENT> c... | Initialize dataset information
| 625941f2d7e4931a7ee9e4fd |
def __init__(self, http_response): <NEW_LINE> <INDENT> self._raw = http_response.text <NEW_LINE> self.json = http_response.json() <NEW_LINE> self._articles = None <NEW_LINE> try: <NEW_LINE> <INDENT> self.responseHeader = self.json['responseHeader'] <NEW_LINE> self.params = self.json['responseHeader']['params'] <NEW_LIN... | De-serialize a json string representing a solr response
:param http_response: complete json response from solr
:type http_response: request.response | 625941f210dbd63aa1bd317f |
def __init__(self, timestamp: int, c: Customer) -> None: <NEW_LINE> <INDENT> Event.__init__(self, timestamp) <NEW_LINE> self.customer = c <NEW_LINE> self._line_num = -1 | Initialize a CustomerArrival event with <timestamp> and customer <c>.
| 625941f2c432627299f05228 |
def media_stop(self): <NEW_LINE> <INDENT> if self.device and 'playback' in self._device_protocol_capabilities: <NEW_LINE> <INDENT> self._local_client_control_fix() <NEW_LINE> self.device.stop(self._active_media_plexapi_type) | Send stop command. | 625941f21b99ca400220b091 |
def testAddConfig_001(self): <NEW_LINE> <INDENT> split = SplitConfig() <NEW_LINE> config = LocalConfig() <NEW_LINE> config.split = split <NEW_LINE> self.validateAddConfig(config) | Test with empty config document. | 625941f2a05bb46b383ecdf9 |
def create_question(question_text, days): <NEW_LINE> <INDENT> time = timezone.now() + datetime.timedelta(days=days) <NEW_LINE> return Question.objects.create(question_text=question_text, pub_date=time) | Create a question with the given 'queston_text' and published the given number of 'days' offset to now (negative for questions published in the past, positive for questions that have yet to be published). | 625941f263b5f9789fde76c3 |
def cancel_tax(self, cancel_tax_request, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('callback'): <NEW_LINE> <INDENT> return self.cancel_tax_with_http_info(cancel_tax_request, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.cancel_tax_with_http_i... | Void a Document
Voids or deletes and existing transaction record from the AvaTax system. To use the XML for this operation specify the request `Content-Type: text/xml`. No modification needs to be made to the URL.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please defi... | 625941f22ae34c7f2600d70d |
def extract(): <NEW_LINE> <INDENT> url = 'https://www.crowdcube.com/investments' <NEW_LINE> hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Charset': 'ISO... | Extract the live investments from crowdcube and return a list of investement
models. | 625941f2dc8b845886cb5b14 |
def test_was_published_recently_with_recent_question(self): <NEW_LINE> <INDENT> time=timezone.now()-datetime.timedelta(hours=1) <NEW_LINE> recent_question=Question(pub_date=time) <NEW_LINE> self.assertIs(recent_question.was_published_recently(),True) | was_published_recently() should retunr True for questions whose pub_date is within the last day. | 625941f2283ffb24f3c55ed8 |
@gob.mapper() <NEW_LINE> def find_leafs(uid): <NEW_LINE> <INDENT> twit = twitter.TwitterResource() <NEW_LINE> user = User.get_id(uid) <NEW_LINE> _save_user_contacts(twit, user, _pick_random_contacts, limit=100) <NEW_LINE> return _my_contacts(user) | for each contact, fetch edges and tweets, pick 100 leaf ids | 625941f2167d2b6e31219172 |
@simple_api.errorhandler(500) <NEW_LINE> def internal_error_server(error): <NEW_LINE> <INDENT> return make_response(jsonify({'error': 'Something Bad Happened', 'status': 'failed'}), 500) | Returns a JSON with failed status and Error 500 | 625941f291af0d3eaac9bffa |
def serialize_numpy(self, buff, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> buff.write(_struct_B.pack(self.command)) <NEW_LINE> <DEDENT> except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(_x)))) <NEW_LINE> except TypeError as te: self._check_types(V... | serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module | 625941f29c8ee82313fbbd55 |
def plot(self, column_for_xticks=None, select=None, overlay=True, width=6, height=4, **vargs): <NEW_LINE> <INDENT> options = self.default_options.copy() <NEW_LINE> options.update(vargs) <NEW_LINE> if column_for_xticks is not None: <NEW_LINE> <INDENT> x_data, y_labels = self._split_column_and_labels(column_for_xticks) <... | Plot line charts for the table.
Args:
column_for_xticks (``str/array``): A column containing x-axis labels
Kwargs:
overlay (bool): create a chart with one color per data column;
if False, each plot will be displayed separately.
vargs: Additional arguments that get passed into `plt.plot`.
... | 625941f2d8ef3951e3243b1b |
def __init__(self): <NEW_LINE> <INDENT> self.ListenerId = None <NEW_LINE> self.ListenerName = None <NEW_LINE> self.Port = None <NEW_LINE> self.CreateTime = None <NEW_LINE> self.Protocol = None <NEW_LINE> self.ListenerStatus = None | :param ListenerId: 监听器ID
:type ListenerId: str
:param ListenerName: 监听器名称
:type ListenerName: str
:param Port: 监听器端口
:type Port: int
:param CreateTime: 监听器创建时间,Unix时间戳
:type CreateTime: int
:param Protocol: 监听器协议
:type Protocol: str
... | 625941f2cc40096d61595f2b |
def test_about_view(dummy_request): <NEW_LINE> <INDENT> from .views.default import home_view <NEW_LINE> info = home_view(dummy_request) <NEW_LINE> assert info["page_title"] == 'Home' | Test home template is in home view. | 625941f2de87d2750b860377 |
def _get_key_values(self, name): <NEW_LINE> <INDENT> results = {} <NEW_LINE> for key, value in self.qs.items(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if not key.startswith(name): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> key_start = key.index('[') + 1 <NEW_LINE> key_end = key.index(']') <NEW_LINE> item_ke... | Return a dict containing key / values items for a given key, used for items like filters, page, etc.
:param str name: name of the querystring parameter
:return dict: a dict of key / values items | 625941f2a79ad161976cc723 |
def testSequentialModelInputShape(self): <NEW_LINE> <INDENT> keras_file = self._getSequentialModel() <NEW_LINE> with self.assertRaises(ValueError) as error: <NEW_LINE> <INDENT> converter = lite.TFLiteConverter.from_keras_model_file( keras_file, input_shapes={'invalid-input': [2, 3]}) <NEW_LINE> <DEDENT> self.assertEqua... | Test a Sequential tf.keras model testing input shapes argument. | 625941f294891a1f4081c08a |
def point_sprites_available(): <NEW_LINE> <INDENT> if forced_point_sprites is not None: <NEW_LINE> <INDENT> return forced_point_sprites <NEW_LINE> <DEDENT> have_point_sprites = True <NEW_LINE> try: <NEW_LINE> <INDENT> gl.glEnable(gl.GL_POINT_SPRITE) <NEW_LINE> gl.glDisable(gl.GL_POINT_SPRITE) <NEW_LINE> <DEDENT> except... | Returns:
bool: tells if ``point sprites`` are available.
For development and diagonostic :class:`cocos.particle.forced_point_sprites`
could be set to force the desired return value. | 625941f20383005118ecfbbe |
def gen_xml(self, dict): <NEW_LINE> <INDENT> root = etree.Element('xml') <NEW_LINE> to_user_name = etree.SubElement(root, wechat_msg_params.KEY_TO_USER_NAME) <NEW_LINE> to_user_name.text = '<![CDATA[' + dict[wechat_msg_params.KEY_TO_USER_NAME] + ']]>' <NEW_LINE> from_user_name = etree.SubElement(root, wechat_msg_params... | 微信返回结果生成
dict:返回的微信信息内容
返回值:XML格式字符串 | 625941f297e22403b379d579 |
def choose_best_campaign_for_user_comparator(search_terms_list, campaigns): <NEW_LINE> <INDENT> search_terms_list = set(search_terms_list) <NEW_LINE> decorated = [(len(c.target_key_words & search_terms_list), c.bid_price, i) for i, c in enumerate(campaigns)] <NEW_LINE> sorted_campaigns = sorted(decorated, reverse=True)... | Returns the best campaign to serve for a given user or None if
no campaigns are applicable. A user can be served a campaign if they
have searched for at least one keyword configured for the campaign.
The "best" campaign to serve is the one with the most search term
matches.
If two or more campaigns have the same number... | 625941f20fa83653e4657595 |
def leaderCandidates( self, jsonFormat=True ): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> cmdStr = "onos:leaders -c" <NEW_LINE> if jsonFormat: <NEW_LINE> <INDENT> cmdStr += " -j" <NEW_LINE> <DEDENT> output = self.sendline( cmdStr ) <NEW_LINE> assert output is not None, "Error in sendline" <NEW_LINE> assert "Command n... | Returns the output of the leaders -c command.
Optional argument:
* jsonFormat - boolean indicating if you want output in json | 625941f2956e5f7376d71448 |
def score_digit(dice: List[int]) -> int: <NEW_LINE> <INDENT> return digit * dice.count(digit) | Digit x number of digits | 625941f2d486a94d0b98e724 |
def testCannotSelectMultiplePresets(self): <NEW_LINE> <INDENT> buttons = self.cc.presetGroup.buttons() <NEW_LINE> self.assertEqual(-1, self.cc.presetGroup.checkedId()) <NEW_LINE> self.cc.btnDown.click() <NEW_LINE> buttons[1].click() <NEW_LINE> self.assertTrue(buttons[1].isChecked()) <NEW_LINE> self.assertFalse(buttons[... | See https://github.com/jamesremuscat/aldatesx/issues/23 | 625941f22ae34c7f2600d70e |
def connect_levels(self, base_transfer_class, base_transfer_params, space_transfer_class, space_transfer_params, fine_level, coarse_level): <NEW_LINE> <INDENT> self.base_transfer = base_transfer_class(fine_level, coarse_level, base_transfer_params, space_transfer_class, space_transfer_params) <NEW_LINE> self.__transfer... | Routine to couple levels with base_transfer operators
Args:
base_transfer_class: the class which can do transfer between the two space-time levels
base_transfer_params (dict): parameters for the space_transfer class
space_transfer_class: the user-defined class which can do spatial transfer
space_transf... | 625941f2e1aae11d1e74a29b |
def Seek(self, *args): <NEW_LINE> <INDENT> return _openfst.LogArcIterator_Seek(self, *args) | Seek(self, unsigned long pos)
Seek to position. | 625941f23346ee7daa2b334f |
def redirect_to_login_or_show_cookie_help(request): <NEW_LINE> <INDENT> if request.META.get('HTTP_REFERER'): <NEW_LINE> <INDENT> return render_to_response('peerinst/cookie_help.html', dict(host=request.get_host())) <NEW_LINE> <DEDENT> return redirect_to_login(request.get_full_path()) | Redirect to login page outside of an iframe, show help on enabling cookies inside an iframe.
We consider the request to come from within an iframe if the HTTP Referer header is set. This
isn't entirely accurate, but should be good enough. | 625941f23eb6a72ae02ecacc |
def get_board_view(self): <NEW_LINE> <INDENT> return [list(act_list) for act_list in reversed(self.board_arrays)] | Returns the view of board
:return: Lists with the board values | 625941f2d18da76e23532abb |
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> if hasattr(self, attr): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr... | Returns the model properties as a dict | 625941f2566aa707497f4b3e |
def auth_for_test(self, perms=u'read'): <NEW_LINE> <INDENT> auth_url = self.auth_url(perms=perms) <NEW_LINE> self.verifier = u'test' | Doesn't wait for anything, sets the verifier to something silly.
Only use this in unit tests. | 625941f2796e427e537b0ba9 |
def main(): <NEW_LINE> <INDENT> input_n = int(input()) <NEW_LINE> input_str = str(input()) <NEW_LINE> result = 0 <NEW_LINE> for i in range(input_n): <NEW_LINE> <INDENT> result += int(input_str[i]) <NEW_LINE> <DEDENT> print(result) | main function | 625941f2d18da76e23532abc |
def main(): <NEW_LINE> <INDENT> money_per_week = 10 <NEW_LINE> i = 1 <NEW_LINE> increase_money = 10 <NEW_LINE> total_week = 52 <NEW_LINE> saving =0 <NEW_LINE> while i <= total_week: <NEW_LINE> <INDENT> saving += money_per_week <NEW_LINE> print('第{}周,存入{}元,账户累计{}元'.format(i,money_per_week,saving)) <NEW_LINE> money_per_w... | 主函数 | 625941f2f9cc0f698b140bd4 |
def test_py_include(): <NEW_LINE> <INDENT> filename = os.path.join(TEST_FOLDER, "models", "python_include.json") <NEW_LINE> model = Model.load(filename) <NEW_LINE> model.run() | Test include in Python document | 625941f25f7d997b8717507b |
def _add_job(self, job): <NEW_LINE> <INDENT> if self._shutdown: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> self._pending_jobs.append(job) <NEW_LINE> result = self._executor.submit(self._invoke_job, job) <NEW_LINE> self._pending_job_results.add(result) <NEW_LINE> self._counter += 1 <NEW_LINE> logger.debug("%s ... | add job to engine for scheduling later
:param job: job should have a 'run' method
:return:True when the jobs is added successfully and False when the
engine has shut down | 625941f24f6381625f115018 |
def followersPageParse(self, response): <NEW_LINE> <INDENT> xpath_users = "//a[@class='user']/@href" <NEW_LINE> users = response.xpath(xpath_users).extract() <NEW_LINE> for index, each in enumerate(users): <NEW_LINE> <INDENT> users[index] = response.urljoin(each) <NEW_LINE> <DEDENT> with open("../datasets/users/user_ur... | 解析followers页面, 获取followers的链接
:param response:
:return: | 625941f26aa9bd52df037386 |
def _find_filament_path(self, filament_name): <NEW_LINE> <INDENT> return next(iter([os.path.join(FILAMENTS_DIR, filament) for filament in os.listdir(FILAMENTS_DIR) if filament.endswith('.py') and filament_name == filament[:-3]]), None) | Resolves the filament full path from the name
Parameters
----------
filament_name: str
the name of the filament whose path if about to be resolved | 625941f2adb09d7d5db6cd6a |
def test_voi_uint8(self): <NEW_LINE> <INDENT> ds = Dataset() <NEW_LINE> ds.PixelRepresentation = 0 <NEW_LINE> ds.BitsStored = 8 <NEW_LINE> ds.VOILUTSequence = [Dataset()] <NEW_LINE> item = ds.VOILUTSequence[0] <NEW_LINE> item.LUTDescriptor = [4, 0, 8] <NEW_LINE> item.LUTData = [0, 127, 128, 255] <NEW_LINE> arr = np.asa... | Test uint VOI LUT with an 8-bit LUT. | 625941f28e05c05ec3eea958 |
def _custom_browser_load(self, instance): <NEW_LINE> <INDENT> file_path = instance.selection[0] <NEW_LINE> self._popup.dismiss() <NEW_LINE> self.ui_creator.playground.sandbox.error_active = True <NEW_LINE> with self.ui_creator.playground.sandbox: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.project_loader.add_cust... | Event Handler for 'on_success' event of self._custom_browser
| 625941f2a219f33f34628f3f |
def load_checkpoint(checkpoint, model, optimizer=None): <NEW_LINE> <INDENT> if not os.path.exists(checkpoint): <NEW_LINE> <INDENT> raise ("File doesn't exist {}".format(checkpoint)) <NEW_LINE> <DEDENT> checkpoint = torch.load(checkpoint, map_location='cpu') <NEW_LINE> model.load_state_dict(checkpoint['state_dict']) <NE... | Loads model parameters (state_dict) from file_path. If optimizer is provided, loads state_dict of
optimizer assuming it is present in checkpoint.
Args:
checkpoint: (string) filename which needs to be loaded
model: (torch.nn.Module) model for which the parameters are loaded
optimizer: (torch.optim) optional:... | 625941f24e696a04525c9a2c |
def allow_migrate(self, db, app_label, model_name=None, **hints): <NEW_LINE> <INDENT> if app_label == 'share_remote': <NEW_LINE> <INDENT> return db == 'remote' <NEW_LINE> <DEDENT> return 'default' | Make sure the auth app only appears in the 'auth_db'
database. | 625941f2f548e778e58cdb5e |
def fslicebefore(astr, sub): <NEW_LINE> <INDENT> findex = astr.find(sub) <NEW_LINE> return astr[findex:] | Return the slice starting at sub in string astr | 625941f24527f215b584ca2f |
@message('not a directory', cls=DirInvalid) <NEW_LINE> @truth <NEW_LINE> def IsDirUserExpand(v): <NEW_LINE> <INDENT> return os.path.isdir(os.path.expanduser(v)) | Verify the directory exists.
>>> IsDirUserExpand()('/')
'/' | 625941f25fdd1c0f98dc0814 |
def get(self, x, y): <NEW_LINE> <INDENT> start = self._translate(x, y) <NEW_LINE> return [self.data[start]] | Returns the pixel (a tuple of length `self.pixelsize`) from the pixel array at x/y | 625941f231939e2706e4d43f |
def apply_PCA(x, mu, P): <NEW_LINE> <INDENT> return np.dot(x - mu, P) | Example of applying PCA. | 625941f2dc8b845886cb5b15 |
@typing.no_type_check <NEW_LINE> def main(argv=None): <NEW_LINE> <INDENT> argv = sys.argv[1:] if argv is None else argv <NEW_LINE> verbose = True if '-v' in argv or '--verbose' in argv else False <NEW_LINE> folder_paths = [entry for entry in argv if entry not in ('-v', '--verbose')] <NEW_LINE> total_removed, total_less... | Process the files separately per folder. | 625941f26fece00bbac2dd24 |
def forward(self, x): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> out = np.dot(self.x, self.W) + self.b <NEW_LINE> return out | forward propagation
Args:
x (numpy.ndarray): input
Returns:
numpy.ndarray: output | 625941f299cbb53fe67931c3 |
def zeroSmallFactors(X, zeroThr=1e-4): <NEW_LINE> <INDENT> for n in range(X.ndims()): <NEW_LINE> <INDENT> zeroIdx = np.where(X.U[n] < zeroThr) <NEW_LINE> X.U[n][zeroIdx] = 0 <NEW_LINE> <DEDENT> return X | Convert the small factors to 0 | 625941f2004d5f362079a90d |
def renderCards(string): <NEW_LINE> <INDENT> cards = string.strip().split(' ') <NEW_LINE> return filter(len, map(lambda x: x.strip(' ,'), cards)) | Splits strings like ' Js, 4d ' | 625941f2435de62698dfe22b |
def transform(self, text, filter): <NEW_LINE> <INDENT> version = self.root.document.get_editable() <NEW_LINE> request = TestRequest() <NEW_LINE> factory = getMultiAdapter((version, request), ITransformerFactory) <NEW_LINE> self.assertTrue(verifyObject(ITransformerFactory, factory)) <NEW_LINE> transformer = factory('tes... | Helper to call transform.
| 625941f2fb3f5b602dac3c78 |
def _add(self): <NEW_LINE> <INDENT> rule = self._rule <NEW_LINE> rule_elt, dummy = self._find_matching_rule() <NEW_LINE> changed = False <NEW_LINE> timestamp = '%d' % int(time.time()) <NEW_LINE> if rule_elt is None: <NEW_LINE> <INDENT> changed = True <NEW_LINE> rule['id'] = '' <NEW_LINE> rule['tracker'] = timestamp <NE... | add or update rule | 625941f276d4e153a657f110 |
def __init__(self, student: Student, student_repo_path, commit_hash, assignment_dir: AssignmentDirectory, faculty_username, faculty_email): <NEW_LINE> <INDENT> self.student = student <NEW_LINE> self.student_repo_path = student_repo_path <NEW_LINE> self.commit_hash = commit_hash <NEW_LINE> self.tests_path = assignment_d... | Simply assign the attributes.
:param student: Student object containing information about the student
:param student_repo_path: path to the student's assignment repository
:param commit_hash: the hash of the commit of the submission
:param faculty_email: email address of the faculty that owns the
assignment | 625941f2d486a94d0b98e725 |
def test_execute_query_ocp_cpu_with_delta_usage__capacity(self): <NEW_LINE> <INDENT> delta = 'usage__capacity' <NEW_LINE> url = reverse('reports-openshift-cpu') <NEW_LINE> client = APIClient() <NEW_LINE> params = { 'delta': delta } <NEW_LINE> url = url + '?' + urlencode(params, quote_via=quote_plus) <NEW_LINE> response... | Test that usage v capacity deltas work. | 625941f2cad5886f8bd275b6 |
def extract_schema(fileobj, keywords, comment_tags, options): <NEW_LINE> <INDENT> def _extract_schema(data, pointer=''): <NEW_LINE> <INDENT> if isinstance(data, list): <NEW_LINE> <INDENT> for index, item in enumerate(data): <NEW_LINE> <INDENT> yield from _extract_schema( item, pointer='{}/{}'.format(pointer, index)) <N... | Yields the "title" and "description" values of a JSON Schema file. | 625941f29b70327d1c4e13b6 |
def getConversationsByStatus(interval,statusFilter): <NEW_LINE> <INDENT> convPred = None <NEW_LINE> segPred = None <NEW_LINE> if statusFilter == 'openLine': <NEW_LINE> <INDENT> segPred = [('segmentEnd','notExists'),('segmentType','interact')] <NEW_LINE> <DEDENT> elif statusFilter == 'open': <NEW_LINE> <INDENT> convPred... | Retrieves a list of all conversations in a current status
Currently defined conversation statuses are 'talking' (conversation has
not ended), 'wrappingUp' (conversation has ended, but no wrap up code),
'ended' (conversation had ended, and wrapup code exists)
:param interval: formatted PureCloud interval string to sea... | 625941f2a8ecb033257d36a9 |
def notify_error( message='Something goes wrong' , error = {} ): <NEW_LINE> <INDENT> log_error( message, error ) <NEW_LINE> flash( message, 'error' ) | A wrapper function to log the erro and the send a flash
message:str
The display text to send in a flash and log
By default 'Somthing goes wrong', but use a more descriptive message.
error: dict
The object error/exeption throw by the application | 625941f244b2445a33932670 |
def create_alien(settings, screen, aliens, alien_number, row_number): <NEW_LINE> <INDENT> alien = Alien(settings, screen) <NEW_LINE> alien_width = alien.rect.width <NEW_LINE> alien.x = alien_width + 2 * alien_width * alien_number <NEW_LINE> alien.rect.x = alien.x <NEW_LINE> alien.rect.y = alien.rect.height + 2 * alien.... | Create an alien, and place it in the row. | 625941f2a79ad161976cc724 |
def has_waiting(self): <NEW_LINE> <INDENT> self._check_owned() <NEW_LINE> return bool(self._waiters) | Returns whether there are active waiters.
| 625941f25fcc89381b1e1ca2 |
def __get_empty_image(self): <NEW_LINE> <INDENT> if not self.__empty: <NEW_LINE> <INDENT> self.__empty = wx.EmptyBitmap(*self.__size) <NEW_LINE> writer = wx.MemoryDC(self.__empty) <NEW_LINE> bg, fg = environment.userinterface.colors <NEW_LINE> writer.SetBrush(wx.Brush(bg)) <NEW_LINE> writer.SetPen(wx.Pen(bg)) <NEW_LINE... | Returns image for "Not found".
if empty image was not generated, generates and
returns image. | 625941f2fff4ab517eb2fa1f |
def compare_bb_dicts_class_by_class(gt_dict,guess_dict, dict_format={'annotations':'annotations','bbox_xywh':'bbox_xywh','object':'object','confidence':'confidence'}, iou_threshold=0.2,visual_output=True,all_results=None): <NEW_LINE> <INDENT> classes = get_classes_in_dicts([gt_dict,guess_dict]) <NEW_LINE> if all_result... | takes gt and guess dicts and determines iou, n_images etc per class
this can be repeatedly called to accumulate stats along the lines of
for gt,guess in zip(gts,guesses):
stats = compare_bb_dicts_class_by_class(gt,guess,visual_output=True,all_results=stats)
:param gt_dict: ground truths dictionary for a given imag... | 625941f28c3a8732951589a1 |
def getActiveCurrency(): <NEW_LINE> <INDENT> pass | returns the current currency | 625941f21f5feb6acb0c5127 |
def kaiser(dtype, N, beta): <NEW_LINE> <INDENT> import_module('vsip.block', dtype) <NEW_LINE> m = import_module('vsip.signal.window', dtype) <NEW_LINE> return vector(block=m.kaiser(N, beta)) | Create a vector with Kaiser window weights.
arguments:
:dtype: data type of the vector (e.g. float)
:N: length of the vector | 625941f2287bf620b61d403e |
def set_definition(self, definition, language=None): <NEW_LINE> <INDENT> self.definition = definition <NEW_LINE> if language is not None: <NEW_LINE> <INDENT> self.set_language(language) <NEW_LINE> <DEDENT> return self | ! @brief Set definition.
@param definition Definition.
@param language Language used for the definition.
@return Definition instance. | 625941f28a349b6b435e8751 |
def get_geetest_image(self, name='demo.png'): <NEW_LINE> <INDENT> left, top, right, bottom = self.get_code_position() <NEW_LINE> print('验证码位置:({}, {}), ({}, {})'.format(left, top, right, bottom)) <NEW_LINE> screenshot = self.get_screenshot() <NEW_LINE> captcha = screenshot.crop((left, top, right, bottom)) <NEW_LINE> ca... | 获取验证码图片
:return: 图片对象 | 625941f23c8af77a43ae3d86 |
def __calc_loss_n_metrics(self): <NEW_LINE> <INDENT> save_path = self.saver_prnd_train.save(self.sess_train, self.save_path_prnd) <NEW_LINE> self.saver_prnd_eval.restore(self.sess_eval, save_path) <NEW_LINE> if FLAGS.ws_nb_iters_feval > 0: <NEW_LINE> <INDENT> nb_iters = FLAGS.ws_nb_iters_feval <NEW_LINE> <DEDENT> else:... | Calculate the loss function's value and evaluation metrics.
Returns:
* loss: loss function's value
* metrics: evaluation metrics | 625941f2cc40096d61595f2c |
def test_band_output(): <NEW_LINE> <INDENT> data = {} <NEW_LINE> mfdnres.analysis.import_res_files( data, filename = r"c:\work\research\data\mfdn\run0339", key_fields = ("interaction","Nmax","hw"), descriptor_format="mfdn_format_5_ho", res_format="mfdn_v14b06", verbose=False ) <NEW_LINE> band = mfdnres.analysis.BandDef... | validation of new consolidated band output
on old JISP+NC run0339 | 625941f24c3428357757c902 |
def _destructively_unify(fstruct1, fstruct2, bindings, forward, trace, fail, fs_class, path): <NEW_LINE> <INDENT> if fstruct1 is fstruct2: <NEW_LINE> <INDENT> if trace: _trace_unify_identity(path, fstruct1) <NEW_LINE> return fstruct1 <NEW_LINE> <DEDENT> forward[id(fstruct2)] = fstruct1 <NEW_LINE> if _is_mapping(fstruct... | Attempt to unify C{fstruct1} and C{fstruct2} by modifying them
in-place. If the unification succeeds, then C{fstruct1} will
contain the unified value, the value of C{fstruct2} is undefined,
and forward[id(fstruct2)] is set to fstruct1. If the unification
fails, then a _UnificationFailureError is raised, and the
value... | 625941f2eab8aa0e5d26e139 |
def max_pool_2x2(x): <NEW_LINE> <INDENT> h_max = tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') <NEW_LINE> return h_max | Perform non-overlapping 2-D maxpooling on 2x2 regions in the input data
:param x: input data
:return: the results of maxpooling (max-marginalized + downsampling) | 625941f21f037a2d8b9467da |
def replace_rule(table, chain, old_rule_d, new_rule_d, ipv6=False): <NEW_LINE> <INDENT> iptc_chain = _iptc_getchain(table, chain, ipv6) <NEW_LINE> iptc_old_rule = encode_iptc_rule(old_rule_d, ipv6) <NEW_LINE> iptc_new_rule = encode_iptc_rule(new_rule_d, ipv6) <NEW_LINE> iptc_chain.replace_rule(iptc_new_rule, iptc_chain... | Replaces an existing rule of a chain | 625941f24f88993c3716c63f |
def __init__(self, argv): <NEW_LINE> <INDENT> self.argns, unused = util.parse_args(argv, gui=True) <NEW_LINE> if argv is None: <NEW_LINE> <INDENT> argv = sys.argv <NEW_LINE> <DEDENT> self.argv = argv <NEW_LINE> if QCoreApplication.instance() is None: <NEW_LINE> <INDENT> self.qApp = QApplication(argv) <NEW_LINE> assert(... | Create the application object
| 625941f2a05bb46b383ecdfa |
def test_create_batch(self): <NEW_LINE> <INDENT> dialogs_models = DialogsModelFactory.create_batch(5) <NEW_LINE> self.assertEqual(DialogsModel.objects.count(), 5) <NEW_LINE> self.assertEqual(len(dialogs_models), 5) | Test the creation of 5 DialogsModel models using a factory | 625941f285dfad0860c3b43c |
def find_lowest_p_layer(minmol, p_layer, equivalent_atoms): <NEW_LINE> <INDENT> return minmol | Permute the equivalent atoms and return the combination with the
lowest p-layer.
TODO: The presence of unpaired electrons complicates stuff. | 625941f2090684286d50f2cf |
def test_sizes_with_nonstandard_size(self): <NEW_LINE> <INDENT> p = self.pager(self.qs(5), 15, 1) <NEW_LINE> self.assertEqual(p.sizes(), [10, 15, 20, 50, 100]) | Current pagesize is always included in page-size options. | 625941f263f4b57ef00016e6 |
def test_export_dset_refs(self): <NEW_LINE> <INDENT> bazs = [] <NEW_LINE> num_bazs = 10 <NEW_LINE> for i in range(num_bazs): <NEW_LINE> <INDENT> bazs.append(Baz(name='baz%d' % i)) <NEW_LINE> <DEDENT> baz_data = BazData(name='baz_data1', data=bazs) <NEW_LINE> bucket = BazBucket(name='bucket1', bazs=bazs.copy(), baz_data... | Test that exporting a written container with a dataset of references works. | 625941f2b57a9660fec33e6b |
def __virtual__(): <NEW_LINE> <INDENT> cmd = __detect_os() <NEW_LINE> if salt.utils.which(cmd): <NEW_LINE> <INDENT> return 'apache' <NEW_LINE> <DEDENT> return False | Only load the module if apache is installed | 625941f2b57a9660fec33e6c |
def test_user_key(self): <NEW_LINE> <INDENT> assert self.zeyple._user_key('non_existant@example.org') is None <NEW_LINE> user_key = self.zeyple._user_key('torvalds@linux-foundation.org') <NEW_LINE> assert user_key == LINUS_ID | Returns the right ID for the given email address | 625941f2f548e778e58cdb5f |
def load_data(city, month, day): <NEW_LINE> <INDENT> df = pd.read_csv(CITY_DATA[city]) <NEW_LINE> df['Start Time'] = pd.to_datetime(df['Start Time']) <NEW_LINE> df['month'] = df['Start Time'].dt.month <NEW_LINE> df['day_of_week'] = df['Start Time'].dt.weekday_name <NEW_LINE> if month != 'All': <NEW_LINE> <INDENT> month... | Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pan... | 625941f27d847024c06be8a0 |
@register_model <NEW_LINE> def resnet50d(pretrained=False, num_classes=1000, in_chans=3, **kwargs): <NEW_LINE> <INDENT> default_cfg = default_cfgs['resnet50d'] <NEW_LINE> if kwargs.pop('features_only', False): <NEW_LINE> <INDENT> model = ResNetFeatures( Bottleneck, [3, 4, 6, 3], stem_width=32, stem_type='deep', avg_dow... | Constructs a ResNet-50-D model.
| 625941f27cff6e4e81117f64 |
def allure(registry, xml_parent, data): <NEW_LINE> <INDENT> publisher_class = 'ru.yandex.qatools.allure.jenkins.AllureReportPublisher' <NEW_LINE> property_class = 'ru.yandex.qatools.allure.jenkins.config.PropertyConfig' <NEW_LINE> results_class = 'ru.yandex.qatools.allure.jenkins.config.ResultsConfig' <NEW_LINE> allure... | yaml: allure
Publish Allure report for the build. Requires the Jenkins
:jenkins-wiki:`Allure Plugin <Allure+Plugin>`.
:arg str jdk: String identifier for a JDK installation in Jenkins
:arg str commandline: String identifier for a Allure-commandline tool
installation
:arg str report-build-policy: String identifier for... | 625941f226238365f5f0f455 |
def _jacobi_witness(self, x_value, n_value): <NEW_LINE> <INDENT> j_value = self._jacobi(x_value, n_value) % n_value <NEW_LINE> f_value = pow(x_value, (n_value - 1) / 2, n_value) <NEW_LINE> if j_value == f_value: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True | Checks if the given x value is witness to n value
non primality.
This check is made according to euler's theorem.
@type x_value: int
@param x_value: The value to be checked for witness.
@type n_value: int
@param n_value: The value to be checked for primality.
@rtype: bool
@return: The result of the checking. | 625941f26e29344779a62bf0 |
def Initialize(filename, credential_path='default'): <NEW_LINE> <INDENT> if credential_path == 'default': <NEW_LINE> <INDENT> credential_path = os.path.split(ee.oauth.get_credentials_path())[0] <NEW_LINE> <DEDENT> path = os.path.join(credential_path, filename) <NEW_LINE> def get_credentials(): <NEW_LINE> <INDENT> try: ... | Authenticate to GEE with the specified credentials
If credential_path is set to 'defualt', it searches for the 'filename' in
the same folder in which credentials are stored locally | 625941f223849d37ff7b3669 |
def get_queryset(self): <NEW_LINE> <INDENT> return Application.objects.filter(job__id=self.kwargs["job_id"]) | Return all applications for this job id. | 625941f28da39b475bd6555b |
def connection(profile_name='default', api_key=None): <NEW_LINE> <INDENT> if api_key is None: <NEW_LINE> <INDENT> profile_fname = datapoint.profile.API_profile_fname(profile_name) <NEW_LINE> if not os.path.exists(profile_fname): <NEW_LINE> <INDENT> raise ValueError('Profile not found in {}. Please install your API \n' ... | Connect to DataPoint with the given API key profile name. | 625941f2377c676e91272786 |
def _handle_prev_events(self, txn, outlier, event_id, prev_events, room_id): <NEW_LINE> <INDENT> self._simple_insert_many_txn( txn, table="event_edges", values=[ { "event_id": event_id, "prev_event_id": e_id, "room_id": room_id, "is_state": False, } for e_id, _ in prev_events ], ) <NEW_LINE> if not outlier: <NEW_LINE> ... | For the given event, update the event edges table and forward and
backward extremities tables. | 625941f2925a0f43d254a45c |
def nitems_read(self, *args, **kwargs): <NEW_LINE> <INDENT> return _howto_swig.header_payload_demux_sptr_nitems_read(self, *args, **kwargs) | nitems_read(header_payload_demux_sptr self, unsigned int which_input) -> uint64_t | 625941f22c8b7c6e89b35d9b |
def bytes_to_base64(b): <NEW_LINE> <INDENT> return base64.b64encode(b).decode() | convert bytes to base64 string
:param b: bytes
:return: base64 string | 625941f2d6c5a1020814462f |
def write_npy(self, file_path): <NEW_LINE> <INDENT> txyz_data = self.ts.txyz <NEW_LINE> np.save(file_path, txyz_data) | Write TDS data into NumPy uncompressed format. | 625941f20c0af96317bb87c6 |
def OnPreferences(self, e): <NEW_LINE> <INDENT> logging.info("Menu-Tools-> Open preferences dialog") <NEW_LINE> dlg = tcui.DialogPreferences(self.parent, self.app) <NEW_LINE> self.app.SetTopWindow(dlg) <NEW_LINE> if dlg.ShowModal() == wx.ID_OK: <NEW_LINE> <INDENT> dlg.Destroy() | Open the preferences dialog | 625941f23539df3088e2e92b |
def setUp(self): <NEW_LINE> <INDENT> meta_data_entity = GenericMetaData(self.WRITABLE_METADATA) <NEW_LINE> self.meta_writer = XMLWriter(meta_data_entity) <NEW_LINE> self.result_path = os.path.join(os.path.dirname(__file__), "Operation.xml") | Sets up necessary files for the tests. | 625941f230bbd722463cc3a8 |
def subscribe(self): <NEW_LINE> <INDENT> lck = self._lib().auto_lock() <NEW_LINE> err = _pjsua.buddy_subscribe_pres(self._id, True) <NEW_LINE> self._lib()._err_check("subscribe()", self, err) | Subscribe to buddy's presence status notification. | 625941f2236d856c2ad44dc2 |
def hierarchical_clustering(self, data = 'open_shut'): <NEW_LINE> <INDENT> feature_list = [] <NEW_LINE> for cluster in self.cluster_list: <NEW_LINE> <INDENT> if data == 'open_shut': <NEW_LINE> <INDENT> feature_list.append([np.log(cluster._get_mean_open()), np.log(cluster._get_mean_shut())]) <NEW_LINE> <DEDENT> elif dat... | Cluster the clusters in the cluster list based on the method. | 625941f20383005118ecfbbf |
@SkipUnless(shelf2_enabled) <NEW_LINE> def shelve_with_log_message(sbox): <NEW_LINE> <INDENT> sbox.build(empty=True) <NEW_LINE> was_cwd = os.getcwd() <NEW_LINE> os.chdir(sbox.wc_dir) <NEW_LINE> sbox.wc_dir = '' <NEW_LINE> sbox.simple_add_text('New file', 'f') <NEW_LINE> log_message = 'Log message for foo' <NEW_LINE> sv... | shelve with log message | 625941f21b99ca400220b093 |
def __send(self, cmd): <NEW_LINE> <INDENT> t0 = time.time() <NEW_LINE> while (time.time()-t0<self.__reconnectTimeout): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> buf = bytes(cmd, 'utf-8') <NEW_LINE> (_, writable, _) = select.select([], [self.__sock], [], DEFAULT_TIMEOUT) <NEW_LINE> if len(writable): <NEW_LINE> <INDEN... | Send command to Robot Controller.
Input parameters:
cmd (str)
Return value:
success (boolean) | 625941f245492302aab5e8a9 |
def Test(self,para={}): <NEW_LINE> <INDENT> optId = 24000 | 测试方法 | 625941f2ad47b63b2c50a55f |
def fill_model(data: List[str], fields: dict, model: "mongo model") -> "mongo model": <NEW_LINE> <INDENT> new_data = {k: data[i] for k, i in fields.items()} <NEW_LINE> for item in new_data.values(): <NEW_LINE> <INDENT> if item: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return <NEW... | Populates a mongo model with SQL query data according to a key map | 625941f20383005118ecfbc0 |
def get_cleave_method(method_string): <NEW_LINE> <INDENT> if method_string == 'seeded-mst': <NEW_LINE> <INDENT> return seeded_mst, False <NEW_LINE> <DEDENT> if method_string == 'seeded-watershed': <NEW_LINE> <INDENT> return edge_weighted_watershed, False <NEW_LINE> <DEDENT> if method_string == 'agglomerative-clustering... | Given the name of a cleave method algorithm, return the function to
call for that algorithm, along with a bool indicating whether or not
the algorithm expects valid node sizes as input.
Returns (func, requires_sizes) | 625941f20fa83653e4657596 |
def _check_play_button(self, mouse_pos): <NEW_LINE> <INDENT> button_clicked = self.play_button.rect.collidepoint(mouse_pos) <NEW_LINE> if button_clicked and not self.stats.game_active: <NEW_LINE> <INDENT> self.settings.initialize_dynamic_settings() <NEW_LINE> pygame.mouse.set_visible(False) <NEW_LINE> self.stats.reset_... | Start a new game when the player clicks Play. | 625941f2099cdd3c635f1237 |
def cart_count(request): <NEW_LINE> <INDENT> if not request.session.has_key('islogin'): <NEW_LINE> <INDENT> return JsonResponse({'res':0}) <NEW_LINE> <DEDENT> conn = get_redis_connection('default') <NEW_LINE> cart_key = 'cart_%d' % request.session.get('passport_id') <NEW_LINE> res = 0 <NEW_LINE> res_list = conn.hyals(c... | 获取用户购物车中商品的数目 | 625941f2d486a94d0b98e726 |
def svg_transform_skewY(params): <NEW_LINE> <INDENT> angle = float(params[0]) * pi / 180 <NEW_LINE> m = Matrix(((1.0, 0, 0), (tan(angle), 1, 0), (0, 0, 1))).to_4x4() <NEW_LINE> return m | Returns a skewY matrix. | 625941f2e1aae11d1e74a29d |
def main_menu(con, screen_width, screen_height, background_image=None, background_color=None, title='Roguelike Game', author='Author', option_new='Play a new game', option_continue='Continue last game', option_quit='Quit', additional_options=None): <NEW_LINE> <INDENT> if background_image: <NEW_LINE> <INDENT> libtcod.im... | Display Main Menu to begin game
:param libtcod.console con: Console to draw menu on
:param int screen_width: Screen size
:param int screen_height: Screen size
:param background_image: Image to Display
:param background_color: Color to use if no image present
:param str title: Game Title text to display
:param str autho... | 625941f2d53ae8145f87a843 |
def __init__(self, parent, number): <NEW_LINE> <INDENT> assert isinstance(number, int) <NEW_LINE> super(BuildStep, self).__init__(parent, number) <NEW_LINE> self.number = number | It's already pre-loaded by definition since the data is retrieve via the
Build object. | 625941f2a934411ee3751c75 |
def __add__(self, other): <NEW_LINE> <INDENT> assert other.__name__() == 'Ctxt' <NEW_LINE> while self.L != other.L: <NEW_LINE> <INDENT> if self.L < other.L: <NEW_LINE> <INDENT> self.scaleDown() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> other.scaleDown() <NEW_LINE> <DEDENT> <DEDENT> modulus = 1 <NEW_LINE> for prime ... | Homomorphic addition.
Return a new Ctxt object with its ciphertext is c + c' = (c0 + c'0, c1 + c'1) | 625941f2e76e3b2f99f3ade1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.