query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Method is used to perform a single row insert into the specified table in the current database. This should be used if only one insert needs to occur as it automatically calls the transactionEnd method and commits the changes; essentially, calling object/class/script does not need to worry about committing the changes.
def singleInsert(self, table_name, fields, field_values, field_types=[]): if not self.checkTable(table_name): self.createTable(table_name, fields, field_types) self.transactionInsert(table_name, fields, field_values) self.transactionEnd()
[ "def insert(self):\n sql = u'INSERT INTO %s' % self.table()\n keys = []\n values = []\n format_values = []\n for field in self.fields():\n attr = object.__getattribute__(self, field)\n if attr.auto_value:\n continue\n keys.append(fie...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method performs a transaction insert. The purpose of this method is to allow for a large number of inserts to the specified table in the current database efficiently. This is done by not performing a commit statement until the super object/class/script specifically calls the transactionEnd method, which then performs t...
def transactionInsert(self, t_name, fields, field_values): query = 'INSERT INTO {0} ({1}) VALUES ({2});' field_list_string = ','.join(fields) query_parameters = ','.join(['?'] * len(fields)) query = query.format(t_name, field_list_string, query_parameters) try: self....
[ "def insert(self, tablename, seqname=None, _test=False, **values):\r\n def q(x): return \"(\" + x + \")\"\r\n \r\n if values:\r\n _keys = SQLQuery.join(values.keys(), ', ')\r\n _values = SQLQuery.join([sqlparam(v) for v in values.values()], ', ')\r\n sql_query =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method counts the number of rows in the specified table in the current database.
def countTable(self, in_table_name): self.cursor.execute('SELECT COUNT(*) FROM {};'.format(in_table_name)) return self.cursor.fetchone()[0]
[ "def count_rows(self, table):\n t = self._metadata.tables[table]\n return self._eng.execute(func.count(t.columns[t.columns.keys()[0]])).scalar()", "def db_count(conn, table):\n sql = f\"SELECT COUNT(*) as count FROM {table};\"\n logger.debug(f\"db_count() sql: {sql}\")\n cursor = conn.curso...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method creates a table in the current database of the passed in table name with the passed in field names and field types. Method first zips together the field names and field types list,
def createTable(self, in_table_name, in_field_names, in_field_types): zipped_fields = zip(in_field_names, in_field_types) fields = ['{} {}'.format(fn, ft) for fn,ft in zipped_fields] query = 'CREATE TABLE {} ({});' self.cursor.execute(query.format(in_table_name, ','.join(fields))) ...
[ "def create_table(con, s_table, tbl, S_type=None, c_rename = None):\n cur = con.cursor()\n from string import join\n if S_type is None:\n S_type=util.col_types(tbl)\n fields = []\n for i,c_name in enumerate(tbl.columns):\n if S_type[i] ==\"i\":\n f_type= \"integer\"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given two object's attributes, if they are equivalent, return valueEquivalent object, else return None.
def index_equivalent_value(indexer, obj1, attr1, obj2, attr2): eq_conds = indexer.index_by_type(ValueEquivalence) for cond in eq_conds: r = cond.relationship obj_list = r.obj_list attr_list = r.attr_list if obj1 in obj_list and obj2 in obj_list \ ...
[ "def equiv_attrs(self, one, two):\n tups = self.tuple_relations()\n return find_closure(tups, [one]) == find_closure(tups, [two])", "def equivalent(self, other):\n return id(self) == id(other)", "def __eq__(self, other):\n for attr in self._attrs_to_save:\n try:\n if ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compare 2 .INI format files and ensure that at minimum customfile contains ALL sections and options from defaultfile. If PATCH is True and EXACT is False update customfile without changing any custom option values. If EXACT is True and PATCH is True erase all custom values and duplicate default entirely. IF PATCH is Fa...
def patch_ini_file(defaultfile, customfile, PATCH=True, EXACT=False): default_options = SafeConfigParser() result = default_options.read(defaultfile) # returns an empty list if file error if result == []: raise IOError personalized_options = SafeConfigParser() result = personalized_options....
[ "def test_get_spec_config_match(self):\n spec_conf = get_spec_config({\n 'defaults': {\n 'default_foo': 'default_bar',\n 'foo': 'bar'\n },\n 'specific': [\n {'mask': ['filenomatch'], 'foo': 'bar_nomatch'},\n {'mask':...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
use patch_ini_file function to test a file for correctness as an INI file
def ini_file_can_be_parsed(filename): from ConfigParser import ParsingError as ParseError from ConfigParser import InterpolationSyntaxError as InterpError import sys result = False print print 'testing: ' + filename try: result = patch_ini_file(filename, filename) print "good...
[ "def test_custom_ini(self, tmpdir):\n fn = tmpdir.join(\"custom.ini\")\n fn.write(\"[pytest]\\nx=1\")\n assert load_config_dict_from_file(fn) == {\"x\": \"1\"}", "def test_pytest_ini(self, tmpdir):\n fn = tmpdir.join(\"pytest.ini\")\n fn.write(\"[pytest]\\nx=1\")\n assert...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes a valid INI filename and returns a dictionary of the sections, options and values
def parse_ini_file_into_dict(filename): output = {} INIfile = SafeConfigParser() result = INIfile.read(filename) # returns an empty list if file error if result == []: raise IOError #iterate through INI file and build dictionary for section_name in INIfile.sections(): section_d...
[ "def __ini_to_dictionary(config_file):\n\n config = configparser.ConfigParser()\n config.read(config_file)\n\n dictionary = {}\n for section in config.sections():\n dictionary[section] = {}\n for option in config.options(section):\n dictionary[section][option] = config.get(secti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
inserts a new Node into the correct sorted position in the list
def sorted_insert(self, value): if self.__head is None: self.__head = Node(value, None) elif value < self.__head.data: self.__head = Node(value, self.__head) else: n = self.__head while n.next_node is not None and n.next_node.data <= value: ...
[ "def sorted_insert(self, value):\n new = Node(value)\n if self.__head is None:\n self.__head = new\n return\n\n cur = self.__head\n if new.data < cur.data:\n new.next_node = self.__head\n self.__head = new\n return\n\n while (...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw a meter line
def updateMeterLine(self, a): self.angle = a x = winw - 190 * cos(a * pi) y = winw - 190 * sin(a * pi) self.canvas.coords(self.meter, winw, winw, x, y)
[ "def draw_line(self, x):\n self.PDF.setStrokeColor(black01)\n self.PDF.setLineWidth(1)\n self.PDF.line(75, x, 550, x)\n self.PDF.setStrokeColor(\"black\")", "def drawSlope(self):\n length = sqrt(1 + self.slope**2) # Length of the line segment over 1 x-unit\n xOffset = (se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Downloads subect 100307 of the WuMinn HCP data and prepares it to be used for the dmipy example notebooks.
def download_and_prepare_dmipy_example_dataset(self): subject_ID = 100307 self.download_subject(subject_ID) self.prepare_example_slice(subject_ID)
[ "def download_proteins():\n print(\"Downloading dataset...\")\n print(\"This might a take while..\")\n url = \"https://portal.nersc.gov/project/m1982/GNN/\"\n file_name = \"subgraph3_iso_vs_iso_30_70length_ALL.m100.propermm.mtx\"\n url = url + file_name\n try:\n req = requests.get(url)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The Mean Squared Error between the two images is the sum of the squared difference between the two images. The lower the error, the more similar the two images are.
def _mean_squared_error(img1, img2): err = np.sum((img1.astype("float") - img2.astype("float")) ** 2) err /= float(img1.shape[0] * img1.shape[1]) return err
[ "def mse(img1, img2): \n # TODO: implement this function.\n error = np.sum((img1.astype(\"float\") - img2.astype(\"float\")) ** 2)\n error = error/float(img1.shape[0] * img2.shape[1])\n\n return error", "def mse(image1: np.ndarray, image2: np.ndarray) -> np.ndarray:\n return np.sqrt(np.power((im...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Permet d'incrémenter (uniquement) le score du joueur
def augmente_score(self, valeur): self._score += valeur
[ "def increment_score(self):\n self.score += 1", "def increaseScore(self):\n self.score = self.score+1", "def increase_score(self):\n self.score += 1", "def updateScore(score):\n return score + 1", "def increase_score(self, score):\r\n self.score += score", "def increase_score(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Based on the distances between each positions relative to each other, identifies the ones that lie within the radius threshold, those will be considered loops.
def _compute_loop_matrix(self, positions: torch.Tensor) -> torch.Tensor: distances = self._location_distances(positions) loops = distances <= self.loop_radius_threshold return loops
[ "def _count_crossings(neurite, radius):\n r2 = radius ** 2\n count = 0\n for start, end in iter_segments(neurite):\n start_dist2, end_dist2 = (morphmath.point_dist2(center, start),\n morphmath.point_dist2(center, end))\n\n count += int(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update if not exceeding total, else set indeterminate range.
def increment_with_overflow(self): if self.n == self.total: self.total = 0 if self._pbar: self._pbar.setRange(0, 0) else: self.update(1)
[ "def update_amount(self, new_amount=None):\n if not new_amount:\n new_amount = self.amount\n if new_amount < self.min:\n new_amount = self.min\n if new_amount > self.max:\n new_amount = self.max\n self.amount = new_amount\n self.build_bar()", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shorthand for `progress(range(args), kwargs)`. Adds tqdm based progress bar to napari viewer, if it exists, and returns the wrapped range object. Returns progress wrapped range object
def progrange(*args, **kwargs): return progress(range(*args), **kwargs)
[ "def tnrange(*args, **kwargs):\n return tqdm_notebook(_range(*args), **kwargs)", "def trange(*args, **kwargs):\n try:\n f = xrange\n except NameError:\n f = range\n \n return tqdm(f(*args), **kwargs)", "def tnrange(*args, **kwargs): # pragma: no cover\n from ._tqdm_notebook impo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate the release notes of a gitlab project from the last release
def generate_release_notes(project_id, endstr = ' <br>', **config): gl = gitlab.Gitlab(**config) project = gl.projects.get(project_id) if not project.mergerequests.list(state='merged'): raise ValueError(f"There is not merged merge request for project {project_id} {project.name}") if not proj...
[ "def get_release_notes(self):\n\n notes = self.output.get_header('RELEASE NOTES')\n notes += 'https://{}/{}/{}/releases'.format(HOST_GITHUB, \\\n self.repo, self.product) + '\\n'\n\n notes += self.output.get_sub_header('COMPARISONS')\n n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves a xkcd comic, from a number, random, or latest xkcd for that xkcd number xkcd random for a random xkcd xkcd latest for the latest xkcd
async def get_xkcd(self, ctx, number = "random"): if not self.module_check(ctx): return if number == "latest": r = requests.get('https://xkcd.com/info.0.json') elif number == "random": r = requests.get('https://xkcd.com/info.0.json') r = json.loads(r.text) random_xkcd = random.randin...
[ "def xkcd(bot, event, *args):\n\n xkcd_obj = _get_comic()\n\n if args:\n\n if args[0] == 'random':\n\n xkcd_obj = _get_comic(randint(1, xkcd_obj['num']))\n\n elif match('^\\d*$', args[0]):\n\n if int(args[0]) <= xkcd_obj['num'] and int(args[0]) >= 1:\n\n xkcd...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handler to be fired up upon comments signal to notify the author of a given article.
def notify_comment(**kwargs): # pragma: no cover actor = kwargs["request"].user receiver = kwargs["comment"].content_object.user obj = kwargs["comment"].content_object notification_handler(actor, receiver, Notification.COMMENTED, action_object=obj)
[ "def comment_added(self, event):\n pass", "def notify(self, thing, redditor, link, body, author):\n if self.quiet or util.is_ignored(redditor):\n return\n\n quote = util.quote(body)\n msg = self.NOTIFICATION_BODY % (thing, link, author, quote)\n\n while msg.__len__() ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list with the ecosystems from the database
def getEcosystems(self): return self.__getColumnData(Q_ECOSYSTEMS, 'ecosystem')
[ "def systems (self):\r\n\r\n\t\t# dance with the API.\r\n\t\tresponse = self.__API(\"server/systems\")\r\n\r\n\t\t# returns a list, we assign it into a dictionary.\r\n\t\tcontent = '{\"systems\":' + response.content + '}'\r\n\r\n\t\t# parse the JSON into a container and return the systems list we just created above...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a string with the last query that was executed
def getLastQuery(self): return self.lastQuery
[ "def get_last_query(self):\n return self.query_history[-1][0] if self.query_history else None", "def get_last_result(self) -> str:\n pass", "def last_data_received_query(self) -> Optional[str]:\n return pulumi.get(self, \"last_data_received_query\")", "def get_last_executed(self, cursor):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns an argument labelled by 'needle' assumes argument immediately follows it's label
def find_arg(needle, haystack): for i in range(0, len(haystack)): if haystack[i] == needle: try: return haystack[i+1] except IndexError: pass return None
[ "def find_needle(haystack):\n return 'found the needle at position {}'.format(haystack.index('needle'))", "def find_arg(self, idx: int, line: Statement,\n cmp: type(lambda: None),\n rule: str, argname: str) -> Statement:\n i = idx\n fantasy = line.fantasy\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prompt the user to choose an item Returns the selected item, or `None`
def pick_item(items, labels, title="Pick an item", label="Pick an item", default=None): if default in items: current = items.index(default) else: current = 0 choice, isok = QtWidgets.QInputDialog.getItem(None, title, label, la...
[ "def ask_for_choice(self):\n return input()", "def get_user_choice():\n user_input = input('Your choice: ')\n return user_input", "def get_user_choice():\n user_input = input(\"Your choice: \")\n return user_input", "def select(self, _: int = 0) -> None:\n if not self.all_items:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prompt the user to pick from a list of classes using Qt This is the same as `pick_item`, but the labels are automatically determined from the classes using the LABEL attribute, and if not set, then the __name__. Returns the class that was selected, or `None`
def pick_class(classes, sort=False, **kwargs): def _label(c): try: return c.LABEL except AttributeError: return c.__name__ if sort: classes = sorted(classes, key=lambda x: _label(x)) choices = [_label(c) for c in classes] return pick_item(classes, choices...
[ "def choose_class(self, *args, **kwargs):", "def pick_item(items, labels, title=\"Pick an item\", label=\"Pick an item\",\n default=None):\n\n if default in items:\n current = items.index(default)\n else:\n current = 0\n\n choice, isok = QtWidgets.QInputDialog.getItem(None, tit...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
MTurk itself is the source of truth for most data required to run tasks on MTurk. The datastore holds sessions to connect with MTurk as well as mappings between MTurk ids and Mephisto ids
def initialize_provider_datastore(self, storage_path: str) -> Any: return MTurkDatastore(datastore_root=storage_path)
[ "def _set_memcache(self):\r\n # Pull directly from the datastore in order to ensure that the\r\n # information is as up to date as possible.\r\n if self.writer == \"datastore\":\r\n data = {}\r\n sessiondata = self._get()\r\n if sessiondata is not None:\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the path to the `wrap_crowd_source.js` file for this provider to be deployed to the server
def get_wrapper_js_path(cls): return os.path.join(os.path.dirname(__file__), "wrap_crowd_source.js")
[ "def path(self) -> str:\n return self.src + \"/\"", "def generate_js_dir():\n\n return pkg_resources.resource_filename('linkedin.mobster.har.visualization.js', None)", "def _get_path_to_front_end():\n dpath = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'fe')\n log(\"F...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove the qualification from the sandbox server, if it exists
def cleanup_qualification(self, qualification_name: str) -> None: mapping = self.datastore.get_qualification_mapping(qualification_name) if mapping is None: return None requester_id = mapping["requester_id"] requester = Requester.get(self.db, requester_id) assert isi...
[ "def test_delete_antivirus_server(self):\n pass", "def test_remove_share(self):\n self.app.delete(url=\"/config/shares?share=80&destination=gsiftp://nowhere&vo=dteam\", status=400)\n self.app.delete(url=\"/config/shares?share=80&destination=gsiftp://nowhere&vo=dteam&source=gsiftp://source\", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fires on Redshift cluster creation, parses the event, starts and passes event summary to the Step Function state machine that will arrange for the Creator tag to be added.
def redshift_lambda_handler(event, context): logging.debug('event: %s', event) detail = event['detail'] event_name = detail['eventName'] creator = get_creator(event) logger.info('Event type: %s', event_name) if is_err_detail(logger, detail): return False if event_name == 'CreateC...
[ "def create_cluster(self):\n\n # Upload bootstrap scripts to S3\n# if self.script_bucket_name:\n# self.upload_to_s3()\n\n # Launch the cluster\n self.emr_response = self.load_cluster()\n self.emr_client = self.boto_client(\"emr\")\n\n # Monitor cluster creati...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the general orthogonal group. The general orthogonal group `GO(n,R)` consists of all `n\times n` matrices over the ring `R` preserving an `n`ary positive definite quadratic form. In cases where there are muliple nonisomorphic quadratic forms, additional data needs to be specified to disambiguate. In the case of ...
def GO(n, R, e=0, var='a'): degree, ring = normalize_args_vectorspace(n, R, var=var) e = normalize_args_e(degree, ring, e) if e == 0: name = 'General Orthogonal Group of degree {0} over {1}'.format(degree, ring) ltx = r'\text{{GO}}_{{{0}}}({1})'.format(degree, latex(ring)) else: ...
[ "def SO(n, R, e=None, var='a'):\n degree, ring = normalize_args_vectorspace(n, R, var=var)\n e = normalize_args_e(degree, ring, e)\n if e == 0:\n name = 'Special Orthogonal Group of degree {0} over {1}'.format(degree, ring)\n ltx = r'\\text{{SO}}_{{{0}}}({1})'.format(degree, latex(ring))\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the special orthogonal group. The special orthogonal group `GO(n,R)` consists of all `n\times n` matrices with determinant one over the ring `R` preserving an `n`ary positive definite quadratic form. In cases where there are muliple nonisomorphic quadratic forms, additional data needs to be specified to disambig...
def SO(n, R, e=None, var='a'): degree, ring = normalize_args_vectorspace(n, R, var=var) e = normalize_args_e(degree, ring, e) if e == 0: name = 'Special Orthogonal Group of degree {0} over {1}'.format(degree, ring) ltx = r'\text{{SO}}_{{{0}}}({1})'.format(degree, latex(ring)) else: ...
[ "def GO(n, R, e=0, var='a'):\n degree, ring = normalize_args_vectorspace(n, R, var=var)\n e = normalize_args_e(degree, ring, e)\n if e == 0:\n name = 'General Orthogonal Group of degree {0} over {1}'.format(degree, ring)\n ltx = r'\\text{{GO}}_{{{0}}}({1})'.format(degree, latex(ring))\n e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the symmetric bilinear form preserved by the orthogonal group.
def invariant_bilinear_form(self): from sage.matrix.constructor import identity_matrix m = identity_matrix(self.base_ring(), self.degree()) m.set_immutable() return m
[ "def sym_bilinear_form(self, name=None, latex_name=None):\n return self.tensor((0,2), name=name, latex_name=latex_name, sym=(0,1))", "def extract_symmetry(self):\n # currently this is only for horizontal symmetry\n if len(self.image.shape) == 3:\n height, width, _ = self.image.shap...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the quadratic form preserved by the orthogonal group.
def invariant_quadratic_form(self): from sage.matrix.constructor import identity_matrix m = identity_matrix(self.base_ring(), self.degree()) m.set_immutable() return m
[ "def invariant_quadratic_form(self):\n m = self.gap().InvariantQuadraticForm()['matrix'].matrix()\n m.set_immutable()\n return m", "def quadratic_constraints(self, *args):\n return self._make_group(self.constraint_type.quadratic, *args)", "def get_quadratic(self, *args):\n\n d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
a Check whether the matrix ``x`` is symplectic.
def _check_matrix(self, x, *args): if self._special and x.determinant() != 1: raise TypeError('matrix must have determinant one') F = self.invariant_bilinear_form() if x * F * x.transpose() != F: raise TypeError('matrix must be orthogonal with respect to the invariant for...
[ "def isspmatrix(x):\n return isinstance(x, spmatrix)", "def test_is_symplectic():\n theta = np.pi / 6\n r = np.arcsinh(1.0)\n phi = np.pi / 8\n S = symplectic.rotation(theta)\n assert symplectic.is_symplectic(S)\n S = symplectic.squeezing(r, theta)\n assert symplectic.is_symplectic(S)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the quadratic form preserved by the orthogonal group.
def invariant_quadratic_form(self): m = self.gap().InvariantQuadraticForm()['matrix'].matrix() m.set_immutable() return m
[ "def invariant_quadratic_form(self):\n from sage.matrix.constructor import identity_matrix\n m = identity_matrix(self.base_ring(), self.degree())\n m.set_immutable()\n return m", "def quadratic_constraints(self, *args):\n return self._make_group(self.constraint_type.quadratic, *...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verifies if a date has already been stored in the repo in order to avoid duplications
def alreadyStored(self, date_): for day in self._repo: if day.date == date_: return True return False
[ "def test_duplicate_detection_with_invalid_date(self):\n service = factories.ServiceFactory.create()\n self.client.force_login(service.project.owned_by)\n\n factories.LoggedHoursFactory.create(\n service=service, rendered_by=service.project.owned_by\n )\n\n response = s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Stores all the days in descending order by the number of activities that take place during said days
def storeDays(self, actRepo): for act in actRepo.getAll(): if self.alreadyStored(act.date) == False: day = Day(act.date, 0) day.setNumberOfActivities(day.getNumberOfActivities(actRepo)) poz = self.findPoz(day) self._repo.insert(po...
[ "def sort_by_remaining_days(self):\n self.seiyuu_objects.sort(key=lambda x: x.get_remaining_days(), reverse=False)", "def get_day_activities(self, ord):\n da = [a for a in self.activities\n if a.start.date() == self.get_date(ord).date()]\n da.sort(key=lambda x: x.start)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Yield successive nsized chunks from arr.
def chunks(arr, n): for i in range(0, len(arr), n): yield arr[i:i + n]
[ "def chunks(arr, n):\n for i in range(0, len(arr), n):\n yield arr[i:i + n]", "def chunks(A, N):\n for i in range(0, len(A)):\n r = A[i:i+N]\n if len(r) == N:\n yield r", "def chunks(data: List[Any], num: int) -> Generator[List[Any], None, None]:\n for i in range(0, len(data),...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this function checks if user's account is lock
def check_lock(username): try: users = file_manager.read_from_file('users_data.json') user = users[username] except KeyError: return 2 if user["status"]: return 1 else: lock_time = datetime.strptime(user["lock_time"], "%Y-%m-%d %H:%M:%S") if lock_time + ...
[ "def can_lock_account(self):\n return False", "def IsLocked(self) -> bool:\n ...", "def is_locked(self):\n now = datetime.datetime.utcnow()\n if self.locked_until and self.locked_until >= now:\n return True\n elif self.locked_until and self.locked_until < now:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Specific volume from SA, CT & p (75term equation) Calculates specific volume from Absolute Salinity, Conservative Temperature and pressure, using the computationallyefficient 75term polynomial expression for specific volume (Roquet et al., 2015).
def specvol(SA, CT, p): SA = np.maximum(SA, 0) xs = np.sqrt(sfac * SA + soffset) ys = CT * 0.025 z = p * 1e-4 specific_volume = (v000 + xs * (v100 + xs * (v200 + xs * (v300 + xs * (v400 + xs * (v500 + xs * v600))))) + ys * (v010 + xs * (v110 + xs * (v210 + ...
[ "def surfaceVolumeFactor(porosity, density, grainDiameter):\n grainRadius = 0.5*grainDiameter\n \n grainSurface = 4.*3.1415926535897931*grainRadius**2 # surface of 1 grain\n \n print(\"grainSurface %e\\n\"%grainSurface)\n \n grainVolume = grainSurface*grainRad...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function will grab the contract addresses from the brownie config if defined, otherwise, it will deploy a mock version of that contract, and return that mock contract.
def get_contract(contract_name): contract_type = CONTRACT_TO_MOCK[contract_name] if network.show_active() in LOCAL_BLOCKCHAIN_ENVIRONMENTS: if len(contract_type) <= 0: deploy_mocks() contract = contract_type[-1] else: contract_address = config["networks"][network.show_act...
[ "def deploy_tester_contract(\n web3: Web3, contracts_manager: ContractManager, deploy_contract: Callable\n) -> Callable:\n\n def f(contract_name: str, **kwargs: Dict) -> Contract:\n json_contract = contracts_manager.get_contract(contract_name)\n contract = deploy_contract(\n web3, CON...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draws the Logo to the window
def drawLogo(self): logoText, logoSize = self.logo.draw() self.drawCenteredText(logoText, logoSize, .5, .25)
[ "def draw_logo(self):\n\n logo_path = os.path.join(MYPATH, '../media/logo_mini.png')\n button = QPushButton('', self)\n button.setIcon(QIcon(logo_path))\n button.setIconSize(QtCore.QSize(80, 80))\n button.setGeometry(20, 30, 80, 80)\n button.setToolTip(\"Open micrOS repo do...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the oldest nr num, that is in DRAFT status It then marks the NR as INPROGRESS, and assigns it to the User as found in the JWT It also moves control of the Request from NRO so that NameX fully owns it
def get(): # GET existing or CREATE new user based on the JWT info try: user = get_or_create_user_by_jwt(g.jwt_oidc_token_info) except ServicesError as se: return jsonify(message='unable to get ot create user, aborting operation'), 500 except Exception as unmanag...
[ "def patch(nr, *args, **kwargs):\n\n # do the cheap check first before the more expensive ones\n # check states\n json_input = request.get_json()\n if not json_input:\n return jsonify({'message': 'No input data provided'}), 400\n\n # find NR\n try:\n u...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Patches the NR. Currently only handles STATE (with optional comment) and Previous State.
def patch(nr, *args, **kwargs): # do the cheap check first before the more expensive ones # check states json_input = request.get_json() if not json_input: return jsonify({'message': 'No input data provided'}), 400 # find NR try: user = get_or_cr...
[ "def _maybe_update_old_line_num(item, cur_old_line_num):\n return _maybe_update_diff_line_num(item, cur_old_line_num, 'old')", "def _patches_rc_increment(cls):\n assert cls._patches_rc >= 0\n cls._patches_rc += 1\n if cls._patches_rc == 1:\n # patches not yet applied\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return a datatables table of Products
def product_datatables(request, country): template = loader.get_template('products_dt.html') context = { 'country': country, } return HttpResponse(template.render(context, request))
[ "def show_all_products():\n\n data = cur.execute(\"\"\"SELECT productid, productname, unitcost, stock FROM catalogue\"\"\").fetchall()\n\n print(tabulate(data, headers=[\"Product ID\", \"Name\", \"Cost\", \"Stock\"]))", "def product_tables(self): \r\n\r\n self.mycursor.execute('CREATE TABLE IF NOT EX...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return Prices of a Product in JSON for chart.js
def price_chart_json(request, prod_id): prices = Product.objects.get(prod_id=prod_id).prices labels = [] data = [] for price in prices: labels.append(price.updated_at.strftime('%Y-%m-%d %H:%M')) data.append(price.price_discounted) output = { 'labels': labels, 'dataset...
[ "def get_product_price_mapping():\n json_path = os.path.abspath('src/products.json')\n \n with open(json_path) as f:\n products = json.load(f)\n return products", "def products():\n page = request.args.get('page')\n sorted_data = get_sorted_products_by_price()\n if not page or int(page...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Lee todas las entradas y asigna los valores al dicionario de valores
def leer(self): for k in self._inserters.keys(): self._valores[k] = self._inserters[k].get_value() self._activado = True
[ "def set_valores(self,valores):\n self.__valores = valores\n for (id_propiedad,valor) in valores.items():\n propiedad = dbaccess.buscar_propiedad(id_propiedad)\n nombre_codif = ''\n if propiedad.get('clase') == u'tecnológica':\n \"\"\" Recorremos las cod...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to calculate nearest square of any number.
def nearest_square(num): answer = 0 while (answer+1)**2 < num: answer += 1 return answer**2
[ "def sqrt_nearest(n):\n a, b = n, 0\n while a != b:\n a, b = a--n//a>>1, a\n return a", "def nearest_sq(n):\n\t# range from 0 to n + 1\n\tfor i in range (n + 1):\n\t\tif (i ** 2 == n):\n\t\t\treturn n\n\t\tif (i ** 2 > n):\n\t\t\t# test to see what is the closest square\n\t\t\tif (abs(((i - 1) ** ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
First disables keyboard input then prints out the passed text's characters over time in the console/terminal window.
def type_out(text): disable_typing.start() text = text + "\n" for c in text: sys.stdout.write(c) sys.stdout.flush() time.sleep(0.01) disable_typing.stop()
[ "def typing(text, speed):\n for char in text:\n sys.stdout.write(char)\n sys.stdout.flush()\n time.sleep(speed)", "def hideCursor():\n print(\"\\u001b[?25l\", end='')", "def typer(text, delay=0.08, out=sys.stdout):\n for char in text:\n out.write(char)\n out.flush()\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Connect to serial device
def connect(self): try: if not self.serial.isOpen(): self.serial = serial.Serial( self.port, self.baudrate, timeout=self.timeout, rtscts=self.hardware_flagging, xonxoff=self.softwa...
[ "def connect(self):\n # open serial port\n try:\n #device = self.get_device_name(self.serial_number)\n device = \"/dev/ttyAMA0\"\n self.serial.port = device\n # Set RTS line to low logic level\n self.serial.rts = False\n self.serial.ope...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Disconnect from serial device
def disconnect(self): try: if self.serial.isOpen(): self.serial.close() print("disconnected from %s") % (self.port) except serial.SerialException as e: msg = "unable to disconnect from %s" % (self.port) raise Exception(msg, e)
[ "def disconnect(self):\n self.serial.close()\n self.connected = 0", "def disconnect_usb(self):\n\n self.device_serial.close()\n self.device_serial = None", "def serial_close(self):\n self.dongle.close()", "def disconnect(self):\n self.arduino.close()\n self.arduino...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test number of articles
def testArticleCount(self): self.articleCount(17)
[ "def num_articles(self):\n\t\treturn len(index)", "def test_count_publications(self):\n pass", "def test_article_list_plugin_article_count():\n article_count = 10\n create_articles(article_count)\n publish_articles_with_publisher(Article.objects.all())\n plugin = init_plugin(ArticleList, arti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test number of sections
def testSectionCount(self): self.sectionCount(3640)
[ "def getN_Sections(self):\n return len(self.sections_dict)", "def number_of_sections(self):\n #print (len(self.config.sections()))\n return len(self.config.sections())", "def sections(self) -> int:\n if self.strategy == AwesomeVersionStrategy.SEMVER:\n return 3\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sigmoid scaled to logarithm of maximum sales scaled by 20%.
def act_sigmoid_scaled(x): return tf.nn.sigmoid(x) * tf.math.log(max_sales) * 1.2
[ "def sigmoid(a):\n\treturn 1 / (1 + np.exp(-a))", "def sigmoid(x):\n\treturn 1 / (1 + m.exp(-x))", "def sigmoid():", "def sigmoid(self, x):\n # Função de ativação\n return 1/(1 + np.exp(-x) )", "def Sigmoid(x):\r\n return 1.0 / (1.0 + np.exp(-x))", "def sigmoid(x):\r\n return 1 / (1 + ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the surface batch reactor with a dissociative adsorption of H2 Here we choose a kinetic model consisting of the dissociative adsorption reaction H2 + 2X 2 HX We use a SurfaceArrhenius for the rate expression.
def test_solve_h2(self): h2 = Species( molecule=[Molecule().from_smiles("[H][H]")], thermo=ThermoData(Tdata=([300, 400, 500, 600, 800, 1000, 1500], "K"), Cpdata=([6.955, 6.955, 6.956, 6.961, 7.003, 7.103, 7.502], "cal/(mol*K)"), ...
[ "def test_2D_m4_2k_sFH():\n scal, velo = setup_2D()\n\n advec = Advection(velo, scal, discretization=d2d,\n method={TimeIntegrator: RK2,\n Interpolation: Linear,\n Remesh: L2_1,\n Support: 'gpu_2k',\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return token or None Get the user's token
def _get_token(self): return user.get_token()
[ "def get_token(request):\n token = request.headers.get('X-Auth-Token')\n\n if token is not None and token not in [\"null\", \"undefined\"]:\n token = request.dbsession.query(Token).filter_by(token=token).first()\n if token is not None:\n return token\n else:\n raise ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The application needs a list of terms to search, and expects them to be in Redis. If there are no terms in Redis, the function calls to populate them
def check_search_terms(redis_client): if redis_client.scard('search_terms') == 0: populate_search_terms(redis_client)
[ "def populate_search_terms(redis_client):\n logging.info('Populating search terms into redis from SQL', extra={'category': 'search_terms'})\n sql_session = get_sql_session()\n search_terms = sql_session.query(SearchTerm.term).all()\n redis_client.sadd('search_terms', *[x.term for x in search_terms])", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pulls a list of search terms from a SQL database and stores them in Redis. If you're forking this application, it may be easier to retrieve the terms from an environment variable.
def populate_search_terms(redis_client): logging.info('Populating search terms into redis from SQL', extra={'category': 'search_terms'}) sql_session = get_sql_session() search_terms = sql_session.query(SearchTerm.term).all() redis_client.sadd('search_terms', *[x.term for x in search_terms])
[ "def check_search_terms(redis_client):\n if redis_client.scard('search_terms') == 0:\n populate_search_terms(redis_client)", "def key_terms():\n shop_names = request.args.get('q')\n if not shop_names:\n resp = jsonify({'error': 'missing query string'})\n return make_response(resp, 42...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks redis to see whether we have hit the Twitter API query limit Theoretically, the pythontwitter client can do this, but there is currently a bug in it
def check_limit(redis_client): if redis_client.llen('query_counter') >= API_RATE_LIMIT: left_val = redis_client.lpop('query_counter') parsed_left_val = float(left_val.decode('utf-8')) current_api_window = (datetime.utcnow() - timedelta(minutes=API_WINDOW_PERIOD)).timestamp() if parse...
[ "def checkRls():\n return api.rate_limit_status()['resources']['search']['/search/tweets']['remaining']", "def test_rate_limit(self):\n status = self.client.rate_limit_status()\n resource_status = status[\"resources\"][\"search\"][\"/search/tweets\"]\n expected_status = {\"remaining\": 450...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds and returns the next search term that the application should query. It does this by querying Redis and sorting the search_terms by score Each search_term's score is set after a query, and depends on how many Tweets the application needs to collect
def get_next_query(redis_client): return redis_client.sort('search_terms', by='*->score')[0].decode('utf-8')
[ "def search(self, terms, limit):\n\n # Initialize scores array\n scores = np.zeros(len(self.ids), dtype=np.float32)\n\n # Score less common terms\n terms, skipped, hasscores = Counter(terms), {}, False\n for term, freq in terms.items():\n # Compute or lookup term weight...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get months and days until the next birthday. Approximate, as it does not count specific month durations, but approximates to the nearest 30 days
def get_next_birthday(birthday, today): try: next_birthday = birthday.replace(year=today.year) except ValueError: # not a leapyear, no february 29th; use the day before next_birthday = birthday.replace(day=28, year=today.year) if next_birthday < today: # next year try: ...
[ "def days_until_next_birthday(self) -> int | None:\n return calculate_days_until(self.date_of_birth, today())", "def get_remaining_days(self):\n now = datetime.now()\n date_now = date(now.year, now.month, now.day)\n if now.month < self.birthdate.month or (now.month == self.birthdate.mo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load MeSH terms to local index.
def index_mesh(source): click.secho( 'Loading MeSH topical headings from {}'.format(source), fg='blue' ) terms = MeSH.load(source, filter='topics') # Adapt to indexer index_name = 'terms-term-v1.0.0' type_name = 'term-v1.0.0' indexable_terms = [ mesh_indexable(t, index=inde...
[ "def load(self, path):\n\n # Load an existing terms database\n self.connection = self.connect(path)\n self.cursor = self.connection.cursor()\n self.path = path\n\n # Load document attributes\n self.ids, self.deletes, self.lengths = [], [], array(\"q\")\n\n self.curso...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load FAST terms to local index.
def index_fast(source): click.secho( 'Loading FAST topical headings from {}'.format(source), fg='blue' ) terms = FAST.load(source) # Adapt to indexer index_name = 'terms-term-v1.0.0' type_name = 'term-v1.0.0' indexable_terms = [ fast_indexable(t, index=index_name, doc_type=...
[ "def load_index(self, fn):\n self._indexer.load_index(fn)", "def fsIndex_save_and_load():", "def load(self, path):\n\n # Load an existing terms database\n self.connection = self.connect(path)\n self.cursor = self.connection.cursor()\n self.path = path\n\n # Load documen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test slice op jit
def test_add_op_jit(): x = np.array([1, 2, 3, 4, 5, 6, 7]) paddle_x = paddle.to_tensor(x).astype("float32") paddle_x.stop_gradient = False print(paddle_x) a = 1 b = 5 out = custom_ops.slice_test(paddle_x, a, b) print("out: ", out) print("numpy out: ", x[a:b]) assert np.allclose(o...
[ "def test_strided_slice_2():\n x = randtool(\"int\", -10, 10, (5, 8, 6, 4, 2, 6))\n axes = [1, 2, 5]\n starts = [6, 5, 4]\n ends = [2, 0, 1]\n strides = [-1, -2, -3]\n tmp = x\n res = tmp[:, 6:2:-1, 5:0:-2, :, :, 4:1:-3]\n obj.run(res=res, x=x, axes=axes, starts=starts, ends=ends, strides=st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
获取手机信息: udid, 系统版本号 系统名称 IOS/ANDROID 设备型号 设备分辨率 Appium可使用的端口
def get_phone_info(self): self.title() # 获取所有手机型号等信息 # self.kill_other_python() android_phone = GetPhoneInfoAndroid().get_phone_info() ios_phone = GetPhoneInfoIos().get_phone_info() device = dict(android_phone, **ios_phone) # Appium可使用的端口 # selected_port...
[ "def get_mobile_info(self):\n # 1. select brand\n self.select_brand()\n # 2. select os\n self.select_os()\n # 3. device_id\n self.gen_device_id()\n # 4. lat lon\n self.gen_lat_lon()\n # 5. mac\n self.gen_mac()", "def device_locate():\n try:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assume bacteria are <5um and therefore gravitational settling and physical filtration are negligible base condition is that initial concentration in cells/mL is scaled by flow in mL/t, giving flux of cells per timestep. However, this is modified by growth and decay and potentially adsorption at cryoconite layers (and i...
def cell_cnc_tracker(Out, U, V, W, t, cell0, cellG, cellD, SHP, cryoconite_locations): Cells = np.random.rand(len(t),SHP[0],SHP[1],SHP[2]) * cell0 CellD = np.zeros(shape=(SHP[0],SHP[1],SHP[2])) + cellD CellG = np.zeros(shape=(SHP[0],SHP[1],SHP[2])) + cellG for i in np.arange(0,SHP[0],1): ...
[ "def update_concentrations_batch(self): \n #--- Update the cell concentrations ---\n # dX_i/dt = mu_i*(1-rmp/100)*X_i*(1 - sum(i,(1-rmp/100)X(i))/carrying_capacity) or \n # (X_i(t+dt) - X_i(t))/dt = mu*(1-rmp/100)*X_i(t)*(1 - sum(i,(1-rmp/100)*X_i(t))/carrying_capacity)\n # where rmp is...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a list of all the image files in the image directory; files ONLY
def make_image_list(directory): only_files = [file for file in listdir(directory) if isfile(join(directory, file))] return only_files
[ "def collect_image_files():\n negs = [] # Non image files found\n for filename in os.listdir('.'):\n if filename.lower().endswith('.jpg') or filename.lower().\\\n endswith('.jpeg'):\n jpg_files.append(filename)\n elif filename.lower().endswith('.gif'):\n gif...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
look for the image real path, if name is None, then return all images under path. system encoded path string
def search_image(name=None, path=['.']): name = strutils.decode(name) for image_dir in path: if not os.path.isdir(image_dir): continue image_dir = strutils.decode(image_dir) image_path = os.path.join(image_dir, name) if os.path.isfile(image_path): return ...
[ "def get_image_by_name(self, name):", "def find_image_for_menu(self):\n name = self.image_name\n for image_format in IMAGES: # try the name with every allowed extensions\n filename = self.get_image_path(f'{name}.{image_format}')\n if os.path.isfile(filename):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the hydraulic cost function that reflects the increasing damage from cavitation and greater difficulty of moving up the transpiration stream with decreasing values of the hydraulic conductance. Also calculates the associated plant vulnerability.
def hydraulic_cost(p, P): # Weibull parameters setting the shape of the vulnerability curve b, c = Weibull_params(p) # MPa, unitless # current maximum plant hydraulic conductance (@ saturation) kmax = p.kmax * f(p.Ps, b, c) # mmol s-1 m-2 MPa-1 # plant vulnerability curve VC = f(P, b, c, re...
[ "def hydraulic_cost(p, P):\n\n # Weibull parameters setting the shape of the vulnerability curve\n b, c = Weibull_params(p) # MPa, unitless\n\n # critical percentage below which cavitation occurs\n kcrit = p.ratiocrit * p.kmax # xylem cannot recover past this\n\n # hydraulic conductance, from kmax ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Uses a combination of symbols and matrices to find the value of variable (y) for which expr(y) is minimised. Being able to express the solution symbolically can be an interesting feature depending on the user's needs.
def symbolic_solve(expr, x, y, xvals, varsol, bound_expr): # return function from expression fun = lambdify((x, y), expr, 'numpy') max_fun = lambdify((x, y), bound_expr, 'numpy') # solutions over varsol match = fun(np.expand_dims(xvals, axis=1), varsol) # closest match to ~ 0. (i.e. supply ~ ...
[ "def solve(equations, variables, eq_matrix, ordinate, symbolic=False):\n if not symbolic:\n solution = ssl.spsolve(ss.csr_matrix(eq_matrix), ordinate) \n solution = dict(zip(variables, solution))\n return [solution, sum(solution.values())]\n else:\n solution = sympy.solve(equations...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Uses matrices to find each value of Ci for which An(supply) ~ An(demand) on the transpiration stream.
def mtx_minimize(p, trans, all_Cis, photo): demand, __, __, __ = calc_photosynthesis(p, np.expand_dims(trans, axis=1), all_Cis, photo) supply = A_trans(p, np.expand_dims(trans, axis=1), all_Cis) # closest match to ~ 0. (i.e. supply ~ demand) idx = bn.nanarg...
[ "def get_stain_matrix(self, I, *args):", "def state_matrix(self):\n # S = np.dot(self.K(), LA.inv(self.M()))\n\n M, K, C = self.M(), self.K(), self.C()\n\n Z = np.zeros(M.shape, dtype=np.float64)\n\n A = np.vstack([\n np.hstack([C, K]),\n np.hstack([-M, Z])\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Splits a list or array into Nroughly equal parts.
def split(a, N): integ = int(len(a) / N) remain = int(len(a) % N) splitted = [a[i * integ + min(i, remain):(i + 1) * integ + min(i + 1, remain)] for i in range(N)] return splitted
[ "def split_list(a, n):\n part_len = len(a) / n\n parts = []\n for i in range(n):\n start_ind = i * part_len\n end_ind = (i + 1) * part_len\n if i == n - 1:\n parts.append(a[start_ind:])\n else:\n parts.append(a[start_ind:end_ind])\n return parts", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the photosynthetic C gain of a plant, where the photosynthetic rate (A) is evaluated over the array of leaf water potentials (P) and, thus transpiration (E), and normalized by the instantaneous maximum A over the full range of E.
def photo_gain(p, trans, photo, res, parallel, solstep, symbolic): # accounting for canopy and leaf conductances is needed further __, gs, gb = leaf_energy_balance(p, trans) # mol m-2 s-1 # ref. photosynthesis for which the dark respiration is set to 0 A_ref, __, __, __ = calc_photosynthesis(p, trans...
[ "def antenna_gain(aperture_efficiency,geometrical_area):\n return aperture_efficiency*geometrical_area/2/Physics.k/1e26", "def gain_opt_total(machine, T):\n return (np.amax(machine) * T)", "def capenergy(C, V):\n energy = 1 / 2 * C * V ** 2\n return energy", "def gain_opt(machine, T):\n res = (n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a mat3 from three vec3 by taking them as columns.
def three_vec3_to_mat3(f: vec3, l: vec3, u: vec3) -> mat3: return mat3(f[0], l[0], u[0], f[1], l[1], u[1], f[2], l[2], u[2])
[ "def getMat3(self):\r\n m11,m12,m13,m14,m21,m22,m23,m24,m31,m32,m33,m34,m41,m42,m43,m44 = self.mlist\r\n return _mat3(m11,m12,m13,\r\n m21,m22,m23,\r\n m31,m32,m33)", "def uvec3(*args):\n return ti.types.vector(3, _get_uint_ip())(*args) # pylint: disable=E...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the value if the key is not present in the cache. If the cache is at capacity remove the oldest item.
def set(self, key, value): try: assert self.capacity > 0 if key not in self.cache: node = Node(key, value) self.cache[key] = node self._enqueue(node) self.num_elements += 1 if self._full_capacity(): ...
[ "def set(self, key, value):\n if (self.curr_inc < self.capacity):\n self.curr_inc += 1\n else:\n print(\"Cache is Full, delete least recently used item from cache and add new item \")\n sorted_list = sorted(self.timestamp_cache, key = self.timestamp_cache.get)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function to get a character by ID.
def get_character(id): return human_data.get(id) or droid_data.get(id)
[ "def get_character(self, name=None, id=None):\n\n if name is None and id is None:\n if len(self.characters) > 1:\n raise TooManyCharactersError(\"There are too many characters to choose from\")\n if len(self.characters) is 0:\n return None\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Allows us to query for a character's friends.
def get_friends(character, _info): return map(get_character, character.friends)
[ "def friends() -> list:\n return _friends", "def get_friends(self):\n\n # return a QuerySet\n person = Profile.objects.filter(id=self.pk)[0]\n friends = person.friends.all()\n return friends", "async def get_friends(_: User = Depends(get_current_user),\n db: S...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Allows us to fetch the undisputed hero of the trilogy, R2D2.
def get_hero(root, _info, episode): if episode == 5: return luke # Luke is the hero of Episode V return artoo # Artoo is the hero otherwise
[ "def get_hero(self, uuid, hero):\n\n # I can't wait for case statements in python (3.10)\n if hero == Heroes.BULK:\n return Bulk(self.api_key, uuid)\n\n elif hero == Heroes.GENERAL_CLUCK:\n return GeneralCluck(self.api_key, uuid)\n\n elif hero == Heroes.CAKE_MONSTER...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Allows us to query for the human with the given id.
def get_human(root, _info, id): return human_data.get(id)
[ "def humangenes_id_get(id): # noqa: E501\n\n\n return query_manager.get_resource(id=id,\n rdf_type_uri=HUMANGENE_TYPE_URI,\n rdf_type_name=HUMANGENE_TYPE_NAME, \n kls=HumanGene)", "def get_by_id(self, id_bacteriophage:int):\n\n self.function += str(id_bacteriophage) + '/'\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Allows us to query for the droid with the given id.
def get_droid(root, _info, id): return droid_data.get(id)
[ "def at(cls, _id):\n return cls.where(cls.primarykey == _id)", "def find(id):\n return QueryBuilder(Card).find(id)", "def get_droid(did):\n conn = create_connection(db_location)\n c = conn.cursor()\n c.execute(\"SELECT * FROM droids WHERE droid_uid = \" + did)\n print(\"DEBUG: *****\")...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Raise an error when attempting to get the secret backstory.
def get_secret_backstory(_character, _info): raise RuntimeError("secretBackstory is secret.")
[ "def test_secret_get_fail(secret):\n with pytest.raises(Exception):\n secret.get()", "def recover_secret(access_token):\n raise NotImplementedError('No Valid Access Detail Recovery Provided')", "def _secret_not_in_order():\n pecan.abort(400, u._(\"Secret metadata expected but not received.\"))",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Allows us to do ["foo"] instead of .secrets.get("foo")
def __getitem__(self, key): value = self.secrets.get(key) if value is None: log.warning(f"Value for '{key}' was not found in the secrets file. Returning 'None'.") return value
[ "def get_secret(name):\n config = ConfigParser()\n config.read('/srv/oclubs/secrets.ini')\n return config.get('secrets', name)", "def test_list_secrets(self):\n pass", "def GetSecret(self, secret):\r\n return self._secrets[secret].strip()", "def apply_secrets():\n for name, value in Secr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recursively walks the dictionary of values, and decrypts values if necessary
def traverse_and_decrypt(self, config): for key, value in config.items(): if isinstance(value, dict): self.traverse_and_decrypt(value) else: config[key] = self.decrypt_string(value)
[ "def decrypt_obj(value, profile=DEFAULT_PROFILE, store=DEFAULT_STORE,\n passphrase=None, key=None):\n def recurse(val):\n return decrypt_obj(val, profile=profile, store=store,\n passphrase=passphrase, key=key)\n if hasattr(value, 'items'):\n if 'value' in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fixture that mocks RFXtrx connection.
async def rfxtrx_dsmr_connection_fixture(hass): transport = MagicMock(spec=asyncio.Transport) protocol = MagicMock(spec=RFXtrxDSMRProtocol) async def connection_factory(*args, **kwargs): """Return mocked out Asyncio classes.""" return (transport, protocol) connection_factory = MagicMo...
[ "def connection():\n return _MockConnection()", "def setUp(self):\n\n self.trace_tracker = TraceTracker()\n self.conn = Mock('httplib.HTTPConnection', tracker=self.trace_tracker)\n mock('httplib.HTTPConnection', mock_obj=self.conn)\n mock('httplib.HTTPSConnection', mock_obj=self.con...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
find a window by its class_name
def find_window(self, class_name, window_name=None): self._handle = win32gui.FindWindow(class_name, window_name)
[ "def find_window(title):\n return FindWindow(None, title)", "def get_window(cls=Window):\n sleep(0.1)\n process_app_events()\n w_ = None\n for w in Window.windows:\n if isinstance(w, cls):\n w_ = w\n break\n\n return w_", "def FindWindowByName(*args, **kwargs):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
put the window in the foreground
def set_foreground(self): shell = win32com.client.Dispatch("WScript.Shell") shell.SendKeys('%') win32gui.SetForegroundWindow(self._handle)
[ "def set_foreground(self):\n win32gui.SetForegroundWindow(self._handle)", "def show_window_background():\n \n window = win32gui.FindWindow(MINECRAFT_CLASS_NAME, MINECRAFT_TITLE + MINECRAFT_VERSION)\n win32gui.SetForegroundWindow(window)\n win32gui.BringWindowToTop(window)", "def SetForeground...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the Equinox Hunt's PID
def find_e_hunt_pid(): for proc in psutil.process_iter(): try: pinfo = proc.as_dict(attrs=['pid', 'name', 'username']) except psutil.NoSuchProcess: pass else: if pinfo["name"] == "The Equinox Hunt.exe": return pinfo['pid'] raise Environ...
[ "def horse_pid(self):\n return self._horse_pid", "def get_PID(self):\n return self.PID", "def getPID(self):\r\n return self.getFieldVal(self.PID)", "def get_pid(self):\n return self.k_p, self.k_i, self.k_d", "def __get_pid(self):\n str_pid = os.getpid() + 65535\n str_he...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get or set ticks per second.
def ticks_per_second(self): return self._ticks_per_second
[ "def ticks_ms() -> int:\n return int()", "def ticks_us() -> int:\n return int()", "def ticks_us():\n\ttry:\n\t\t# pylint: disable=no-member\n\t\treturn time.ticks_us()\n\texcept:\n\t\treturn time.time_ns()//1000", "def tick(self):\n prev_last_tick = self.last_tick_\n self.last_tick_ = timeit.defau...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get or set max_fps.
def max_fps(self): return self._max_fps
[ "def get_fps():\n return bpy.context.scene.render.fps / bpy.context.scene.render.fps_base", "def set_fps(self, fps=25):\n # self._root.knob('fps').setValue(fps)\n pass", "def fps(self):\n if not self.environment.video_info_supported:\n return None\n return self.e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get or set use_wait.
def use_wait(self): return self._use_wait
[ "def get_no_wait(self) -> bool:\n # read the original value passed by the command\n no_wait = self.raw_param.get(\"no_wait\")\n\n # this parameter does not need dynamic completion\n # this parameter does not need validation\n return no_wait", "def config_wait_time(config):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get or set max_frame_skip.
def max_frame_skip(self): return self._max_frame_skip
[ "def get_max_frames(self):\n return 8", "def max_frame_size(self):\n return self[SettingsFrame.SETTINGS_MAX_FRAME_SIZE]", "def max_step(self) -> Optional[int]:\n return self._max_step", "def num_replay_files_to_skip(self):\n return self.__num_to_skip", "def max_frame_age(self) ->...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Game loop timer. Call once per game loop to calculate runtime values. After calling, check the update_ready() and frame_ready() methods. Sleep cycles are injected if use_wait=True. Returns the number of milliseconds that have elapsed since the last call to tick().
def tick(self): TIME = self._get_ticks() DT = self._ticks = (TIME - self.time) / self.dilation self._elapsed += self._ticks self.time = TIME # Update runtime stats and counters every second. if self._elapsed >= 1.0: self._elapsed %= 1.0 ...
[ "def time(self) -> float:\n return self.state.game_loop / 22.4 # / (1/1.4) * (1/16)", "def tick(self):\r\n self.ct = pygame.time.get_ticks()\r\n if self.ct < self.nt:\r\n pygame.time.wait(self.nt-self.ct)\r\n self.nt+=self.wait\r\n else: \r\n self.nt =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Schedule an item to be called back each time tick() is called.
def schedule(self, func, *args, **kwargs): self.unschedule(func) item = _Item(func, 0, args, kwargs) self.schedules.append(item)
[ "def tick(self, time):\n pass", "def tick(self, tick):\n self._tick = tick", "def tick(self, tick):", "def tick(self):\n if self.time >= 0:\n if self.time == 0:\n self.when_end()\n self.time -= 1", "def schedule_update(self, func, *args, **kwargs):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Schedule an item to be called back each time update_ready is True.
def schedule_update(self, func, *args, **kwargs): self.unschedule(func) item = _Item(func, -1, args, kwargs) self.update_schedules.append(item)
[ "def schedule_update(self):\r\n self.update_event = Clock.schedule_interval(self.update, 1.0 / self.config_dict['Tasks']['Boids']['update_frequency'])", "def update_ready(self):\n self._ready = self.ready", "def _update_item_status(s_item: models.ScheduledOperation):\n now = datetime.now(ZoneIn...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Schedule an item to be called back each time update_ready is True. Items are called in order of priority, low to high. If the clock's update_callback is not None, its priority is always 0.0.
def schedule_update_priority(self, func, pri, *args, **kwargs): self.unschedule(func) new_item = _Item(func, pri, args, kwargs) for i,sched in enumerate(self.update_schedules): if sched.pri > new_item.pri: self.update_schedules.insert(i, new_item) retu...
[ "def schedule_update(self):\r\n self.update_event = Clock.schedule_interval(self.update, 1.0 / self.config_dict['Tasks']['Boids']['update_frequency'])", "def schedule_update(self, func, *args, **kwargs):\n self.unschedule(func)\n item = _Item(func, -1, args, kwargs)\n self.update_sched...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Schedule an item to be called back each time frame_ready is True.
def schedule_frame(self, func, *args, **kwargs): self.unschedule(func) item = _Item(func, 0.0, args, kwargs) self.frame_schedules.append(item)
[ "def schedule(self):\r\n n = self.next()\r\n if n is not None:\r\n if self.clock:\r\n self.cl = self.clock.callLater(n, self.run)\r\n else:\r\n self.cl = core.call_later(n, self.run)\r\n else:\r\n self.cl = None", "def schedule(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Schedule an item to be called back each time frame_ready is True. Items are called in order of priority, low to high. If the clock's frame_callback is not None, its priority is always 0.0.
def schedule_frame_priority(self, func, pri, *args, **kwargs): self.unschedule(func) new_item = _Item(func, pri, args, kwargs) for i,sched in enumerate(self.frame_schedules): if sched.pri > new_item.pri: self.frame_schedules.insert(i, new_item) return ...
[ "def schedule_frame(self, func, *args, **kwargs):\n self.unschedule(func)\n item = _Item(func, 0.0, args, kwargs)\n self.frame_schedules.append(item)", "def schedule(self, callback, *args, **kwargs):\n if self.is_running:\n pyglet.clock.schedule(callback, *args, **kwargs)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unschedule a managed function.
def unschedule(self, func): for sched in ( self.schedules, self.update_schedules, self.frame_schedules, self.interval_schedules, ): for item in list(sched): if item.func == func: sched.remove(item)
[ "def unschedule(function_pointer: Callable):\n pyglet.clock.unschedule(function_pointer)", "def trigger_unregister(self, func: EvalFunc) -> None:\n self.triggers.discard(func)\n self.triggers_delay_start.discard(func)", "def unschedule(self):\n response = self._post(self.uri_for(\"unsche...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set window caption for both Pygame clock and GameClock.
def set_caption(): if USE_PYGAME_CLOCK: pygame.display.set_caption( 'Loop=Pygame Kill=%s MaxFPS=%d Runtime:[FPS=%d Balls=%d]' % ( DO_KILL, PYGAME_FPS, pygame_clock.get_fps(), len(sprite_group))) else: pygame.display.set_caption( ' '...
[ "def window_set_caption(game_settings):\n if game_settings.legacy_flag:\n pygame.display.set_caption(\"Alien Invaders\")\n else:\n pygame.display.set_caption(\"Kingdom Invaders\")", "def set_caption_pygame():\n pygame.display.set_caption(\n 'Loop=Pygame Kill=%s MaxFPS=%d Runtime:[FPS...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for the validate_str_substitution function when there are too many specifiers for a single value.
def test_single_specifier_needed(self): template = '{0} one too many {1}' value_count = 1 msg = ('The formatter should only contain one ' '"{}" specifier for the source field.') with six.assertRaisesRegex(self, ValidationError, msg): validate_str_substitution(t...
[ "def test_mult_specifiers_missing(self):\n template = '{0} too few {1}'\n value_count = 3\n msg = ('The formatter contains too few \"{}\" '\n 'specifiers for the number of source fields.')\n with six.assertRaisesRegex(self, ValidationError, msg):\n validate_str_s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for the validate_str_substitution function when there are too many specifiers for a multiple values.
def test_too_many_specifiers(self): template = '{0} too {1} many {2}' value_count = 2 msg = ('The number of "{}" specifiers in the formatter ' 'exceeds the number of source fields.') with six.assertRaisesRegex(self, ValidationError, msg): validate_str_substitut...
[ "def test_mult_specifiers_missing(self):\n template = '{0} too few {1}'\n value_count = 3\n msg = ('The formatter contains too few \"{}\" '\n 'specifiers for the number of source fields.')\n with six.assertRaisesRegex(self, ValidationError, msg):\n validate_str_s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }