code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def splitData(data, featureIndex): <NEW_LINE> <INDENT> attrValues = [point[featureIndex] for (point, label) in data] <NEW_LINE> for aValue in set(attrValues): <NEW_LINE> <INDENT> dataSubset = [(point, label) for (point, label) in data if point[featureIndex] == aValue] <NEW_LINE> yield dataSubset
Iterate over the subsets of data corresponding to each value of the feature at the index featureIndex.
625941ced268445f265b4f97
def test_create_client_with_no_service_name(self): <NEW_LINE> <INDENT> self.flags(catalog_info='volumev3::public', group='cinder') <NEW_LINE> with mock.patch('cinderclient.client.Client') as mock_client: <NEW_LINE> <INDENT> cinder.cinderclient(self.context) <NEW_LINE> <DEDENT> self.assertEqual(1, len(mock_client.call_a...
Tests that service_name is not required and not passed through when constructing the cinder client Client object if it's not configured.
625941ce6fb2d068a760f1c7
def __init__(self, instance_name_tags=None, vpc_name_tag=None, central_node_name_tag=None, boto3_profile='default', cpu_thresh=0.5, shutdown_cpu_thresh=0.005, cool_down_mins=5, lookback_mins=10, time_between_checks_mins=1): <NEW_LINE> <INDENT> self.session = boto3.Session(profile_name=boto3_profile) <NEW_LINE> self.ec2...
Control nodes based on CPU usage with the supplied parameters. **IMPORTANT** If specifying instance_name_tags, it is assumed the 0th index of this list is the cerntal node. If specifying vpc name tag, all instances are controlled and must specify the name tag of the central node. **The central node is never shutdown ...
625941ced4950a0f3b08c478
def clear_all_data(self): <NEW_LINE> <INDENT> lis = self.find_elements('.listDataTrFirstTd input') <NEW_LINE> self.wait_elem_disappear('.weui_mask_transparent') <NEW_LINE> if lis!=None and len(lis)>0: <NEW_LINE> <INDENT> for li in lis: <NEW_LINE> <INDENT> li.click() <NEW_LINE> <DEDENT> bt = ButtonPhonePage(self.driver)...
清空所有数据
625941ce293b9510aa2c33c0
def delete_existing_xls(xls_path): <NEW_LINE> <INDENT> if os.path.exists(xls_path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> log.debug("Removing XLS " + xls_path) <NEW_LINE> os.remove(xls_path) <NEW_LINE> <DEDENT> except WindowsError as e: <NEW_LINE> <INDENT> log.error("WindowsError: could not delete file") <NEW_LI...
:param xls_path: the name of the xls file to delete :type xls_path: basestring :raises WindowsError
625941cebe7bc26dc91cd729
def cut_file(fileName, posFlag, lFeatureTemplate, dBrand): <NEW_LINE> <INDENT> dir, name = os.path.splitext(fileName) <NEW_LINE> middle = '_pos' if posFlag else '' <NEW_LINE> writer = open( dir + middle + '.cut', 'w') <NEW_LINE> reader = open(fileName, 'rb') <NEW_LINE> reccnt = 0 <NEW_LINE> for line in reader: <NEW_LIN...
cut from file and output to filename.cut
625941ce046cf37aa974ce71
def generate_token(self, email, is_admin, user_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> payload = { 'exp': datetime.utcnow() + timedelta(minutes=60), 'iat': datetime.utcnow(), 'sub': email, 'user_id': user_id, 'role': is_admin } <NEW_LINE> return jwt.encode( payload, os.getenv('SECRET_KEY'), algorithm='HS256' ...
Generates the Auth Token for the currently logging in user :returns: string
625941cecb5e8a47e48b7bd4
def compare_version_strings(version_str1: str, version_str2: str, sep: str = ".", sep2: str = None) -> int: <NEW_LINE> <INDENT> versions_1 = [int(v) for v in version_str1.split(sep)] <NEW_LINE> versions_2 = [int(v) for v in version_str2.split(sep if not sep2 else sep2)] <NEW_LINE> versions_1 += [0] * max(0, len(version...
Compares two strings containing version strings. Version strings should be of the following format xxx[sep]yyyy[sep] ..., where (xxxx) and (yyyy) should be numbers, and a separator, which can be the default ".", or can be set for each version string separately. Running examples would be: compare_version_strings("2.0.1...
625941ce97e22403b379d0c3
def fields(self): <NEW_LINE> <INDENT> return ('title', 'service_url', 'parent_provider', 'scopes', 'contacts', 'monitored', 'host_name', 'created', 'modified', 'state')
hardcoded for a start - to be overwritten in the specific classes
625941ce23e79379d52ee68d
def read_corpora(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> corpora = self.databaseAdapter.get_db().corpus <NEW_LINE> for corpus_id in self.corpora_ids: <NEW_LINE> <INDENT> corpus = corpora.find_one({"_id": ObjectId(corpus_id)}) <NEW_LINE> self.corpora.append(Corpus(corpus_id, corpus["title"], corpus["contents...
Read in all corpora that are specified for a given transaction
625941ced8ef3951e3243667
def _init_graph(self, pants_ignore_patterns, build_ignore_patterns, exclude_target_regexps, target_specs, target_roots, workdir, graph_helper, subproject_build_roots): <NEW_LINE> <INDENT> if not graph_helper: <NEW_LINE> <INDENT> native = Native.create(self._global_options) <NEW_LINE> native.set_panic_handler() <NEW_LIN...
Determine the BuildGraph, AddressMapper and spec_roots for a given run. :param list pants_ignore_patterns: The pants ignore patterns from '--pants-ignore'. :param list build_ignore_patterns: The build ignore patterns from '--build-ignore', applied during BUILD file searching. :param ...
625941ce091ae35668667087
def setSourceUrl(self, sourceUrl): <NEW_LINE> <INDENT> self.sourceUrl = sourceUrl
:param sourceUrl: (Optional) 拉流地址 - 支持rtmp
625941ceec188e330fd5a8c8
def read_bitcoin_config(dbdir): <NEW_LINE> <INDENT> from ConfigParser import SafeConfigParser <NEW_LINE> class FakeSecHead(object): <NEW_LINE> <INDENT> def __init__(self, fp): <NEW_LINE> <INDENT> self.fp = fp <NEW_LINE> self.sechead = '[all]\n' <NEW_LINE> <DEDENT> def readline(self): <NEW_LINE> <INDENT> if self.sechead...
Read the blockwage.conf file from dbdir, returns dictionary of settings
625941ce50485f2cf553cec3
def refresh_history(self): <NEW_LINE> <INDENT> old_funcs = [] <NEW_LINE> for key in self.func_data: <NEW_LINE> <INDENT> old_funcs.append(key) <NEW_LINE> <DEDENT> old_vars = [] <NEW_LINE> for key in self.var_data: <NEW_LINE> <INDENT> old_vars.append(key) <NEW_LINE> <DEDENT> self.OptimizationHistory() <NEW_LINE> new_func...
Refresh opt_his data if the history file has been updated.
625941cef7d966606f6aa12e
def __init__(self): <NEW_LINE> <INDENT> self.screen_width = 1200 <NEW_LINE> self.screen_height = 800 <NEW_LINE> self.bg_color = (230,230,230) <NEW_LINE> self.ship_speed = 1.5 <NEW_LINE> self.ship_limit = 3 <NEW_LINE> self.bullet_speed = 1.5 <NEW_LINE> self.bullet_width = 3 <NEW_LINE> self.bullet_height = 15 <NEW_LINE> ...
Static game settings
625941ceb830903b967e9a34
def block(self, block_size, axis=None, coords_policy="first", **kws): <NEW_LINE> <INDENT> self._raise_if_scalar() <NEW_LINE> axis = self._wrap_axis(axis) <NEW_LINE> dim = self.dims[axis] <NEW_LINE> check_kws = dict( mom_dims=None, dims=None, attrs=None, coords=None, indexes=None ) <NEW_LINE> if coords_policy in ["first...
block average along an axis Parameters ---------- block_size : int size of blocks to average over axis : str or int, default=0 axis/dimension to block average over args : tuple positional arguments to CentralMomentsBase.block coords_policy : {'first','last',None} Policy for handling coordinates along `...
625941ce3539df3088e2e474
def _get_disk_size(self): <NEW_LINE> <INDENT> with self.allocate() as docker: <NEW_LINE> <INDENT> for field in docker.info()['DriverStatus']: <NEW_LINE> <INDENT> if field[0]=='Data Space Used': <NEW_LINE> <INDENT> return parse_size(field[1]) <NEW_LINE> <DEDENT> <DEDENT> logging.error('"Data Space Used" field was not fo...
Returns data used by Docker in bytes.
625941ce498bea3a759b9bd8
def missing_check_code(self, field, depth, input_map, cmv, metric): <NEW_LINE> <INDENT> code = u"%sif (%s is None):\n" % (INDENT * depth, map_data(self.fields[field]['slug'], input_map, True)) <NEW_LINE> value = value_to_print(self.output, self.fields[self.objective_id]['optype']) <NEW_LINE> code += u"%sr...
Builds the code to predict when the field is missing
625941ce29b78933be1e57d5
def acc_settings(self): <NEW_LINE> <INDENT> user_manager = UserManager() <NEW_LINE> acc = AccSetiingsDialog(self.user, parent=self) <NEW_LINE> dialog = acc.exec() <NEW_LINE> if dialog == QtWidgets.QDialog.Accepted: <NEW_LINE> <INDENT> user_manager.create_avatar(acc.fname['fname'], self.user) <NEW_LINE> self.set_avatar(...
Параметры аккаунта
625941ce7cff6e4e81117aaf
def perms(string): <NEW_LINE> <INDENT> if len(string) == 1 and is_regex(string) == True: <NEW_LINE> <INDENT> return {string} <NEW_LINE> <DEDENT> if len(string) < 1: <NEW_LINE> <INDENT> return {string} <NEW_LINE> <DEDENT> final, things_changed, first_word = list(), perms(string[1:]), string[0] <NEW_LINE> for changes in ...
(str) -> set REQ: length of string is greater than 0 >>> perms('ap') {'pa', 'ap'} >>> perms('zain') {'niza', 'izan', 'inaz', 'aniz', 'nzai', 'izna', 'ainz', 'zian', 'znia', 'anzi', 'azni', 'azin', 'naiz', 'znai', 'iazn', 'inza', 'nzia', 'nazi', 'zina', 'zani', 'niaz', 'ianz', 'zain', 'aizn'} >>> perms('ok') {'ok', '...
625941ce956e5f7376d70f97
def DescribeFirmwareTaskDistribution(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> params = request._serialize() <NEW_LINE> body = self.call("DescribeFirmwareTaskDistribution", params) <NEW_LINE> response = json.loads(body) <NEW_LINE> if "Error" not in response["Response"]: <NEW_LINE> <INDENT> model = mo...
本接口用于查询固件升级任务状态分布 :param request: Request instance for DescribeFirmwareTaskDistribution. :type request: :class:`tencentcloud.iotvideo.v20201215.models.DescribeFirmwareTaskDistributionRequest` :rtype: :class:`tencentcloud.iotvideo.v20201215.models.DescribeFirmwareTaskDistributionResponse`
625941ce60cbc95b062c666d
def observeState(self, gameState): <NEW_LINE> <INDENT> pacmanPosition = gameState.getPacmanPosition() <NEW_LINE> noisyDistances = gameState.getNoisyGhostDistances() <NEW_LINE> if len(noisyDistances) < self.numGhosts: return <NEW_LINE> emissionModels = [busters.getObservationDistribution(dist) for dist in noisyDistances...
Resamples the set of particles using the likelihood of the noisy observations. As in elapseTime, to loop over the ghosts, use: for i in range(self.numGhosts): ... A correct implementation will handle two special cases: 1) When a ghost is captured by Pacman, all particles should be updated so that the gh...
625941ce71ff763f4b5497b5
def parse(self, html): <NEW_LINE> <INDENT> self.downloads_have_occured = False <NEW_LINE> self.unstoppable = True <NEW_LINE> html = self.crash_prevention(html) <NEW_LINE> self.tk.call(self._w, "parse", html) <NEW_LINE> self.setup_widgets() <NEW_LINE> if not self.downloads_have_occured: <NEW_LINE> <INDENT> self.done_loa...
Parse HTML code
625941ce73bcbd0ca4b2c1a0
def resizeEvent(self, event): <NEW_LINE> <INDENT> if self._pixmap: <NEW_LINE> <INDENT> scaled_pixmap = self._scale_pixmap(self._pixmap) <NEW_LINE> self._scaled_width = scaled_pixmap.width() <NEW_LINE> super(ImageWidget, self).setPixmap(scaled_pixmap) <NEW_LINE> self._update_btn_position() <NEW_LINE> <DEDENT> super(Imag...
Override the default implementation to resize the pixmap while preserving its aspect ratio. :param event: The resize event object. :type event: :class:`~PySide.QtGui.QResizeEvent`
625941cea934411ee37517bd
def has_object_write_permission(self, request): <NEW_LINE> <INDENT> if hasattr(self, "subscription"): <NEW_LINE> <INDENT> return self.subscription.has_object_write_permission(request) <NEW_LINE> <DEDENT> return True
Check if the requesting user has write permissions on the instance. Args: request: The request to check permissions for. Returns: A boolean indicating if the requesting user has write permissions to the instance.
625941ce4d74a7450ccd42ed
def test_transform_conditional(self): <NEW_LINE> <INDENT> portal = self.layer['portal'] <NEW_LINE> import os <NEW_LINE> file_contents = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'input2.odt')).read() <NEW_LINE> pt = portal.portal_transforms <NEW_LINE> converter = pt.convertTo(target_mimetype='applic...
We have an input file with a conditional text (with comments)
625941ce5f7d997b87174bc2
def spiralOrder_(self, matrix): <NEW_LINE> <INDENT> if matrix == None or len(matrix) < 1: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> rows = len(matrix) <NEW_LINE> columns = len(matrix[0]) <NEW_LINE> if rows == 1: <NEW_LINE> <INDENT> return matrix[0] <NEW_LINE> <DEDENT> res = [] <NEW_LINE> if columns == 1: <NEW_L...
:type matrix: List[List[int]] :rtype: List[int]
625941ce4428ac0f6e5ba91c
def run_data(d, box_num): <NEW_LINE> <INDENT> path0 = 'E:/' + box_num + '/' <NEW_LINE> output_path = 'Y:/' + box_num + '/' + d.strftime("%Y_%m") + '/' <NEW_LINE> if not os.path.exists(output_path): <NEW_LINE> <INDENT> os.makedirs(output_path) <NEW_LINE> <DEDENT> output_file = output_path + 'ts_' + d.strftime("%d") <NEW...
for a given day and box, create npz files for each bgo timestamps and hist the data in 2ms timebins
625941ced268445f265b4f98
def palindrome(self, s): <NEW_LINE> <INDENT> rlt = 0 <NEW_LINE> n = len(s) <NEW_LINE> dp = [[0] * n for _ in range(n)] <NEW_LINE> visited = set() <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> for j in range(i + 1): <NEW_LINE> <INDENT> curStr = s[j: i + 1] <NEW_LINE> if i == j or (i == j + 1 and s[i] == s[j]) or (dp...
LC 647 变种 DP, 从j到i的子串做出二维DP 需要找到 unique substring,记得用 set 去除得到 unique string https://leetcode.com/problems/palindromic-substrings/
625941cedd821e528d63b2d2
def is_first_fix_any(bzapi, flaw_bug, current_target_release): <NEW_LINE> <INDENT> if current_target_release[-1] != '0': <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> tracker_ids = flaw_bug.depends_on <NEW_LINE> if not tracker_ids: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> tracker_bugs = [b for b in bza...
Check if a flaw bug is considered a first-fix for a GA target release for any of its trackers components. A return value of True means it should be attached to an advisory.
625941ce566aa707497f4692
def label(boundary, should_invert=False, param_boundaries=[[0.0, 20.0], [0,1.0]], epsilon=0.01, num_points=200, lipschitz_param=0.05): <NEW_LINE> <INDENT> if should_invert: <NEW_LINE> <INDENT> my_boundary = utils.invert(boundary, param_boundaries) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> my_boundary = boundary <NE...
Takes a boundary, and returns its proper label, which is True or False. Correct implementation will depend on context, and in the extreme case will require computation done by the human.
625941ce5e10d32532c5f050
def _filter_files(self, src, pattern, links, excludes, ignore_case): <NEW_LINE> <INDENT> filenames = [] <NEW_LINE> linked_folders = [] <NEW_LINE> for root, subfolders, files in os.walk(src, followlinks=True): <NEW_LINE> <INDENT> if root in self._excluded: <NEW_LINE> <INDENT> subfolders[:] = [] <NEW_LINE> continue <NEW_...
return a list of the files matching the patterns The list will be relative path names wrt to the root src folder
625941ceb830903b967e9a35
def IBBMessageHandler(self, conn, stanza): <NEW_LINE> <INDENT> sid = stanza.getTagAttr('data', 'sid') <NEW_LINE> seq = stanza.getTagAttr('data', 'seq') <NEW_LINE> data = stanza.getTagData('data') <NEW_LINE> log.debug('ReceiveHandler called sid->%s seq->%s' % (sid, seq)) <NEW_LINE> try: <NEW_LINE> <INDENT> seq = int(seq...
Receive next portion of incoming datastream and store it write it to temporary file. Used internally.
625941ced486a94d0b98e26f
def __setattr__(self, name, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.__class__._valid[name](value) <NEW_LINE> super(self.__class__, self).__setattr__(name, value) <NEW_LINE> <DEDENT> except (KeyError, ValueError) as e: <NEW_LINE> <INDENT> logging.error(e)
Set an attribute value after checking validity. :param name: attribute name :param value: desired attribute value :raises ValueError: if attribute value is invalid
625941ceff9c53063f47c31d
def _create_blockdevice_id_for_test(dataset_id): <NEW_LINE> <INDENT> return "blockdevice-" + unicode(dataset_id)
Generates a blockdevice_id from a dataset_id for tests that do not use an ``IBlockDeviceAPI``. :param dataset_id: A unicode or uuid dataset_id to generate the blockdevice_id for.
625941ce50485f2cf553cec4
def pic_2d(coef,set,sol): <NEW_LINE> <INDENT> x_sub_axis = numpy.arange(0, coef['X']+set['Hh'], set['h']) <NEW_LINE> y_sub_axis = numpy.arange(0, coef['Y']+set['Hh'], set['h']) <NEW_LINE> x_sub_axis, y_sub_axis = numpy.meshgrid(x_sub_axis, y_sub_axis) <NEW_LINE> c_sol = numpy.zeros((set['Nx']/2+1, set['Ny']/2+1)) <NEW_...
Record for ecm, vegf
625941ce004d5f362079a45d
def get_guessed_word(secret_word, letters_guessed): <NEW_LINE> <INDENT> displayed_word = "" <NEW_LINE> for letter in secret_word: <NEW_LINE> <INDENT> index = letters_guessed.find(letter) <NEW_LINE> if(index < 0): <NEW_LINE> <INDENT> displayed_word = displayed_word + "_" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dis...
secretWord: string, the random word the user is trying to guess. This is selected on line 9. lettersGuessed: list of letters that have been guessed so far. returns: string, of letters and underscores. For letters in the word that the user has guessed correctly, the string should contain the letter at the correct posi...
625941ce498bea3a759b9bd9
def interesting_oper(op): <NEW_LINE> <INDENT> return op.is_a(lal.OpAnd, lal.OpOr, lal.OpAndThen, lal.OpOrElse, lal.OpXor)
Check that op is a relational operator, which are the operators that interrest us in the context of this script. :rtype: bool
625941ce45492302aab5e3ed
def test_user_id_is_error(self): <NEW_LINE> <INDENT> add_black_user_api = AddBlackUserApi(self.anchor_login_name) <NEW_LINE> add_black_user_api.get({'user_id': self.user_id + '333333', 'anchor_id': self.anchor_id, 'blacker_type': 'forbid_visit'}) <NEW_LINE> self.assertEqual(add_black_user_api.get_code(),801027) <NEW_LI...
测试请求接口用户ID错误 :return:
625941ce167d2b6e31218cc0
def _populate_participated_offers(request): <NEW_LINE> <INDENT> return Offer.objects.filter(volunteers=request.user)
Populate offers that current user participate.
625941ce6e29344779a6273c
def to_string(self, a_dict): <NEW_LINE> <INDENT> names = [key for key in a_dict.keys()] <NEW_LINE> names.sort() <NEW_LINE> rows = ['<tr %s><td %s>%s</td><td %s>%s</td></tr>' % (DictConverter.TR_CLASS, DictConverter.TD_KEY_CLASS, to_string(name), DictConverter.TD_VALUE_CLASS, to_string(a_dict.get(name))) ...
Generate a str value in the fitnesse HashMarkupTable format from a dict of typed name,value pairs
625941ce2c8b7c6e89b358ea
def get_url( endpoint_or_url: t.Optional[str], qparams: t.Optional[t.Dict[str, str]] = None ) -> t.Optional[str]: <NEW_LINE> <INDENT> if not endpoint_or_url: <NEW_LINE> <INDENT> return endpoint_or_url <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return transform_url(url_for(endpoint_or_url), qparams) <NEW_LINE> <DEDENT...
Returns a URL if a valid endpoint is found. Otherwise, returns the provided value. :param endpoint_or_url: The endpoint name or URL to default to :param qparams: additional query params to add to end of url :return: URL
625941ce377c676e912722d2
def distSq(el2, el1): <NEW_LINE> <INDENT> sum_ = 0 <NEW_LINE> for i in range(len(el1)): <NEW_LINE> <INDENT> sum_ += (el1[i] - el2[i])**2 <NEW_LINE> <DEDENT> return sum_
Computes the euclidean distance between two given tuples of same dimension
625941ced164cc6175782e78
@app.route('/application') <NEW_LINE> def application(): <NEW_LINE> <INDENT> return flask.send_file(pkg_resources.resource_stream(PACKAGE, 'static/carrie.apk'), attachment_filename='carrie.apk', as_attachment=True, mimetype='application/vnd.android.package-archive')
Return the Android application
625941ce5e10d32532c5f051
def find_common_parent(merge_commit): <NEW_LINE> <INDENT> if len(merge_commit.parents) == 1: <NEW_LINE> <INDENT> return merge_commit.parents[0] <NEW_LINE> <DEDENT> parentA = merge_commit.parents[0] <NEW_LINE> parentB = merge_commit.parents[1] <NEW_LINE> while parentA != parentB: <NEW_LINE> <INDENT> if parentA.committed...
find_common_parent given a merge commit object, this function will grab the two parents of that merge commit and find a common parent for them -- the commit at which the line of work originally branched into two lines of work. That common parent commit object will be returned.
625941ce96565a6dacc8f7f5
def test_TwoTonPage_read(self): <NEW_LINE> <INDENT> two_ton_page = TwoTonPage(mocked=True) <NEW_LINE> assert two_ton_page is not None <NEW_LINE> status = two_ton_page.fetch_taplist(brewery='Two Ton') <NEW_LINE> assert not status
Test that we can do basic read of page
625941ce8a43f66fc4b5418f
def forward(cell, hostports, tktfwd_spn=None): <NEW_LINE> <INDENT> failure = 0 <NEW_LINE> for idx, hostport in enumerate(hostports): <NEW_LINE> <INDENT> host, port = hostport <NEW_LINE> _LOGGER.info( 'Forwarding tickets to cell: %s/%d - %s:%s', cell, idx, host, port ) <NEW_LINE> purge = bool(os.name == 'nt' and idx == ...
Forward tickets to several ticket lockers.
625941ce2eb69b55b151c9d9
def calculate_uVu(self, npoints=1000): <NEW_LINE> <INDENT> x = np.linspace(0, self.radius, npoints) <NEW_LINE> uVu = np.zeros(len(self.LM)) <NEW_LINE> lm_index = 0 <NEW_LINE> for l in self.L: <NEW_LINE> <INDENT> uVuL = 4*np.pi*simps(self.psi(l,x)*self.vnl(l,x)*x**2 / (2*l+1), x) <NEW_LINE> for lm in xrange(l**2, (l+1)*...
Redundancy is used here to allow for numpy array operations instead of python loops in application of non-local pseudopotential. A typical radius is < 1 Angstrom so 1000 points should always be sufficiently accurate
625941ce30c21e258bdfa5c8
def perform(self, event): <NEW_LINE> <INDENT> callable = self.metadata.get_callable() <NEW_LINE> obj = callable() <NEW_LINE> mv = self.mayavi <NEW_LINE> mv.add_module(obj) <NEW_LINE> mv.engine.current_selection = obj
Performs the action.
625941cefbf16365ca6f62ef
def word_process(self): <NEW_LINE> <INDENT> for i in range(len(self.word)): <NEW_LINE> <INDENT> self.letter_list.append(self.word[i]) <NEW_LINE> <DEDENT> for letter in self.word: <NEW_LINE> <INDENT> if letter != " ": <NEW_LINE> <INDENT> self.dashes = self.dashes + '_' <NEW_LINE> self.dashes = self.dashes + ' ' <NEW_LIN...
Create dashes from len(word).
625941ce2ae34c7f2600d25b
def getFileList(self): <NEW_LINE> <INDENT> return glob.glob(os.path.join(self.gridFolder, self.fluxFilesFilter))
List all model files available in grid
625941ce31939e2706e4cf94
def define_gradient_routine_numerical(self): <NEW_LINE> <INDENT> calculate_e = self.define_energy_routine() <NEW_LINE> def calculate_grad(): <NEW_LINE> <INDENT> gradient = np.zeros([len(self),3]) <NEW_LINE> for i in range(len(self)): <NEW_LINE> <INDENT> ipos = self.posList[i] <NEW_LINE> ipos += vdx <NEW_LINE> vPlusX = ...
Return the function that would calculate the gradients (negative forces) of the atoms in the molecule instance.
625941cee76e3b2f99f3a935
def get_tvm_output(graph_def): <NEW_LINE> <INDENT> sym, params = nnvm.frontend.from_tensorflow(graph_def) <NEW_LINE> target = 'llvm' <NEW_LINE> batch_size = 1 <NEW_LINE> num_hidden=2 <NEW_LINE> num_layers=1 <NEW_LINE> input_size = 2 <NEW_LINE> out_shape = (1, 2) <NEW_LINE> out_state_shape=(2, 1, 2) <NEW_LINE> shape_dic...
Compute TVM output
625941ceb545ff76a8913f40
def _create_rest_url(host, version, sid, category, resource, subcategory=None, query_id=None, second_query_id=None, options=None): <NEW_LINE> <INDENT> url = ('/'.join([host, 'webservices/rest', version, category ])) <NEW_LINE> if query_id is not None: <NEW_LINE> <INDENT> url += '/' + query_id <NEW_LINE> <DEDENT> if sub...
Creates the URL for querying the REST service
625941ce8c0ade5d55d3eae5
def levenshtein_analysis(self, field_weights=None): <NEW_LINE> <INDENT> if field_weights is None: <NEW_LINE> <INDENT> if not isinstance(self.field_weights, dict): <NEW_LINE> <INDENT> raise ValueError('Expected a dict for `field_weights` parameter, ' 'got {}'.format(type(self.field_weights))) <NEW_LINE> <DEDENT> <DEDENT...
Updates the status of the file clusters comparing the cluster key files with a levenshtein weighted measure using either the header_fields or self.header_fields. Parameters ---------- field_weights: dict of strings with floats A dict with header field names to float scalar values, that indicate a distance measure ...
625941cefff4ab517eb2f566
def print_message(message, snippet=True): <NEW_LINE> <INDENT> if snippet: <NEW_LINE> <INDENT> print("{}\nMESSAGE ID: {}\nSnippet: {}\n{}".format('#'*len(message['snippet']), message['id'], message['snippet'], '#'*len(message['snippet']))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> message_parts = scraper.message_to_...
Prints a Gmail Message to the terminal :param dict message: Gmail message formatted from JSON format into a Python dict :param bool snippet: Flag to indicate whether we should print a snippet of the message or the whole thing. On by default. :return: Nothing
625941ce92d797404e3042b4
def test_on_created(self): <NEW_LINE> <INDENT> filename = 'file.txt' <NEW_LINE> src_filepath = os.path.join(TEST_SHARING_FOLDER, filename) <NEW_LINE> content = 'content of file' <NEW_LINE> content_md5 = hashlib.md5(content).hexdigest() <NEW_LINE> received_data = {'filepath': filename, 'md5': content_md5} <NEW_LINE> wit...
" Test EVENTS: test on created event of watchdog, expect a upload requests
625941ce2eb69b55b151c9da
def _traverse_graph(self, root_task_id, seen=None, dep_func=None, include_done=True): <NEW_LINE> <INDENT> if seen is None: <NEW_LINE> <INDENT> seen = set() <NEW_LINE> <DEDENT> elif root_task_id in seen: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> if dep_func is None: <NEW_LINE> <INDENT> def dep_func(t): <NEW_LINE...
Returns the dependency graph rooted at task_id This does a breadth-first traversal to find the nodes closest to the root before hitting the scheduler.max_graph_nodes limit. :param root_task_id: the id of the graph's root :return: A map of task id to serialized node
625941ce8c0ade5d55d3eae6
@njit(parallel=True) <NEW_LINE> def quadratic_small_planet_zp(z, k, ldc): <NEW_LINE> <INDENT> npt = z.size <NEW_LINE> npv = k.size <NEW_LINE> bs = zeros(npt) <NEW_LINE> mus = zeros(npt) <NEW_LINE> for ipt in range(npt): <NEW_LINE> <INDENT> bs[ipt] = abs(z[ipt]) <NEW_LINE> mus[ipt] = sqrt(1. - min(bs[ipt]**2, 1.0)) <NEW...
Small planet approximation with quadratic limb darkening. Parallelised transit model using the small-planet approximation as a function of normalized planet-star separation. The function is meant to be used to evaluate the model for npv radius ratios and limb darkening coefficients in parallel, where npv should be r...
625941ce1b99ca400220abdc
def display(self): <NEW_LINE> <INDENT> num_sources = self.options.handler.options_dict['sources'] <NEW_LINE> num_citations = self.options.handler.options_dict['citations'] <NEW_LINE> dialog = Gtk.Dialog("Populate sources and citations tool", self.uistate.window, Gtk.DialogFlags.MODAL|Gtk.DialogFlags.DESTROY_WITH_PARENT...
Constructs the GUI, consisting of a message, and fields to enter the required number of sources and citations
625941ce0a50d4780f666fbd
def servicedelegationrule_add_target( self, a_cn, o_all=True, o_raw=False, o_no_members=False, o_servicedelegationtarget=None, **kwargs ): <NEW_LINE> <INDENT> method = 'servicedelegationrule_add_target' <NEW_LINE> _args = list() <NEW_LINE> _args.append(a_cn) <NEW_LINE> _params = dict() <NEW_LINE> _params['all'] = o_all...
Add target to a named service delegation rule. :param a_cn: Delegation name :type a_cn: str :param o_all: Retrieve and print all attributes from the server. Affects command output. :type o_all: bool :param o_raw: Print entries as stored on the server. Only affects output format. :type o_raw: bool :param o_...
625941cebe7bc26dc91cd72a
def update_comp_config( self ): <NEW_LINE> <INDENT> pass
Update the configurations for this component.
625941ceab23a570cc2502ad
def __init__(self, timestamp, fields): <NEW_LINE> <INDENT> self.timestamp = timestamp <NEW_LINE> self.fields = fields
Construct Span Log. @param timestamp: Timestamp of the span log. @param fields: Fields of the span log.
625941cead47b63b2c50a0aa
def __onHideDecors(self): <NEW_LINE> <INDENT> Settings()['hidedecors'] = not Settings()['hidedecors']
Triggered when a hide decorators button is pressed
625941ce287bf620b61d3b8e
def onOpen(self, ws): <NEW_LINE> <INDENT> self.logger.info('Connect success Roomid:{0}.'.format(self.roomid))
The callback func when ws occur open.
625941ce4a966d76dd55113a
def mean_riders_for_max_station(ridership): <NEW_LINE> <INDENT> max_rider = ridership['R006'].mean() <NEW_LINE> print(max_rider) <NEW_LINE> overall_mean = ridership.values.mean() <NEW_LINE> mean_for_max = ridership['R006'].mean() <NEW_LINE> return (overall_mean, mean_for_max)
Fill in this function to find the station with the maximum riders on the first day, then return the mean riders per day for that station. Also return the mean ridership overall for comparsion. This is the same as a previous exercise, but this time the input is a Pandas DataFrame rather than a 2D NumPy array.
625941cecad5886f8bd27104
def get_model_info(self): <NEW_LINE> <INDENT> info = {} <NEW_LINE> if self.model.input is not None: <NEW_LINE> <INDENT> info['in'] = { 'name': self.model.input.name, 'shape': dim_to_json(self.model.input.shape) } <NEW_LINE> <DEDENT> if self.model.output is not None: <NEW_LINE> <INDENT> info['out'] = { 'name': self.mode...
Returns information about inputs and outputs of the model
625941ce6fece00bbac2d869
def get_trading_dates(self, start, end, code=None, underlying=None): <NEW_LINE> <INDENT> if isinstance(start, str): <NEW_LINE> <INDENT> start = parser.parse(start) <NEW_LINE> <DEDENT> if isinstance(end, str): <NEW_LINE> <INDENT> end = parser.parse(end) <NEW_LINE> <DEDENT> start = start.replace(hour=0, minute=0, second=...
填写code或者underlying参数,优先使用code :param start: :param end: :param code: :param underlying: :return:
625941ce67a9b606de4a7fe4
def place(self, node): <NEW_LINE> <INDENT> if self.prob == None: <NEW_LINE> <INDENT> self.solve() <NEW_LINE> <DEDENT> place = self.prob.solution.node_info(node) <NEW_LINE> return place
Returns physical placement of the node node: node in the virtual topology return: name of the physical host to use
625941cea8ecb033257d31f7
def deliver(self, payload): <NEW_LINE> <INDENT> payload = msgpack.unpackb(payload, raw=False, use_list=False) <NEW_LINE> return self._monitor._q.put(payload)
MQTT doesn't have dedicated channels. Call this to inject all payloads destined for this transport's topic.
625941ce4c3428357757c452
def avail_sizes(call=None): <NEW_LINE> <INDENT> if call == 'action': <NEW_LINE> <INDENT> raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option' ) <NEW_LINE> <DEDENT> global compconn <NEW_LINE> if not compconn: <NEW_LINE> <INDENT> compconn = get_con...
Return a list of sizes from Azure
625941cecdde0d52a9e5315e
def set_state_category(self): <NEW_LINE> <INDENT> self.set_color('color_idle') <NEW_LINE> self.BtnEnd.setEnabled(False) <NEW_LINE> self.BtnNew.setEnabled(True) <NEW_LINE> self.BtnTrue.setEnabled(False) <NEW_LINE> self.BtnFalse.setEnabled(False) <NEW_LINE> self.BtnNext.setEnabled(True) <NEW_LINE> self.BtnTimer.setEnable...
sets controls states when Category Selected :return:
625941ce4428ac0f6e5ba91d
def run(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> logs_generator = self.container.logs( stream=True, stdout=self.stdout, stderr=self.stderr ) <NEW_LINE> for line in logs_generator: <NEW_LINE> <INDENT> if self.encoding is not None and isinstance(line, bytes): <NEW_LINE> <INDENT> line = line.decode(self.encodin...
Tail the container logs as a separate thread.
625941cebd1bec0571d9075a
def test_09_Scratches(self): <NEW_LINE> <INDENT> targets = {"scratch/scratch-simulator": "scratch-simulator", "scratch/scratch-simulator.cc": "scratch-simulator", "scratch-simulator": "scratch-simulator", "scratch/subdir/scratch-simulator-subdir": "subdir_scratch-simulator-subdir", "subdir/scratch-simulator-subdir": "s...
! Tries to build scratch-simulator and subdir/scratch-simulator-subdir @return None
625941cebe8e80087fb20d6d
def zGetOperandRow(self, row): <NEW_LINE> <INDENT> operData = [] <NEW_LINE> for i in range(1,8): <NEW_LINE> <INDENT> operData.append(self.zGetOperand(row=row, column=i)) <NEW_LINE> <DEDENT> for i in range(12, 14): <NEW_LINE> <INDENT> operData.append(self.zGetOperand(row=row, column=i)) <NEW_LINE> <DEDENT> for i in rang...
Returns a row of the Multi Function Editor Parameters ---------- row : integer the operand row number Returns ------- opertype : string operand type, column 1 in MFE int1 : integer column 2 in MFE int2 : integer column 3 in MFE data1 : float column 4 in MFE data2 : float column 5 in MFE data3 ...
625941ce3346ee7daa2b2e96
def createissuewallnote(self, project_id, issue_id, content): <NEW_LINE> <INDENT> data = {"body": content} <NEW_LINE> request = requests.post("{0}/{1}/issues/{2}/notes".format(self.projects_url, project_id, issue_id), verify=self.verify_ssl, headers=self.headers, data=data) <NEW_LINE> if request.status_code == 201: <NE...
Create a new note
625941ce26238365f5f0ef99
def read_text(text): <NEW_LINE> <INDENT> list_of_words = text.split() <NEW_LINE> list_of_dicts = [{'Preceding Word' : ''}] <NEW_LINE> preceding_word = '' <NEW_LINE> should_add = True <NEW_LINE> for word in list_of_words: <NEW_LINE> <INDENT> for curr_dict in list_of_dicts: <NEW_LINE> <INDENT> if curr_dict['Preceding Wor...
Generates archive based on text.
625941ce4e4d5625662d4502
def diff_mtime_map(map1, map2): <NEW_LINE> <INDENT> if cmp(sorted(map1), sorted(map2)) != 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
Is there a change to the mtime map? return a boolean
625941ce56b00c62f0f14784
def cantidad_avonada(persona, concepto, evento=None): <NEW_LINE> <INDENT> db = current.db <NEW_LINE> sum = db.pago.cantidad.sum() <NEW_LINE> query = (db.pago.persona_id == persona.id) <NEW_LINE> query &= (db.pago.tipo_pago_id == concepto.id) <NEW_LINE> if evento is not None: <NEW_LINE> <INDENT> query &= (db.pago.evento...
Dado el id de una persona calcula la suma total de sus pago dado un concepto
625941ce32920d7e50b282fb
def tearpage(filename, startpage=0, lastpage=0): <NEW_LINE> <INDENT> with tempfile.NamedTemporaryFile() as tmp: <NEW_LINE> <INDENT> shutil.copy(filename, tmp.name) <NEW_LINE> try: <NEW_LINE> <INDENT> input_file = PdfFileReader(open(tmp.name, 'rb')) <NEW_LINE> <DEDENT> except PdfReadError: <NEW_LINE> <INDENT> fixPdf(fil...
Copy filename to a tempfile, write pages startpage..N to filename. :param filename: PDF filepath :param startpage: number of pages to delete from the cover :param lastpage: number of pages to delete from the bacl
625941ced7e4931a7ee9e049
def take_nd( self, indexer, axis: int = 0, new_mgr_locs=None, fill_value=lib.no_default ): <NEW_LINE> <INDENT> if fill_value is lib.no_default: <NEW_LINE> <INDENT> fill_value = None <NEW_LINE> <DEDENT> new_values = self.values.take(indexer, fill_value=fill_value, allow_fill=True) <NEW_LINE> assert not (self.ndim == 1 a...
Take values according to indexer and return them as a block.
625941ce30dc7b7665901a91
def project_absent(name, profile=None, **connection_args): <NEW_LINE> <INDENT> return tenant_absent(name, profile=profile, **connection_args)
Ensure that the keystone project is absent. Alias for tenant_absent from V2 API to fulfill V3 API naming convention. .. versionadded:: Carbon name The name of the project that should not exist .. code-block:: yaml delete_nova: keystone.project_absent: - name: nova
625941cef8510a7c17cf9828
def show_engineer_table(filer_by='break_chance'): <NEW_LINE> <INDENT> machine_data = db_call_machine_state() <NEW_LINE> machines_list = [id for id in machine_data['id']] <NEW_LINE> ii_answer = ii_module.calculate_breakout(machines_list) <NEW_LINE> answer = [] <NEW_LINE> return answer
Отображает сводную таблицу инженера
625941ce8a349b6b435e829e
def set_min_output_buffer(self, *args): <NEW_LINE> <INDENT> return _blocks_swig5.tuntap_pdu_sptr_set_min_output_buffer(self, *args)
set_min_output_buffer(tuntap_pdu_sptr self, long min_output_buffer) set_min_output_buffer(tuntap_pdu_sptr self, int port, long min_output_buffer)
625941ce85dfad0860c3af86
def with_retries(f: Callable[[], Any], max_attempts: int = 3) -> Any: <NEW_LINE> <INDENT> for n in range(max_attempts + 1): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return f() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> if n < max_attempts: <NEW_LINE> <INDENT> logging.warning(f"Got an error, {n+1...
Runs a function with retries, using exponential backoff. For more information: https://developers.google.com/drive/api/v3/handle-errors?hl=pt-pt#exponential-backoff Args: f: A function that doesn't receive any input. max_attempts: The maximum number of attempts to run the function. Returns: The retur...
625941ce566aa707497f4693
def showEvent(self, event): <NEW_LINE> <INDENT> super(Notification, self).showEvent(event) <NEW_LINE> width, pgeo = self._parent.width() / 2, self._parent.geometry() <NEW_LINE> conditional_vertical = settings.NOTIFICATION_POSITION in (0, 1) <NEW_LINE> conditional_horizont = settings.NOTIFICATION_POSITION in (0, 2) <NEW...
Method takes an event to show the Notification
625941ce4a966d76dd55113b
def execute_sql(sql, params): <NEW_LINE> <INDENT> dsn_tns = oracle.makedsn(Config().get('oraclehost'), Config().get('oracleport'), Config().get('oraclesid')) <NEW_LINE> conn = oracle.connect(user=Config().get('oracleuser'), password=Config().get('oraclepassword'), dsn=dsn_tns) <NEW_LINE> cursor = conn.cursor() <NEW_LIN...
执行oracle sql语句 :param sql: sql语句,变量使用 :var或者:1,:2表示 :param params: 变量值,传入元祖 :return: query_result(查询结果),否则返回None
625941ce5510c4643540f50f
def atm_velocity(alt: float, mach: float, alt_units: str='ft', velocity_units: str='ft/s') -> float: <NEW_LINE> <INDENT> a = atm_speed_of_sound(alt, alt_units=alt_units, velocity_units=velocity_units) <NEW_LINE> V = mach * a <NEW_LINE> return V
Freestream Velocity \f$ V_{\infty} \f$ Parameters ---------- alt : float altitude in alt_units Mach : float Mach Number \f$ M \f$ alt_units : str; default='ft' the altitude units; ft, kft, m velocity_units : str; default='ft/s' the velocity units; ft/s, m/s, in/s, knots Returns ------- velocity : flo...
625941ce44b2445a339321c1
def test_04_createrepoupdate_simplemdfilenames(self): <NEW_LINE> <INDENT> self.assert_same_results(os.path.relpath(self.indir)) <NEW_LINE> self.assert_same_results(os.path.relpath(self.indir), "--update --simple-md-filenames")
Repo from empty directory - specified by relative path
625941ce3d592f4c4ed1d198
def copy_all_asset_metadata(self, source_course_key, dest_course_key, user_id): <NEW_LINE> <INDENT> for revision in [ModuleStoreEnum.RevisionOption.published_only, ModuleStoreEnum.RevisionOption.draft_only]: <NEW_LINE> <INDENT> super(DraftVersioningModuleStore, self).copy_all_asset_metadata( self._map_revision_to_branc...
Copies to and from both branches
625941ce656771135c3eb99a
def start(self) -> None: <NEW_LINE> <INDENT> self.command(b"\x02")
Send a start bit.
625941cec432627299f04d71
def APASS_R(magDict): <NEW_LINE> <INDENT> g_mag = np.array(magDict['g_mag']) <NEW_LINE> s_g_mag = np.array(magDict['e_g_mag']) <NEW_LINE> r_mag = np.array(magDict['r_mag']) <NEW_LINE> s_r_mag = np.array(magDict['e_r_mag']) <NEW_LINE> ga_ra = g_mag - r_mag <NEW_LINE> sig_ga_ra = np.sqrt(s_g_mag**2 + s_r_mag**2) ...
Computes the R-band magnitude from APASS sloan magnitudes
625941cee76e3b2f99f3a936
def call_send(*args): <NEW_LINE> <INDENT> raise ProcessCallNotDefined("call_send has not been defined!")
This function needs to be defined by the class that inherits this object.
625941ce01c39578d7e74f67
def attach_to_map(self, map_model): <NEW_LINE> <INDENT> pass
*Virtual.* Callback called when a map is initialized to be used with the camera. Typically, map-specific initialization is be done here. *map_model* is a handle to the MapModel, so that information such as the map size can be retrieved.
625941ce91f36d47f21ac61e
def prune(self): <NEW_LINE> <INDENT> for dirname, _dirnames, _filenames in os.walk(self.export_path): <NEW_LINE> <INDENT> if os.path.basename(dirname) == 'obsolete': <NEW_LINE> <INDENT> logger.info("Removing %s" % dirname) <NEW_LINE> shutil.rmtree(dirname)
Prunes unneeded code from the export prior to packaging
625941ce6fece00bbac2d86a
def p_closedProtoStmt(p): <NEW_LINE> <INDENT> add_node(p, 'closedProtoStmt')
closedProtoStmt : stmt | IF '(' simpleExpression ')' closedProtoStmt ELSE closedProtoStmt
625941ce24f1403a92600c91
def create_job_detail(company_name, job_title, application_deadline, job_listing_url, state, city, application_listed, salary): <NEW_LINE> <INDENT> job_detail = JobDetail(company_name = company_name, job_title = job_title, application_deadline = application_deadline, job_listing_url = job_listing_url, state = state , c...
Create and return Job Details
625941ce442bda511e8be543
def get_real_instance_class(self): <NEW_LINE> <INDENT> return ContentType.objects.get_for_id(self.polymorphic_ctype_id).model_class()
Normally not needed. If a non-polymorphic manager (like base_objects) has been used to retrieve objects, then the real class/type of these objects may be determined using this method.
625941ce7d43ff24873a2dcb
def generate_cosine_matrix_inferSent(): <NEW_LINE> <INDENT> print('%s, start' % (time.ctime())) <NEW_LINE> n_size = 108626 <NEW_LINE> n_dimension = 4096 <NEW_LINE> emb_matrix = np.zeros((n_size, 4096)) <NEW_LINE> inferSent_path = '%s/dataset.InferSent.vec' % (DIR_DATA_SET_TELLING) <NEW_LINE> with open(inferSent_path) a...
Due to the scale of inferSent matric, the efficient way to find the most similar sentence is matrix multiplication Reference: https://stackoverflow.com/questions/41905029/create-cosine-similarity-matrix-numpy?rq=1
625941ce167d2b6e31218cc1
def menu_for_operations(): <NEW_LINE> <INDENT> employee_data_save_object = EmployeeDataSaver() <NEW_LINE> try: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> choice = input('enter the choice for the \n 1: Enter the data for Emplpoyee \n 2: for printing \n 3: delete \n 4: Editing \n 5: exit \n') <NEW_LINE> if choi...
Definition of menu for operations method. Here we creating the object for the employee_data_saver
625941ce009cb60464c634dd