query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Load the data in the file as YAML, then deserialize into the model with the schema
def load_yaml_file(self, path): with path.open('r') as handle: data = load_yaml(handle) self.set_all(**self.SCHEMA.load(data).data)
[ "def parseModelFromFile(inputFile):\n with open(inputFile, 'r') as f:\n modelData = yaml.safe_load(f.read())\n return modelData", "def load_yaml():\n yamlfullpath = os.path.join(THISDIR, 'ff_data.yaml')\n\n with open(yamlfullpath, 'r') as stream:\n ff_data = yaml.safe_load(stream)\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transform the dataframes train_data and test_data using the simple_pre_process_text_df fuction
def pre_process_df(train_data, test_data): train_data["text"] = train_data["sentence1"] + ", " + train_data["sentence2"] # noqa test_data["text"] = test_data["sentence1"] + ", " + test_data["sentence2"] train_data.drop(["sentence1", "sentence2"], axis=1, inplace=True) test_data.drop(["sentence1", "sent...
[ "def pre_process_df_and(train_data, test_data):\n train_data[\"text\"] = train_data[\"sentence1\"] + \", \" + train_data[\"sentence2\"] # noqa\n test_data[\"text\"] = test_data[\"sentence1\"] + \", \" + test_data[\"sentence2\"]\n train_data.drop([\"sentence1\", \"sentence2\"], axis=1, inplace=True)\n t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transform the dataframes train_data and test_data using the simple_pre_process_text_df fuction
def pre_process_df_and(train_data, test_data): train_data["text"] = train_data["sentence1"] + ", " + train_data["sentence2"] # noqa test_data["text"] = test_data["sentence1"] + ", " + test_data["sentence2"] train_data.drop(["sentence1", "sentence2"], axis=1, inplace=True) test_data.drop(["sentence1", "...
[ "def pre_process_df(train_data, test_data):\n train_data[\"text\"] = train_data[\"sentence1\"] + \", \" + train_data[\"sentence2\"] # noqa\n test_data[\"text\"] = test_data[\"sentence1\"] + \", \" + test_data[\"sentence2\"]\n train_data.drop([\"sentence1\", \"sentence2\"], axis=1, inplace=True)\n test_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
(Python 3) Funcion que devuelve una lista con strings de todos las interfaces de red que tenga tu computadora
def get_interfaces(): with open('/proc/net/dev','r') as f: #Abrimos el archivo con la informacion de red interfaces = [] for linea in f: if ':' in linea: interfaces.append(linea[:linea.find(':')]) #Extraemos los primeros caracteres de las lineas con informacion d...
[ "def list():\n\n\treturn netifaces.interfaces()", "def monitoredInterfaceList(self):\n\n ifs = []\n confStr = self.config.linksToMonitor\n specLinks = parseConfStr(confStr)\n topo = self.net.topo\n topoLinks = topo.iterLinks()\n for s,d in specLinks:\n if (s,d)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new bundle and add it at the end of the document.
def create_bundle(self): self._highest_bundle_id += 1 bundle = Bundle(document=self, bundle_id=str(self._highest_bundle_id)) self.bundles.append(bundle) bundle.number = len(self.bundles) return bundle
[ "def add_bundle(self, doc_id, prov_document, identifier):\n\n data = {\n 'content': prov_document,\n 'rec_id': identifier\n }\n\n self.request(\"documents/\" + str(doc_id) + \"/bundles/\", data)\n return True", "def addBundle(self):\n if se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load a document from a conlluformatted file.
def load_conllu(self, filename): reader = ConlluReader(files=filename) reader.process_document(self)
[ "def _load_conll(path) -> Document:\n\n def create_sentence() -> Sentence:\n sent = Sentence()\n sent[POS] = []\n sent[DEP] = []\n return sent\n\n sents = []\n with open(path) as src:\n sent = create_sentence()\n for line in src:\n info = line.strip().sp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Store a document into a conlluformatted file.
def store_conllu(self, filename): writer = ConlluWriter(files=filename) writer.process_document(self)
[ "def save_one_sync(self, document):\n if (not isinstance(document, Document)):\n raise ValueError(\"Document must be an instance of Document\")\n\n file_path = make_valid_path(self.base_path, document)\n\n with open(file_path, \"x\") as file:\n file.write(document.data)", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Main handling function. Wraps deckoverview.
def main(): logging.basicConfig(format="%(asctime)s %(levelname)-5.5s %(message)s", stream=sys.stdout, level=logging.DEBUG) # Parse options parser = argparse.ArgumentParser(description='Generate a Commander decklist') parser.add_argument("--layout", help=...
[ "def print_deck(self):\r\n print('full deck: [top] ', end='')\r\n for i in self.deck:\r\n print(i, end=' ')\r\n print('[bottom]')", "async def deckstats(self, ctx, *, sort_key: str=\"\"):\n\n\n # Use a line_table instead of a block_table for better mobile experience\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
REACH INTO THE MODULES AND OBJECTS TO SET CONSTANTS. THINK OF THIS AS PRIMITIVE DEPENDENCY INJECTION FOR MODULES. USEFUL FOR SETTING DEBUG FLAGS.
def set(constants): if not constants: return constants = wrap(constants) for k, new_value in constants.leaves(): errors = [] try: old_value = pyDots.set_attr(sys.modules, k, new_value) continue except Exception, e: errors.append(e) ...
[ "def set_enabled_constants(modname):\n\n # Re-import here because these were deleted from namespace on init.\n import importlib\n import warnings\n from astropy.utils import find_current_module\n from . import utils as _utils\n\n try:\n modmodule = importlib.import_module('.constants.' + mo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function will import the subscription details from a designated csv file. The output is a list of sub/pw tuples.
def importDetails(details): sublist = [] sub_no ='' for row in details: sub_no = row[0].rsplit('@')[0] pw = row[1] entry = (sub_no, pw) sublist.append(entry) return sublist
[ "def get_transcriptions_from_csv(fileobj):\n reader = csv.DictReader(fileobj)\n fields = {'YYYY','MM','DD','PERMALINK','TRANSCRIPTION'}\n transcribed= []\n for row in reader:\n cleaned_row = {k: row[k] for k in row.viewkeys() & fields if row[k]}\n if 'TRANSCRIPTION' in cleaned_row: transcr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function takes sub/pw tuple, checks to see if already ported. If already ported, remove from provisioning list and place in own list. Return both lists.
def check_list_for_existing_ports (subdata): list_of_existing_ports =[] not_ported_subs = [] count = 0 # count needed for subdata list pop if required. for row in subdata: print (" Checking {0} in NGIN GNP Database.".format(row[0])) prov_logger.info(" Checking {0} in NGIN GNP Data...
[ "def taken_ports():\n odoo = 'odoo' if env.api.system != 'wheezy' else 'openerp'\n ports = sudo('grep _port /srv/{odoo}/*/*cfg /srv/{odoo}/*/*/*cfg'\n '|cut -d= -f2|sort|uniq'\n .format(odoo=odoo)).splitlines()\n ports += sudo('grep \\.bind /srv/{odoo}/*/*cfg /srv/{odoo}/*/...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the hosted office subscription.
def create_hosted_office(sub, pw): s1 = ims.hostedOfficeSubscriber(sub) session = {} session['emaSession'] = ema.emaLogin() session['sub_pw'] = pw # Get password from xls sheet and put here result = s1.subscriberCreate(session) ema.ema_logout(session['emaSession']) return res...
[ "def create_subscription(self):\n\n self.clear_subscriptions()\n\n # creating new subscription\n r = self.fitbit_service.post('http://api.fitbit.com/1/user/-/apiSubscriptions/%s.json' % self.userid, data={}, header_auth=True)\n logging.info('Adding new subscription for user %s. The code: %s Message: %s'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Download the plugin, name, Drupdates oragnization on Github.
def download_plugin(name): uri = 'https://github.com/drupdates/' + name + '.git' plugins_dir = Utils.check_dir(os.path.join('~', '.drupdates', 'plugins')) if not bool(urlparse(uri).netloc): msg = ("Error: {0} url, {1}, is not a valid url").format(name, uri) raise Drupdate...
[ "def _download( self ):\n self._system.execute_command( \"git\", [\"clone\", \"git@github.com:snoplus/snogoggles.git\", \n self.get_install_path()], cwd=os.getcwd(), verbose=True)", "def download(ui, repo, clname, **opts):\n\tcl, patch, err = DownloadCL(ui, rep...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recursively gets all substructures up to a maximum size starting from an atom in a substructure.
def get_substructures_from_atom(atom: Chem.Atom, max_size: int, substructure: Set[int] = None) -> Set[FrozenSet[int]]: assert max_size >= 1 if substructure is None: substructure = {atom.GetIdx()} substructures = {frozenset(substructur...
[ "def get_substructures(atoms: List[Chem.Atom],\n sizes: List[int],\n max_count: int = None) -> Set[FrozenSet[int]]:\n max_count = max_count or float('inf')\n\n random.shuffle(atoms)\n\n substructures = set()\n for atom in atoms:\n # Get all substructures ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets up to max_count substructures (frozenset of atom indices) from a molecule.
def get_substructures(atoms: List[Chem.Atom], sizes: List[int], max_count: int = None) -> Set[FrozenSet[int]]: max_count = max_count or float('inf') random.shuffle(atoms) substructures = set() for atom in atoms: # Get all substructures up to max size...
[ "def get_substructures_from_atom(atom: Chem.Atom,\n max_size: int,\n substructure: Set[int] = None) -> Set[FrozenSet[int]]:\n assert max_size >= 1\n\n if substructure is None:\n substructure = {atom.GetIdx()}\n\n substructures = {frozense...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts a substructure (set of atom indices) to a feature string by sorting and concatenating atom and bond feature vectors.
def substructure_to_feature(mol: Chem.Mol, substructure: FrozenSet[int], fg_features: List[List[int]] = None) -> str: if fg_features is None: fg_features = [None] * mol.GetNumAtoms() substructure = list(substructure) atoms = [Chem.Mol.GetAtomW...
[ "def feat_info_to_str(feat_list, add_id=False):\n #add part handling texts with a all_sent_f_list as + arg\n #feat_list = [(fn, fs[fn]) for fn in features.keys()]\n feat_list.sort()\n feature_n = [el[0] for el in feat_list]\n float_fs = [] #needed?\n float_fs = map(lambda x: str(float(x[1])), feat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads the Vocab a model was trained with.
def load_vocab(path: str) -> Vocab: return torch.load(path, map_location=lambda storage, loc: storage)['args'].vocab
[ "def load_vocab():\n # vocab loaded internally at google\n unused = r.sp_model\n del unused\n return r", "def load_vocab(vocab_file):\n # If vocab previously created, load from disk\n if os.path.exists(vocab_file):\n with open(vocab_file, 'rb') as handle:\n vocab = pickle.load(handle)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Do a call on tequila'server
def do_query(call, data=None): if data: # Tequila's encoding data = '\n'.join(['{}={}'.format(k, v) for k, v in data.items()]) r = requests.post('{}/cgi-bin/tequila/{}'.format(settings.TEQUILA_SERVER, call), data=data) else: r = requests.get('{}/cgi-bin/tequila/{}'.format(sett...
[ "def call(self):\n self.call() # Call a function", "def polling_call(self) -> global___Snippet.ClientCall:", "def daytonaCli(self, *args):\n (obj, command, params, actionID, sync) = (args[0], args[1], args[2], args[3], args[4])\n lctx = LOG.getLogger(\"scheduler-clilog\", \"DH\")\n\n cli_param_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build an HttpResponseRedirect for a faillure
def build_faillure(request, string): return HttpResponseRedirect("{}?why={}".format(settings.TEQUILA_FAILURE, string))
[ "def genredirect(location):\n code = 303\n raise bottle.HTTPResponse(\"\",status=code,Location=location)", "def redirect(location, status=302, trusted=False):", "def redirect(url):", "def _redirect_with_error(self, redirect_uri, problem_detail):\n return redirect(self._error_uri(redirect_uri, pro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Collects user's checkout details
def collect_details(): user_details = [] user_details.append( input("\tEnter your first name for checkout purposes\n\t(press Enter to continue)\n\n\t")) user_details.append( input("\n\tEnter your last name for checkout purposes\n\t(press Enter to continue)\n\n\t")) user_details.append(input( "\n\tEnter your...
[ "def _extract(self):\n if not self._user_details:\n self._user_details = github_user_details(self._user_name)\n today_date = datetime.date.today()\n account_creation_date = self._user_details['account_created_at'].date()\n account_updated_at = self._user_details['l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checks twitter for restock notifications
def restock_checker(last_check_time = "2020-12-23 14:20:00") -> tuple: # config settings for twitter scraping (via twint) cfg = tw.Config() cfg.Username = "tendmoney" cfg.Since = last_check_time # tweets since last check # cfg.Limit = 1 # max num tweets cfg.Search = "DiscountMoneyStore.com" # search term # r...
[ "def check_updates():\n\n # Initiate \n twit = TwitterStatus()\n\n # Load stored entries\n twit.load() \n\n # Start with Friend Timeline\n for i in twit.api.GetFriendsTimeline():\n twit.check_status(i)\n\n # Next lets do Replies\n for i in twit.api.GetReplies():\n twit.check...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
readParams(file) > devuelve un diccionario con los datos del fichero de parámetros en un diccionario y los valores como strings
def readParams(file): parametros={} f=open(file,'r') lineas=f.readlines() f.close() for linea in lineas: if linea[0]=='#': continue else: trozos=linea.split('#')[0] trozos=trozos.split() if len(trozos[1:])>1: #parámetro con más de un valor parametros[trozos[0]]=troz...
[ "def ReadParameterFile(pf):\n f = open(pf, \"r\")\n pf_dict = SetDefaultParameterValues()\n for line in f:\n if not line.split(): \n continue\n if line.split()[0][0] == \"#\": \n continue\n \n # This will prevent crashes if there is not a blank line at the ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
signal_handler(signal, frame) > Para poder capturar el sigterm y borrar el lockfile
def signal_handler(signal, frame): output.write("Recibí un SIGTERM (habló launch_single_simulation)\n") try: os.remove(lockFileName) output.write("El lockfile se borró correctamente\n") except: output.write("La petó al intentar borrar el lockfile\n") pass ...
[ "def sigint_handler(signal, frame):\n rclpy.shutdown()\n if prev_sigint_handler is not None:\n prev_sigint_handler(signal)", "def _sigterm_handler(self, signum, frame):\n os.kill(os.getpid(), signal.SIGINT)", "def sigterm_handler(_signo, _stack_frame):\n sys.exit(0)", "def signal_handle...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
secureCompute(nombrePaso,doneFileName,lockFileName,comando,outFileName) nombrePaso = catálogo, VVmax o STY (solo para verbose) doneFileName = nombre del fichero de done lockFileName = nombre del fichero de lock comando = lo que se enviará si todo está correcto outFileName = nombre del fichero de salida de comando
def secureCompute(nombrePaso,doneFileName,lockFileName,comando,outFileName): doneFile=0; lockFile=0 doneFile=os.access(doneFileName,os.F_OK) if not(doneFile): # El paso no está hecho if verbose: output.write("No está hecho el "+nombrePaso+"\n") lockFile=os.access(lockFileName,os.F_OK...
[ "def cipher_execution(op, input, output, password):\n command = [\n EXEC_NAME,\n op,\n input,\n '-o',\n output,\n '-k',\n password\n ]\n start_time = time.time()\n subprocess.call(command, 1)\n end_time = time.time() - start_time\n print(\"%s took %...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cleanup orphan tracks and empty playlists.
def clean(): tracks = [] removed_playlists = 0 for playlist in PlaylistManager.find(): if len(playlist.tracks) == 0: PlaylistManager.remove(playlist.id) removed_playlists += 1 else: tracks += playlist.tracks tracks = list(set(tracks)) removed_tr...
[ "def cleanup(self):\n self.all_wav_to_mp3()\n self.past_songs_db.close()\n self.move_tracks_to_music_folder( )\n self.delete_leftovers()\n print \"Cleanup finished\"", "def clear_playlists():\n global kk_slider_queue\n global aircheck_queue\n global aircheck_playlist_cr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns average of all stored heart rates for user since some time if given
def average_hr(self, since_time=None): try: import numpy as np except ImportError as e: print("Necessary import failed: {}".format(e)) return None hr = np.array(self.heart_rate) if since_time is not None: hr_adjusted = np.array([]) ...
[ "def interval_average():\r\n import statistics as st\r\n from tach_detect import tach_detect\r\n r = request.get_json()\r\n try:\r\n email = r[\"user_email\"]\r\n except KeyError:\r\n return jsonify(\"no email input\"), 400\r\n raise LookupError(\"no email input\")\r\n check_e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adjust age and age units to fit analysis ranges
def adjust_age(self): try: from tools import valid_units except ImportError as e: print("Necessary import failed: {}".format(e)) if not valid_units(self.age_units): print("Given unit is not supported: {}".format(self.age_units)) raise ValueError() ...
[ "def adjust_ages(AgesIn):\n# get a list of age_units first\n age_units,AgesOut,factors,factor,maxunit,age_unit=[],[],[],1,1,\"Ma\"\n for agerec in AgesIn:\n if agerec[1] not in age_units:\n age_units.append(agerec[1])\n if agerec[1]==\"Ga\":\n factors.append(1e9)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines lower bound for tachycardia given age of User
def tachycardic_range(self): self.adjust_age() if self.age_units == "day": if self.age <= 2: return 159 elif self.age <= 6: return 166 elif self.age_units == "week": return 182 elif self.age_units == "month": ...
[ "def closest_user_age():\n\t\tif user_age in rating_by_age_dict:\n\t\t\treturn user_age\n\t\treturn min(\n\t\t\trating_by_age_dict.keys(),\n\t\t\tkey=lambda x: abs(x - user_age)\n\t\t)", "def lower_age(self):\n return self._lower_age", "def normalize_people_age(age):\n # for g in range(16, 100, 20):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Connect to an LDAP server
def _ldap_server_connect(): ldap_server = current_app.config['LDAP_SERVER'] ldap_port = int(current_app.config['LDAP_PORT']) ldap_use_tls = current_app.config['LDAP_USE_TLS'] ldap_key_path = current_app.config['LDAP_KEY_PATH'] ldap_sa_bind_dn = current_app.config['LDAP_SA_BIND_DN'] ldap_sa_passw...
[ "def connect_ldap(self, server=\"ldap.example.com\", port=389, user=None, password=None):\n try:\n ldap_server = Server(server, port = port, get_info = ALL)\n self.conn = Connection(ldap_server, user = user, password = password)\n self.is_connected = self.conn.bind()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load Edward Snelson's 1d regression data set []. It contains 200 examples of a few oscillations of an example function. It has seen extensive use as a toy dataset for illustrating qualitative behaviour of Gaussian process approximations.
def snelson1d(path): path = os.path.expanduser(path) inputs_path = os.path.join(path, 'snelson_train_inputs') outputs_path = os.path.join(path, 'snelson_train_outputs') # Contains all source as well. We just need the data. url = 'http://www.gatsby.ucl.ac.uk/~snelson/SPGP_dist.zip' if not (os.path.exists(i...
[ "def nnRegression(data):", "def fake_regression_data():\n\n N = 500\n np.random.seed(42)\n x1 = np.random.normal(size=N)\n x2 = np.random.binomial(n=N, p=0.5)\n x3 = np.random.exponential(scale=10.0, size=N)\n x4 = np.random.poisson(lam=10, size=N)\n y = x1 + x2 + x3 + x4 + np.random.normal(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
expand fit results from the good cells to cells with not so good fitting results.
def expand_fit_results(self, fitResultsDF): # Now we have the good fits! # We'll have to find fits for cells # where we didn't find good fits. expFitDataTupleArr = [] minLat = round( self.sapsVelsDF["MLAT"].min() ) maxLat = round( self.sapsVelsDF["MLAT"].max() ) m...
[ "def exponential_fit(self, neutral_cells=10000):\n\n self.model_type = '3-parameter exponential model'\n\n # Initialize model parameters\n p = Parameters()\n\n # Create a fit attribute to detect growing trajectories\n # if fit = True append fitness parameter for fitting else fix fitness=-0.1\n if ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot the fitted velocities on a map. Mostly for verification purposes!
def plot_lshell_map(self, fitResultsDF,\ baseDir="/home/bharat/Documents/code/new-vel-data/fit-figs/"): import seaborn as sns import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from matplotlib.colors import Normalize # Seaborn styling ...
[ "def plotVelocity(self):\n\t\tfit_fun = np.poly1d(self.fit)\n\t\tmpl.plot(self.time,self.velocity,'bs')\n\t\tmpl.show()", "def plot_velocity(self, ln, t):\n import matplotlib.pyplot as plt\n fig, ax = plt.subplots( nrows=1, ncols=1 ) # create figure & 1 axis\n\n vel = []\n dist = []\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads the contacts from the excel sheet, and then calls the add_contact function to add the contact to the DB.
def read_contacts(filename: str, database) -> None: wb = xlrd.open_workbook(filename) # opens the excel workbook sheet = wb.sheet_by_index(0) # gets the sheet number_of_rows = sheet.nrows # total number of rows in the sheet blank_counter = 0 # Will count the number of blank phone numbers # Lo...
[ "def get_all_contacts(phB):\n\n f = open(\"Laboratory/Lab9/contacts.txt\", \"r\")\n contacts = f.read().split(\"\\n\")\n f.close()\n\n print(\"Data from the file\")\n print(contacts)\n\n print()\n for c in contacts:\n l = c.split(\", \")\n\n name = l[0].split(\" \")\n phone...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if the current contact already exists in the database, and adds it if it does not exist. Otherwise, the contact is added to the "duplicates" table.
def add_contact(database, name: str, email: str, phone: int) -> None: # Searches the database for the the current contact (excel row) cursor = database.execute("SELECT DISTINCT name, email, phone FROM contacts " "WHERE name = ? AND email =? OR phone = ?", (name, email, phone)) ...
[ "def add_contact(contact):\n db = get_db()\n \n if contact.get_hash_name() not in db:\n db[contact.get_hash_name()] = json.loads(contact.json())\n write_db(db)\n else:\n sys.exit(logger.fail('fatal: contact already exists'))", "def add(self, name, phonenumber):\n numbers = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Increate post's upvote counter
def upvote(self, request, pk=None): post = self.get_object() post.upvotes += 1 post.save() serializer = self.get_serializer(post) return Response(serializer.data, status.HTTP_200_OK)
[ "def up_vote(cls, user, message):\r\n pass", "def recieve_upvotes(self, num_upvotes):\n self.upvotes += num_upvotes", "def up_vote(cls, user, message):\n pass", "def test_upvote_modifies_post_score(self):\n post = Post.objects.get(body=\"123ABC Body\")\n self.assertEqual(pos...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a timer set to expire after `duration` sec.
def __init__(self, duration=0.0): super(Timer, self).__init__() self.duration = duration # For storing aritrary data with timers self.data = Bunch.Bunch() self.timer = QtCore.QTimer() self.timer.setSingleShot(True) self.timer.setTimerType(QtCore.Qt.PreciseTimer)...
[ "def after(cls, duration: float | None = None) -> Deadline:\n started_at = time()\n expires_at = duration + started_at if duration is not None else duration\n deadline = cls(expires_at)\n deadline.started_at = started_at\n return deadline", "def start_single_timer(context, durat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Start the timer. If `duration` is not None, it should specify the time to expiration in seconds.
def start(self, duration=None): if duration is None: duration = self.duration self.set(duration)
[ "def start_single_timer(context, duration):\n _cancel_all_timers(context)\n _start_a_timer(\n context.bus, utterance=\"set a timer for \" + duration, response=[\"started-timer\"]\n )", "def __init__(self, duration=0.0):\n super(Timer, self).__init__()\n\n self.duration = duration\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a Ginga colormap into a QPixmap
def cmap2pixmap(cmap, steps=50): import numpy as np inds = np.linspace(0, 1, steps) n = len(cmap.clst) - 1 tups = [cmap.clst[int(x * n)] for x in inds] rgbas = [QColor(int(r * 255), int(g * 255), int(b * 255), 255).rgba() for r, g, b in tups] im = QImage(steps, 1, QImage.For...
[ "def convertToQPixelmap(self, imgToConvert):\n \n # Conversion en image QImage\n if ( len(imgToConvert.shape) == 3 ):\n img_qimg = QtGui.QImage(imgToConvert.data, \n imgToConvert.shape[1], \n imgToConvert.shape[0],...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the (degrees, direction) of a scroll motion Qt event.
def get_scroll_info(event): # 15 deg is standard 1-click turn for a wheel mouse # TODO: use pixelDelta() for better handling on hi-res devices? point = event.angleDelta() dx, dy = point.x(), point.y() delta = math.sqrt(dx ** 2 + dy ** 2) if dy < 0: delta = -delta ang_rad = math.ata...
[ "def _get_scroll(self, event):\n scroll_y = Quartz.CGEventGetIntegerValueField(\n event, Quartz.kCGScrollWheelEventDeltaAxis1)\n scroll_x = Quartz.CGEventGetIntegerValueField(\n event, Quartz.kCGScrollWheelEventDeltaAxis2)\n return scroll_x, scroll_y", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sums passed in numbers returning the total, also update the global variable num_hundreds with the amount of times 100 fits in total
def sum_numbers(numbers: list) -> int: global num_hundreds total = sum(numbers) num_hundreds += total // 100 return total
[ "def sum_numbers(numbers: list) -> int:\n global num_hundreds\n\n total = sum(numbers)\n num_hundreds += (total // 100)\n\n return total", "def sum_numbers(numbers: list) -> int:\n global num_hundreds\n total = sum(numbers)\n hundreds_value = len(list(range(0, total, 100))) - 1\n if (total...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns a boolean indicating if the dicts are different and a DeepDiff dictlike object that describes the differences.
def diff_dicts(dict_1, dict_2): differ = deepdiff.DeepDiff(dict_1, dict_2) return len(differ) > 0, differ
[ "def diff_dict(self, a_dict, b_dict):\n if set(a_dict.keys()) != set(b_dict.keys()):\n return True\n for k in a_dict:\n # TODO: numeric precision for floats, nested dictionaries etc etc\n if a_dict[k] != b_dict[k]:\n return True\n return False", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add links, data = (plugin, url) tuple. Internal method should use API.
def addLinks(self, data, package): self.db.addLinks(data, package, OWNER) self.evm.dispatchEvent("packageUpdated", package)
[ "def add_links(self, *args):\n for link in args:\n self.add_link(link)", "def createLinks(self,link):\n self.links.append(link)", "def add_link(self, link):\n raise NotImplementedError", "def add_data_url(self, url: str):\r\n if 'urls' in self.metadata:\r\n se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return a TreeCollection and fill the info data of containing packages. optional filter only unfnished files
def getTree(self, pid, full, state): view = TreeCollection(pid) # for depth=1, we don't need to retrieve all files/packages root = pid if not full else None packs = self.db.getAllPackages(root) files = self.db.getAllFiles(package=root, state=state) # updating from cach...
[ "def filter_package_content(package, fun):\n packageContent = dirPackage(package)\n filtered = [p.__name__ for p in filter(fun, packageContent)]\n return filtered", "def setup_package_data():\n\n \n data = [\n # 2013 test event xml\n os.path.join(u'2013-data', u'trec20...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return number of downloads
def getDownloadCount(self): if self.downloadcount == -1: self.downloadcount = self.db.downloadcount() return self.downloadcount
[ "def download_count(self):\n pass", "def count_files_to_download(soup: BeautifulSoup, url: str) -> int: # noqa: WPS210\n count = 0\n for download_object, (key, always_download) in DOWNLOAD_OBJECTS.items():\n for object_ in soup.find_all(download_object):\n item_link = object_.get(k...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checks if package is finished and calls addonmanager
def checkPackageFinished(self, pyfile): ids = self.db.getUnfinished(pyfile.packageid) if not ids or (pyfile.id in ids and len(ids) == 1): if not pyfile.package().setFinished: self.core.log.info(_("Package finished: %s") % pyfile.package().name) self.core.addo...
[ "def bundlerDone(self):\n\t\tif self.bundler.forceBundler==True: return False\n\t\telse: return True", "def post_install_pkg(self, installable_pkg):\n pass", "def finish(self):\n self._ensure(running = True)\n self._ensure_button('Finish')\n self._ensure_buttons_valid()\n _LOG...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
move all fids to pid
def moveFiles(self, fids, pid): f = self.getFileInfo(fids[0]) if not f or f.package == pid: return False if not self.getPackageInfo(pid): raise PackageDoesNotExists(pid) # TODO move real files self.db.moveFiles(f.package, fids, pid) return True
[ "def pid_hunt_and_kill(self, exit):\n\n for root, dirs, files in os.walk(self.workdir):\n #print root, dirs, files\n for found_file in files:\n if found_file.endswith('.pid'):\n file_path = os.path.join(root, found_file)\n pid_file = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
restart all failed links
def restartFailed(self): # failed should not be in cache anymore, so working on db is sufficient self.db.restartFailed()
[ "def web_restart():", "def _restart(self):\n pass", "def cmd_resymlink(self,*datadirs):\n for datadir in datadirs:\n print(\"Checking %s\"%datadir)\n sun = sunreader.SunReader(datadir)\n chain = sun.chain_restarts()\n if len(chain) <= 1:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
reads the data from file and creates the Payment objects
def read_data(): data = open("database.txt", "r", encoding="UTF-8") # opening the file for line in data: # iterating through the database.txt file if line[0] == "#": # this is comment, so skip it continue else: values = line.split(",") # split line into values for i in range(len(values)): ...
[ "def __init__(self, batchPayment):\n self.network = {}\n with open(batchPayment, encoding='utf-8', newline='\\n') as fin:\n # skip the header line\n fin.readline()\n for line in fin:\n tokens = line.split(',')\n id1 = tokens[1].strip()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates Payment object and inserts it into payments and calendar_dict dictionaries
def insert_payment(pd, p_d, v): # if the payment comes on Saturday or Sunday it needs to be moved to the following Monday # print(p_d.strftime("%a"), v[2]) if p_d.strftime("%a") == "Sat": if v[0] != "income": p_d += timedelta(days=2) else: p_d += timedelta(days=-1) elif p_d.strftime("%a") == "...
[ "def create_payment(self):\n today = timezone.now().date()\n due_date = today + datetime.timedelta(days=1)\n\n try:\n payment = self.contract.payment_set.get()\n previous_cost = payment.cost\n previous_due_date = payment.due_date\n except Payment.DoesNotE...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the date of next payment
def calculate_next_payment(frequency, payment_date, payment_month): if frequency == 1 or frequency == 4: # weekly or four-weekly next_payment = payment_date + timedelta(weeks=frequency) elif frequency == 2: # monthly next_payment = payment_date.replace(month=payment_month + 1) else: next_payment = date...
[ "def update_next_payment_date(self):\n latest = self.contributions.all().order_by('-cleared_on')[:1]\n interval = int(self.interval)\n # if there is any contribution dated after payment start\n if latest.count() and latest[0].cleared_on and (latest[0].cleared_on > self.payments_start_dat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns all currently active WETH, DAI trading pairs from RadarRelay, sorted by volume in descending order.
async def get_active_exchange_markets(cls) -> pd.DataFrame: async with aiohttp.ClientSession() as client: async with client.get("https://api.radarrelay.com/v2/markets?include=ticker,stats") as response: response: aiohttp.ClientResponse = response if response.status !=...
[ "def return_currency_pairs(self):\n return list(sorted(list(c for c in self.return_24_volume().keys()\n if not c.startswith('total'))))", "async def fetch_trading_pairs() -> List[str]:\n raise NotImplementedError", "def orderPairs(self):\n pairsByTickers = {}\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shortcut to get the timestamp of creation from the associated viztrail. Returns datetime.datetime
def created_at(self): return self.viztrail.created_at
[ "def creation_timestamp(self) -> str:\n return pulumi.get(self, \"creation_timestamp\")", "def get_creation_time(self):\n return self.get_attr('date_created')", "def creation_timestamp(self):\n return self._creation_timestamp", "def get_creation_time(self):\n return self.creation_t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shortcut to access the handle for the default branch of the viztrail. Returns vizier.viztrail.branch.BranchHandle
def get_default_branch(self) -> Optional[BranchHandle]: return self.viztrail.get_default_branch()
[ "def default_branch(self):\n\n return self.data[\"defaultBranchRef\"][\"name\"]", "def default_branch(self) -> str:\n return pulumi.get(self, \"default_branch\")", "def _get_default_branch(path, remote):\n try:\n p = subprocess.run(\n [\"git\", \"symbolic-ref\", f\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shortcut to get the last modified timestamp from the associated viztrail. Returns datetime.datetime
def last_modified_at(self): return self.viztrail.last_modified_at
[ "def last_modified_date_time(self):\n if \"lastModifiedDateTime\" in self._prop_dict:\n return datetime.strptime(self._prop_dict[\"lastModifiedDateTime\"].replace(\"Z\", \"\"), \"%Y-%m-%dT%H:%M:%S.%f\")\n else:\n return None", "def last_modified(self) -> datetime:\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shortcut to get the name of the associated viztrail. Returns string
def name(self): return self.viztrail.name
[ "def name(self):\n\t\treturn self.path[-1].get(\"name\")", "def get_name(self) -> str:", "def chain_name(self) -> str:\n return pulumi.get(self, \"chain_name\")", "def name(self):\n return self.step.real_name", "def Name(self) -> str:", "def vpd_name(self) -> str:\n return pulumi.get(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
iround(number) > integer Round a number to the nearest integer.
def iround(x): return int(round(x) - .5) + (x > 0)
[ "def int_round(number):\n if number > 0:\n return int(number + 0.5)\n else:\n return int(number - 0.5)", "def iround(x):\n return int(round(x) - .5) + (x > 0)", "def _round_to_int(aqi: float) -> int:\n if aqi % 1 < 0.5:\n return int(aqi)\n else:\n return int(aqi + 0.5)",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns True iff we're running 3 or above.
def is_running_py3(): return sys.version_info >= (3, 0)
[ "def has_threekind(self):\n if len(self.ranks) == 0:\n self.rank_hist()\n for val in self.ranks.values():\n if val >= 3:\n return True\n return False", "def Is3State(self):\r\n\r\n return self._is3State", "def is_version_3_or_newer() -> bool:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wird kurz vor Schreiben des LDAPObjects aufgerufen und fügt die Attribute objectClass und ast4ucsSrvchild (Verweis zum Superordinate) hinzu. Bei neuen Modulen müssen die objectClass und der Attributname des SuperordinateVerweises angepasst werden
def _ldap_addlist(self): return [('objectClass', ['ast4ucsMailbox']), ('ast4ucsSrvchildServer', self.superordinate.dn)]
[ "def getSubclass(self):\r\n return objectSubclassHandle", "def update_derived_class_records():\n derive_class_hierarchy()", "def append_base_class_to_acdb_entity(self) -> None:\n # This is only needed for DXFEntity, so applying this method\n # automatically to all entities is waste of ru...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
下载资源并解密保存在 `base_path + filename` 文件中
def download_and_decrypt(decrypt_obj, uri, base_path, filename, max_retry_times = 5): # 设置重传 retry_time = 0 resp = None while not isinstance(resp, requests.Response): try: resp = requests.get(uri, headers=getRandomHeaders()) except requests.exceptions.SSLError: r...
[ "def download(self):\n if not self.url:\n raise RuntimeError(self.tips)\n\n download_file_name = os.path.join(\n self.raw_path, os.path.splitext(os.path.basename(self.url))[0]\n )\n file_format = self.url.split(\".\")[-1]\n if \"amazon\" in self.url:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cleans scene AND image
def clean_all(self): self.scene.clear() self.image.fill(Qt.color0)
[ "def applyMorphologicalCleaning(self, image):", "def _toss_garbage(scene):\n for i in bpy.data.images:\n if i.name.endswith(\"_LIGHTMAPGEN.png\"):\n bpy.data.images.remove(i)\n for i in bpy.data.meshes:\n for uv_tex in i.uv_textures:\n if uv_tex.name == \"LIGHTMAPGEN\":\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks data of all "Circle" lineEdits
def check_circle(self) -> list or None: x_text = self.ui.lineEditCX.text() xc = float(x_text) if checker.check_float(x_text) else None y_text = self.ui.lineEditCY.text() yc = float(y_text) if checker.check_float(y_text) else None radius_text = self.ui.lineEditRad.text() r...
[ "def check_ellipse(self) -> list or None:\n x_text = self.ui.lineEditEX.text()\n xc = float(x_text) if checker.check_float(x_text) else None\n y_text = self.ui.lineEditEY.text()\n yc = float(y_text) if checker.check_float(y_text) else None\n a_text = self.ui.lineEditEA.text()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks data of all "Ellipse" lineEdits
def check_ellipse(self) -> list or None: x_text = self.ui.lineEditEX.text() xc = float(x_text) if checker.check_float(x_text) else None y_text = self.ui.lineEditEY.text() yc = float(y_text) if checker.check_float(y_text) else None a_text = self.ui.lineEditEA.text() a = fl...
[ "def onMouseEdit(self, event):\n\n data = self.app.data\n axes = self.hemisphereMat.figure.axes[0].axes\n\n if not event.inaxes:\n return False\n if event.dblclick:\n return False\n\n if self.ui.checkEditHorizonMask.isChecked():\n suc = self.editHo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
User chooses colour in QColorDialog. Colour of frame sets chosen colour.
def choose_colour(self) -> None: self.chosen_colour = QtWidgets.QColorDialog.getColor(Qt.white, self, "Выберите цвет") self.pen_colour = self.chosen_colour self.palette.setColor(QPalette.Background, self.chosen_colour) self.ui.frame.setPalette(self.palette)
[ "def pickColour(self):\n colour = QColorDialog.getColor()\n if colour.isValid():\n self.user[\"Colour\"] = colour.name()\n self.ui.l_colour.setText(self.user[\"Colour\"])", "def colourSelect(self):\r\n self.set_colour = QtGui.QColorDialog.getColor()\r\n self.colou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Changes colour of pen (using radio buttons)
def change_colour(self) -> None: if self.ui.radioButtonWhite.isChecked(): self.pen_colour = QColor(Qt.white) elif self.ui.radioButtonColour.isChecked(): self.pen_colour = self.chosen_colour else: # Impossible but better to control message.show_error(config.PR...
[ "def radiobtn_call(self):\n\t\tradSel = self.radVar.get()\n\t\tif radSel == 0:\n\t\t\tself.win.configure(background = self.colors[0])\n\t\tif radSel == 1:\n\t\t\t\tself.win.configure(background = self.colors[1])\n\t\tif radSel == 2:\n\t\t\tself.win.configure(background = self.colors[2])", "def _style_radiobutton(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the Pants binary name, e.g. './pants'.
def bin_name() -> str: # NB: This will be called at import-time in several files to define static help strings # (e.g. "help=f'run `{bin_name()} fmt`"). # # Ideally, we'd assert this is set unconditionally before Pants imports any of the files which # use it, to give us complete confidence we won't ...
[ "def get_binary_name():\n return os.path.basename(inspect.stack()[-1][1])[:16]", "def program_name(self):\n return \"./spooner.py\"", "def get_program_name():\n program_name = sys.argv[0]\n if not program_name.startswith(\"./\"):\n program_name = os.path.basename(program_name)\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine if evolution is positive or negative. From trend type determined in config.toml for each KPIs, picking right color to return
def get_color(val, trendType): if(val > 0): if(trendType == 'normal'): color = 'red' else: color = 'green' elif(val < 0): if(trendType == 'normal'): color = 'green' else: color = 'red' else: color = 'blue' return col...
[ "def GetBelowRangeColor(self):\n ...", "def color_differentiator(elevation):\n if elevation < 1000:\n return 'green'\n elif 1000 <= elevation < 3000:\n return 'orange'\n else:\n return 'red'", "def TrueColor(self) -> int:", "def color_availability( ecc, size ):\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate rolling average from a column. We apply mean for each values of a specific column within the range of last week date and date itself
def get_rolling_average(date, df, column): lowestDate = datetime.strftime( datetime.strptime(date, "%Y-%m-%d") - timedelta(days=6), "%Y-%m-%d" ) return df[ (df['date'] >= lowestDate) & (df['date'] <= date) ].mean()[column].mean().round(0)
[ "def rolling_mean(df: pd.DataFrame, window: int, column: typing.Union[typing.List, str] = 'close'):\n return df[column].groupby(level='symbol', group_keys=False).rolling(window).mean()", "def get_rolling_mean(values, window):\r\n return pd.rolling_mean(values, window=window)", "def get_rolling_mean(values...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enrich dataframe for KPIs that need to be calculated.
def enrich_dataframe(df, name): if(name == 'taux_incidence'): df['taux_incidence'] = df['P']*100000/df['pop'] if(name == 'taux_positivite'): df['taux_positivite'] = df['P']/df['T'] * 100 if(name == 'taux_occupation'): df['TO'] = df['TO']*100 if(name == 'vaccins_vaccines_couv_maje...
[ "def reorganize_experimental_pKa_dataframe(dataframe):\n\n # reorganize experimental data: I want each row to represent one pKa.\n data = []\n\n for i, row in enumerate(dataframe.iterrows()):\n pKa1_mean = np.NaN\n pKa2_mean = np.NaN\n pKa3_mean = np.NaN\n\n mol_id = row[1][\"Mo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Redirect to good function depending of type of KPI needed. If mean param is set to True, we need to calculate the mean of kpis, if not, we calculate the stock.
def get_kpi_by_type(df, level, code_level, trendType, column, mean): if(mean): res = process_rolling_average(df, level, code_level, trendType, column) else: res = process_stock(df, level, code_level, trendType, column) return res
[ "def _astroscrappy_gain_apply_helper(cleaned_data, gain,\n gain_apply, old_interface):\n if gain != 1.0:\n if gain_apply:\n if not old_interface:\n # New interface does not gain correct, old one did.\n return cleaned_data * gain\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print statistics about a set of samples and associated values
def print_statistics(samples, values=None, sample_labels=None, value_labels=None): num_vars, nsamples = samples.shape if values is None: values = np.empty((nsamples, 0)) if values.ndim == 1: values = values[:, np.newaxis] num_qoi = values.shape[1] assert nsamples == values.shape[0] ...
[ "def displaysamples(samples):\n for samp in samples:\n for i in range (0, samp.getNumberOfFeatures()):\n print (samp.getfeatures())[i], #features are comma-separated\n print", "def collect_show_statistics(self):\n epocs = 0\n examples = 0\n channels = 0\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" discrete_sampling samples iid from a discrete probability measure x = discrete_sampling(N, prob, states) Generates N iid samples from a random variable X whose probability mass function is prob(X = states[j]) = prob[j], 1 <= j <= length(prob). If states is not given, the states are gives by 1 <= state <= length(pr...
def discrete_sampling(N, probs, states=None): p = probs.squeeze()/np.sum(probs) bins = np.digitize( np.random.uniform(0., 1., (N, 1)), np.hstack((0, np.cumsum(p))))-1 if states is None: x = bins else: assert(states.shape[0] == probs.shape[0]) x = states[bins] retu...
[ "def sample_discrete_states(\n key,\n num_samples,\n *,\n num_states,\n sample_with_replacement = False):\n sample_key, key = jax.random.split(key)\n states = jax.random.choice(\n sample_key, num_states, (num_samples,), replace=sample_with_replacement)\n return states, key", "def categorica...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the appropriate input form for the inference procedure.
def _get_encoding_form(self, input): if self.inference_procedure == 'direct': return input else: raise NotImplementedError
[ "def inference():", "def inference(self, *inputs):\n raise NotImplementedError", "def inference():\n raise NotImplementedError(\"Inference method not implemented\")", "def inference_parameters(self):\n raise NotImplementedError", "def getSymbolicInput(self):\n return self._inputS...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method to step the latent level forward in the sequence.
def step(self): self.latent.step()
[ "def step(self, state):", "def step(self):\n self.current_step = min(self.steps, self.current_step + 1)", "def _step(self, whence):\n pass", "def train_loop_pre(self, current_step):\r\n pass", "def _step_snell(self) -> None:\n self.snell.step()", "def step(self):\n \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method to reinitialize the latent level (latent variable and any state variables in the generative / inference procedures).
def re_init(self): self.latent.re_init() if 're_init' in dir(self.inference_model): self.inference_model.re_init() if 're_init' in dir(self.generative_model): self.generative_model.re_init()
[ "def _uninitialize(self):\n self._variables.uninitialize()\n self._initialize_time()", "def initialize_variables(self):\n self.sess.run(self.init)", "def reinitialize(self):\r\n self._lr_scheduler = None\r\n self._optimizer = None\r\n self._wrapped_criterion = None\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method to obtain inference parameters.
def inference_parameters(self): params = nn.ParameterList() if 'parameters' in dir(self.inference_model): params.extend(list(self.inference_model.parameters())) params.extend(list(self.latent.inference_parameters())) return params
[ "def inference_parameters(self):\n raise NotImplementedError", "def inference_parameters(self):\n params = nn.ParameterList()\n params.extend(list(self.inf_mean_output.parameters()))\n params.extend(list(self.inf_log_var_output.parameters()))\n # params.extend(list(self.approx_p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method to obtain generative parameters.
def generative_parameters(self): params = nn.ParameterList() if 'parameters' in dir(self.generative_model): params.extend(list(self.generative_model.parameters())) params.extend(list(self.latent.generative_parameters())) return params
[ "def generative_parameters(self):\n raise NotImplementedError", "def get_parameters(self, module: RLModule) -> Sequence[ParamType]:", "def generate_params(self, *args, **kwargs):\n pass", "def parameters(self):\n for parameters in self:\n for parameter in parameters:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Filter this queryset to select status objects as of status_date.
def filter_status_as_of(self, status_date: datetime.date) -> QuerySet: return self.model._filter_queryset_status_as_of(self, status_date)
[ "def filter_date_status(qs, status, from_date, to_date):\n if Enquiry.FinalisedOrder in status:\n return qs.filter(cnf_loading_date__gte=from_date, \\\n cnf_loading_date__lte=to_date, status__exact=status).distinct() \\\n .order_by('-enquiry_id')\n elif Enquiry...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Filter queryset to select status objects as of status_date. Can be used on querysets where the base object is not a subclass of StatusModel, in which case the django model path to the relevant StatusModel subclass should be provided in 'status_model_path'. e.g. StatusModel._filter_queryset_status_as_of(queryset = Invoi...
def _filter_queryset_status_as_of(cls, queryset: QuerySet, status_date: datetime.date, status_model_path: str = '', return_type: Literal(['queryset', 'q_obj']) = 'queryset') -> QuerySet: if status_model_path != '': status_model_path += '__' # append this to get...
[ "def filter_status_as_of(self, status_date: datetime.date) -> QuerySet:\n return self.model._filter_queryset_status_as_of(self, status_date)", "def filter_date_status(qs, status, from_date, to_date):\n if Enquiry.FinalisedOrder in status:\n return qs.filter(cnf_loading_date__gte=from_date...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a new StatusModel record for an observed object. Any previously 'current' status (if one exists) is marked as ending the day prior to the new status, and the new status is added with no end date. If the prior status starts on the same day as the new status, the prior status is removed completely.
def add_status(cls, new_status: StatusModel): # start or ensure we're in a transaction transaction_context = db_transaction.atomic if not in_db_transaction() else nullcontext with transaction_context(): if new_status.applies_to is not None: raise StatusCreati...
[ "def last_known_status(self, status):\n statuses_table = boto3.resource('dynamodb').Table(CASE_STATUS_TABLE)\n statuses_table.put_item(Item={\n 'receipt_number': self.receipt_number,\n 'last_known_status': status\n })", "def add_observes_between(observer_id: int, observed_id: in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Empty all of the output labels. Empty the list string too.
def __clear(self): for i in range(len(self.buttons_list)): self.labels_strvar[i].set("") if self.buttons_list[i]["state"] == DISABLED: self.buttons_list[i]["state"] = NORMAL self.entered_list = [] return
[ "def clear_all(cls):\n del cls.text_labels[:]", "def remove_all_node_labels(self):\n self.node_labels = []", "def clear_all_outputs(self):\n for cell in self.cells():\n if cell['cell_type'] == 'code':\n cell['outputs'] = []\n if 'prompt_number' in ce...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load Target via requests
def load_target(cls, scheme, path, fragment, username, password, hostname, port, query, load_method, **kwargs): url = cls.rebuild_url(scheme, path, fragment, username, password, hostname, port, query) expected_status_code = kwargs.pop...
[ "def load(self, url):\n pass", "def load(self, response: Response, target):\n if target is None:\n return None\n data = response.json\n if data is None:\n return None\n return target(**data)", "def _scrape_load(self, req, instruction, description, then):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write settings to a new config file
def write(self, fn): with open(fn, 'w') as f: self.config.write(f)
[ "def _write_config(self, config):\n with self._open_config_file(mode='w') as config_file:\n config.write(config_file)", "def _writeConfigFile(self):\n configfile = open(self.config_file, \"w\")\n self.config.write(configfile)\n configfile.close()", "def write_config_file()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Menemukan bilangan bulat x di dalam suatu deret fibonacci. Apabila x ada di dalam suatu deret fibonacci, maka kembalikan True. Jika tidak ada, maka kembalikan False
def find_fibonacci(x: int) -> bool: # write your code here a = 1 b = 1 while True: #Looping sampai ketemu return if x == 0: return True elif b <= x: if b == x: return True else: temp = b b = b + a a = temp el...
[ "def fib(x):\n \n if x == 0 or x == 1:\n return 1\n else:\n return fib(x-1) + fib(x-2)", "def fib(x):\n\tassert type(x) == int and x >= 0 #assert checks to make sure line = true\n\tif x == 0 or x ==1:\n\t\treturn 1\n\telse:\n\t\treturn fib(x-1) + fib(x-2)", "def fib(x):\r\n if x =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
通过 userid 搜索用户; >返回NetorkProfile
def _search_userid(self, userid: str, level: int, reason) -> iter: if not isinstance(userid, str): self._logger.error("Invalid userid") return res: NetworkProfile = self.__get_user_by_userid(userid, reason) return res
[ "def get(self, username):\n\t\tdb = getattr(g, 'db', None)\n\n\t\tqry = \"SELECT username,email,active,steamid FROM\\\n\t\t\tprofiles WHERE username = %s;\"\n\t\twith db as cursor:\n\t\t\tcursor.execute(qry, (username,))\n\n\t\treturn {'profile':cursor.fetchone()}", "def get(self, request, user_id=None):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
通过 url 搜索用户; >返回NetorkProfile
def _search_url(self, userurl: str, level: int, reason) -> iter: if not isinstance(userurl, str): self._logger.error("Invalid userurl") return res: NetworkProfile = self.__get_user_by_url(userurl, reason) return res
[ "def get(self, username):\n\t\tdb = getattr(g, 'db', None)\n\n\t\tqry = \"SELECT username,email,active,steamid FROM\\\n\t\t\tprofiles WHERE username = %s;\"\n\t\twith db as cursor:\n\t\t\tcursor.execute(qry, (username,))\n\n\t\treturn {'profile':cursor.fetchone()}", "def search(request, params):\n profiles = P...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses a text by ignoring non ascii characters and replacing \\n with \n.
def parse_text(text): return str(str(text).encode("ascii", "ignore")).replace("\\n","\n").replace("b'","")
[ "def normalize_newlines(text):\n return re.sub(\"\\r\\n|\\r\", \"\\n\", text)", "def normalize_newlines(text: str) -> str:\n return text.replace(\"\\r\\n\", \"\\n\").replace(\"\\r\", \"\\n\")", "def normalize_newlines(text):\n # text = force_text(text)\n re_newlines = re.compile(r'\\r\\n|\\r') # Us...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shows the traceback of the last error.
def error_traceback(): Logger.log('ERROR', traceback.format_exc())
[ "def showtraceback(self):\n try:\n import traceback\n if sys.exc_info()[2] is not None:\n exc_info = traceback.extract_tb(sys.exc_info()[2])\n txt = 'Unexpected Error:'\n txt = txt + '\\n Type : '+str(sys.exc_type) \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves an exception to the local folder storage.
def save_exception(exc): LOG.error("Error - %s", str(exc)) hour = time.strftime("_%H_%M_%S") today = time.strftime("_%d_%m_%Y") data = (str(exc)+traceback.format_exc()) file = open("./logs/ERROR_"+threading.currentThread().getName()+today+".log",'a+') #Replace to fix OSError ...
[ "def dump_exception_store(self, fp):\n LOGGER.debug('Writing the exception store to file \"%s\".', fp.name)\n pickle.dump(self._exception_store, fp)", "def _save_crasher(run_dir: str, smp: sample.Sample,\n exception: sample_runner.SampleError,\n crasher_dir: str) ->...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of sentences from a paragraph This is a rather naive implementation; there are probably better ones out there Assumes that the paragraph has proper punctuation.
def get_sentences(paragraph): punctuation = re.compile(r'[\.!?]') sentences = [sentence.strip() for sentence in punctuation.split(paragraph)] sentences = filter(lambda x: x, sentences) return sentences
[ "def SplitToSentence(self,Paragraph):\n replaced = re.sub('\\n',' ',Paragraph)\n sentences = re.split(r' *[\\.\\?!][\\'\"\\)\\]]* *', replaced)\n return [sent for sent in sentences if sent]", "def get_paragraphs_sentences(text_paragraphs, namespace=NAMESPACE):\n sentences = []\n for par...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a summary of a paragraph This is a naive implementation and does not use advanced NLP techniques `paragraph` is one big long string `num_sentences` the number of sentences desired in the summary
def summarize(paragraph, num_sentences=SUMMARY_NUM_SENTENCES): sentences = get_sentences(paragraph) paragraph_num_sentences = len(sentences) limit = min(paragraph_num_sentences, num_sentences) summary_sentences = sentences[:limit] if paragraph_num_sentences < num_sentences: # the original wa...
[ "def generate_paragraph(m, n_sentences, max_words_per_sentence):\n text = \"\"\n for i in range(n_sentences):\n sentence = m.generate_sentence(max_words_per_sentence)\n text = text + \" \" + sentence\n\n return text", "def createParagraph(self, nsentences=0, words=[]):\n ww = []\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add value in trie In each trie node check the given key present if its not present then create the object do same for remaining key and store metadata at end of key object
def add(self,root,key,value): node = root for digit in key: child = node.children[ord(digit)-ord('0')] if(child==None): node.children[ord(digit)-ord('0')] = TrieNode(digit) node = node.children[ord(digit)-ord('0')] node.value = ValueMe...
[ "def insert_key(key, v, trie):\n if not key or has_key(key, trie):\n return\n\n for char in key:\n branch = _get_child_branch(trie, char)\n if not branch:\n new_branch = [char]\n trie.append(new_branch)\n trie = new_branch\n else:\n trie ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return list of key value pair recursively return [(key,value)]
def getAllKeyValuePair(self,root,key): if root==None: return [] node = root result = [] for index,child in enumerate(node.children): if(child!=None): if(child.value!=None): result.append((key+str(index),child.value.va...
[ "def kv_tuple_list(d):\n return [(k, v) for k, v in d.items()]", "def items(self):\n return [(kvp.key, kvp.value) for kvp in self.keyvaluepair_set.all()]", "def getKeyValuePairs(self):\r\n keyValueList = []\r\n for i in range(len(self.keys)):\r\n if self.keys[i] != None:\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that all primers are ok
def check_primers(self): primer_keys=['sequence','description'] if self.data.has_key('primer_dict'): for primer in self.data['primer_dict'].keys(): for key in primer_keys: if not self.data['primer_dict'][primer].has_key(key): self.d...
[ "def test_ok_mm_primer(self):\r\n primers = ['AAAA', 'GGGG']\r\n self.assertEqual(ok_mm_primer('AAAA', primers, 0), True)\r\n self.assertEqual(ok_mm_primer('AAAA', primers, 3), True)\r\n self.assertEqual(ok_mm_primer('CCCC', primers, 0), False)\r\n self.assertEqual(ok_mm_primer('C...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialise the Tk variables
def init_tkvars(self): for key in self.defaultprefs: value = self.defaultprefs[key] if type(value) is types.IntType: var = self.__dict__[key] = IntVar() elif type(value) is types.StringType: var = self.__dict__[key] = StringVar() v...
[ "def _init_tkvars(self,PO):\n for name,param in PO.params().items():\n self._create_tkvar(PO,name,param)", "def initGUIVars(self):\r\n # Updatable labels\r\n self.curr_dir_lbl = StringVar()\r\n self.curr_dir_lbl.set(\"\")\r\n self.num_imgs_lbl = StringVar()\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
handle shift left click for seq selection
def handle_left_shift_click(self, event): #placeholder to prevent handle_left_click being called return
[ "def mouse_left_down(self):\n pass", "def leftButtonDown(self):\n\t\tautopy.mouse.toggle(True,autopy.mouse.LEFT_BUTTON)", "def LeftClick(self):\n self._PressLeftButton()\n self._ReleaseAllButtons()", "def shift(self, event):\n self._systematics.Shift(event)", "def RightClick(self):\n self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write a single aa sequence in the sequence window
def print_aa_seq(self,sequence,y,position=0,frame=0,font=None): for letter in sequence: position=position+1 x,y_junk=self.get_aa_pos_on_screen(position,frame) self.seq_win_objs[self.seqframe.create_text(x,y,text=letter,font=font,anchor='w')]=1 return
[ "def writeseq(afile, seq):\n print(seq, file=afile)", "def generate_aa_sequence_for_disp(aa_seq):\n return re.sub(\"(.{50})\", \"\\\\1\\n\", aa_seq, 0, re.DOTALL)", "def write_sequence(self):\n\n staves = self.get_sequence()\n\n with open(self.output_file, 'w') as out_file:\n\n pr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
From X and Y coordinate, return the DNA base number
def get_DNApos_fromcoords(self,x,y): # Are we close to the DNA sequence? if abs(y-self.seq_row)>10: return None # ok, DNA it is pos=int(float(x-self.seq_xstart+4.0)/self.base_scale.get()) return pos
[ "def base(self, x, y):\r\n \r\n rx = 2*x\r\n if x >= 0:\r\n rx += 3\r\n \r\n ry = 2*y\r\n if y < 0:\r\n ry -= 1\r\n \r\n return long(rx),long(ry)", "def dna_number(bp_seq):\r\n # Hint: use dna_digit\r\n\r\n # YOUR CODE HERE\r", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return the x and y position of the aa on the screen frame is 0, 1 or 2
def get_aa_pos_on_screen(self,position,frame): position=position*3+float(frame)-1 x,y=self.get_base_pos_on_screen(position) y=y+20.0+float(frame)*15.0 return x,y
[ "def position(self) -> Tuple[int, int]:\n xy = ffi.new(\"int[2]\")\n lib.SDL_GetWindowPosition(self.p, xy, xy + 1)\n return xy[0], xy[1]", "def getPos(self):\r\n return (self.rect.centery,self.rect.centerx)", "def get_position(self):\n\t\treturn (self.x, self.y)", "def _displayToEy...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Invert the DNA sequence
def invert_seq(self): if not self.data['DNAseq']: self.invert_seq_var.set(0) self.warning('No DNA sequence loaded','You have to load a DNA sequence first') return inverted='' for count in range(len(self.data['DNAseq'])): pos=-count-1 in...
[ "def reverse_transcribe(self):\n rna_alphabet = _convert_alphabet(self._alphabet, RnaSequence._reverse_transcription)\n return DnaSequence._from_ndarray(self._sequence, rna_alphabet)", "def __invert__(self) -> Seq:\n return self.reverse_complement()", "def complement(self):\n\n rna_s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the complementary DNA sequence
def complementary_seq(self): if not self.data['DNAseq']: self.complement_seq_var.set(0) self.warning('No DNA sequence loaded','You have to load a DNA sequence first') return compl={'A':'T','T':'A','C':'G','G':'C'} comDNA='' for base in self.data['DNAse...
[ "def get_complementary_sequence(dna):\n\n comp_dna = ''\n \n for char in dna: \n comp_dna = comp_dna + get_complement(char)\n\n return comp_dna", "def get_complementary_sequence (seq):\n new_seq = ''\n for char in seq:\n compel = get_complement(char)\n new_seq = new...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }