code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def benchmark_irnn_mnist_bs_256(self): <NEW_LINE> <INDENT> batch_size = 256 <NEW_LINE> metrics, wall_time, extras = benchmark_util.measure_performance( self._build_model, x=self.x_train, y=self.y_train, batch_size=batch_size, optimizer=tf.keras.optimizers.RMSprop(learning_rate=self.learning_rate), loss='categorical_crossentropy', metrics=['accuracy']) <NEW_LINE> self.report_benchmark(wall_time=wall_time, metrics=metrics, extras=extras)
Measure performance with batch_size=256.
625941b9d7e4931a7ee9dd96
def make_file_state(file_path, clear) -> None: <NEW_LINE> <INDENT> if clear: <NEW_LINE> <INDENT> main.remove_import_pdb(file_path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> main.put_import_pdb(file_path)
Remove or put import pdb statement.
625941b93c8af77a43ae3618
@plugin_function("plugins.version") <NEW_LINE> def version(): <NEW_LINE> <INDENT> return VERSION
Returns the version number of the plugin manager. Returns: str
625941b991af0d3eaac9b88f
def get_collaborators(self, per_page=30, q=None, exclude_project=None): <NEW_LINE> <INDENT> params = filter_locals(locals()) <NEW_LINE> query_params = dict_to_query_params(params) <NEW_LINE> path = "organizations/{}/collaborators{}".format(self.id, query_params) <NEW_LINE> return [ Collaborator(x, organization=self, client=self._client) for x in self._client.get(path) ]
get collaborators for this organization
625941b9ff9c53063f47c077
def distanceMots(texte): <NEW_LINE> <INDENT> motFreq={} <NEW_LINE> mots=texte.split() <NEW_LINE> for mot in mots: <NEW_LINE> <INDENT> motFreq[mot]=motFreq.get(mot,0)+1/len(mots) <NEW_LINE> <DEDENT> return motFreq
la fonction prend un texte comme entrée et elle retourne un dictionnaire avec les fréquences relatives de chaque mot
625941b9adb09d7d5db6c60d
def eigenx(x): <NEW_LINE> <INDENT> if typex(x) != 'oper': <NEW_LINE> <INDENT> raise TypeError('not an oper') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if x.shape[0] != x.shape[1]: <NEW_LINE> <INDENT> raise TypeError('not a square oper') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> w, v = LA.eigh(x) <NEW_LINE> vk = [] <NEW_LINE> for i in range (len(w)): <NEW_LINE> <INDENT> vk.append(transx(qx(v[:,i]))) <NEW_LINE> <DEDENT> return w, vk
eigenvalue and eigenvector Parameters: ----------- x : operator Returns: -------- w : [..., ...] ndarray vk : [[...,...],[...,...]] matrix vk[i] is the normalized "ket" eigenvector accroding to eigenvelue w[i]
625941b938b623060ff0ac6a
def main(): <NEW_LINE> <INDENT> male_set = {'male', 'm'} <NEW_LINE> female_set = {'female', 'f'} <NEW_LINE> result_dict = {} <NEW_LINE> with open(data_path, 'r', newline='') as csvfile: <NEW_LINE> <INDENT> rows = csv.reader(csvfile) <NEW_LINE> for i, row in enumerate(rows): <NEW_LINE> <INDENT> if i == 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if i % 50 == 0: <NEW_LINE> <INDENT> print('正在处理第{}行数据...'.format(i)) <NEW_LINE> <DEDENT> age_val = row[1] <NEW_LINE> gender_val = row[2] <NEW_LINE> country_val = row[3] <NEW_LINE> gender_val = gender_val.replace(' ', '') <NEW_LINE> gender_val = gender_val.lower() <NEW_LINE> if country_val not in result_dict: <NEW_LINE> <INDENT> result_dict[country_val] = [0, 0, 0, 0] <NEW_LINE> <DEDENT> if gender_val in female_set: <NEW_LINE> <INDENT> result_dict[country_val][0] += 1 <NEW_LINE> if int(age_val) > 1 and int(age_val) < 80: <NEW_LINE> <INDENT> result_dict[country_val][2] += int(age_val) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> elif gender_val in male_set: <NEW_LINE> <INDENT> result_dict[country_val][1] += 1 <NEW_LINE> if int(age_val) > 1 and int(age_val) < 80: <NEW_LINE> <INDENT> result_dict[country_val][3] += int(age_val) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> with open('age_country.csv', 'w', newline='', encoding='utf-16') as csvfile: <NEW_LINE> <INDENT> csvwriter = csv.writer(csvfile, delimiter=',') <NEW_LINE> csvwriter.writerow(['国家', '男性平均年龄', '女性平均年龄']) <NEW_LINE> for k, v in list(result_dict.items()): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> csvwriter.writerow([k, v[2]/v[0], v[3]/v[1]]) <NEW_LINE> <DEDENT> except ZeroDivisionError: <NEW_LINE> <INDENT> if v[0] == 0 and v[1] != 0: <NEW_LINE> <INDENT> csvwriter.writerow([k, 0, v[3]/v[1]]) <NEW_LINE> <DEDENT> elif v[0] != 0 and v[1] == 0: <NEW_LINE> <INDENT> csvwriter.writerow([k, v[2]/v[0], 0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> csvwriter.writerow([k, 0, 0])
主函数
625941b960cbc95b062c63c3
def get_queryset(self, request): <NEW_LINE> <INDENT> qs = super(DocumentAdmin, self).get_queryset(request) <NEW_LINE> if request.user.is_superuser: <NEW_LINE> <INDENT> return qs <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return qs.filter(user=request.user)
only show the current user's docs
625941b97c178a314d6ef2d4
def find_prime_polynomials(generator=2, c_exp=8, fast_primes=False, single=False): <NEW_LINE> <INDENT> root_charac = 2 <NEW_LINE> field_charac = int(root_charac**c_exp - 1) <NEW_LINE> field_charac_next = int(root_charac**(c_exp+1) - 1) <NEW_LINE> prim_candidates = [] <NEW_LINE> if fast_primes: <NEW_LINE> <INDENT> prim_candidates = rwh_primes1(field_charac_next) <NEW_LINE> prim_candidates = [x for x in prim_candidates if x > field_charac] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> prim_candidates = range(field_charac+2, field_charac_next, root_charac) <NEW_LINE> <DEDENT> correct_primes = [] <NEW_LINE> for prim in prim_candidates: <NEW_LINE> <INDENT> seen = bytearray(field_charac+1) <NEW_LINE> conflict = False <NEW_LINE> x = GF2int(1) <NEW_LINE> for i in range(field_charac): <NEW_LINE> <INDENT> x = x.multiply(generator, prim, field_charac+1) <NEW_LINE> if x > field_charac or seen[x] == 1: <NEW_LINE> <INDENT> conflict = True <NEW_LINE> break <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> seen[x] = 1 <NEW_LINE> <DEDENT> <DEDENT> if not conflict: <NEW_LINE> <INDENT> correct_primes.append(prim) <NEW_LINE> if single: return prim <NEW_LINE> <DEDENT> <DEDENT> return correct_primes
Compute the list of prime polynomials for the given generator and galois field characteristic exponent.
625941b9bde94217f3682c77
def pick_questions(): <NEW_LINE> <INDENT> return Questions[0:2]
Pick questions based on expected length of response and other factors in tags
625941b90a366e3fb873e692
def onInit( isReload ): <NEW_LINE> <INDENT> pass
base cell 都有 回调函数
625941b9fff4ab517eb2f2b4
def get_data_tushare(self,code,ktype ='D',start='2020-01-01',end="2020-12-31"): <NEW_LINE> <INDENT> dfData = tushare.get_k_data(code = code, start= start, end = end, ktype =ktype, retry_count=3, pause=0.001).sort_index() <NEW_LINE> dfData.index = pd.to_datetime(dfData.date) <NEW_LINE> dfData['openinterest'] = 0 <NEW_LINE> if self.fromLocal: <NEW_LINE> <INDENT> dfData.to_csv(os.path.join(self.dataPath, "tushare_{}.csv".format(code))) <NEW_LINE> <DEDENT> return dfData
单代码获取数据 :return:
625941b9a934411ee3751515
def evaluate(self, expr, binds=None): <NEW_LINE> <INDENT> if binds: <NEW_LINE> <INDENT> scope_builder = ScopeBuilder() <NEW_LINE> for key, value in binds.items(): <NEW_LINE> <INDENT> scope_builder.let(key, _arg_to_ast(value)) <NEW_LINE> <DEDENT> scope_builder.ret(expr) <NEW_LINE> expr = scope_builder.get() <NEW_LINE> <DEDENT> if isinstance(expr, Function): <NEW_LINE> <INDENT> assert not ir_pass.free_vars(expr) <NEW_LINE> <DEDENT> if isinstance(expr, (Function, GlobalVar)): <NEW_LINE> <INDENT> return self._make_executor(expr) <NEW_LINE> <DEDENT> func = Function([], expr) <NEW_LINE> return self._make_executor(func)()
Evaluate a Relay expression on the executor. Parameters ---------- expr: tvm.relay.Expr The expression to evaluate. binds: Map[tvm.relay.Var, tvm.relay.Expr] Additional binding of free variable. Returns ------- val : Union[function, Value] The evaluation result.
625941b926068e7796caeb54
def __field_wrapped(self, field, value, output_format): <NEW_LINE> <INDENT> if (len(value) > 0): <NEW_LINE> <INDENT> return self.__format_line_wrapped(field, value, output_format) + ',\n' <NEW_LINE> <DEDENT> return ''
add the value into the return structure, only if a value was defined in Solr :param field: :param value: :param output_format: :return:
625941b9d268445f265b4cf0
def __data_generation(self, list_IDs_temp): <NEW_LINE> <INDENT> y = np.empty((self.batch_size,), dtype=self.labeltype) <NEW_LINE> X = self.ie.get_batch(list_IDs_temp, from_set = self.from_set) <NEW_LINE> for i, ID in enumerate(list_IDs_temp): <NEW_LINE> <INDENT> y[i] = self.labels[ID] <NEW_LINE> <DEDENT> return X, y
Generates data containing batch_size samples
625941b915baa723493c3ded
def write_vector(vector, outfile): <NEW_LINE> <INDENT> out_dir = os.path.dirname(outfile) <NEW_LINE> if not os.path.exists(out_dir): <NEW_LINE> <INDENT> os.makedirs(out_dir) <NEW_LINE> <DEDENT> vector = vector.copy() <NEW_LINE> for k in vector: <NEW_LINE> <INDENT> if isinstance(vector[k], np.ndarray): <NEW_LINE> <INDENT> vector[k] = vector[k].round(4).tolist() <NEW_LINE> <DEDENT> <DEDENT> with open(outfile, 'w') as f: <NEW_LINE> <INDENT> json.dump(vector, f, separators=(',', ': '), indent=4) <NEW_LINE> f.write('\n') <NEW_LINE> <DEDENT> print(" ... wrote {}".format(outfile))
Save vector data for a timestep as JSON
625941b994891a1f4081b923
def load_private_key_file(path): <NEW_LINE> <INDENT> with open(path, 'rb') as f: <NEW_LINE> <INDENT> data = f.read() <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> key = load_pem_private_key(data, None, default_backend()) <NEW_LINE> log_debug("Successfully loaded PEM encoded private key from {0}.".format(path)) <NEW_LINE> return key <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> key = load_der_private_key(data, None, default_backend()) <NEW_LINE> log_debug("Successfully loaded DER encoded private key from {0}.".format(path)) <NEW_LINE> return key <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> raise ValueError("The private key file was loaded successfully, but it does not seem to be a PEM/DER encoded private key.")
Loads the private key from the specified file (can be DER or PEM encoded). Args: path (str) : Path of the private key file to load. Returns: The loaded private key (cryptography private key, not OpenSSL private key!)
625941b9ec188e330fd5a621
def reviewer_stats(df): <NEW_LINE> <INDENT> reviewer_scores = df.groupby(['Reviewer Full Name', 'Control Number', 'Topic'])['Weighted Original Score'].sum() <NEW_LINE> reviewer_avgs = reviewer_scores.groupby('Reviewer Full Name').mean() <NEW_LINE> reviewer_stdevs = reviewer_scores.groupby('Reviewer Full Name').std(ddof=0) <NEW_LINE> return reviewer_avgs, reviewer_stdevs
Isolates scores from individual reviewers and returns each reviewer's mean score and standard deviation as a tuple of pandas Series in the format (all means, all stdevs) df: pandas DataFrame. Cleaned df of the format returned by import_data()
625941b9de87d2750b85fc09
def obtener_intervenciones_por_dia(self, ano, mes, dia): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> intervenciones = self.intervencionquirurgica_set.filter(fecha_intervencion__year=ano, fecha_intervencion__month=mes, fecha_intervencion__day=dia, reservacion__estado='A').order_by('hora_inicio') <NEW_LINE> return intervenciones <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return None
Devuelve un diccionario en donde se tiene para un dia, las intervenciones quirurgicas Parametros: ano -> Ano de la fecha a consultar mes -> Mes de la fecha a consultar dia -> Dia de la fecha a consultar
625941b98da39b475bd64df2
def static_caller(flickr_method,static = False): <NEW_LINE> <INDENT> def decorator(method) : <NEW_LINE> <INDENT> @wraps(method) <NEW_LINE> def static_call(*args,**kwargs): <NEW_LINE> <INDENT> token,kwargs = _get_token(None,**kwargs) <NEW_LINE> method_args,format_result = method(*args,**kwargs) <NEW_LINE> method_args["auth_handler"] = token <NEW_LINE> r = method_call.call_api(method = flickr_method,**method_args) <NEW_LINE> try : <NEW_LINE> <INDENT> return format_result(r,token) <NEW_LINE> <DEDENT> except TypeError : <NEW_LINE> <INDENT> return format_result(r) <NEW_LINE> <DEDENT> <DEDENT> static_call.flickr_method = flickr_method <NEW_LINE> static_call.isstatic = True <NEW_LINE> return StaticCaller(static_call) <NEW_LINE> <DEDENT> return decorator
This decorator binds a static method to the flickr method given by 'flickr_method'. The wrapped method should return the argument dictionnary and a function that format the result of method_call.call_api. Some method can propagate authentication tokens. For instance a Person object can propagate its token to photos retrieved from it. In this case, it should return its token also and the result formating function should take an additional argument token.
625941b9fff4ab517eb2f2b5
def euler_angles_from_matrix(R): <NEW_LINE> <INDENT> phi = 0.0 <NEW_LINE> if np.isclose(R[2,0], -1.0): <NEW_LINE> <INDENT> theta = np.pi / 2.0 <NEW_LINE> psi = np.arctan2(R[0,1], R[0,2]) <NEW_LINE> <DEDENT> elif np.isclose(R[2,0], 1.0): <NEW_LINE> <INDENT> theta = -np.pi / 2.0 <NEW_LINE> psi = np.arctan2(-R[0,1], -R[0,2]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> theta = -np.arcsin(R[2,0]) <NEW_LINE> cos_theta = np.cos(theta) <NEW_LINE> psi = np.arctan2(R[2,1] / cos_theta, R[2,2] / cos_theta) <NEW_LINE> phi = np.arctan2(R[1,0]/cos_theta, R[0,0] / cos_theta) <NEW_LINE> <DEDENT> return np.degrees(psi), np.degrees(theta), np.degrees(phi)
See http://www.close-range.com/docs/Computing_Euler_angles_from_a_rotation_matrix.pdf Parameters ---------- R: np.array (3,3). Rotation matrix. Returns ------- psi: float. Roll angle (in degrees). theta: float. Pitch angle (in degrees). phi: float. Yaw angle (in degrees).
625941b97047854f462a1288
def errorToString(errorCode): <NEW_LINE> <INDENT> cErr = ctypes.c_int32(errorCode) <NEW_LINE> errStr = ("\0"*constants.MAX_NAME_SIZE).encode("ascii") <NEW_LINE> _staticLib.LJM_ErrorToString(cErr, errStr) <NEW_LINE> return _decodeASCII(errStr)
Returns the the name of an error code. Args: errorCode: The error code to look up. Returns: The error name string. Note: If the constants file that has been loaded does not contain errorCode, this returns a message saying so. If the constants file could not be opened, this returns a string saying so and where that constants file was expected to be.
625941b916aa5153ce3622f3
def addAction(self, id, name, action, condition='', permission='', category='Plone', visible=1, appId=None, icon_expr='', description='', REQUEST=None, ): <NEW_LINE> <INDENT> if not name: <NEW_LINE> <INDENT> raise ValueError('A name is required.') <NEW_LINE> <DEDENT> a_expr = action and Expression(text=str(action)) or '' <NEW_LINE> c_expr = condition and Expression(text=str(condition)) or '' <NEW_LINE> if type(permission) != type(()): <NEW_LINE> <INDENT> permission = permission and (str(permission), ) or () <NEW_LINE> <DEDENT> new_actions = self._cloneActions() <NEW_LINE> new_action = PloneConfiglet(id=str(id), title=name, action=a_expr, condition=c_expr, permissions=permission, category=str(category), visible=int(visible), appId=appId, description=description, icon_expr=icon_expr, ) <NEW_LINE> new_actions.append(new_action) <NEW_LINE> self._actions = tuple(new_actions) <NEW_LINE> if REQUEST is not None: <NEW_LINE> <INDENT> return self.manage_editActionsForm( REQUEST, manage_tabs_message='Added.')
Add an action to our list.
625941b99f2886367277a70c
def nltk_ibm_one(data, iter=5): <NEW_LINE> <INDENT> dual_text = [] <NEW_LINE> for d_i in range(len(data)): <NEW_LINE> <INDENT> fr_sent = word_tokenize(data[d_i]['fr']) <NEW_LINE> eng_sent = word_tokenize(data[d_i]['en']) <NEW_LINE> dual_text.append(AlignedSent(fr_sent, eng_sent)) <NEW_LINE> <DEDENT> ibm_one = IBMModel1(dual_text, iter) <NEW_LINE> print("Probability score for the: ") <NEW_LINE> print(ibm_one.translation_table['maison']['house'])
Returns probability scores of translations based on nltk.translate.ibm1 module
625941b93cc13d1c6d3c71ff
def setVisible(self, isVisible): <NEW_LINE> <INDENT> self._isSensitive = isVisible <NEW_LINE> if isVisible: <NEW_LINE> <INDENT> self.dialog = GladeWidget( root='anagrafica_complessa_detail_dialog', callbacks_proxy=self, path='anagrafica_complessa_detail_dialog.glade') <NEW_LINE> self.dialogTopLevel = self.dialog.getTopLevel() <NEW_LINE> self.dialogTopLevel.set_title(self._windowTitle) <NEW_LINE> self.dialogTopLevel.get_content_area().pack_start(self.getTopLevel(), True, True, 0) <NEW_LINE> self.dialog.ok_button.connect('grab_focus', self.on_ok_button_grab_focus) <NEW_LINE> Environment.windowGroup.append(self.dialogTopLevel) <NEW_LINE> self.dialogTopLevel.set_transient_for(self._anagrafica.getTopLevel()) <NEW_LINE> self.placeWindow(self.dialogTopLevel) <NEW_LINE> self.dialogTopLevel.show_all() <NEW_LINE> self.setFocus() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.dialogTopLevel in Environment.windowGroup: <NEW_LINE> <INDENT> Environment.windowGroup.remove(self.dialogTopLevel) <NEW_LINE> <DEDENT> self.dialogTopLevel.get_content_area().remove(self.getTopLevel()) <NEW_LINE> self.on_top_level_closed() <NEW_LINE> self.dialogTopLevel.destroy()
Make the window visible/invisible
625941b9b7558d58953c4d96
def inArea(x, y ,settings): <NEW_LINE> <INDENT> if 0<=x<settings.block_ynum and 0<=y<settings.block_xnum: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
定界函数,判断坐标(x,y)是否合法
625941b929b78933be1e5534
def builtin(self, predname): <NEW_LINE> <INDENT> if predname in self.preddict: <NEW_LINE> <INDENT> return self.preddict[predname][0] <NEW_LINE> <DEDENT> return None
Return a CongressBuiltinPred with name PREDNAME or None.
625941b9d99f1b3c44c67412
def reorderComps(self, sortIDs): <NEW_LINE> <INDENT> for key in self._FieldDims: <NEW_LINE> <INDENT> arr = getattr(self, key) <NEW_LINE> dims = self._FieldDims[key] <NEW_LINE> if arr.ndim == 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if dims[0] == 'K' and 'K' not in dims[1:]: <NEW_LINE> <INDENT> arr = arr[sortIDs] <NEW_LINE> <DEDENT> elif dims[0] == 'K' and dims[1] == 'K' and 'K' not in dims[2:]: <NEW_LINE> <INDENT> arr = arr[sortIDs, :][:, sortIDs] <NEW_LINE> <DEDENT> elif 'K' not in dims: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> elif dims[0] != 'K' and dims[1] == 'K': <NEW_LINE> <INDENT> arr = arr[:, sortIDs] <NEW_LINE> <DEDENT> elif dims[0] != 'K' and dims[2] == 'K': <NEW_LINE> <INDENT> arr = arr[:, :, sortIDs] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError('TODO' + key + str(dims)) <NEW_LINE> <DEDENT> self.setField(key, arr, dims=dims)
Rearrange internal order of all fields along dimension 'K'
625941b90c0af96317bb8064
@app.route('/api/v1/recipe/:id', ['GET', 'OPTIONS']) <NEW_LINE> def api_v1_recipe(id): <NEW_LINE> <INDENT> if bottle.request.method == 'OPTIONS': <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> return { 'recipes': [ recipe.to_dict() for recipe in db.Recipe.select().where( db.Recipe.id == id ) ] }
Get a given recipe from db
625941b95f7d997b87174916
def solve(matrix, visible): <NEW_LINE> <INDENT> current = list(list(r) for r in matrix) <NEW_LINE> while True: <NEW_LINE> <INDENT> changes = tuple(get_changes(current, visible)) <NEW_LINE> if not changes: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> for col, row, val in changes: <NEW_LINE> <INDENT> current[row][col] = val <NEW_LINE> <DEDENT> <DEDENT> return tuple(tuple(r) for r in current)
shift positions until equilibrium is reached.
625941b9fbf16365ca6f6038
def test_authorize(self): <NEW_LINE> <INDENT> order = make_test_order(self.US, '') <NEW_LINE> self.assertEqual(order.balance, order.total) <NEW_LINE> self.assertEqual(order.total, Decimal('125.00')) <NEW_LINE> processor = utils.get_processor_by_key('PAYMENT_DUMMY') <NEW_LINE> processor.create_pending_payment(order=order, amount=order.total) <NEW_LINE> self.assertEqual(order.pendingpayments.count(), 1) <NEW_LINE> self.assertEqual(order.payments.count(), 1) <NEW_LINE> pending = order.pendingpayments.all()[0] <NEW_LINE> self.assertEqual(pending.amount, order.total) <NEW_LINE> payment = order.payments.all()[0] <NEW_LINE> self.assertEqual(payment.amount, Decimal('0')) <NEW_LINE> self.assertEqual(pending.capture, payment) <NEW_LINE> self.assertEqual(order.balance_paid, Decimal('0')) <NEW_LINE> self.assertEqual(order.authorized_remaining, Decimal('0')) <NEW_LINE> processor.prepare_data(order) <NEW_LINE> result = processor.authorize_payment() <NEW_LINE> self.assertEqual(result.success, True) <NEW_LINE> auth = result.payment <NEW_LINE> self.assertEqual(type(auth), OrderAuthorization) <NEW_LINE> self.assertEqual(order.authorized_remaining, Decimal('125.00')) <NEW_LINE> result = processor.capture_authorized_payment(auth) <NEW_LINE> self.assertEqual(result.success, True) <NEW_LINE> payment = result.payment <NEW_LINE> self.assertEqual(auth.capture, payment) <NEW_LINE> order = Order.objects.get(pk=order.id) <NEW_LINE> self.assertEqual(order.status, 'New') <NEW_LINE> self.assertEqual(order.balance, Decimal('0'))
Test making an authorization using DUMMY.
625941b9b57a9660fec336fc
def readPositioners(self): <NEW_LINE> <INDENT> for p in self.positioners: <NEW_LINE> <INDENT> p.read()
Reads current values of all positioner fields from record)
625941b9dc8b845886cb53b0
def fit(self, X, y): <NEW_LINE> <INDENT> super(GCPEiVelocity, self).fit(X, y) <NEW_LINE> self.POU = 0 <NEW_LINE> if len(y) >= self.r_minimum: <NEW_LINE> <INDENT> top_y = sorted(y)[-self.N_BEST_Y:] <NEW_LINE> velocities = [top_y[i + 1] - top_y[i] for i in range(len(top_y) - 1)] <NEW_LINE> self.POU = np.exp(self.MULTIPLIER * np.mean(velocities))
Train a gaussian process like normal, then compute a "Probability Of Uniform selection" (POU) value.
625941b9435de62698dfdacf
def add_node_prop(self, prop, prop_map): <NEW_LINE> <INDENT> self.node_props.append(prop) <NEW_LINE> for i in range(len(self.json_graph["nodes"])): <NEW_LINE> <INDENT> self.json_graph["nodes"][i][prop] = prop_map[self.json_graph["nodes"][i]["id"]]
Adds a node property to the json_graph *Positional arguments:* .. option:: prop The name of the property to add .. option:: prop_map A mapping from node ID's to property values
625941b9bf627c535bc13052
def f(xpts, *gaussParams): <NEW_LINE> <INDENT> return f_raw(xpts, *gaussParams).ravel()
The normal function call for this function. Performs checks on valid arguments, then calls the "raw" function. :return:
625941b923849d37ff7b2f0d
def doctest_Game(): <NEW_LINE> <INDENT> pass
Tests for Game >>> from pyspacewar.game import Game >>> g = Game() >>> g.world.objects [] >>> g.time_source.ticks_per_second == Game.TICKS_PER_SECOND True
625941b9462c4b4f79d1d54c
def test_arXiv_comments(self): <NEW_LINE> <INDENT> self.assertEqual( self.hepform_json['note'], self.record['public_notes'][0]['value'] )
Test if arXiv comments are created correctly.
625941b9004d5f362079a1b2
def testzerowidth(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError) as e: <NEW_LINE> <INDENT> a = Rectangle(0, 5) <NEW_LINE> <DEDENT> self.assertEqual(e.exception.args[0], "width must be > 0")
Tries a zero width
625941b985dfad0860c3acd4
def get_requirements(parent, reqs, dependencies, ambiguities, query, hints, filters, whatreqs, pick_first): <NEW_LINE> <INDENT> requirements = [] <NEW_LINE> for require in reqs: <NEW_LINE> <INDENT> required_packages = query.filter(provides=require, latest=True, arch=primary_arch) <NEW_LINE> if len(required_packages) == 0 and multi_arch: <NEW_LINE> <INDENT> required_packages = query.filter(provides=require, latest=True, arch=multi_arch) <NEW_LINE> <DEDENT> if len(required_packages) == 0: <NEW_LINE> <INDENT> required_packages = query.filter(provides=require, latest=True, arch='noarch') <NEW_LINE> <DEDENT> if len(required_packages) == 0: <NEW_LINE> <INDENT> print("No package for [%s] required by [%s-%s-%s.%s]" % ( str(require), parent.name, parent.version, parent.release, parent.arch), file=sys.stderr) <NEW_LINE> continue <NEW_LINE> <DEDENT> if len(required_packages) > 1: <NEW_LINE> <INDENT> found = False <NEW_LINE> for choice in hints: <NEW_LINE> <INDENT> for rpkg in required_packages: <NEW_LINE> <INDENT> if rpkg.name == choice: <NEW_LINE> <INDENT> found = True <NEW_LINE> append_requirement(requirements, parent, rpkg, filters, whatreqs) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if found: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> if not found: <NEW_LINE> <INDENT> if pick_first: <NEW_LINE> <INDENT> for rpkg in required_packages: <NEW_LINE> <INDENT> if rpkg.name in dependencies: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> for rpkg in required_packages: <NEW_LINE> <INDENT> if rpkg.arch == 'noarch' or rpkg.arch == primary_arch or rpkg.arch == multi_arch: <NEW_LINE> <INDENT> append_requirement(requirements, parent, rpkg, filters, whatreqs) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> continue <NEW_LINE> <DEDENT> unresolved = {} <NEW_LINE> for rpkg in required_packages: <NEW_LINE> <INDENT> unresolved["%s#%s" % (rpkg.name, rpkg.arch)] = rpkg <NEW_LINE> <DEDENT> ambiguities.append(unresolved) <NEW_LINE> <DEDENT> continue <NEW_LINE> <DEDENT> append_requirement(requirements, parent, required_packages[0], filters, whatreqs) <NEW_LINE> <DEDENT> return requirements
Share code for recursing into requires or recommends
625941b976e4537e8c3514f3
def _do_request(self, method, url, headers={}, params={}, data={}, json=None, files={}, raise_for_status=True, stream=False): <NEW_LINE> <INDENT> if method == 'get': <NEW_LINE> <INDENT> func = requests.get <NEW_LINE> <DEDENT> elif method == 'post': <NEW_LINE> <INDENT> func = requests.post <NEW_LINE> <DEDENT> elif method == 'put': <NEW_LINE> <INDENT> func = requests.put <NEW_LINE> <DEDENT> elif method == 'patch': <NEW_LINE> <INDENT> func = requests.patch <NEW_LINE> <DEDENT> elif method == 'delete': <NEW_LINE> <INDENT> func = requests.delete <NEW_LINE> <DEDENT> rx_dict = {} <NEW_LINE> retries = 0 <NEW_LINE> current_wait_time = 1 <NEW_LINE> max_retries = 5 <NEW_LINE> yandex_retry_codes = [500, 503] <NEW_LINE> while retries < max_retries: <NEW_LINE> <INDENT> headers['Authorization'] = self._get_auth_header() <NEW_LINE> r = func(url, headers=headers, params=params, data=data, json=json, files=files, stream=stream) <NEW_LINE> try: <NEW_LINE> <INDENT> rx_dict = r.json() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> if r.status_code in yandex_retry_codes: <NEW_LINE> <INDENT> logger.warning('Yandex send response code {}, will retry...'.format(r.status_code)) <NEW_LINE> time.sleep(current_wait_time) <NEW_LINE> current_wait_time *= 2 <NEW_LINE> retries += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> if raise_for_status == True: <NEW_LINE> <INDENT> r.raise_for_status() <NEW_LINE> <DEDENT> return r, rx_dict
Does a standard requests call with the passed params but also: 1. Sets the authorization header 2. Will check for server errors in the response and back off if needed or raise an exception if appropriate. :param method: one of 'get', 'post', 'put', 'delete' :param server_error_retries: set to the number of retries when encountering a pesky Server Error. :return: (r, rx_dict) tuple
625941b97cff6e4e81117801
def link_conf_matrix_plotter(self, *parents): <NEW_LINE> <INDENT> self.conf_matrix_plotters = [] <NEW_LINE> prev = parents <NEW_LINE> for i in range(1, len(self.decision.confusion_matrixes)): <NEW_LINE> <INDENT> mp = plotting_units.MatrixPlotter( self, name=(CLASS_NAME[i] + " matrix")) .link_attrs(self.decision, ("input", "confusion_matrixes")) .link_from(*prev) <NEW_LINE> mp.input_field = i <NEW_LINE> mp.link_attrs(self.loader, "reversed_labels_mapping") <NEW_LINE> mp.gate_skip = ~self.decision.epoch_ended <NEW_LINE> self.conf_matrix_plotters.append(mp) <NEW_LINE> prev = mp, <NEW_LINE> <DEDENT> return prev[0]
Creates the list of instances of :class:`veles.plotting_units.MatrixPlotter`. Links the first :class:`veles.plotting_units.MatrixPlotter` unit with \*parents. Links each :class:`veles.plotting_units.MatrixPlotter` unit from previous :class:`veles.plotting_units.MatrixPlotter` unit. Links attributes of :class:`veles.plotting_units.MatrixPlotter` units from attributes of :class:`veles.znicz.decision.DecisionBase` cd descendant. Returns the last of :class:`veles.plotting_units.MatrixPlotter` units. Arguments: parents: units, from whom will be link the first of :class:`veles.plotting_units.MatrixPlotter` units.
625941b973bcbd0ca4b2bef9
def agent_identity(self, agent_uuid): <NEW_LINE> <INDENT> if '/' in agent_uuid or agent_uuid in ['.', '..']: <NEW_LINE> <INDENT> raise ValueError('invalid agent') <NEW_LINE> <DEDENT> identity_file = os.path.join(self.install_dir, agent_uuid, 'IDENTITY') <NEW_LINE> with ignore_enoent, open(identity_file, 'rt') as file: <NEW_LINE> <INDENT> return file.readline(64)
Return the identity of the agent that is installed. The IDENTITY file is written to the agent's install directory the the first time the agent is installed. This function reads that file and returns the read value. @param agent_uuid: @return:
625941b9091ae35668666de1
def gauss(x, *p): <NEW_LINE> <INDENT> A, mu, sigma = p <NEW_LINE> return A*np.exp(-(x-mu)**2/(2.*sigma**2))
Model gaussian to fit to data.
625941b95166f23b2e1a4fd5
def test_release_lock_and_re_acquire(self, lock_server): <NEW_LINE> <INDENT> name = uuid.uuid4().hex <NEW_LINE> client_1 = lock_server.get_client() <NEW_LINE> client_1.connect() <NEW_LINE> acquired = client_1.lock(name) <NEW_LINE> assert acquired <NEW_LINE> client_1.release() <NEW_LINE> client_1.close() <NEW_LINE> lucky_client = self.get_client_with_lock_acquired(lock_server, name) <NEW_LINE> assert lucky_client
Test that a locks can be acquired again after it's released
625941b9566aa707497f43f5
def main(): <NEW_LINE> <INDENT> gset = Gtk.Settings.get_default() <NEW_LINE> themename = gset.get_property("gtk-theme-name") <NEW_LINE> cache(themename) <NEW_LINE> prefdark = gset.get_property("gtk-application-prefer-dark-theme") <NEW_LINE> css = Gtk.CssProvider.get_named(themename).to_string() <NEW_LINE> lines = css.split("\n") <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> if "@define-color" not in line: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if "theme_text_color" in line: <NEW_LINE> <INDENT> setconfig("color_norm_fg", rgb2hex(line)) <NEW_LINE> <DEDENT> if "theme_selected_bg_color" in line: <NEW_LINE> <INDENT> setconfig("color_sel_bg", rgb2hex(line)) <NEW_LINE> <DEDENT> if "theme_selected_fg_color" in line: <NEW_LINE> <INDENT> setconfig("color_sel_fg", rgb2hex(line)) <NEW_LINE> <DEDENT> <DEDENT> inside = False <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> if "menu {" in line: <NEW_LINE> <INDENT> inside = True <NEW_LINE> continue <NEW_LINE> <DEDENT> if inside: <NEW_LINE> <INDENT> if "{" in line: <NEW_LINE> <INDENT> inside = False <NEW_LINE> break <NEW_LINE> <DEDENT> process_line(line)
main
625941b9be383301e01b5308
def get_tasks(self): <NEW_LINE> <INDENT> return self.session.query(Task).all()
return all the tags
625941b94d74a7450ccd403e
def draw_board(self, fg, bg, font_sz): <NEW_LINE> <INDENT> self.coord = {} <NEW_LINE> self.label = {} <NEW_LINE> self.board = [] <NEW_LINE> for i in range(self.degree): <NEW_LINE> <INDENT> self.board.append([0] * self.degree) <NEW_LINE> frm = Frame(self) <NEW_LINE> frm.pack(expand=YES, fill=BOTH) <NEW_LINE> for j in range(self.degree): <NEW_LINE> <INDENT> widget = Label(frm, fg=fg, bg=bg, text=' ', font=('courier', font_sz, 'bold'), relief=SUNKEN, bd=4, padx=10, pady=10) <NEW_LINE> widget.pack(side=LEFT, expand=YES, fill=BOTH) <NEW_LINE> widget.bind('<Button-1>', self.on_left_click) <NEW_LINE> self.coord[widget] = (i, j) <NEW_LINE> self.label[(i, j)] = widget <NEW_LINE> self.board[i][j] = EMPTY
draws the game board
625941b93eb6a72ae02ec356
def get(self, *args, **kwargs): <NEW_LINE> <INDENT> return super(BaseElasticsearchManyMappedAPIView, self).get(*args, **kwargs)
Get all of the reports of the requested data type associated with the referenced parent instance.
625941b9a8370b771705271c
def get_state(self): <NEW_LINE> <INDENT> return self.n_consumed,self.prev_eos_probs
State consists of the number of consumed words, and the accumulator for previous EOS probability estimates if we don't use point estimates.
625941b9711fe17d825421ee
def AddTestRunnerOptions(option_parser, default_timeout=60): <NEW_LINE> <INDENT> option_parser.add_option('-t', dest='timeout', help='Timeout to wait for each test', type='int', default=default_timeout) <NEW_LINE> option_parser.add_option('-c', dest='cleanup_test_files', help='Cleanup test files on the device after run', action='store_true') <NEW_LINE> option_parser.add_option('--num_retries', dest='num_retries', type='int', default=2, help='Number of retries for a test before ' 'giving up.') <NEW_LINE> option_parser.add_option('-v', '--verbose', dest='verbose_count', default=0, action='count', help='Verbose level (multiple times for more)') <NEW_LINE> profilers = ['devicestatsmonitor', 'chrometrace', 'dumpheap', 'smaps', 'traceview'] <NEW_LINE> option_parser.add_option('--profiler', dest='profilers', action='append', choices=profilers, help='Profiling tool to run during test. ' 'Pass multiple times to run multiple profilers. ' 'Available profilers: %s' % profilers) <NEW_LINE> option_parser.add_option('--tool', dest='tool', help='Run the test under a tool ' '(use --tool help to list them)') <NEW_LINE> option_parser.add_option('--flakiness-dashboard-server', dest='flakiness_dashboard_server', help=('Address of the server that is hosting the ' 'Chrome for Android flakiness dashboard.')) <NEW_LINE> option_parser.add_option('--skip-deps-push', dest='push_deps', action='store_false', default=True, help='Do not push dependencies to the device. ' 'Use this at own risk for speeding up test ' 'execution on local machine.') <NEW_LINE> AddBuildTypeOption(option_parser)
Decorates OptionParser with options applicable to all tests.
625941b997e22403b379ce15
def _write_cache_index_map_section(self): <NEW_LINE> <INDENT> self._write_report('%s %s\n'%(_MARKER_SECTION_BEGIN, _SECTION_NAME_CACHE_INDEX_MAP)) <NEW_LINE> self._write_report('%s %d\n'%(_FIELD_NAME_NUM_CACHE_INDICES, len(self._cache_idx_to_tensor_idx))) <NEW_LINE> for cache_idx in range(0, len(self._cache_idx_to_tensor_idx)): <NEW_LINE> <INDENT> tensor_idx = self._cache_idx_to_tensor_idx[cache_idx] <NEW_LINE> line = '%d %d\n'%(cache_idx, tensor_idx) <NEW_LINE> self._write_report(line) <NEW_LINE> <DEDENT> self._write_report('%s %s\n'%(_MARKER_SECTION_END, _SECTION_NAME_CACHE_INDEX_MAP))
Writes the mapping from cache index to tensor index to the report.
625941b95fc7496912cc3802
@task <NEW_LINE> def readme(ctx): <NEW_LINE> <INDENT> ctx.run("restructuredtext-lint README.rst")
Lint the README for reStructuredText syntax issues
625941b985dfad0860c3acd5
def test_index_gates(self): <NEW_LINE> <INDENT> qr = QuantumRegister(2) <NEW_LINE> qc = QuantumCircuit(qr) <NEW_LINE> qc.h(0) <NEW_LINE> qc.cx(0, 1) <NEW_LINE> qc.h(1) <NEW_LINE> qc.h(0) <NEW_LINE> self.assertEqual(qc.data.index((HGate(), [qr[0]], [])), 0) <NEW_LINE> self.assertEqual(qc.data.index((CXGate(), [qr[0], qr[1]], [])), 1) <NEW_LINE> self.assertEqual(qc.data.index((HGate(), [qr[1]], [])), 2)
Verify finding the index of a inst/qarg/carg tuple in circuit.data.
625941b9ad47b63b2c509e05
def query_repositories(clobber=False): <NEW_LINE> <INDENT> global REPOSITORIES <NEW_LINE> if clobber: <NEW_LINE> <INDENT> REPOSITORIES = {} <NEW_LINE> if os.path.exists(REPOSITORIES_FILE): <NEW_LINE> <INDENT> os.remove(REPOSITORIES_FILE) <NEW_LINE> <DEDENT> <DEDENT> if REPOSITORIES: <NEW_LINE> <INDENT> return REPOSITORIES <NEW_LINE> <DEDENT> if os.path.exists(REPOSITORIES_FILE): <NEW_LINE> <INDENT> LOG.debug("Loading %s" % REPOSITORIES_FILE) <NEW_LINE> fd = open(REPOSITORIES_FILE) <NEW_LINE> REPOSITORIES = json.load(fd) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> th_client = TreeherderClient(protocol='https', host=TREEHERDER_URL) <NEW_LINE> treeherderRepos = th_client.get_repositories() <NEW_LINE> REPOSITORIES = {} <NEW_LINE> for th_repo in treeherderRepos: <NEW_LINE> <INDENT> if th_repo['active_status'] == "active": <NEW_LINE> <INDENT> repo = {} <NEW_LINE> repo['repo'] = th_repo['url'] <NEW_LINE> repo['repo_type'] = th_repo['dvcs_type'] <NEW_LINE> repo['graph_branches'] = [th_repo['name'].capitalize()] <NEW_LINE> REPOSITORIES[th_repo['name']] = repo <NEW_LINE> <DEDENT> <DEDENT> with open(REPOSITORIES_FILE, "wb") as fd: <NEW_LINE> <INDENT> json.dump(REPOSITORIES, fd) <NEW_LINE> <DEDENT> <DEDENT> return REPOSITORIES
Return dictionary with information about the various repositories. The data about a repository looks like this: .. code-block:: python "ash": { "repo": "https://hg.mozilla.org/projects/ash", "graph_branches": ["Ash"], "repo_type": "hg" }
625941b98a349b6b435e7ff0
@task <NEW_LINE> def dump(schema=None): <NEW_LINE> <INDENT> schemas = blueprint.get('schemas', {}).keys() <NEW_LINE> if not schemas: <NEW_LINE> <INDENT> info("No schemas were provided in Postgres settings.") <NEW_LINE> return <NEW_LINE> <DEDENT> if not schema: <NEW_LINE> <INDENT> if len(schemas) == 1: <NEW_LINE> <INDENT> schema = schemas[0] <NEW_LINE> <DEDENT> elif schemas: <NEW_LINE> <INDENT> for i, schema in enumerate(schemas, start=1): <NEW_LINE> <INDENT> print("{i}. {schema}".format(i=i, schema=schema)) <NEW_LINE> <DEDENT> valid_indices = '[1-{}]+'.format(len(schemas)) <NEW_LINE> schema_choice = prompt('Select schema to dump:', default='1', validate=valid_indices) <NEW_LINE> schema = schemas[int(schema_choice) - 1] <NEW_LINE> <DEDENT> <DEDENT> with sudo('postgres'): <NEW_LINE> <INDENT> now = datetime.now().strftime('%Y-%m-%d') <NEW_LINE> output_file = '/tmp/{}_{}.backup'.format(schema, now) <NEW_LINE> filename = os.path.basename(output_file) <NEW_LINE> options = [ '-c', '-F', 'tar', '-f', output_file, ] <NEW_LINE> dump_options = blueprint.get('schemas', {})[schema].get('dump', {}) <NEW_LINE> if dump_options: <NEW_LINE> <INDENT> options += ['--exclude-table-data=' + table for table in dump_options.get('exclude_table_data', [])] <NEW_LINE> <DEDENT> info('Dumping schema {}...', schema) <NEW_LINE> run('pg_dump ' + ' '.join(options + [schema])) <NEW_LINE> info('Downloading dump...') <NEW_LINE> local_file = '~/{}'.format(filename) <NEW_LINE> files.get(output_file, local_file) <NEW_LINE> <DEDENT> with sudo(), silent(): <NEW_LINE> <INDENT> debian.rm(output_file) <NEW_LINE> <DEDENT> info('New smoking hot dump at {}', local_file)
Dump and download all configured, or given, schemas. :param schema: Specific schema to dump and download.
625941b9507cdc57c6306b50
def formatwarning(message, category, filename, lineno, line=None): <NEW_LINE> <INDENT> if issubclass(category, ExecutionWarning): <NEW_LINE> <INDENT> s = u"%s: %s\n" % (category.__name__, message) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s = u'%s: %s, at line %s, in "%s"\n' % (category.__name__, message, lineno, filename) <NEW_LINE> <DEDENT> return s
Redefined format warning for maya.
625941b9293b9510aa2c3115
@pytest.mark.parametrize("data, horizon, expected", [([1, 2, 3, 4, 5], 12, 12), ([1, 2, 3, 4, 5], 24, 24), ([1, 2, 3], 8, 8) ]) <NEW_LINE> def test_average_forecast_input_series(data, horizon, expected): <NEW_LINE> <INDENT> model = b.Average() <NEW_LINE> model.fit(pd.Series(data)) <NEW_LINE> preds = model.predict(horizon) <NEW_LINE> assert len(preds) == expected
test the average class accepts pandas series
625941b930dc7b76659017e6
def __init__(self, name, network): <NEW_LINE> <INDENT> _BaseObject.__init__(self, network) <NEW_LINE> _Taggable.__init__(self, 'artist') <NEW_LINE> self.name = name
Create an artist object. # Parameters: * name str: The artist's name.
625941b9dd821e528d63b027
def top(self): <NEW_LINE> <INDENT> if self.is_empty(): <NEW_LINE> <INDENT> raise ValueError("Stack is Empty") <NEW_LINE> <DEDENT> return self._head.value
查询栈顶元素
625941b99b70327d1c4e0c50
def get_rupture_enclosing_polygon(self, dilation=0): <NEW_LINE> <INDENT> max_rup_radius = self._get_max_rupture_projection_radius() <NEW_LINE> return self.location.to_polygon(max_rup_radius + dilation)
Returns a circle-shaped polygon with radius equal to ``dilation`` plus :meth:`_get_max_rupture_projection_radius`. See :meth:`superclass method <openquake.hazardlib.source.base.SeismicSource.get_rupture_enclosing_polygon>` for parameter and return value definition.
625941b9d8ef3951e32433b9
def Load(self,m): <NEW_LINE> <INDENT> if isinstance(m,mspace.mspace): <NEW_LINE> <INDENT> self.m=m <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('invalid mspace object')
Load the mspace into mspaceExp
625941b92ae34c7f2600cfae
def extract_data(self, target): <NEW_LINE> <INDENT> angle = px2angle(target.width) <NEW_LINE> x_difference = (target.x - self.img_centerX) / self.img_centerX <NEW_LINE> diag_dist = px2dist(target.width) <NEW_LINE> horiz_dist = dist2horizontal(diag_dist) <NEW_LINE> self.distance_stabilizer.insert_measure(horiz_dist) <NEW_LINE> draw_data = {"Shooter Angle": angle, "X Difference": x_difference, "Horizontal Distance": self.distance_stabilizer.biggest()} <NEW_LINE> network_data = {"Shooter Angle": angle, "X Difference": x_difference} <NEW_LINE> return network_data, draw_data
625941b9e64d504609d746bd
def dots_test(self): <NEW_LINE> <INDENT> self._assert_username(".", False) <NEW_LINE> self._assert_username("..", False) <NEW_LINE> self._assert_username("...", True)
Test dots.
625941b93c8af77a43ae3619
def _register_directory(self, directory_type, use_name="name"): <NEW_LINE> <INDENT> if use_name == "name": <NEW_LINE> <INDENT> dir_location = "/".join([self._parent_dir, directory_type, self.NAME]) <NEW_LINE> <DEDENT> elif use_name == "generic": <NEW_LINE> <INDENT> dir_location = "/".join([self._parent_dir, directory_type, self.TYPE]) <NEW_LINE> <DEDENT> elif isinstance(use_name, str) and not use_name == "": <NEW_LINE> <INDENT> raise NameError("You must give either 'name' or 'generic'. Recieved %s. This entry is %s for 'name' and %s for 'generic'" % (use_name, use_name == "name", use_name == "generic")) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dir_location = "/".join([self._parent_dir, directory_type]) <NEW_LINE> <DEDENT> setattr(self, directory_type + "_dir", dir_location) <NEW_LINE> if not os.path.exists(dir_location): <NEW_LINE> <INDENT> os.makedirs(dir_location)
Sets an attribute ``component.<directory_type>_dir`` and creates the directory if it doesn't exist. Parameters ---------- directory_type : str The name of the directory type you want to register/create use_name : str, optional Default is "name". If this is set, the directory type will contain a sub-directory with the SimElement's ``NAME`` attribute. If you use "generic", you get a generic name for the subfolder. If you put anything "false"-y, you do not get a subname. Examples -------- >>> example_sim_element = SimElement() >>> example_sim_element._register_directory("outdata") >>> example_sim_element.outdata_dir ./outdata/component >>> example_sim_element._register_directory("analysis", use_name=False) >>> example_sim_element.analysis_dir ./analysis
625941b944b2445a33931f1c
def echo(msg): <NEW_LINE> <INDENT> pass
only for debug
625941b94e4d5625662d4259
def weight(self, svid): <NEW_LINE> <INDENT> N = self.N <NEW_LINE> if not svid in N: <NEW_LINE> <INDENT> return 0.01 <NEW_LINE> <DEDENT> if N[svid] > 20: <NEW_LINE> <INDENT> return 1.0 <NEW_LINE> <DEDENT> return 1.0 - (20 - N[svid])/20.0
return weighting to be used in position least squares
625941b98e7ae83300e4ae48
def level_emission(self, level): <NEW_LINE> <INDENT> return self.emission
Emission for level. override it to assign different emissions for different levels @param level: level where 0 is the root @return: a emission matrix (indexable object) with rows as states and columns as values for emission
625941b9498bea3a759b992d
def get_name_utf8(self): <NEW_LINE> <INDENT> return escape_as_utf8(self.name.encode('utf-8 ')if isinstance(self.name, str) else self.name)
Not all names are utf-8, attempt to construct it as utf-8 anyway.
625941b9711fe17d825421ef
def _init_revision(self, options): <NEW_LINE> <INDENT> with mo.MMALCameraInfo() as camera_info: <NEW_LINE> <INDENT> camera_num = options['camera_num'] <NEW_LINE> info = camera_info.control.params[mmal.MMAL_PARAMETER_CAMERA_INFO] <NEW_LINE> revision = 'ov5647' <NEW_LINE> if camera_info.info_rev > 1: <NEW_LINE> <INDENT> revision = info.cameras[camera_num].camera_name.decode('ascii') <NEW_LINE> <DEDENT> if PiCamera.MAX_RESOLUTION is PiCameraMaxResolution: <NEW_LINE> <INDENT> PiCamera.MAX_RESOLUTION = mo.PiResolution( info.cameras[camera_num].max_width, info.cameras[camera_num].max_height, ) <NEW_LINE> <DEDENT> <DEDENT> if PiCamera.MAX_FRAMERATE is PiCameraMaxFramerate: <NEW_LINE> <INDENT> if revision.lower() == 'ov5647': <NEW_LINE> <INDENT> PiCamera.MAX_FRAMERATE = 90 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> PiCamera.MAX_FRAMERATE = 120 <NEW_LINE> <DEDENT> <DEDENT> self._revision = revision
Query the firmware for the attached camera revision; older firmwares can't return the revision but only support the OV5647 sensor so we can assume that revision in such a case. This is also where the placeholder objects for MAX_RESOLUTION and MAX_FRAMERATE are replaced with their actual values
625941b955399d3f05588530
def create_table(self, table_name, *fields): <NEW_LINE> <INDENT> q = f" CREATE TABLE {table_name} (" <NEW_LINE> if fields: <NEW_LINE> <INDENT> for field in fields: <NEW_LINE> <INDENT> q += f'{field}, ' <NEW_LINE> <DEDENT> q = q[:len(q)-2] <NEW_LINE> q += ' )' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Creating the Table without any Fields!!!") <NEW_LINE> <DEDENT> with self.conn: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.c.execute(q) <NEW_LINE> print(f"TABLE Created ---> {table_name}") <NEW_LINE> <DEDENT> except sqlite3.OperationalError: <NEW_LINE> <INDENT> print(f"TABLE ---> ({table_name}) already exists!!") <NEW_LINE> <DEDENT> <DEDENT> self.conn.commit()
Parameters: table_name = The name of the table you want to create. fields = The fields along with their Type whic needs to be added to the Table. Ex :('firstname text', 'salary integer') Description: To Create Table in the Database along with specific fields.
625941b97b180e01f3dc4682
def add_cardlist(self, new_cardlist: CardList): <NEW_LINE> <INDENT> duplicate_cardlist = self.find_cardlist(new_cardlist) <NEW_LINE> if duplicate_cardlist is None: <NEW_LINE> <INDENT> self.cardlists.append(new_cardlist) <NEW_LINE> logger.info("Cardlist ({}) was added on the Board ({})".format(new_cardlist.id, self.id))
Adding new cardlist :param new_cardlist: new cardlist :return:
625941b992d797404e304006
def get_step_data(self, request, step): <NEW_LINE> <INDENT> return request.session[self.data_session_key][step]
Retrieves data for the specified step
625941b9ec188e330fd5a622
def set_session(session): <NEW_LINE> <INDENT> global _SESSION <NEW_LINE> _SESSION = session
Sets the global TensorFlow session. # Arguments session: A TF Session.
625941b945492302aab5e13d
def log(self, msg): <NEW_LINE> <INDENT> self.ansible.log(msg)
Prints log message to system log. Arguments: msg {str} -- Log message
625941b9cad5886f8bd26e5f
def __getitem__(self,key): <NEW_LINE> <INDENT> return self.d[key]
Return item with given key.
625941b9aad79263cf3908b8
def get_security_token(self): <NEW_LINE> <INDENT> if UtilClient.is_unset(self._credential): <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> token = self._credential.get_security_token() <NEW_LINE> return token
Get security token by using credential @rtype: unicode @return: security token
625941b98c0ade5d55d3e83c
def test_site_ga_id(self): <NEW_LINE> <INDENT> settings.SITE_GA_ID = 'UA-42868657-2' <NEW_LINE> request = self.factory.get('/') <NEW_LINE> context_extras = page(request) <NEW_LINE> page_context = context_extras['page'] <NEW_LINE> expected_page_context = { 'ga_id': settings.SITE_GA_ID } <NEW_LINE> self.assertEqual(page_context, expected_page_context, '%s must be %s' % (page_context, expected_page_context))
Tests that only SITE_GA_ID is defined
625941b9d58c6744b4257add
def getMatches(link,title,types=['ODI','T20I']): <NEW_LINE> <INDENT> http = urllib3.PoolManager() <NEW_LINE> r = http.request('GET', link) <NEW_LINE> soup = BeautifulSoup(r.data, 'lxml') <NEW_LINE> match = soup.findAll("div", {"class": 'cb-srs-mtchs-tm'}) <NEW_LINE> results,venue,links,typ = [],[],[],[] <NEW_LINE> for m in match: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> results.append(m.find_all('a')[1].text.strip()) <NEW_LINE> venue.append(m.div.text.strip()) <NEW_LINE> typ.append(m.span.text.strip().split()[-1].strip()) <NEW_LINE> links.append('https://www.cricbuzz.com/live-cricket-scorecard/'+"/".join(m.a['href'].split('/')[2:])) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return pd.DataFrame( {'title':title,'result':results, 'venue':venue, 'link':links, 'type':typ } )
link : series link title: title of series types: 'list to filter match'
625941b930bbd722463cbc3f
def find_link(self, soup, img_num=0): <NEW_LINE> <INDENT> link = soup.findAll('a')[int(img_num) + 3] <NEW_LINE> return [ self.images_domain + link['href'], link.text]
extract link to page holding image we want
625941b950485f2cf553cc15
def against_contigs(log, blast_db, query_file, hits_file, **kwargs): <NEW_LINE> <INDENT> cmd = [] <NEW_LINE> if kwargs['protein']: <NEW_LINE> <INDENT> cmd.append('tblastn') <NEW_LINE> cmd.append('-db_gencode {}'.format(kwargs['blast_db_gencode'])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cmd.append('blastn') <NEW_LINE> <DEDENT> cmd.append('-db {}'.format(blast_db)) <NEW_LINE> cmd.append('-query {}'.format(query_file)) <NEW_LINE> cmd.append('-out {}'.format(hits_file)) <NEW_LINE> cmd.append('-outfmt 15') <NEW_LINE> command = ' '.join(cmd) <NEW_LINE> log.subcommand(command, kwargs['temp_dir'], timeout=kwargs['timeout'])
Blast the query sequence against the contigs. The blast output will have the scores for later processing.
625941b91f037a2d8b94607b
@decorators.check_perm <NEW_LINE> def get_custom_monitor_num(request, cc_biz_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> monitor_num = len(Monitor.objects.filter(biz_id=cc_biz_id, monitor_type='custom', is_enabled=True)) <NEW_LINE> res = { 'result': True, 'message': '', 'data': monitor_num } <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.error(traceback.format_exc()) <NEW_LINE> res = { 'result': False, 'message': u"查询接口失败:%s" % e, 'data': [] } <NEW_LINE> <DEDENT> return render_json(res)
获取自定义监控数量 :param request: :param cc_biz_id: :return:
625941b923849d37ff7b2f0e
def alert(request, status, message): <NEW_LINE> <INDENT> return render( request, "exam/alert.html", { "status": status, "message": message } )
Shows page with message :param request: :param status: status (success, danger ... for bootstrap) :param message: message :return:
625941b938b623060ff0ac6c
def test_password_quality(self): <NEW_LINE> <INDENT> factories.PasswordQualityFactory.create(participant=self.old, is_insecure=True) <NEW_LINE> factories.PasswordQualityFactory.create(participant=self.tim, is_insecure=False) <NEW_LINE> self._migrate() <NEW_LINE> self.assertFalse(self.tim.passwordquality.is_insecure)
Only password quality from the newer participant is kept.
625941b90a366e3fb873e694
def draw(self, surface): <NEW_LINE> <INDENT> if self.__visible: <NEW_LINE> <INDENT> if self.active and self.active_image: <NEW_LINE> <INDENT> surface.blit(self.active_image, self.active_rect) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> surface.blit(self.image, self.rect) <NEW_LINE> <DEDENT> if self.text: <NEW_LINE> <INDENT> surface.blit(self.text.image, self.text.rect)
:param surface: :return:
625941b9a934411ee3751517
def is_full(board): <NEW_LINE> <INDENT> board_is_full = True <NEW_LINE> for row in board: <NEW_LINE> <INDENT> for col in row: <NEW_LINE> <INDENT> if col == 0: <NEW_LINE> <INDENT> board_is_full = False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return board_is_full
Returns True if board is full.
625941b930bbd722463cbc40
def test_home_view_returns_response(): <NEW_LINE> <INDENT> from PeerMid.views.default import home_page <NEW_LINE> request = testing.DummyRequest() <NEW_LINE> response = home_page(request) <NEW_LINE> assert isinstance(response, Response)
Home view returns a Response object.
625941b94428ac0f6e5ba66f
def reset_parcov(self, arg=None): <NEW_LINE> <INDENT> self.logger.statement("resetting parcov") <NEW_LINE> self.__parcov = None <NEW_LINE> if arg is not None: <NEW_LINE> <INDENT> self.parcov_arg = arg
reset the parcov attribute to None Args: arg (`str` or `pyemu.Matrix`): the value to assign to the parcov attribute. If None, the private __parcov attribute is cleared but not reset
625941b963b5f9789fde6f62
def init ( self, parent ): <NEW_LINE> <INDENT> self.control = LEDNumberCtrl( parent, -1 ) <NEW_LINE> self.control.SetAlignment( LEDStyles[ self.factory.alignment ] ) <NEW_LINE> self.set_tooltip()
Finishes initializing the editor by creating the underlying toolkit widget.
625941b9fff4ab517eb2f2b7
def makeCompMove(self): <NEW_LINE> <INDENT> row, col = -1, -1 <NEW_LINE> while not self.makeMove(row, col, 'O'): <NEW_LINE> <INDENT> col = random.randint(1,boardSize) <NEW_LINE> row = random.randint(1,boardSize) <NEW_LINE> <DEDENT> print("Computer chose: "+str(row)+","+str(col))
function ALPHA-BETA-SEARCH(state) returns an action v ←MAX-VALUE(state,−∞,+∞) return the action in ACTIONS(state) with value v function MAX-VALUE(state,α, β) returns a utility value if TERMINAL-TEST(state) then return UTILITY(state) # determine if state is terminal or not, a terminal state is when the board is full, or when min or max wins it is terminal v ←−∞ for each a in ACTIONS(state) do v ←MAX(v, MIN-VALUE(RESULT(s,a),α, β)) if v ≥ β then return v α←MAX(α, v) return v function MIN-VALUE(state,α, β) returns a utility value if TERMINAL-TEST(state) then return UTILITY(state) v ←+∞ for each a in ACTIONS(state) do v ←MIN(v, MAX-VALUE(RESULT(s,a) ,α, β)) if v ≤ α then return v β←MIN(β, v) return v
625941b9a4f1c619b28afebe
def _message_symbol(self, msgid): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return [md.symbol for md in self.msgs_store.get_message_definitions(msgid)] <NEW_LINE> <DEDENT> except UnknownMessageError: <NEW_LINE> <INDENT> return msgid
Get the message symbol of the given message id Return the original message id if the message does not exist.
625941b963d6d428bbe4436c
def serialize_property(self, value): <NEW_LINE> <INDENT> if isinstance(value, self.LITERAL_PROPERTY_TYPES): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> return port.to_u(value)
Serialize a Mixpanel property value. According to https://mixpanel.com/docs/properties-or-segments/property-data-types the allowed types are string, numeric, boolean, date (represented as a string) and list.
625941b99c8ee82313fbb5f2
def post_order(self): <NEW_LINE> <INDENT> return super(AVLBST, self).post_order()
Inherit method from superclass.
625941b930dc7b76659017e7
def conv_backward_naive(dout, cache): <NEW_LINE> <INDENT> dx, dw, db = None, None, None <NEW_LINE> x, w, b, conv_param = cache <NEW_LINE> pad = conv_param['pad'] <NEW_LINE> stride = conv_param['stride'] <NEW_LINE> F, C, HH, WW = w.shape <NEW_LINE> N, C, H, W = x.shape <NEW_LINE> H_new = 1 + (H + 2 * pad - HH) / stride <NEW_LINE> W_new = 1 + (W + 2 * pad - WW) / stride <NEW_LINE> dx = np.zeros_like(x) <NEW_LINE> dw = np.zeros_like(w) <NEW_LINE> db = np.zeros_like(b) <NEW_LINE> s = stride <NEW_LINE> x_padded = np.pad(x, ((0, 0), (0, 0), (pad, pad), (pad, pad)), 'constant') <NEW_LINE> dx_padded = np.pad(dx, ((0, 0), (0, 0), (pad, pad), (pad, pad)), 'constant') <NEW_LINE> for i in xrange(N): <NEW_LINE> <INDENT> for f in xrange(F): <NEW_LINE> <INDENT> for j in xrange(H_new): <NEW_LINE> <INDENT> for k in xrange(W_new): <NEW_LINE> <INDENT> window = x_padded[i, :, j*s:HH+j*s, k*s:WW+k*s] <NEW_LINE> db[f] += dout[i, f, j, k] <NEW_LINE> dw[f] += window * dout[i, f, j, k] <NEW_LINE> dx_padded[i, :, j*s:HH+j*s, k*s:WW+k*s] += w[f] * dout[i, f, j, k] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> dx = dx_padded[:, :, pad:pad+H, pad:pad+W] <NEW_LINE> return dx, dw, db
A naive implementation of the backward pass for a convolutional layer. Inputs: - dout: Upstream derivatives. - cache: A tuple of (x, w, b, conv_param) as in conv_forward_naive Returns a tuple of: - dx: Gradient with respect to x - dw: Gradient with respect to w - db: Gradient with respect to b
625941b9b830903b967e9793
def make_instance(self, include_optional): <NEW_LINE> <INDENT> if include_optional : <NEW_LINE> <INDENT> return DriverExternalIds( ) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return DriverExternalIds( )
Test DriverExternalIds include_option is a boolean, when False only required params are included, when True both required and optional params are included
625941b9b7558d58953c4d98
def get_geo_info(filename, band=1): <NEW_LINE> <INDENT> sourceds = gdal.Open(filename, GA_ReadOnly) <NEW_LINE> ndv = sourceds.GetRasterBand(band).GetNoDataValue() <NEW_LINE> xsize = sourceds.RasterXSize <NEW_LINE> ysize = sourceds.RasterYSize <NEW_LINE> geot = sourceds.GetGeoTransform() <NEW_LINE> projection = osr.SpatialReference() <NEW_LINE> projection.ImportFromWkt(sourceds.GetProjectionRef()) <NEW_LINE> datatype = sourceds.GetRasterBand(band).DataType <NEW_LINE> datatype = gdal.GetDataTypeName(datatype) <NEW_LINE> return ndv, xsize, ysize, geot, projection, datatype
Gets information from a Raster data set
625941b9eab8aa0e5d26d9db
def test_save_multiple_users(self): <NEW_LINE> <INDENT> self.user.saveUser() <NEW_LINE> test_user = User("Ray", "12345678") <NEW_LINE> test_user.saveUser() <NEW_LINE> self.assertEqual(len(User.userList), 2)
method to test multiple saved users
625941b9e8904600ed9f1da6
def find_xml_generator(name="castxml"): <NEW_LINE> <INDENT> if sys.version_info[:2] >= (3, 3): <NEW_LINE> <INDENT> path = _find_xml_generator_for_python_greater_equals_33(name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> path = _find_xml_generator_for_legacy_python(name) <NEW_LINE> <DEDENT> if path == "" or path is None: <NEW_LINE> <INDENT> raise Exception("No c++ parser found. Please install castxml.") <NEW_LINE> <DEDENT> return path.rstrip(), name
Try to find a c++ parser (xml generator) Args: name (str): name of the c++ parser (e.g. castxml) Returns: path (str), name (str): path to the xml generator and it's name If no c++ parser is found the function raises an exception. pygccxml does currently only support castxml as c++ parser.
625941b9379a373c97cfa9c7
def emit(self, ev_name): <NEW_LINE> <INDENT> for callback in self.callbacks[ev_name]: <NEW_LINE> <INDENT> callback(self)
Emit an event, triggered every callback registered to it.
625941b9925a0f43d2549cf1
def renderHook(self): <NEW_LINE> <INDENT> pass
Hook for post processing
625941b929b78933be1e5536
def _emitNewImageInfo(self): <NEW_LINE> <INDENT> printInfo("INFO: %s: MARKETPLACE_AND_IMAGEID %s %s" % (os.path.basename(self.args[0]), self.targetMarketplace, self.snapshotMarketplaceId))
To be able to recover image ID from log file by image creation test.
625941b90fa83653e4656e3a