code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
@app.route('/questions/add', methods=['GET', 'POST']) <NEW_LINE> def create(): <NEW_LINE> <INDENT> stuff = request.get_json() <NEW_LINE> if not stuff: <NEW_LINE> <INDENT> return jsonify({"message": "Question cannot be empty"}) <NEW_LINE> <DEDENT> title = stuff.get('title') <NEW_LINE> content = stuff.get('content') <NEW...
adding new questions
625941e10fa83653e4657350
def which(filename): <NEW_LINE> <INDENT> locations = os.environ.get("PATH").split(os.pathsep) <NEW_LINE> candidates = [] <NEW_LINE> for location in locations: <NEW_LINE> <INDENT> candidate = os.path.join(location, filename) <NEW_LINE> if os.path.isfile(candidate): <NEW_LINE> <INDENT> candidates.append(candidate) <NEW_L...
unix-style `which` implementation
625941e1eab8aa0e5d26def1
def sqlite_workaround(sender, connection, **kwargs): <NEW_LINE> <INDENT> if connection.vendor == 'sqlite': <NEW_LINE> <INDENT> cursor = connection.cursor() <NEW_LINE> cursor.execute('PRAGMA legacy_alter_table = ON;')
Enable integrity constraint with sqlite.
625941e1b830903b967e9c9f
@login_required <NEW_LINE> def import_contacts(request, template_name="friends/suggestions/import_contacts.html", extra_context=None): <NEW_LINE> <INDENT> import_in_progress = False <NEW_LINE> import_contacts_task_id = request.session.pop("import_contacts_task_id", None) <NEW_LINE> if import_contacts_task_id: <NEW_LINE...
If there is import_contacts_task_id in session pop it up and show info about this task using _import_status method. If there is no import_contacts_task_id in session check if there is google_authsub_token, facebook_token, twitter_token, yahoo_token or linkedin_token in session and import contacts according to this tok...
625941e1b7558d58953c52a5
def render_template(template_filename, context): <NEW_LINE> <INDENT> log.info("Rendering template: %s", template_filename) <NEW_LINE> return TEMPLATE_ENVIRONMENT.get_template(template_filename).render(context)
parse the xml file and return the content as a text :param template_filename: template filename path :param context: dictionary containing configurations :return: xml as a string
625941e11f5feb6acb0c4ee2
def PatchDatasets(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!')
Patch one or more datasets. The process is atomic, i.e. either all or no datasets are patched. If there is an error for one dataset, the process will stop, revert the transaction and return the error.
625941e185dfad0860c3b1f4
def __binary_read(self, addr, bytes, max_bytes=127): <NEW_LINE> <INDENT> buf = "" <NEW_LINE> while len(buf)< bytes: <NEW_LINE> <INDENT> L = len(buf) <NEW_LINE> read_blocks = min((bytes-L)/4, max_bytes) <NEW_LINE> self.flushInput() <NEW_LINE> self.__write('\x80' + chr(read_blocks) + pack(self.endian + 'I', addr+L)) <NEW...
Given the address of the register, reads and returns binary string containing contents of the register ---------------------- addr : address of the register to read from byte : number of bytes to read starting from the addr max_bytes :(don't change) maximum number of characters(blocks) that can be read at once(NOT FOR ...
625941e156ac1b37e6264561
def _get_previous_field_time(variable, year, month, day, hour, stream="enda"): <NEW_LINE> <INDENT> if stream == "enda": <NEW_LINE> <INDENT> return {"year": year, "month": month, "day": day, "hour": int(hour / 3) * 3} <NEW_LINE> <DEDENT> if stream == "oper": <NEW_LINE> <INDENT> return {"year": year, "month": month, "day...
Get the latest time, before the given time, for which there is saved data
625941e1ac7a0e7691ed445d
def __init__(self, item_codec, codecs_by_index={}, begin_delim="[", item_delim=",", end_delim="]", hook=None, unhook=None, hook_mode=None, allowedtype=(list, tuple), notify_encode=None, notify_decode=None, multiline=True, skip_whitespace_between_items=True, discardbufferdata=True, name="ListCodec" ): <NEW_LINE> <INDENT...
'item_codec': Default codec used to encode/decode items in list. 'codecs_by_index': Specify codecs to use for specific indices (overriding item_codec). 'begin_delim': Character or string used to mark beginning of list. If strip_whitespace == True, this parameter should NOT start with any whitespace! 'item_d...
625941e1ac7a0e7691ed445e
def move_right(self): <NEW_LINE> <INDENT> logging.debug('Moving Right') <NEW_LINE> self._toggle_pins([ self.PIN_MAP['RIGHT_BACKWARD'], ], 0.5)
Move the Killdozer Right.
625941e196565a6dacc8fa62
def visit(self, visitor: "CSTVisitorT") -> "Module": <NEW_LINE> <INDENT> with visitor.resolve(self): <NEW_LINE> <INDENT> return self.module.visit(visitor)
Convenience method to resolve metadata before performing a traversal over ``self.module`` with ``visitor``. See :func:`~libcst.Module.visit`.
625941e1cc40096d61595ce7
@require_http_methods(["GET", "POST"]) <NEW_LINE> def index(request): <NEW_LINE> <INDENT> global too_many_messages <NEW_LINE> if request.method == "POST": <NEW_LINE> <INDENT> new_item = planned_message( id=int(request.POST['id']), email=request.POST['email'], message = request.POST['message'], sec=int(request.POST['sec...
Вывод списка поставленных сообщений по GET, добавление по POST
625941e126238365f5f0f20b
def insert_people(self, person_list, c): <NEW_LINE> <INDENT> for person in person_list: <NEW_LINE> <INDENT> office = person.office.name if person.office else "" <NEW_LINE> c.execute( "INSERT INTO person_table (id, name, designation, " + "office) VALUES ('{}', '{}', '{}', '{}')".format( person.id, person.name, person.de...
This function executes the sql command insert to save each person in the Database
625941e17b25080760e397ef
def compute_sub(guard_str): <NEW_LINE> <INDENT> parens = [] <NEW_LINE> sub = [] <NEW_LINE> for i in range(len(guard_str)): <NEW_LINE> <INDENT> if guard_str[i] == '(': <NEW_LINE> <INDENT> parens.append(i) <NEW_LINE> <DEDENT> if guard_str[i] == ')': <NEW_LINE> <INDENT> j = parens.pop() <NEW_LINE> g = guard_str[j:i + 1].s...
Given a guard, return its sub-guards
625941e1b545ff76a89141ad
def filename(): <NEW_LINE> <INDENT> pass
return an associated filename, or `None`
625941e15fc7496912cc3d16
def find_NumSamplesPerSweep(self,): <NEW_LINE> <INDENT> return len(self.sweep_data[0]) if len(self.sweep_data) > 0 else 0
Function to find number of samples in each sweep from file header (if available)
625941e1711fe17d825426fb
def add_recipe(self, recipe): <NEW_LINE> <INDENT> recipe_hash = recipe.sha1_hex() <NEW_LINE> if recipe_hash not in self.recipes.keys(): <NEW_LINE> <INDENT> self.recipes[recipe_hash] = recipe <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
Mark recipe for insertion and perform the action
625941e18a43f66fc4b543f9
def buildPerspProjMat(self, m, fov, aspect, znear, zfar): <NEW_LINE> <INDENT> PI_OVER_360 = 0.00872664625 <NEW_LINE> xymax = 100 <NEW_LINE> ymax = znear * math.tan(fov * PI_OVER_360); <NEW_LINE> ymin = -xymax; <NEW_LINE> xmin = -xymax; <NEW_LINE> width = xymax - xmin; <NEW_LINE> height = xymax - ymin; <NEW_LINE> depth ...
DEBUG - THIS NEVER WORKED - UNTESTED #http://stackoverflow.com/questions/8633034/basic-render-3d-perspective-projection-onto-2d-screen-with-camera-without-openg # Transpose from column major to row major # [0 4 8 12] # [0 1 2 3] # [1 5 9 13] # [4 5 6 7] # [2 6 10 14] # [8 9 10 11] # [3 ...
625941e1cad5886f8bd27371
def overlap_almost_static_test(self): <NEW_LINE> <INDENT> def gen(): <NEW_LINE> <INDENT> for i in range(6): <NEW_LINE> <INDENT> yield numpy.array([[i * 11]]) <NEW_LINE> <DEDENT> <DEDENT> window = stream_functions.window(gen(), 3, 0.5) <NEW_LINE> numpy.testing.assert_array_equal(next(window), [[0], [11], [22]]) <NEW_LIN...
Test with such a big overlap that same block is returned several times
625941e11f037a2d8b946595
def test_intell_view_has_title(self): <NEW_LINE> <INDENT> c = Client() <NEW_LINE> res = c.get('/intell/') <NEW_LINE> assert b'<title>The start</title>' in res.content
.
625941e1d53ae8145f87a601
def __init__(self, document, visitor_cls): <NEW_LINE> <INDENT> self.visitor_cls = visitor_cls <NEW_LINE> self.document = document
:param document: The docutils document to use as a rendering base. This is *not* the document to render, but rendering a snippet requires a full document for things like settings and a reporter. :type document: docutils.nodes.document :param visitor_c...
625941e14527f215b584c7eb
def test_environment_create(self): <NEW_LINE> <INDENT> environment = self.create_murano_object('environment', 'TestMuranoSanityEnv') <NEW_LINE> env_list = self.listing('environment-list') <NEW_LINE> list(map(lambda x: x.pop('Updated', None), env_list + [environment])) <NEW_LINE> list(map(lambda x: x.pop('Created', None...
Test scenario: 1) create environment 2) check that created environment exist
625941e1c4546d3d9de72dcf
def test42_add(self): <NEW_LINE> <INDENT> self.username = Config().get('ZD_NAME') <NEW_LINE> self.psw = Config().get('PASSWORD') <NEW_LINE> self.loginid = Config().get('ZD_NAME') <NEW_LINE> self.phone = Config().get('PHONE') <NEW_LINE> self.A.IntoModule("总代1") <NEW_LINE> i = self.driver.find_element_by_id("mainIframe")...
新增总代理
625941e132920d7e50b2856b
def to_admin(login_url): <NEW_LINE> <INDENT> inject(login_url, "SET Users.User.1.X_ADB_Role AdminUser") <NEW_LINE> inject(login_url, "SET Users.User.1.X_ADB_CLIAccessCapable true")
Makes the default account admin.
625941e1de87d2750b86012e
def __init__(self, file, mode="r", compression=ZIP_STORED, allowZip64=True): <NEW_LINE> <INDENT> if mode not in ('r', 'w', 'x', 'a'): <NEW_LINE> <INDENT> raise RuntimeError("ZipFile requires mode 'r', 'w', 'x', or 'a'") <NEW_LINE> <DEDENT> _check_compression(compression) <NEW_LINE> self._allowZip64 = allowZip64 <NEW_LI...
Open the ZIP file with mode read 'r', write 'w', exclusive create 'x', or append 'a'.
625941e121a7993f00bc808e
def add_candidate(self, data, timestamp=None, proof=0): <NEW_LINE> <INDENT> if self.__candidate is not None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if timestamp is None: <NEW_LINE> <INDENT> timestamp = datetime.now() <NEW_LINE> <DEDENT> interval = timestamp - self.last_block.time...
Insert a new candidate in the chain Return: (logical): true where the candidate can be assigned
625941e126068e7796caf07c
def test_voi_zero_entries(self): <NEW_LINE> <INDENT> ds = dcmread(VOI_08_1F) <NEW_LINE> seq = ds.VOILUTSequence[0] <NEW_LINE> seq.LUTDescriptor = [0, 0, 16] <NEW_LINE> assert 256 == len(seq.LUTData) <NEW_LINE> arr = np.asarray([0, 255, 256, 65535]) <NEW_LINE> msg = r"index 256 is out of bounds" <NEW_LINE> with pytest.r...
Test that 0 entries is interpreted correctly.
625941e1aad79263cf390ddf
def _getuptime(self): <NEW_LINE> <INDENT> uptime_cmd = "/usr/bin/uptime" <NEW_LINE> (retval, output) = utils.safe_getstatusoutput( uptime_cmd ) <NEW_LINE> if retval != 0: <NEW_LINE> <INDENT> log.log( "<system>system._getuptime(): error calling '%s'"%(uptime_cmd), 5 ) <NEW_LINE> return None <NEW_LINE> <DEDENT> uptime_re...
Get system statistics from the output of the 'uptime' command.
625941e1379a373c97cfaedf
def create_tables(): <NEW_LINE> <INDENT> with warnings.catch_warnings(): <NEW_LINE> <INDENT> warnings.simplefilter('ignore') <NEW_LINE> connection = Connection.connect_to_database() <NEW_LINE> cursor = connection.cursor() <NEW_LINE> create_table_categories_req = "CREATE TABLE IF NOT EXISTS categories(" ...
Create tables if not exists
625941e17c178a314d6ef7fd
def test_forms(self): <NEW_LINE> <INDENT> for required in (True, False): <NEW_LINE> <INDENT> form = Form.objects.create(title="Form", status=CONTENT_STATUS_PUBLISHED) <NEW_LINE> for (i, (field, _)) in enumerate(fields.NAMES): <NEW_LINE> <INDENT> form.fields.create(label="Field %s" % i, field_type=field, required=requir...
Simple 200 status check against rendering and posting to forms with both optional and required fields.
625941e115baa723493c4310
def read_three_colors(file): <NEW_LINE> <INDENT> triplet = [] <NEW_LINE> color = bytearray() <NEW_LINE> while True: <NEW_LINE> <INDENT> this_byte = file.read(1) <NEW_LINE> if this_byte.isdigit(): <NEW_LINE> <INDENT> color += this_byte <NEW_LINE> <DEDENT> elif color or (triplet and this_byte == b""): <NEW_LINE> <INDENT>...
Generator to read integer values from file, in groups of three. Each value can be len 1-3, for values 0 - 255, space padded. :return tuple[int]:
625941e194891a1f4081be43
def save_data_array(filefolder, filename, array_to_save, image_object=None, interp_order=3, reshape=True): <NEW_LINE> <INDENT> if image_object is not None: <NEW_LINE> <INDENT> affine = image_object.original_affine[0] <NEW_LINE> image_pixdim = image_object.output_pixdim[0] <NEW_LINE> image_axcodes = image_object.output_...
write image data array to hard drive using image_object properties such as affine, pixdim and axcodes.
625941e191af0d3eaac9bdb4
def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> start, end = self.get_start_end_dates(self.request) <NEW_LINE> if start or end is not None: <NEW_LINE> <INDENT> category_list = [] <NEW_LINE> misc_items = 0 <NEW_LINE> discount = 0 <NEW_LINE> category_sales = {} <NEW_LINE> count_test_items = 0 <NEW_LINE> out = {...
Return sales per category { 'category': amount_of_sales, 'category': amount_of_sales }
625941e107d97122c4178c2c
def close_db(self): <NEW_LINE> <INDENT> if hasattr(self, '_cur_'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._cur_.close() <NEW_LINE> <DEDENT> except MySQLdb.ProgrammingError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> if hasattr(self, '_db_'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._db_.c...
Close the conection if it remains open
625941e1adb09d7d5db6cb26
def load_test_step(self, step, test, first_step=None) -> YAMLStep: <NEW_LINE> <INDENT> step_mapping = { "action": self.get_step_field(step.get("action"), test, first_step), "argument_1": self.get_step_field(step.get("argument_1"), test, first_step), "argument_2": self.get_step_field(step.get("argument_2"), test, first_...
Loads a test step Arguments: step {dict} -- Step details from file Keyword Arguments: first_step {TBBaseStep} -- First Step (default: {None}) Returns: YAMLStep -- The loaded step
625941e1498bea3a759b9e47
def SVM_binary_minimum(classifier: ActiveLearner, X_pool: modALinput, random_tie_break: bool = False) -> Tuple[np.ndarray, modALinput]: <NEW_LINE> <INDENT> decision_function = np.array([svm.decision_function(X_pool) for svm in classifier.estimator.estimators_]).T <NEW_LINE> min_abs_dist = np.min(np.abs(decision_functio...
SVM binary minimum multilabel active learning strategy. For details see the paper Klaus Brinker, On Active Learning in Multi-label Classification (https://link.springer.com/chapter/10.1007%2F3-540-31314-1_24) Args: classifier: The multilabel classifier for which the labels are to be queried. Must be an SVM model ...
625941e1d18da76e23532873
def p_exp_binop(p): <NEW_LINE> <INDENT> p[0] = ('binop', p[1], p[2], p[3])
exp : exp OROR exp | exp ANDAND exp | exp EQUALEQUAL exp | exp LT exp | exp GT exp | exp LE exp | exp GE exp | exp PLUS exp | exp MINUS exp | exp TIMES exp | exp DIVIDE exp
625941e176e4537e8c351a0e
def toDict(self): <NEW_LINE> <INDENT> dict_legs = [] <NEW_LINE> for leg in self.data['legs']: <NEW_LINE> <INDENT> leg = leg.toDict() <NEW_LINE> leg['index'] = len(dict_legs) <NEW_LINE> dict_legs.append(leg) <NEW_LINE> <DEDENT> order = self.data.copy() <NEW_LINE> order['legs'] = dict_legs <NEW_LINE> return order
Generate a python dictionary from this Order instance
625941e1bde94217f3683186
def __init__( self, *, op: Union[str, "JsonPatchOperation"], path: str, value: Optional[Any] = None, from_property: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(JsonPatchDocument, self).__init__(**kwargs) <NEW_LINE> self.op = op <NEW_LINE> self.path = path <NEW_LINE> self.value = value <NEW_LINE> self.fr...
:keyword op: Required. The operation to be performed. Possible values include: "add", "remove", "replace", "move", "copy", "test". :paramtype op: str or ~azure.quantum._client.models.JsonPatchOperation :keyword path: Required. A JSON-Pointer. :paramtype path: str :keyword value: A value to be used in the operation on ...
625941e1435de62698dfdfe6
def update(self, items, uselimit=True): <NEW_LINE> <INDENT> self.clear() <NEW_LINE> self.curfactory = csinfo.factory(self.currepo, self.custom) <NEW_LINE> self.curitems = items <NEW_LINE> if not items or not self.currepo: <NEW_LINE> <INDENT> self.updatestatus() <NEW_LINE> return False <NEW_LINE> <DEDENT> if self.compac...
Update the item list. Public arguments: items: List of revision numbers and/or patch file paths. You can pass a mixed list. The order will be respected. uselimit: If True, some of items will be shown. return: True if the item list was updated successfully, False if it wasn't updated.
625941e1d268445f265b5207
def get_cores(self): <NEW_LINE> <INDENT> return {str(x.name): x for x in self.db.find()}
Get a dict with all cores, indexed by the core name
625941e11f037a2d8b946596
def get_avg_distance(self, graph): <NEW_LINE> <INDENT> edges = graph.edges() <NEW_LINE> logging.debug("edge attr: {}".format(nx.get_edge_attributes(graph, "weight"))) <NEW_LINE> edge_dist = list(map(lambda x: graph[x[0]][x[1]]["weight"] * 80, edges)) <NEW_LINE> logging.debug("edge_dist: {}".format(edge_dist)) <NEW_LINE...
This method gets the average link distance for a given input graph :param graph: Graph to calculate the average link distance for :return: average link distance :rtype: float
625941e191f36d47f21ac88f
def _get_service_teams_cost( self, date, forecast, service_environments, ): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for team in Team.objects.all(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> team_cost = plugin_runner.run( 'scrooge_costs', 'team_plugin', type='total_cost', date=date, team=team, forecast=forecast, s...
Calculates total cost of teams for given pricing service, using real or forecast prices/costs. Total cost is calculated for period of time (between start and end) and for specified service environments.
625941e1f7d966606f6aa3a2
def test_example(self): <NEW_LINE> <INDENT> argument = [1, 2, 3] <NEW_LINE> expected = [0, 2, 4] <NEW_LINE> dp.double_preceding(argument) <NEW_LINE> self.assertEqual(expected, argument, "This test is a given.")
Test the example given in problem
625941e1dc8b845886cb58cf
def levelOrder(self, root): <NEW_LINE> <INDENT> res = [] <NEW_LINE> level = [root] <NEW_LINE> while root and level: <NEW_LINE> <INDENT> res.append([node.val for node in level]) <NEW_LINE> level = [child for node in level for child in (node.left, node.right) if child] <NEW_LINE> <DEDENT> return res
:type root: TreeNode :rtype: List[List[int]]
625941e1bf627c535bc13568
def Application(args=None, raw=False, autoExit=True, url=None): <NEW_LINE> <INDENT> global _app <NEW_LINE> if _app is None: <NEW_LINE> <INDENT> if args is None: <NEW_LINE> <INDENT> args = sys.argv <NEW_LINE> <DEDENT> if url is None: <NEW_LINE> <INDENT> url = '' <NEW_LINE> <DEDENT> if not args: <NEW_LINE> <INDENT> args ...
Instantiates and returns the Application instance.
625941e1462c4b4f79d1da68
def prefixSum(self, a): <NEW_LINE> <INDENT> i = a + 1 <NEW_LINE> total = 0 <NEW_LINE> while i > 0: <NEW_LINE> <INDENT> total += self.s[i] <NEW_LINE> i -= (i & -i) <NEW_LINE> <DEDENT> return total
:param int a: index in t, negative a will return 0 :returns: t[0] + ... + t[a]
625941e10a50d4780f66722e
def count_nutrition_grade(food_facts_df): <NEW_LINE> <INDENT> food_facts_df['Count'] = 1 <NEW_LINE> food_facts_df["year"] = food_facts_df["created_datetime"].dt.year <NEW_LINE> nutrition_over_time_reduced = food_facts_df[['year', 'nutrition_grade', 'Count']] <NEW_LINE> nutrition_over_time_reduced = nutrition_over_time_...
Count grades based on year and grade. :param food_facts_df: :return: food_facts_df_counted
625941e182261d6c526ab83d
def __add__(self, other): <NEW_LINE> <INDENT> return self.add(other)
переопределяет оператор + , возвращает вектор
625941e1fff4ab517eb2f7d7
def test_load_node_set_by_id_existing(self): <NEW_LINE> <INDENT> id_set = ['skill_00'] <NEW_LINE> q = ['create (s:Skill {id: \'skill_00\'} )'] <NEW_LINE> op = DBO_raw_query_set(q) <NEW_LINE> self.db_ctl.exec_op(op) <NEW_LINE> with self.webapp.test_client() as c: <NEW_LINE> <INDENT> req, req_data = self._json_post(c, '/...
Loading an existing node test
625941e1796e427e537b0961
def newJob(self): <NEW_LINE> <INDENT> conn = sqlite3.connect(settings.DB_PATH) <NEW_LINE> c = conn.cursor() <NEW_LINE> process_id = self.process_id <NEW_LINE> new_title = self.new_title.get() <NEW_LINE> if (not new_title) or (not new_title.strip()): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> new_remark = self.new_r...
用于开始计时器
625941e14527f215b584c7ec
def check_runner_report_junit(self): <NEW_LINE> <INDENT> mock_cluster = LocalhostCluster(num_nodes=1000) <NEW_LINE> session_context = tests.ducktape_mock.session_context() <NEW_LINE> test_methods = [TestThingy.test_pi, TestThingy.test_ignore1, TestThingy.test_ignore2, TestThingy.test_failure] <NEW_LINE> ctx_list = self...
Check we can serialize results into a xunit xml format. Also ensures that the XML report adheres to the Junit spec using xpath queries
625941e1009cb60464c63748
def has_cached(self, inst): <NEW_LINE> <INDENT> return self._method.has_cached(inst)
Returns :keyword:`True` if a result has been cached for the property on the specified instance: >>> class Example(object): >>> >>> @fin.cache.property >>> def one(self): >>> return 1 >>> e = Example() >>> Example.one.has_cached(e) False >>> e.one 1 >>> Exam...
625941e13539df3088e2e6e4
def compute_posterior_mean_mcmc(self, force_monte_carlo=False): <NEW_LINE> <INDENT> posterior_mean_mcmc = 0 <NEW_LINE> for gp in self._gaussian_process_list: <NEW_LINE> <INDENT> posterior_mean_mcmc += C_GP.compute_posterior_mean( gp._gaussian_process, self._num_fidelity, cpp_utils.cppify(self._points_to_sample), ) <NEW...
Compute the knowledge gradient at ``points_to_sample``, with ``points_being_sampled`` concurrent points being sampled. .. Note:: These comments were copied from :meth:`moe.optimal_learning.python.interfaces.expected_improvement_interface.ExpectedImprovementInterface.compute_expected_improvement` ``points_to_sample`...
625941e1bd1bec0571d909c8
def test_db_map(self): <NEW_LINE> <INDENT> class WildDBNames(Model): <NEW_LINE> <INDENT> id = columns.UUID(primary_key=True, default=uuid4) <NEW_LINE> content = columns.Text(db_field="words_and_whatnot") <NEW_LINE> numbers = columns.Integer(db_field="integers_etc") <NEW_LINE> <DEDENT> db_map = WildDBNames._db_map <NEW_...
Tests that the db_map is properly defined -the db_map allows columns
625941e166656f66f7cbc546
def test_add_overlay_overwrite(self): <NEW_LINE> <INDENT> builder = ConfigBuilder().add_overlay("DiscoveryCommunity", "anonymous id", [], [], {}, [], allow_duplicate=False) <NEW_LINE> expected = { 'class': "DiscoveryCommunity", 'key': "anonymous id", 'walkers': [], 'bootstrappers': [], 'initialize': {}, 'on_start': [] ...
Check if the allow duplicate flag does not introduce duplicates.
625941e1cb5e8a47e48b7e3e
def insert_char(string, char, pos): <NEW_LINE> <INDENT> return string[:pos] + char + string[pos:]
Insert substring in a string.
625941e1dd821e528d63b53f
def set_normalised_progress(self, norm_progress: int): <NEW_LINE> <INDENT> if type(norm_progress) != float and type(norm_progress) != int: <NEW_LINE> <INDENT> raise TypeError("Normalised progress must be a float or an integer, not {}!".format(type(norm_progress))) <NEW_LINE> <DEDENT> elif _NORMALISED_MIN > norm_progres...
Function used to set the progress value from a normalised value, using MIN/MAX normalisation :param norm_progress: Normalised value to update the progress with
625941e14d74a7450ccd455d
def home(request): <NEW_LINE> <INDENT> stories = Story.objects.all().order_by('pubdate')[:3] <NEW_LINE> no_sidebar = True <NEW_LINE> return render_to_response('home/home.html', locals(), context_instance=RequestContext(request))
Display homepage (logged in or not)
625941e1d486a94d0b98e4e0
@app.route('/hero/<string:hero_name>', methods=['GET']) <NEW_LINE> def get_hero_by_hero_name(hero_name: str): <NEW_LINE> <INDENT> hero = mongo.db.lost_hero.find_one_or_404({'hero_name': hero_name}) <NEW_LINE> return jsonify({'Hero Info': data_template(hero)})
Information about particular hero. :param hero_name: name of a hero to find.
625941e1a934411ee3751a2e
def _update_view(self): <NEW_LINE> <INDENT> NavigationToolbar2._update_view(self) <NEW_LINE> self._myParent.evt_view_updated() <NEW_LINE> return
view update called by home(), back() and forward() :return:
625941e156ac1b37e6264562
def __init__(self, console_height, console_width): <NEW_LINE> <INDENT> self.console_height, self.console_width = console_height, console_width <NEW_LINE> self.win_height, self.win_width = 8, 50 if console_width >= 50 else console_width <NEW_LINE> begin_y, begin_x = util.center_start(console_height, console_width, self....
Initialize IntroScreen :param console_height: the height of the console :param console_width: the width of the console :return: null
625941e1e1aae11d1e74a054
def response_add(self, request, obj, post_url_continue=None): <NEW_LINE> <INDENT> if '_addanother' not in request.POST and '_popup' not in request.POST: <NEW_LINE> <INDENT> request.POST['_continue'] = 1 <NEW_LINE> <DEDENT> return super(UsuarioAdmin, self).response_add(request, obj, post_url_continue)
Determines the HttpResponse for the add_view stage. It mostly defers to its superclass implementation but is customized because the User model has a slightly different workflow.
625941e18e7ae83300e4b367
def getRoute(self, origin, dest, maxJumpLy, avoiding=[], stationInterval=0): <NEW_LINE> <INDENT> if isinstance(origin, Station): <NEW_LINE> <INDENT> origin = origin.system <NEW_LINE> <DEDENT> if isinstance(dest, Station): <NEW_LINE> <INDENT> dest = dest.system <NEW_LINE> <DEDENT> if origin == dest: <NEW_LINE> <INDENT> ...
Find a shortest route between two systems with an additional constraint that each system be a maximum of maxJumpLy from the previous system. Args: origin: System (or station) to start from, dest: System (or station) to terminate at, maxJumpLy: Maximum light years between systems, ...
625941e10fa83653e4657352
def convert_components(components): <NEW_LINE> <INDENT> converted_components = [] <NEW_LINE> for component in components: <NEW_LINE> <INDENT> converted_components.append(convert_component(component)) <NEW_LINE> <DEDENT> return converted_components
Construct a list of QueryComponents from 'components' Args: components: A list of QueryComponents or tuples
625941e1379a373c97cfaee0
def run(self): <NEW_LINE> <INDENT> super(VennTableTool, self).run() <NEW_LINE> self._create_venn_table() <NEW_LINE> self.end()
运行
625941e17d43ff24873a303c
def loss(self, X, y=None, reg=0.0): <NEW_LINE> <INDENT> W1, b1 = self.params['W1'], self.params['b1'] <NEW_LINE> W2, b2 = self.params['W2'], self.params['b2'] <NEW_LINE> N, D = X.shape <NEW_LINE> scores = None <NEW_LINE> relu_layer = np.maximum(0, np.dot(X, W1) + b1) <NEW_LINE> scores = np.dot(relu_layer, W2) + b2 <NEW...
Compute the loss and gradients for a two layer fully connected neural network. Inputs: - X: Input data of shape (N, D). Each X[i] is a training sample. - y: Vector of training labels. y[i] is the label for X[i], and each y[i] is an integer in the range 0 <= y[i] < C. This parameter is optional; if it is not passed...
625941e1167d2b6e31218f2e
def score(self, eval_data, eval_metric, num_batch=None, batch_end_callback=None, score_end_callback=None, reset=True, epoch=0, sparse_row_id_fn=None): <NEW_LINE> <INDENT> assert self.binded and self.params_initialized <NEW_LINE> if reset: <NEW_LINE> <INDENT> eval_data.reset() <NEW_LINE> <DEDENT> if not isinstance(eval_...
Runs prediction on ``eval_data`` and evaluates the performance according to the given ``eval_metric``. Checkout `Module Tutorial <http://mxnet.io/tutorials/basic/module.html>`_ to see a end-to-end use-case. Parameters ---------- eval_data : DataIter Evaluation data to run prediction on. eval_metric : EvalMetric o...
625941e1baa26c4b54cb14b6
def pop(self): <NEW_LINE> <INDENT> if len(self.output) == 0: <NEW_LINE> <INDENT> while self.input: <NEW_LINE> <INDENT> self.output.append(self.input.pop()) <NEW_LINE> <DEDENT> <DEDENT> return self.output.pop()
Removes the element from in front of queue and returns that element. :rtype: int
625941e10383005118ecf97b
def toFeatures(self,object): <NEW_LINE> <INDENT> s = structure(object) <NEW_LINE> try: <NEW_LINE> <INDENT> f = self.structureToFeatureMiner[s].features <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise ValueError("Structure never encountered before") <NEW_LINE> <DEDENT> return s,extract(object,f)
Returns a pair (s,f) where s is an object structure description and f is a flattened feature vector. If the structure is not recognized, a ValueError is raised.
625941e14e4d5625662d476d
def leafs(self): <NEW_LINE> <INDENT> return self.filter(lft=models.F('rght') - 1)
Leaf birds do not contain anything
625941e11f5feb6acb0c4ee3
def __init__(self, config): <NEW_LINE> <INDENT> self.config = MqttClient.default_config <NEW_LINE> if config: <NEW_LINE> <INDENT> for k, v in config.iteritems(): <NEW_LINE> <INDENT> self.config[k] = v <NEW_LINE> <DEDENT> <DEDENT> self.mqtt_client = Client() <NEW_LINE> self.mqtt_client.username_pw_set(config["username"]...
Initialize information for the client provide configurations as parameter, if None provided the configurations would be defaults see MqttClient.default_config for configurations format
625941e1460517430c394516
def setup_config(app, configfilename=None): <NEW_LINE> <INDENT> log.debug('setup configuration') <NEW_LINE> app.config.from_object('%s.defaultconfig' % __name__) <NEW_LINE> if configfilename: <NEW_LINE> <INDENT> app.config.from_pyfile(configfilename) <NEW_LINE> <DEDENT> if 'P2PTRACKERCONFIG' in os.environ: <NEW_LINE> <...
Load the configuration for this app
625941e1ac7a0e7691ed445f
def OnManipulationStarting(self,*args): <NEW_LINE> <INDENT> pass
OnManipulationStarting(self: UIElement,e: ManipulationStartingEventArgs) Provides class handling for the System.Windows.UIElement.ManipulationStarting routed event that occurs when the manipulation processor is first created. e: A System.Windows.Input.ManipulationStartingEventArgs that contains the event ...
625941e1d4950a0f3b08c6e4
def clean_item_status(record): <NEW_LINE> <INDENT> options = { "on shelf": "CAN_CIRCULATE", "missing": "MISSING", "on loan": "CAN_CIRCULATE", "in binding": "IN_BINDING", } <NEW_LINE> try: <NEW_LINE> <INDENT> record["status"] = options[record["status"]] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise Item...
Translates item statuses.
625941e1aad79263cf390de0
@with_device <NEW_LINE> def uptime(): <NEW_LINE> <INDENT> up, idle = map(float, read('/proc/uptime').split()) <NEW_LINE> return up
uptime() -> float Returns: Uptime of the device, in seconds
625941e1bde94217f3683187
def test_x86_64_elf_parse(self): <NEW_LINE> <INDENT> dyn_nexe = os.path.join(DATA_DIR, 'test_dynamic_x86_64.nexe') <NEW_LINE> static_nexe = os.path.join(DATA_DIR, 'test_static_x86_64.nexe') <NEW_LINE> arch, dynamic = create_nmf.ParseElfHeader(dyn_nexe) <NEW_LINE> self.assertEqual(arch, 'x86-64') <NEW_LINE> self.assertT...
Test parsing of x86-64 elf header.
625941e15510c4643540f775
def calculate_signals(self, event): <NEW_LINE> <INDENT> if event.type == EventType.SENTIMENT: <NEW_LINE> <INDENT> ticker = event.ticker <NEW_LINE> if ticker != "SPY": <NEW_LINE> <INDENT> if ( self.invested[ticker] is False and event.sentiment >= self.sent_buy ): <NEW_LINE> <INDENT> print("LONG %s at %s" % (ticker, even...
Calculate the signals for the strategy.
625941e1711fe17d825426fd
def setUp(self): <NEW_LINE> <INDENT> lam_left = np.array([0.0, .25, .4]) <NEW_LINE> lam_right = np.array([1.0, 4.0, .5]) <NEW_LINE> lam_width = lam_right - lam_left <NEW_LINE> self.lam_domain = np.zeros((3, 2)) <NEW_LINE> self.lam_domain[:, 0] = lam_left <NEW_LINE> self.lam_domain[:, 1] = lam_right <NEW_LINE> num_sampl...
Test dimension, number of samples, and that all the samples are within lambda_domain.
625941e1be383301e01b5819
def create_room_json(nid, name, zone, avail, capacity): <NEW_LINE> <INDENT> data = {} <NEW_LINE> data['id'] = nid <NEW_LINE> data['name'] = name <NEW_LINE> data['zone'] = zone <NEW_LINE> data['avail'] = avail <NEW_LINE> data['capacity'] = capacity <NEW_LINE> return json.dumps(data)
Creates JSON Room Object
625941e14a966d76dd5513ac
def test_PathMismatch(self): <NEW_LINE> <INDENT> for gPath in self.PathMissMatch: <NEW_LINE> <INDENT> with self.assertRaises(TypeError, msg = str(gPath)): <NEW_LINE> <INDENT> self.TestFunction(self.Data, gPath, 9, bStrict = True) <NEW_LINE> <DEDENT> with self.assertRaises(TypeError, msg = str(gPath)): <NEW_LINE> <INDEN...
Checks that TypeError sub-class exception is raised if a generic path is of the proper type, but the path element type does not match the type of the object at the respective nesting level. Test ID: TEST-T-550. Covers requirements REQ-FUN-550 and REQ-AWM-500.
625941e13d592f4c4ed1d3fe
def bootstrap(): <NEW_LINE> <INDENT> local("git submodule init") <NEW_LINE> local("git submodule update") <NEW_LINE> local("virtualenv {}".format(ENV_DIR)) <NEW_LINE> requirements = os.path.join(BASE_DIR, 'requirements.txt') <NEW_LINE> with virtualenv(): <NEW_LINE> <INDENT> local("pip install -r {}".format(requirements...
Setup virtual env and python packages.
625941e1cad5886f8bd27373
def get_app_dir(): <NEW_LINE> <INDENT> app_path = sys.path[0] <NEW_LINE> if os.path.isfile(app_path): <NEW_LINE> <INDENT> app_path = os.path.dirname(app_path) <NEW_LINE> <DEDENT> if os.path.isfile(os.path.join(app_path, "custom_config.py")): <NEW_LINE> <INDENT> app_path = os.path.abspath(app_path) <NEW_LINE> return app...
The application directory is the one where the default custom_config.py file resides. :returns: app_path - the path to the applicatin directory
625941e124f1403a92600efd
def extract_metadata(self, name=None): <NEW_LINE> <INDENT> meta_xml = self.metadata(as_pretty_xml=True) <NEW_LINE> if meta_xml is None: <NEW_LINE> <INDENT> logger.info("unable to access the metadata") <NEW_LINE> return <NEW_LINE> <DEDENT> if name is None: <NEW_LINE> <INDENT> name = os.path.join(self.default_metadata_fi...
Save metadata on disk name The file path where the metadata will be saved. If None, use a default name.
625941e150485f2cf553d135
def parse_test_data(best_result, vocab): <NEW_LINE> <INDENT> docs, labels = read_data(os.path.join('data', 'test')) <NEW_LINE> tokens = [] <NEW_LINE> for doc in docs: <NEW_LINE> <INDENT> toks = tokenize(doc, keep_internal_punct=best_result['punct']) <NEW_LINE> tokens.append(toks) <NEW_LINE> <DEDENT> X,vocab = vectorize...
Using the vocabulary fit to the training data, read and vectorize the testing data. Note that vocab should be passed to the vectorize function to ensure the feature mapping is consistent from training to testing. Note: use read_data function defined above to read the test data. Params: best_result...Element of eval_a...
625941e1d53ae8145f87a603
def test_match_or_target_is_changed(self) -> None: <NEW_LINE> <INDENT> dataset = InflatedFeatureFilteredDataset( TensorDataset(original_inputs, original_targets), {1: 2, 2: 1}, match_type=any ) <NEW_LINE> for idx in [2, 3, 4, 5]: <NEW_LINE> <INDENT> assert original_targets[idx] == dataset[idx][1] <NEW_LINE> <DEDENT> fo...
Tests whether the target is changed for an 'any' feature match.
625941e1c4546d3d9de72dd1
def checkValues(self): <NEW_LINE> <INDENT> if self.dskValues['dskErrorFlag']: <NEW_LINE> <INDENT> status = self.CRITICAL <NEW_LINE> self.infoText = self.dskValues['dskErrorMsg'] <NEW_LINE> <DEDENT> for column in self.thresholds: <NEW_LINE> <INDENT> self.evalThresholds(column, self.dskValues[column], self.thresholds[col...
Do the actual checks on the status of the disk.
625941e176e4537e8c351a0f
def computeC(self, freqs, z_mat_arg, e_eqs=None, channel_names=None): <NEW_LINE> <INDENT> z_mat_arg = self._preprocessZMatArg(z_mat_arg) <NEW_LINE> if isinstance(freqs, float) or isinstance(freqs, complex): <NEW_LINE> <INDENT> freqs = np.array([freqs]) <NEW_LINE> <DEDENT> if e_eqs is None: <NEW_LINE> <INDENT> e_eqs = [...
Fit the models' capacitances to a given impedance matrix. !!! This function assumes that the conductances are already fitted!!! Parameters ---------- freqs: np.array (dtype = complex) Frequencies at which the impedance matrix is evaluated zf_mat: np.ndarray (ndim = 3, dtype = complex) The impe...
625941e126068e7796caf07e
def test_with_upgrade(self): <NEW_LINE> <INDENT> result = parse_options(['upgrade', self.sitedir1]) <NEW_LINE> self.assertIsNotNone(result) <NEW_LINE> self.assertIsInstance(result['command'], UpgradeCommand) <NEW_LINE> self.assertEqual(result['site_paths'], [self.sitedir1])
Testing rb-site parse_options with upgrade
625941e1d18da76e23532874
def get_import_resource_kwargs(self, request, *args, **kwargs): <NEW_LINE> <INDENT> return self.get_resource_kwargs(request, *args, **kwargs)
Prepares/returns kwargs used when initializing Resource
625941e1d164cc61757830e9
def setup_socket(self, server_url, message_handler): <NEW_LINE> <INDENT> def on_socket_open(*args): <NEW_LINE> <INDENT> self.send_alive() <NEW_LINE> <DEDENT> def on_new_message(*args): <NEW_LINE> <INDENT> message_handler(args[0]) <NEW_LINE> <DEDENT> def on_disconnect(*args): <NEW_LINE> <INDENT> self.disconnected = True...
Sets up a socket for an agent
625941e15f7d997b87174e36
def __init__(self, show_result=None,vocab=None, print_ratio=False): <NEW_LINE> <INDENT> if vocab and not hasattr(vocab, "to_word"): <NEW_LINE> <INDENT> raise TypeError( f"`vocab` in {_get_func_signature(self.__init__)} must be Fastnlp.core.Vocabulary," f"got {type(vocab)}.") <NEW_LINE> <DEDENT> self.confusiondict = {} ...
:param show_result: list type, 数据类型需要和target保持一致 :param vocab: 需要有to_word方法,建议直接使用Fastnlp.core.Vocabulary。 :param print_ratio: 限制print的输出,False只输出数量Confusion Matrix, True还会输出百分比Confusion Matrix, 分别为行/列
625941e1379a373c97cfaee1
def parse_request_data(): <NEW_LINE> <INDENT> album = request.forms.get("album") <NEW_LINE> artist = request.forms.get("artist") <NEW_LINE> genre = request.forms.get("genre") <NEW_LINE> year = request.forms.get("year") <NEW_LINE> album = Album( album=album, artist=artist, genre=genre, year=year ) <NEW_LINE> validate_va...
Parses data from POST-request.
625941e1d7e4931a7ee9e2b9
def test_quantity_iterability(): <NEW_LINE> <INDENT> q1 = [15.0, 17.0] * u.m <NEW_LINE> assert isiterable(q1) <NEW_LINE> q2 = six.next(iter(q1)) <NEW_LINE> assert q2 == 15.0 * u.m <NEW_LINE> assert not isiterable(q2) <NEW_LINE> pytest.raises(TypeError, iter, q2)
Regressiont est for issue #878. Scalar quantities should not be iterable and should raise a type error on iteration.
625941e130bbd722463cc162
def get_mit_bih_segments(data: wfdb.Record, annotations: wfdb.Annotation, labels: np.ndarray, left_offset: int = 99, right_offset: int = 160, fixed_length: Optional[int] = None) -> Tuple[np.ndarray, np.ndarray]: <NEW_LINE> <INDENT> i = 0 <NEW_LINE> annot_segments = [] <NEW_LINE> while (i < len(annotations.symbol)): <NE...
It generates the segments of uninterrupted sequences of arrythmia beats into the corresponding arrythmia groups in labels. Parameters ---------- data : wfdb.Record The arrythmia signal as a wfdb Record class annotations : wfdb.Annotation The set of annotations as a wfdb Annotation class labels : array-like ...
625941e1e5267d203edce033
def sumRegion(self, row1, col1, row2, col2): <NEW_LINE> <INDENT> sum = 0 <NEW_LINE> return self.dp[row2+1][col2+1] - self.dp[row1][col2+1] - self.dp[row2+1][col1] + self.dp[row1][col1]
:type row1: int :type col1: int :type row2: int :type col2: int :rtype: int
625941e13eb6a72ae02ec881
def test_performance(self): <NEW_LINE> <INDENT> for gender, age, event, performance, expected in [ ('M', 12, '1500', '4:32.00', 1154), ('M', 12, '1000W', '280.30', 1137), ('M', 12, '200H68.0cm18.29m', '30.50', 1138), ('M', 12, 'PV', '2.50', 965), ('M', 12, 'SP3Kg', '5.00', 379), ('M', 12, 'SP3Kg', '10.0', 922), ('M', 1...
test returned points. Input string or float perfprmance
625941e173bcbd0ca4b2c410
def get_user_likes_count_by_qs(like_qs): <NEW_LINE> <INDENT> return like_qs.count()
通过qs获取用户点赞的个数 :param like_qs: :return:
625941e1d18da76e23532875
def _build_page(self, page_name, data): <NEW_LINE> <INDENT> page = { 'type': 'page', 'title': page_name, 'body': { 'storage': { 'representation': 'storage', 'value': data['content'], } }, 'metadata': { 'properties': { 'editor': { 'value': 'v1', } } }, 'space': { 'key': self.space_key, }, } <NEW_LINE> return page
build a page entity used for a new or updated page event Will return a dictionary containing the minimum required information needed for a `put` event when publishing a new or update page. Args: page_name: the page title to use on the page data: the page data to apply
625941e176e4537e8c351a10
def tag_directions(self): <NEW_LINE> <INDENT> ngs = list(self.spec._nonghost_slice) <NEW_LINE> for i, periodic in enumerate(reversed(self.spec._periodicity)): <NEW_LINE> <INDENT> if not periodic: <NEW_LINE> <INDENT> ngs[i] = slice(None) <NEW_LINE> <DEDENT> <DEDENT> uniq_types = set(np.unique(self._type_map.base)) <NEW_...
Creates direction tags for nodes that support it. Direction tags are a way of summarizing which distributions at a node will be undefined after streaming. :rvalue: True if there are any nodes supporting tagging, False otherwise
625941e1091ae356686672f3