query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Allows user to edit study notes
def edit_current_note(): note_id = request.form.get("note_id") edited_note = Note.query.get(note_id) edited_note.title_note = request.form.get("title") edited_note.note = request.form.get("note") db.session.commit() return "note edited"
[ "def __edit_current_note():\n os.system('clear')\n os.system('cls')\n\n title = input('Do you want to edit the title? (Y/n)? ')\n if title.lower() == 'y':\n new_title = input('Enter new title: ')\n else:\n new_title = None\n\n body = input('Do you want...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
notifies author of question when a user has commented on their question
def notify_author_comment(comment, author_email, author_username ,question, question_title, comment_author): content = "Hello " + author_username + ","+ "\n" + "\n" + "Fellow camper, " + comment_author + " has commented on your question:" + "\n" + question_title + "\n" + question + "!" + "\n" + "\n" +"They have ...
[ "def comment_on(self):\n pass", "def on_comment_was_posted(sender, comment, target, user_data, request, **kwargs):\n if comment.user:\n if request.user.is_authenticated() and request.user.is_active:\n comment.is_public = True\n comment.save()\n notify_comment_foll...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
allows user to add a vote to a comment
def add_vote(): comment_id = request.form.get("comment_id") voted_item = request.form.get("voted_item") comment = Comment.query.get(int(comment_id)) vote_check = Vote.query.filter(Vote.comment_id == int(comment_id), Vote.user_id == session['user_id']).first() if vote_check: ...
[ "def cmd_comment_vote(client, args):\n comment_vote = client.comment_vote(args.comment_id, args.vote)\n generate_output({'comment_vote': comment_vote})", "async def vote_comment(*, comment: models.Comment = Depends(resolve_comment), vote: int = Path(..., ge=-1, le=1),\n current_user: m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function returns a secret word that the player is trying to guess in the game. This function initially has a very small list of words that it can select from to make it easier for you to write and debug the main game playing program. In Part II of writing this program, you will reimplement this function to select ...
def get_word(): words = [] for line in open(LEXICON_FILE): line = line.strip() words.append(line) index = random.randrange(0,len(words)) return words[index]
[ "def get_word():\n \"\"\"index = random.randrange(3)\n if index == 0:\n return 'HAPPY'\n elif index == 1:\n return 'PYTHON'\n else:\n return 'COMPUTER'\n \"\"\"\n\n filename = open(LEXICON_FILE, \"r\") #opening the file\n word_list = [] #empty is to store words in the...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
To play the game, we first select the secret word for the player to guess and then play the game using that secret word.
def main(): secret_word = get_word() play_game(secret_word)
[ "def main():\n secret_word = get_word()\n print(secret_word)\n play_game(secret_word)", "def play_turn(self):\n \n print('\\nOptions:')\n print('- You can save your game any time by typing \"save\" instead of a letter.')\n print('- You can quit any time by typing \"quit\" inst...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the Cumulative Match Characteristic (CMC) This function assumes that gallery labels have no duplication. If there are duplications, random downsampling will be performed on gallery labels, and the computation will be repeated to get an average result.
def cmc(distmat, glabels=None, plabels=None, ds=None, repeat=None): m, n = distmat.shape if glabels is None and plabels is None: glabels = np.arange(0, m) plabels = np.arange(0, n) if isinstance(glabels, list): glabels = np.asarray(glabels) if isinstance(plabels, list): p...
[ "def compute_mcc(prediction_seq, real_seq, sec_structure):\n tp = sum([prediction_seq[i] == sec_structure and real_seq[i] == sec_structure for i in range(len(prediction_seq))])\n fn = sum([prediction_seq[i] != sec_structure and real_seq[i] == sec_structure for i in range(len(prediction_seq))])\n fp = sum([...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate requested XGBoost models, and download if necessary
def validate_requested_xgb_model(xgboost_model_files, xgboost_model_hashes, model_dir): for _, model_file in xgboost_model_files.items(): if not check_model_presence( model_file, xgboost_model_hashes[model_file], model_dir ): download_model(model_file, xgboost_model_hashes[mo...
[ "def load_and_check_all_models(self):\n completed_models = []\n failed_models = []\n for trg_lang, modelpaths in self.models.items():\n model = self.download_model(trg_lang)\n if model is not None:\n completed_models.append(trg_lang)\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize xgboost models and return them in a dict with ion types as keys.
def initialize_xgb_models(xgboost_model_files, model_dir, nthread) -> dict: xgb.set_config(verbosity=0) xgboost_models = {} for ion_type in xgboost_model_files.keys(): model_file = os.path.join(model_dir, xgboost_model_files[ion_type]) logger.debug(f"Initializing model from file: `{model_fil...
[ "def gnn_model_dict():\n\n from .message_passing import agnnconv, econv, gatconv, meta, nnconv, nnconv_elu, nnconv_old\n\n models = {\n \"agnnconv\" : agnnconv.AGNNConvModel,\n \"econv\" : econv.EConvModel,\n \"gatconv\" : gatconv.GATConvModel,\n \"nnconv\" ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pad the encoder input sequence with pad_id up to max_len.
def pad_encoder_input(self, max_len, pad_id): while len(self.enc_input) < max_len: self.enc_input.append(pad_id)
[ "def pad_encoder_input(self, max_len, pad_id):\n\t\twhile len(self.enc_input) < max_len:\n\t\t\tself.enc_input.append(pad_id)\n\t\tif self.hps.pointer_gen.value:\n\t\t\twhile len(self.enc_input_extend_vocab) < max_len:\n\t\t\t\tself.enc_input_extend_vocab.append(pad_id)", "def pad_sequence(sequence, max_length, p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Open a .psd file into a layered image.
def openLayer_PSD(file: str) -> LayeredImage: from psdtoolsx import PSDImage from psdtoolsx.constants import BlendMode as psdB blendLookup = { psdB.NORMAL: BlendType.NORMAL, psdB.MULTIPLY: BlendType.MULTIPLY, psdB.COLOR_BURN: BlendType.COLOURBURN, psdB.COLOR_DODGE: BlendType.COLOURDODGE, psdB.OVERLAY: Ble...
[ "def load_psd_from_file(self, file_path):\n self.psd_file = PSDImage.load(file_path)", "def createLayeredPsdFile(*args, imageFileName: Union[List[AnyStr, AnyStr, AnyStr],\n List[List[AnyStr, AnyStr, AnyStr]]]=None, psdFileName: AnyStr=\"\",\n xResolution: int...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save a layered image as .psd.
def saveLayer_PSD(fileName: str, layeredImage: LayeredImage) -> None: del fileName, layeredImage Logger(FHFormatter()).logPrint("Saving PSDs is not implemented in psdtoolsx", LogType.ERROR) raise NotImplementedError
[ "def openLayer_PSD(file: str) -> LayeredImage:\n\tfrom psdtoolsx import PSDImage\n\tfrom psdtoolsx.constants import BlendMode as psdB\n\n\tblendLookup = {\n\t\tpsdB.NORMAL: BlendType.NORMAL,\n\t\tpsdB.MULTIPLY: BlendType.MULTIPLY,\n\t\tpsdB.COLOR_BURN: BlendType.COLOURBURN,\n\t\tpsdB.COLOR_DODGE: BlendType.COLOURDO...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Dispatch requests asynchronously and return the time taken, as well as the results.
def dispatch(method, get_data, ports): reqs = (grequests.request(method, f'http://localhost:{port}/', json=data) for port in ports for data in get_data) responses = grequests.map(reqs) total_duration = sum([res.elapsed.total_seconds() for res in responses]) return total_duration, responses
[ "def test_http_speed(self):\n log.msg(\"timing retrival time for %s\"\n %self.http_url)\n def got_response(body):\n self.report['http_response_time'] = (datetime.now() - self.http_request_start_time).total_seconds()\n self.report['http_success'] = True\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a function that takes the current desired environment and applies it to this objects assigned farm.
def _update_environment(self, environment: Environment) -> None: e_vals, f_vals = environment.values, self.farm_status.values self._generic_update(e_vals, f_vals, 'water_temp', 'water_heater', 'water_cooler') # only works if hydroponic self._generic_update(e_vals, f_vals, 'pH', 'ph_up', 'ph_do...
[ "def apply(self, env: Environment) -> Environment:\n\n raise NotImplementedError()", "def _environment(self):\n # type: () -> AppEnvironment", "def environment(self, environment):\n \n self._environment = environment", "def apply_environ(self):\n if self.manager is None:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This API returns the realtime and historical sector performances calculated from S&P500 incumbents.
def get_sector(self): _FUNCTION_KEY = "SECTOR" # The keys for the json output _DATA_KEYS = ["Rank A: Real-Time Performance", "Rank B: 1 Day Performance", "Rank C: 5 Day Performance", "Rank D: 1 Month Performance", "Rank E: 3 Month Performance", "Rank F: Ye...
[ "def sectorPerformance(token=\"\", version=\"stable\", filter=\"\", format=\"json\"):\n return _get(\"stock/market/sector-performance\", token, version, filter)", "def s_and_p_500_tickers_by_sector():\n sectors_tickers={} #dictionary\n wikipedia_url = \"https://en.wikipedia.org/wiki/List_of_S%26P_500_com...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Call the ESO SkyCalc CLI and save atmospheric data used by this package. Data consists of zenith transmission curves and extinctioncorrected airglow emission spectra tabulated on a 0.01nm grid covering 3001100nm. Data are saved to a FITS file data/atmosphere.fits relative to this package's installation directory.
def prepare_atmosphere(overwrite=True): path = astropy.utils.data._find_pkg_data_path('../data/atmosphere.fits') if not overwrite and os.path.exists(path): print('Atmosphere file exists and overwrite is False.') return # Specify how SkyCalc will be called. params = dict( airmass=...
[ "def _create_sky_model(sky_file, ra, dec, stokes_i_flux):\n if not os.path.isdir(os.path.dirname(sky_file)):\n os.makedirs(os.path.dirname(sky_file))\n fh = open(sky_file, 'w')\n for ra_, dec_, I_ in zip(ra, dec, stokes_i_flux):\n fh.write('%.14f, %.14f, %.3f\\n' % (ra_, dec_, I_))\n fh.cl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prepare the solar spectrum used by this package. Download the STIS reference solar spectrum and convert to the format used by this package by restricting to optical wavelengths (3001100nm) and save as a binary FITS table. This solar spectrum is documented in `Bohlin, Dickinson, & Calzetti 2001,
def prepare_solarspec(overwrite=True): path = astropy.utils.data._find_pkg_data_path('../data/solarspec.fits') if not overwrite and os.path.exists(path): print('Solarspec file exists and overwrite is False.') return print('Downloading reference solar spectrum...') t = astropy.table.Table...
[ "def writeFCspec(self):\n\t\t#print(self.path_out_folder)\n\t\tif os.path.isdir(self.path_out_folder)==False:\n\t\t\t#print(\"test\")\n\t\t\tos.system('mkdir -p '+self.path_out_folder)\n\t\t\n\t\t#ff=open(self.path_to_spectrum[:-5]+\"_fc_tc.dat\",'w')\n\t\t#n.savetxt(ff,n.transpose([self.lambd,self.fluxl,self.fluxl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if lons, lats are the same for different fields in fieldset
def checkField(fieldset, text=True): if text: print "\nFieldset contains the following fields:" for i in range(len(fieldset.fields)): print fieldset.fields[i].name ulon = fieldset.U.grid.lon ulat = fieldset.U.grid.lat udep = fieldset.U.grid.depth vlon = fieldset.V.grid.l...
[ "def check_same_fields(fields1: QgsFields, fields2: QgsFields):\n len_ok = len(fields1) == len(fields2)\n name_ok = fields1.names() == fields2.names()\n field_origin_ok = all(\n fields1.fieldOrigin(i) == fields2.fieldOrigin(i)\n for i, (f1, f2) in enumerate(zip(fields1, fields2))\n )\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find indices for GlobCurrent data
def getIndicesGlobCurrent(lons, lats): if np.size(lons) == 1: lon_0, lon_1 = int(np.floor(lons-5)), int(np.ceil(lons+5)) else: lon_0, lon_1 = int(np.round(np.min(lons))), int(np.round(np.max(lons))) if np.size(lats) == 1: lat_0, lat_1 = int(np.floor(lats-5)), int(np.ceil(lats+5)) ...
[ "def indices(self):", "def find_used_index(fs_data, used_data, suffix='_IMAGE'):\n fs_x = fs_data['x']\n fs_y = fs_data['y']\n used_x = used_data['X' + suffix]\n used_y = used_data['Y' + suffix]\n return find_index(fs_x, fs_y, used_x, used_y)", "def find_fs_index(used_data, fs_data, suffix='_IMAG...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if the given pointindices (x, y) is an coast point. Method is by checking for [0, 0, U] or for [U, 0, 0], with center point as given point. Use direction ("x" or "y") to find coasts perpendicular to the given direction. If None, then check for both "x" and "y".
def checkCoast1d(fieldset, x, y, direction=None, time=0): if direction == None: coast_x = checkCoast1d(fieldset, x, y, direction="x") coast_y = checkCoast1d(fieldset, x, y, direction="y") return coast_x, coast_y elif direction == "x": dims_U = fieldset.U.data.shape vect...
[ "def test_find_center_point_of_circle(self):\n\n point_a = (0, 20)\n point_b = (20, 0)\n point_3 = (0, -20)\n\n assert find_center_point_of_circle(\n point_a, point_b, point_3) == (\n (0, 0), 20)", "def pointValid(p):\n (x, y, z) = p\n return (inCircle(p) an...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Search for gridpoints that represent coasts, i.e. groups of points with velocities [U, 0, 0] or [0, 0, U] (or V). Then calculate the new center value as + abs(U factor) + constant. Returns two fields (U and V) with 'imaginary'velocities at the coast. Function works for fieldsets with fields U and V with two spatial coo...
def createCoastVelocities(fieldset, factor=True, abs=True, constant=0): vel_U = fieldset.U.data vel_V = fieldset.V.data dims_U = vel_U.shape dims_V = vel_V.shape lons_U = fieldset.U.grid.lon lons_V = fieldset.V.grid.lon lats_U = fieldset.U.grid.lat lats_V = fieldset.V.grid.lat if fa...
[ "def get_uvcircle(Grid):\n \n# center of circulation\n loc=-67.5;lac=41.5; \n dx=(Grid['lonc']-loc)*Grid['coslatc']\n dy=(Grid['latc']-lac)\n di=np.sqrt(dx*dx+dy*dy)\n an=np.angle(dx+1j*dy)\n# velocity is linearly increasing with distance \n# 0.1 m/s at 1 deg distance away from center \n# cyclon...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a new fieldset that results from fieldset + coastfields
def addGlobCurrentCoast(fieldset, coastfields): [field_coast_U, field_coast_V, lons, lats] = coastfields new_fieldset = fieldset if np.shape(fieldset.U.data)[0] == np.shape(fieldset.V.data)[0]: nt = np.shape(fieldset.U.data)[0] else: print "addGlobCurrentCoast(): fieldset.U.data and fie...
[ "def build_fieldsets(cls) -> None:\n meta = getattr(cls, 'Meta', None)\n\n if meta:\n # Patch the list of fieldsets to contain the standard fieldset\n # for naming and enabling the configuration.\n fieldsets = getattr(meta, 'fieldsets', ())\n\n if not fields...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove particles that are on land. Particles on land are particles with velocities 0 at grid points around. For parameter 'method', use 'grid' or 'interpolated'; 'interpolated' is much faster than 'grid'.
def removeLandParticles(fieldset=None, particleset=None, show=False, filename=None, indices={}, method='interpolated'): if particleset is None: print "removeLandParticles(): no particles found, returning" return if filename is None and fieldset is None: print "removeLandParticles(): no f...
[ "def remove_outside_particles(species, fld, n_guard, left_proc, right_proc):\n if species.use_cuda:\n # Remove outside particles on GPU, and copy buffers on CPU\n float_send_left, float_send_right, uint_send_left, uint_send_right = \\\n remove_particles_gpu( species, fld, n_guard, left_p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
end_of_day create a new object
def test_new_object(self): now = datetime.now() eod = end_of_day(now) self.assertNotEqual(now, eod)
[ "def add_end_tournament(self):\n self.end_date = datetime.now()\n return convert_date(self.end_date)", "def create_instance(self, date):\n raise NotImplementedError", "def end(self):\n self.end_date = arrow.now()", "def test__end_of_day(self):\n\n result = end_of_day\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Move the values in the 'source' key to the 'dest' key for cases in the 'collection' collection in the 'db' where their caseReference.sourceId matches 'source_id'. If 'dry_run' is set, then don't actually change anything, but do report on which cases would be modified.
def move_notes(db, collection, source_id, source, dest, dry_run): logging.info(f"Moving values from {source} to {dest} in collection: {collection}") query = { "caseReference.sourceId": source_id } if dry_run: logging.info("Dry running notes movement") cases = db[collection].find(query) ...
[ "def insert_cases(self):\n\n cur_d = self.app.conn.cursor()\n # Remove all duplicate cases and case text lists from source data\n cur_d.execute(\"select name from cases\")\n res_cases_dest = cur_d.fetchall()\n existing_case_names = [r[0] for r in res_cases_dest]\n '''for r ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an XPath proxy instance bound with the schema.
def xpath_proxy(self) -> XMLSchemaProxy: raise NotImplementedError
[ "def from_schema_ref(self):\n return self._from_schema_ref", "def get_xpath_accessor(self):\n return {\"xpath_accessor\": self.values}", "def proxy():\n return Proxy()", "def getterxml_instance():\n return GetterXml()", "def xpath_node(self) -> Union[SchemaElementNode, LazyElementNode]:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an XPath node for applying selectors on XSD schema/component.
def xpath_node(self) -> Union[SchemaElementNode, LazyElementNode]: raise NotImplementedError
[ "def xpath(self, node, path):\n\n return node.xpath(path, namespaces=self.namespaces)", "def xpath_proxy(self) -> XMLSchemaProxy:\n raise NotImplementedError", "def xpath(self, expr, *args):\n xpath_expr = expr.format(*args)\n result = self.tree.xpath(xpath_expr, namespaces=QUASAR_NA...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a dictionary with namespaces for XPath selection.
def _get_xpath_namespaces(self, namespaces: Optional[NamespacesType] = None) \ -> Dict[str, str]: if namespaces is None: namespaces = {k: v for k, v in self.namespaces.items() if k} namespaces[''] = self.xpath_default_namespace elif '' not in namespaces: n...
[ "def get_namespaces(self):\n\n nsmap = {}\n for ns in self.xml_root.xpath('//namespace::*'):\n if ns[0]:\n nsmap[ns[0]] = ns[1]\n self.nsmap = nsmap\n\n # set inverted nsmap\n self.nsmap_inv = {v: k for k, v in self.nsmap.items()}", "def ns_prefix_dict(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds all XSD subelements matching the path.
def findall(self, path: str, namespaces: Optional[NamespacesType] = None) -> List[E]: path = _REGEX_TAG_POSITION.sub('', path.strip()) # Strip tags positions from path namespaces = self._get_xpath_namespaces(namespaces) parser = XPath2Parser(namespaces, strict=False) context = XPathSche...
[ "def findall(self, path):\n if self.parser == XML_node.etree:\n return [XML_node(a, self.parser) for a in self.data.findall(path)]", "def _findall(self, element, path_string):\n return element.findall(self._qualify_path(path_string, self.namespace))", "def findall(self, xpath):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an iterator for the XSD element and its subelements. If tag is not `None` or '', only XSD elements whose matches tag are returned from the iterator. Local elements are expanded without repetitions. Element references are not expanded because the global elements are not descendants of other elements.
def iter(self, tag: Optional[str] = None) -> Iterator[E]: def safe_iter(elem: Any) -> Iterator[E]: if tag is None or elem.is_matching(tag): yield elem for child in elem: if child.parent is None: yield from safe_iter(child) ...
[ "def getelements(filename_or_file, tag):\n context = iter(etree.iterparse(filename_or_file, events=('start', 'end')))\n _, root = next(context) # get root element\n for event, elem in context:\n if event == 'end' and elem.tag == tag:\n yield elem\n root....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an iterator for the child elements of the XSD component. If tag is not `None` or '', only XSD elements whose name matches tag are returned from the iterator.
def iterchildren(self, tag: Optional[str] = None) -> Iterator[E]: if tag == '*': tag = None for child in self: if tag is None or child.is_matching(tag): yield child
[ "def iter(self, tag: Optional[str] = None) -> Iterator[E]:\n def safe_iter(elem: Any) -> Iterator[E]:\n if tag is None or elem.is_matching(tag):\n yield elem\n for child in elem:\n if child.parent is None:\n yield from safe_iter(child)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a new instance of the collection with the given state.
def for_state(self, state): return self.__class__( self.session, state=state, term=self.term, order=self.order, direction=self.direction, issues=self.issues, categories=self.categories, organizations=self.organizati...
[ "def get_state_collection_client():\n\n logger.debug('Creating state_collection_client.')\n try:\n db_client = get_db_client()\n state_db_name = os.environ['STATE_DB']\n state_collection_name = os.environ['STATE_COLLECTION']\n state_collection = db_client[state_db_name][state_colle...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a new instance of the collection with the given term.
def for_term(self, term): return self.__class__( self.session, state=self.state, term=term, order=self.order, direction=self.direction, issues=self.issues, categories=self.categories, organizations=self.organization...
[ "def from_term(term):\n if term is None:\n return term\n elif isinstance(term, (six.string_types, int, float)):\n return term\n elif isinstance(term, dict):\n return {k: from_term(v) for k, v in term.items()}\n elif isinstance(term, list):\n return [from_term(t) for i, t in e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a new instance of the collection with the given organizations.
def for_organizations(self, organizations): return self.__class__( self.session, state=self.state, term=self.term, order=self.order, direction=self.direction, issues=self.issues, categories=self.categories, organiza...
[ "def organizations(self):\r\n return organizations.Organizations(self)", "def organization_factory(_context, request):\n return OrganizationService(session=request.db)", "def organizations(self):\n self.elements('organizations')", "def organization_factory(context, request):\n return Organ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a new instance of the collection with the given categories.
def for_categories(self, categories): return self.__class__( self.session, state=self.state, term=self.term, order=self.order, direction=self.direction, issues=self.issues, categories=categories, organizations=self....
[ "def create_collection(project: str, category: str) -> Collection:\n # Check the project and the category exist\n try:\n project_metadata = COLLECTIONS_METADATA[project]\n except KeyError:\n print(f\"Project doesn't exist: {project}\")\n try:\n category_metadata = project_metadata.g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Filters the given query by the state of the collection.
def filter_query(self, query): if self.state: query = query.filter(self.model_class.state == self.state) if self.term: term = '%{}%'.format(self.term) query = query.filter( or_( *[column.ilike(term) for column in self.term_columns]...
[ "def filter_query(self, query):\n return query.filter(self.expression)", "def get_filtered_query(self, query):\n raise NotImplementedError(\"please implement get_filtered_query\")", "def filter(self, **query):\n\n if self._query != '':\n query = '(%s) AND (%s)' % (self._query, se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Orders the given query by the state of the collection.
def order_query(self, query): direction = desc if self.direction == 'desc' else asc if self.order in inspect(self.model_class).columns.keys(): attribute = getattr(self.model_class, self.order) elif self.order == 'group.name': attribute = func.coalesce(UserGroup.name, '')...
[ "def sort_queries(self):\n if self.sort_attribute:\n self.queries.sort(key=lambda x: getattr(x.stats,\n self.sort_attribute),\n reverse=self.reverse)\n return", "def sort_query(request: Request, Model: Restalc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a new notice. A unique, URLfriendly name is created automatically for this notice using the title and optionally numbers for duplicate names. Returns the created notice.
def add(self, title, text, **optional): issues = optional.pop('issues', None) categories = optional.pop('categories', None) organizations = optional.pop('organizations', None) notice = self.model_class( state='drafted', name=self._get_unique_name(title), ...
[ "def insert_notice():\n error = None\n\n # Initialize forms\n doc_change_notice_form = DocChangeNoticeForm(request.form, csrf_enabled=False)\n doc_change_id = doc_change_notice_form.doc_change_id.data\n\n # Get Users from DB\n users = User.query.order_by(User.name).all()\n doc_change_notice_for...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Model loader Load saved models from a given type.
def load_all_models(save_models_dir: str, model_type: str, model_i: int): try: with open(os.path.join(save_models_dir, f"{model_type}_{model_i}.pkl"), "rb") as save_model: model = pickle.load(save_model) except Exception as e: logger.error(f"Error is: {e}") return None ...
[ "def _load_model(self):\n pass", "def load_models_by_type(model_type):\n\n # loading the models for each language supported\n return [(lang_id, load_model(lang_id, model_type)) for lang_id in language_id_to_code_mapper]", "def load(path_to_model):\n pass", "def load_model(language_id, mode...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the previous player in the game
def previous_player(current_player, players): if len(players) == 1: return players[0] if current_player != players[0]: return players[players.index(current_player) - 1] return players[-1]
[ "def get_prev_player(self):\r\n prev_cmd = self.get_last_cmd()\r\n if prev_cmd is None:\r\n return None # No previous player\r\n prev_player = prev_cmd.new_player\r\n return prev_player", "def previous(self):\n return self._call_player_proxy('Prev', None)", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Expand pool to fit all available disk space.
async def expand(self, job, id, options): pool = await self.middleware.call('pool.get_instance', id) if osc.IS_LINUX: if options.get('passphrase'): raise CallError('Passphrase should not be supplied for this platform.') # FIXME: We have issues in ZoL where when po...
[ "def _grow(self):\n self.capacity *= self.factor\n temp = [None] * self.capacity\n for i in range(self.size):\n temp[i] = self.store[i]\n self.store = temp", "def _shrink(self):\n self.capacity = round(self.capacity / self.factor)\n temp = [None] * self.capacit...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simplify operation IDs so that generated API clients have simpler function names. Should be called only after all routes have been added.
def use_route_names_as_operation_ids(app: FastAPI) -> None: for route in app.routes: if isinstance(route, APIRoute): route.operation_id = route.name # in this case, 'read_items'
[ "def use_route_names_as_operation_ids(app: FastAPI) -> None:\n for route in app.routes:\n if isinstance(route, APIRoute):\n route.operation_id = humps.camelize(route.name)", "def _get_operation_id(self, path, method):\n method_name = getattr(self.view, 'action', method.lower())\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Receives a path and returns it's chmods as string.
def getModeString(fullPath, stats): bits = "rwx" modes = "" permissions = ( S_IRUSR, S_IWUSR, S_IXUSR, S_IRGRP, S_IWGRP, S_IXGRP, S_IROTH, S_IWOTH, S_IXOTH, ) fileType = getFileType(f...
[ "def _path_to_string(path):\n\n return \"/\".join(str(item) for item in path)", "def path_to_string(path: Path) -> str:\n assert_continuous(path)\n\n pieces = [\"M {} {}\".format(path[0].p0[0], path[0].p0[1])]\n for curve in iter(path): # iter cast not strictly necessary\n piece = \"C {} {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Labels the SMT query as unsatisfiable, and associates the unsatisfiable query with an unsatisfiable core generated by an SMT solver.
def labelUnsat(self, unsatCore): self.satisfiability = Satisfiability.UNSAT self.model = None self.unsatCore = unsatCore
[ "def labelUnknown(self):\n self.satisfiability = Satisfiability.UNKNOWN\n self.model = None\n self.unsatCore = []", "def _unsat_core(self, s): # pylint:disable=no-self-use,unused-argument\n\n raise BackendError(\"backend doesn't support unsat_core\")", "def set_unsatisfiable(self):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Labels the satisfiability of the SMT query as unknown.
def labelUnknown(self): self.satisfiability = Satisfiability.UNKNOWN self.model = None self.unsatCore = []
[ "def set_unknown(self):\n self.unknown = True\n self.satisfiable = False\n self.unsatisfiable = False", "def set_unsatisfiable(self):\n self.unknown = False\n self.satisfiable = False\n self.unsatisfiable = True", "def _label_unknowns_unitary(self):\n for v in se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Writes the SMT query associated with this
def writeSmtQueryToFile(self, location): try: smtQueryFileHandler = open(location, "w") except EnvironmentError as e: errMsg = ("Error writing the SMT query to a file " "located at %s: %s" % (location, e)) raise GameTimeError(errMsg) else...
[ "def write(self, query):\n pass", "def _write_out_query_fasta(self):\n with open('tax_query.fasta', 'w') as f:\n for i, seq in enumerate(self.query_set):\n f.write(f'>seq_{i}\\n')\n f.write(f'{seq}\\n')", "def output_query(outFile, query):\n outFile.writ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Writes the model generated by an SMT solver in response to the SMT query, if the query is satisfiable, to a file.
def writeModelToFile(self, location): try: modelFileHandler = open(location, "w") except EnvironmentError as e: errMsg = ("Error writing the model generated by an SMT solver " "in response to the SMT query to a file located at %s: " "%s...
[ "def writeSolution(self, fname):\n raise NotImplementedError", "def writeSmtQueryToFile(self, location):\n try:\n smtQueryFileHandler = open(location, \"w\")\n except EnvironmentError as e:\n errMsg = (\"Error writing the SMT query to a file \"\n \"l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Writes the unsatisfiable core generated by an SMT solver in response to the SMT query, if the query is unsatisfiable, to a file.
def writeUnsatCoreToFile(self, location): try: unsatCoreFileHandler = open(location, "w") except EnvironmentError as e: errMsg = ("Error writing the unsatisfiable core generated by " "an SMT solver in response to the SMT query to " "a f...
[ "def writeSolution(self, fname):\n raise NotImplementedError", "def writeSmtQueryToFile(self, location):\n try:\n smtQueryFileHandler = open(location, \"w\")\n except EnvironmentError as e:\n errMsg = (\"Error writing the SMT query to a file \"\n \"l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads an SMT query from the file provided.
def readQueryFromFile(location): try: queryFileHandler = open(location, "r") except EnvironmentError as e: errMsg = ("Error reading the SMT query from the file " "located at %s: %s" % (location, e)) raise GameTimeError(errMsg) else: with queryFileHandler: ...
[ "def read_queries(filename=\"data/queries/example.txt\") -> [Query]:\n with open(filename, 'r') as file:\n return [__parse_query(q) for q in file]", "def load_query(query_filename):\n with open(query_filename) as f:\n return f.read()", "def read_queries(query_file='query.text'):\n queries...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns stopping policy function that stops after the first positive result
def stop_at_detection(lag=1): def policy(model, hist): # stop if there was a positive result after lag time return (model.lastPositive>=0) and (model.lastPositive+lag <= model.t) return policy
[ "def test_lambda_stopping_criterion():\n stopcrit = LambdaStoppingCriterion(stopcrit=lambda tol: tol < 1e-6)\n assert stopcrit(1e-12)", "def early_stopping(stats, curr_patience, prev_val_loss):\n # TODO implement early stopping\n curr_val_loss = stats[-1][1]\n if (curr_val_loss > prev_val_loss):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return a textual representation of the entry data only
def render_data(self): if self.data: #print "ENTRY DATA: %s" % type(self.data) #make sure that data is buffered with a blank line at the end #makes the resulting log easier to read. #if there are more than one blanklines, can leave them last_line = sel...
[ "def tostring(self, entry):\n return self.str_format % entry.attrib", "def get_entry_text(self):\n return self.entry.get_text()", "def repr_entry(entry):\n ret = entry['type']\n if 'level' in entry:\n ret += \"/\" + entry['level']\n if 'state' in entry:\n ret += \"/\" + entr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return a textual representation of the entry include_path assumed to be false in some places
def render(self, include_path=False): entry = u'' entry += self.render_first_line() #in most cases we do not want to show the source path, #(it can change easily and frequently, and is determined on read) #but when merging and reviewing (summarize) #it could be useful to...
[ "def path_value(self, **kwargs):\n s = \"\"\n show_meta = kwargs.get(\"show_meta\", self.SHOW_META)\n show_path = show_meta and kwargs.get(\"show_path\", self.SHOW_PATH)\n if show_path:\n call_info = self.reflect.info\n if call_info:\n s = \"({}:{})\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks whether address string is a valid email
def is_email(address): try: validate_email(address) return True except: return False
[ "def is_valid_email(string: str) -> bool:\n return len(string) <= EMAIL_MAX_LENGTH and \\\n bool(EMAIL_PATTERN.match(string))", "def is_email(address):\n\n return IS_EMAIL_RE.match(address) is not None", "def is_email_valid(email_address):\n return invalid_email_reason(email_address, '') is No...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run when form input is valid, creates Group and GroupLines
def form_valid(self, form): print("CreateGroupView.form_valid()") print("Is Authenticated:", self.request.user.is_authenticated) print(self.request.user.id, "-", self.request.user) print(form['group_guests'].value()) # Create Group new_group = GuestGroup() new_g...
[ "def create_group(self, data):\n\n self.submit_form(data)", "def add_group(self,form,prefix,name,items,**extra):\n w = InputGroup(prefix+name,**extra)\n form.addWidget(w)\n if w.isCheckable:\n self.fields.append(w)\n\n if self.autoprefix:\n prefix += name+'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Insert data into sub categories table
def subcategories(data): if data: for i in data: cat_obj = CategoriesModel.objects.get(id=i['catid']) sub_category = SubCategories(cat_id=cat_obj, sub_categories=i['subcategory']) sub_category.save()
[ "def insert_categories(self):\n\n cur_d = self.conn_d.cursor()\n # Insert top level categories\n remove_list = []\n for c in self.categories_s:\n if c['supercatname'] is None:\n self.summary_msg += _(\"Adding top level category: \") + c['name'] + \"\\n\"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return excel data as list of dictionaries by passing file path, sheet name
def excel_to_json(file_path, sheet=None): df = pd.read_excel(file_path, sheet_name=sheet) columns = [str(k) for k in df.columns] data = [dict(zip(columns, row)) for row in df.values] return data
[ "def read_excel(self):\n # 定义一个空列表\n datas = []\n for i in range(1, self.rowNum):\n # 定义一个空字典\n sheet_data = {}\n for j in range(self.colNum):\n # 获取单元格数据类型\n c_type = self.table.cell(i, j).ctype\n # 获取单元格数据\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests if a bucket list method is returned by the create bucket list method.
def test_create_bucket_list_return(self): bucket = BucketList("", "") bucket = bucket.create_bucket_list("Name", "Completed") self.assertIsInstance(bucket, BucketList)
[ "def test_list(self):\n responses.add(\n responses.Response(\n method='GET',\n url='https://connection.keboola.com/v2/storage/buckets',\n json=list_response\n )\n )\n buckets_list = self.buckets.list()\n assert isinstance...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests if the create bucket list method checks for a name
def test_create_bucket_list_name(self): bucket = BucketList("", "") bucket = bucket.create_bucket_list("") self.assertEqual(bucket, "Please provide a name for your bucket list", )
[ "def test_bucketlist_item_creation_with_Existing_name(self):\n resp = self.client.post(\"/auth/register/\", data=self.user_details)\n self.assertEqual(resp.status_code, 201)\n result = self.client.post(\"/auth/login/\", data=self.user_details)\n access_token = json.loads(result.data.deco...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new dataset in the datastore. Expects at least the list of columns and the rows for the dataset. Raises ValueError if (1) the column identifier are not unique, (2) the row identifier are not uniqe, (3) the number of columns and values in a row do not match, (4) any of the column or row identifier have a negati...
def create_dataset(self, columns, rows, annotations=None): # Validate (i) that each column has a unique identifier, (ii) each row # has a unique identifier, and (iii) that every row has exactly one # value per column. _, max_row_id = validate_dataset(columns=columns, rows=rows) #...
[ "def _create_dataset_and_records_from_rows(self, rows):\n dataset = self._create_dataset_from_rows(rows)\n resp = self._upload_records_from_rows(rows, dataset.pk)\n self.assertEqual(resp.status_code, status.HTTP_200_OK)\n return dataset", "def validate_dataset(columns, rows):\n # En...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete dataset with given identifier. Returns True if dataset existed and False otherwise.
def delete_dataset(self, identifier): # Delete the dataset directory if it exists. Otherwise return False dataset_dir = self.get_dataset_dir(identifier) if not os.path.isdir(dataset_dir): return False shutil.rmtree(dataset_dir) return True
[ "def delete_dataset(self, dataset_id):\n try:\n datasets = self.bigquery.datasets()\n request = datasets.delete(projectId=self.project_id,\n datasetId=dataset_id)\n request.execute()\n return True\n except Exception, e:\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read a full dataset from the data store. Returns None if no dataset with the given identifier exists.
def get_dataset(self, identifier): # Test if a subfolder for the given dataset identifier exists. If not # return None. dataset_dir = self.get_dataset_dir(identifier) if not os.path.isdir(dataset_dir): return None # Load the dataset handle return FileSystemDat...
[ "def read_one_data(data_id):\n \n read_data = None\n\n try:\n read_data = np.load(path.join(config[\"data-dir\"], \"{}.npy\".format(data_id)))\n except Exception as e:\n print(\"read_one_data failed: {}\", data_id)\n print(e)\n\n return read_data", "def _get_dataset_from_db(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate that (i) each column has a unique identifier, (ii) each row has a unique identifier, and (iii) each row has exactly one value per column. Returns the maximum column and row identifiers. Raises ValueError in case of a schema violation.
def validate_dataset(columns, rows): # Ensure that all column identifier are zero or greater, unique, and smaller # than the column counter (if given) col_ids = set() for col in columns: if col.identifier < 0: raise ValueError('negative column identifier \'' + str(col.identifier) + '...
[ "def check_columns_unique(data):\n for col in data:\n print(f\"La columna {col} tiene estos valores únicos:\", data[col].unique())", "def _check_columns_unique(self, columns: List[str]):\n assert len(columns) == len(set(columns))", "def _unique_check(df: DataFrame, column: str) -> None:\n if...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decodes a TTBencoded TsRow into a list
def decode_timeseries_row(self, tsrow, tsct, convert_timestamp=False): row = [] for i, cell in enumerate(tsrow): if cell is None: row.append(None) elif isinstance(cell, list) and len(cell) == 0: row.append(None) else: if...
[ "def decode_vector_of_t(as_bytes: typing.List[int]) -> list:\n raise NotImplementedError()", "def ConvertRow(self, row):\n i = 0\n data = []\n for entry in row['f']:\n data.append(self.Convert(entry['v'], self.schema[i]))\n i += 1\n return tuple(data)", "def decode_list(as_b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replace every selection with the passed text
def replace_text_in_selections(view, edit, text): for region in view.sel(): view.replace(edit, region, text)
[ "def __PerformSubstitutions(self, text):\n\n for substitution in self.substitutions:\n pattern, replacement = self.SplitValue(substitution)\n text = re.compile(pattern,re.M).sub(replacement, text)\n return text", "def find_replace_all(self):\n old_term = self.text_find.g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize the person Store name, email and grade information for a person in the tutor system.
def __init__(self, first, last, email, grade): self.first_name = first self.last_name = last self.email = email self.grade = grade
[ "def __init__(self, name, surname):\n\t\t\n\t\tself.grades = {}\n\t\tself.attendance = 0\n\t\t\n\t\tif not (isinstance(name, str) and isinstance(surname, str)):\n\t\t\tname, surname = \"None\", \"None\"\n\t\tself.name, self.surname = name, surname", "def __init__(self, name, grade):\n self.student_info = {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a session to the list with the given timeslot
def add_session(self, timeslot): new_session = Session(self, timeslot) self.sessions.append(new_session)
[ "def add_timeslot(self, timeslot):\n self.times.append(timeslot)", "def add_session(self, session):\n self.__session_list.append(session)", "def addLesson(self, lesson: Lesson, room: Room, timeslot):\r\n self.timeslotMap[timeslot].append((lesson, room))", "def timeslot(self, timeslot:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return list of unbooked sessions
def get_free_sessions(self): return [session for session in self.sessions if not session.is_booked()]
[ "def get_booked_sessions(self):\n return [session for session in self.sessions if session.is_booked()]", "def get_upcoming_sessions(self):\n return [session for session in self.sessions if not session.is_complete()]", "def _inactiveplayers():\n\n rosters = _activerosters()\n dbrosters = _eid...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return list of booked sessions
def get_booked_sessions(self): return [session for session in self.sessions if session.is_booked()]
[ "def list_sessions(self):\n return self.store.list()", "def get_sessions_list():\n sessions = Session.query.all()\n result = sessions_schema.dump(sessions).data\n return jsonify({'status': 'success', 'message': None, 'data': result}), 200", "def list_sessions(self):\n return self.sessions...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set student attribute in given session and add to our list
def book_session(self, session, subject): session.set_student(self) session.set_subject(subject) self.sessions.append(session)
[ "def add_session_attr(typename, session):\n old_session = getattr(typename, 'session', None)\n setattr(typename, 'session', session)\n yield\n if old_session:\n setattr(typename, 'session', old_session)", "def add_student(self, student):\n self.student_list.append(student)", "def add_student(stude...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove student attribute from session Before removing attribute, also makes sure that the student does not clear a session that is not theirs
def unbook_session(self, session): confirm = input("Are you sure you want to unbook this session? (y/n) ") if confirm.lower().startswith("y") and session in self.sessions: session.remove_student() session.remove_subject() self.sessions.remove(session)
[ "def removeStudent(self):\n if not self.profile:\n return self\n if self.profile.student_info:\n self.profile.student_info.delete()\n self.profile.student_info = None\n self.profile.put()\n return self.profile", "def delete(self, student_name):\r\n if student_name in self.dict_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return list of all future sessions
def get_upcoming_sessions(self): return [session for session in self.sessions if not session.is_complete()]
[ "def list_sessions(self):\n return self.sessions.list_sessions()", "def list_sessions(self):\n return self.store.list()", "def get_sessions(self):\n\n return self.all_sessions", "def _active_sessions(self) -> List[SessionInfo]:\n return [\n SessionInfo(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method returns the x,y coordinates of a selected unit. Mask is a set of bools from comaprison with feature layer.
def coordinates(self, mask): y,x = mask.nonzero() return list(zip(x,y))
[ "def coords(self):\n if self._mask is not None:\n return self._coords[np.where(self._mask == 1)]\n return self._coords", "def get_mask_coordination(cls, _object) -> Coordinates:\n coords = Coordinates(\n int(_object['bndbox']['xmin']),\n int(_object['bndbox'][...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Categories should have slugs with length less than 50 characters
def test_slugs_max_length(self): self.assertLessEqual(len(str(self.cat_short.slug)), 50) self.assertLessEqual(len(str(self.cat_long.slug)), 50)
[ "def test_slugs_truncate(self):\n self.assertFalse(str(self.cat_long.slug).endswith('a' * 8))\n self.assertTrue(str(self.cat_short.slug).endswith('-name'))", "def test_slugs_max_length(self):\n self.assertLessEqual(len(str(self.art_short.slug)), 50)\n self.assertLessEqual(len(str(self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Long category names should have slugs truncated
def test_slugs_truncate(self): self.assertFalse(str(self.cat_long.slug).endswith('a' * 8)) self.assertTrue(str(self.cat_short.slug).endswith('-name'))
[ "def create_slug_from_category_name(sender, instance, *args, **kwargs):\n if not instance.slug:\n instance.slug = slugify(instance.name)", "def format_category_name(category):\n\n category_words = category.name.rstrip().replace(',', '').replace(\"'\", '').split(\" \")\n return \"-\".join(category_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Articles should have correctly formed slugs
def test_slugify(self): self.assertEqual(self.art_short.slug, 'short-article-title') regex = r'[@:%._\+~#=]+' self.assertNotRegex(self.art_short.slug, regex) self.assertNotRegex(self.art_long.slug, regex)
[ "def test_slug_made_from_title(self):\n response = self.create_article()\n self.assertIn(slugify(self.article['article']['title']),\n json.loads(response.content)['data']['article']['slug'])", "def test_content_slug(self):\n title1: Content = ContentFactory(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Articles should have slugs with length less than 50 characters
def test_slugs_max_length(self): self.assertLessEqual(len(str(self.art_short.slug)), 50) self.assertLessEqual(len(str(self.art_long.slug)), 50)
[ "def test_slugs_max_length(self):\n self.assertLessEqual(len(str(self.cat_short.slug)), 50)\n self.assertLessEqual(len(str(self.cat_long.slug)), 50)", "def test_slugs_truncate(self):\n self.assertFalse(str(self.art_long.slug).endswith('a' * 8))\n self.assertTrue(str(self.art_short.slug...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Long articles names should have slugs truncated
def test_slugs_truncate(self): self.assertFalse(str(self.art_long.slug).endswith('a' * 8)) self.assertTrue(str(self.art_short.slug).endswith('-title'))
[ "def test_slugs_truncate(self):\n self.assertFalse(str(self.cat_long.slug).endswith('a' * 8))\n self.assertTrue(str(self.cat_short.slug).endswith('-name'))", "def test_slugs_max_length(self):\n self.assertLessEqual(len(str(self.art_short.slug)), 50)\n self.assertLessEqual(len(str(self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Searches for note with given id
def _find_note(self, id): for note in self.notes: if note.id == id: return note return None
[ "def _find_note(self, note_id):\n for note in self.notes:\n if str(note.id) == str(note_id):\n return note\n return None", "def _find_note(self, note_id):\n for note in self.notes:\n if note.id == note_id:\n return note\n return None"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds the note with given id and changes its tag to given value
def modify_tags(self, id, new_tag): for note in self.notes: if note.id == id: note.memo = new_tag
[ "def modify_tags(self, note_id, tags):\n try:\n self._find_note(note_id).tags = tags\n except AttributeError:\n print(f\"Note with id {note_id} not found\")", "def modify_tags(self, note_id, tags):\n\t\tself._find_note(note_id).tags = tags", "def modify_tags(note_id, tags):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transform a list of values into a 2D numpy array (aka memory) of probaility distributions. Int > 1.0 at int index, 0.0 everywhere else None > Uniformly distributed 1.0/len(values) E.g. [2, 1, None] > nparray [ [0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [0.333, 0.333, 0.333] ]
def values_to_distribution_memory(values): length = len(values) memory = np.zeros([length, length], dtype=np.float32) uniform_density = 1.0 / float(length) for i, val in enumerate(values): if val != None: memory[i][val] = 1.0 else: memory[i].fill(uniform_density) ...
[ "def rv(value_list):\n return np.array([value_list])", "def poissonify(arr):\n return np.random.poisson(arr).astype(np.float32)", "def init_probability_2d(self):\n retval = []\n for a in range(0,28):\n retval.append([])\n for b in range(0,28):\n #first el...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transform a batch of value lists into a batch of 2D numpy arrays of probability distributions.
def batch_to_distribution_memories(batch): batch_memory = [] for value_array in batch: batch_memory.append(values_to_distribution_memory(value_array)) return batch_memory
[ "def values_to_distribution_memory(values):\n length = len(values)\n memory = np.zeros([length, length], dtype=np.float32)\n uniform_density = 1.0 / float(length)\n for i, val in enumerate(values):\n if val != None:\n memory[i][val] = 1.0\n else:\n memory[i].fill(unif...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a batch of input/target memory pairs, where the task specifies the target transformation.
def next_batch(memory_dim, batch_length, task): batch_inputs = [] batch_targets = [] difficulty = 0.0 for _ in xrange(batch_length): # Values as integers random_input = task.generate_random_input(difficulty, memory_dim) target_output = task.run(random_input) # Values as ...
[ "def _generate_batch(self, tasks: List):\n x_batch = np.stack([np.random.uniform(low=self.domain_bounds[0], high=self.domain_bounds[1], size=(self.inner_update_k, 1)) for _ in range(len(tasks))])\n y_batch = np.stack([[tasks[t](x) for x in x_batch[t]] for t in range(len(tasks))])\n\n return x_b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
校验是否需要元素存在。超过隐性等待时间不中断程序,继续执行 stuta =1:元素应该显示,stuta =2:元素应该隐藏,状态值只能是str类型
def elementIsNeedExist(self, by, element, stuta): putlog = Log() if stuta == '1': try: self.driver.find_element(by, element) except: putlog.error('没有找到元素,元素隐藏:%s' % element) self.getScreens() else: putlog...
[ "def check_list_status(todo_list): # Checks if the list is completely hidden\r\n # (2), completely empty (1), or neither (0)\r\n if len(todo_list) == 0:\r\n state = 1 # Empty List\r\n else:\r\n state = 2 # Entirely Hidden List\r\n for item_index in range(len(todo_list)):\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns bool, dict If connected, the link quality described by certain attributes such as e.g. bandwidth, loss, ...
def _distance_2_link_quality(self, distance): raise NotImplementedError
[ "def read_wlan_stats():\n\n with os.popen(\"iwconfig {}\".format(WLAN_INTERFACE), \"r\") as f:\n for l in f:\n if \"Quality\" in l:\n v = _to_keys(l.split())\n quality = float(eval(str(v.get('Link', 0.0))))\n strength = float(eval(str(v.get('Signal',...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decorator for creating detailed exception reports for thrown exceptions
def exception_report(storage_backend=LocalErrorStorage(), output_format="html", data_processor=None): def _exception_reports(func, *args, **kwargs): try: return func(*args, **kwargs) except Exception as e: exc_type, exc_value, tb = sys.exc_info() report_location...
[ "def create_exception_report(exc_type, exc_value, tb, output_format, storage_backend, data_processor=None, get_full_tb=False):\n exception_data = get_exception_data(exc_type, exc_value, tb, get_full_tb=get_full_tb)\n if data_processor:\n exception_data = data_processor(exception_data)\n\n if output_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the first_blood of this LolStatsTeamGame.
def first_blood(self, first_blood): self._first_blood = first_blood
[ "def first_blood_time(self):\n return self._get(\"first_blood_time\")", "def first_dragon(self, first_dragon):\n\n self._first_dragon = first_dragon", "def testHealthAssessStoolBlood(self):\n attr = self.session.create_visit_attr()\n\n self.util.boolTypeTest(self, attr, \"stool_blood...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the first_tower of this LolStatsTeamGame.
def first_tower(self, first_tower): self._first_tower = first_tower
[ "def set_first_turn(self):\r\n first_turn = self.init_data[2]\r\n self.board.turn = first_turn", "def set_first_player(self):\n if self.player2.won_previous:\n self.current_player = self.player2\n else: self.current_player = self.player1", "def first_dragon(self, first_dra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the first_inhibitor of this LolStatsTeamGame.
def first_inhibitor(self, first_inhibitor): self._first_inhibitor = first_inhibitor
[ "def first_installment(self, first_installment):\n\n self._first_installment = first_installment", "def start_game(self, first_player_idx):\n self.curr_player_idx = first_player_idx\n return", "def first_six(self, first_six):\n\n self._first_six = first_six", "def first_open_instal...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the first_baron of this LolStatsTeamGame.
def first_baron(self, first_baron): self._first_baron = first_baron
[ "def set_first(self, value):\n if value not in (\"player\", \"computer\", \"random\"):\n raise SettingsError(\"Invalid choice\")\n self._parser.set(\"settings\", \"first\", value)\n self._save()", "def first_dragon(self, first_dragon):\n\n self._first_dragon = first_dragon",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the first_dragon of this LolStatsTeamGame.
def first_dragon(self, first_dragon): self._first_dragon = first_dragon
[ "def first_tower(self, first_tower):\n\n self._first_tower = first_tower", "def set_first_turn(self):\r\n first_turn = self.init_data[2]\r\n self.board.turn = first_turn", "def start_game(self, first_player_idx):\n self.curr_player_idx = first_player_idx\n return", "def firs...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the first_rift_herald of this LolStatsTeamGame.
def first_rift_herald(self, first_rift_herald): self._first_rift_herald = first_rift_herald
[ "def first_tower(self, first_tower):\n\n self._first_tower = first_tower", "def set_first_turn(self):\r\n first_turn = self.init_data[2]\r\n self.board.turn = first_turn", "def first_dragon(self, first_dragon):\n\n self._first_dragon = first_dragon", "def set_steering_drift(self, d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the opponent_id of this LolStatsTeamGame.
def opponent_id(self, opponent_id): self._opponent_id = opponent_id
[ "def opponent(self, opponent):\n\n self._opponent = opponent", "def set_opponent(self, opponent):\r\n self.opponent = opponent\r\n self.deck.set_opponent(self.opponent)\r\n self.hand.set_opponent(self.opponent)", "def opponent_stat(self, opponent_stat):\n\n self._opponent_stat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the opponent of this LolStatsTeamGame.
def opponent(self, opponent): self._opponent = opponent
[ "def set_opponent(self, opponent):\r\n self.opponent = opponent\r\n self.deck.set_opponent(self.opponent)\r\n self.hand.set_opponent(self.opponent)", "def set_opponent(self, op):\n self._opponent = op", "def opponent_stat(self, opponent_stat):\n\n self._opponent_stat = opponen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the day of this LolStatsTeamGame.
def day(self, day): self._day = day
[ "def setDay(self, *args):\n return _libsbml.Date_setDay(self, *args)", "def time_of_day(self, value):\n self.time_of_day_value = value", "def set_day_step(self) -> None:\n self.day_step = (self.total_steps % DAY_DURATION)", "def setTime(self, timeObj, day=None):\n\n # override day ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the date_time of this LolStatsTeamGame.
def date_time(self, date_time): self._date_time = date_time
[ "def set_time(self, time):\n self.game_inst.set_time(time)", "def set_time(self, time):\n self._time = time", "def set_time(self, time):\n pass", "def set_time(self, set_time):\n\n self._set_time = set_time", "def set_datetime(self, date):\n self.date = date", "def sent_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the match_name of this LolStatsTeamGame.
def match_name(self, match_name): self._match_name = match_name
[ "def set_teamname(self, new_name):\n self.teamname = new_name", "def team_name(self, team_name):\n\n self._team_name = team_name", "def name_match_mode(self, name_match_mode):\n\n self._name_match_mode = name_match_mode", "def _update_team_name(self):\r\n\t\tnew_team_name = self._entry_te...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the kills of this LolStatsTeamGame.
def kills(self, kills): self._kills = kills
[ "def get_kills_2v2v2(self, uuid):\n\n return self.template(uuid, \"kills_teams\")", "def turret_kills(self, turret_kills):\n\n self._turret_kills = turret_kills", "def unreal_kills(self, unreal_kills):\n\n self._unreal_kills = unreal_kills", "def resetSkills(self):\r\n \"\"\" Reset...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the assists of this LolStatsTeamGame.
def assists(self, assists): self._assists = assists
[ "def set_assists_per_turnover(self):\n bx = self.get_standard_stats()\n ratio = bx[\"assists\"]\n if bx[\"turnovers\"] > 0:\n ratio = bx[\"assists\"] / bx[\"turnovers\"]\n self.assists_per_turnover = \"%.2f\" % round(ratio, 2)", "def teams(self, teams):\n\n self._team...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the deaths of this LolStatsTeamGame.
def deaths(self, deaths): self._deaths = deaths
[ "def set_death(self, d, line_number=0):\n self.death = d\n self._death_line = line_number\n self._age_line = line_number", "def _set_deaths(self, deaths_num, db_session):\n deaths_obj = db_session.query(db.MiscValue).filter(db.MiscValue.mv_key == 'current-deaths').one()\n deaths...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the largest_killing_spree of this LolStatsTeamGame.
def largest_killing_spree(self, largest_killing_spree): self._largest_killing_spree = largest_killing_spree
[ "def largest_multi_kill(self, largest_multi_kill):\n\n self._largest_multi_kill = largest_multi_kill", "def killing_spree(self, killing_spree):\n\n self._killing_spree = killing_spree", "def max_players(self, max_players):\n\n self._max_players = max_players", "def non_heap_max(self, non_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the largest_multi_kill of this LolStatsTeamGame.
def largest_multi_kill(self, largest_multi_kill): self._largest_multi_kill = largest_multi_kill
[ "def largest_killing_spree(self, largest_killing_spree):\n\n self._largest_killing_spree = largest_killing_spree", "def set_max(self, max):\n self.set_val((self.val[0], max))", "def non_heap_max(self, non_heap_max):\n\n self._non_heap_max = non_heap_max", "def maximum_level(self, maximum_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }