query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
This method gets all fields mentioned in the statements.
def _get_fields_from_statements(self, statement): columns_fields = [] if statement is not None: columns_fields = list(set([x for col in statement for x in re.findall(Pheno2SQL.RE_COLUMN_NAME, col)])) return columns_fields
[ "def fields(self):\n return super(InsertCursor, self).fields", "def get_fields(self, table_name):\n return self.get_table_meta(table_name)['fields']", "def _get_fields(self):\n return self._fields", "def fields(self):\n return super(SearchCursor, self).fields", "def get_query_fie...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method returns a list of fields (either its column specification, like c64_0_0 or its rename like myfield) that are of type integer.
def _get_integer_fields(self, columns): int_columns = [] for col in columns: if col == 'eid': continue match = re.search(Pheno2SQL.RE_FULL_COLUMN_NAME_RENAME, col) if match is None: continue col_field = match.group('fiel...
[ "def _get_fields(self, table):\n fields = list()\n for column in table.columns:\n fields.append({'id': column.name, 'type': str(column.type)})\n return fields", "def dtypes(self):\n dtypes = []\n for field in self.fields.values():\n dtypes += len(field) * [...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DataSize is update with the lenght of head, payload and eop expected
def setDataSize(self, head,payload,eop): self.dataSize = len(head)+len(payload)+len(eop)
[ "def __payload_size(self):\n return (\n self.SIZE_LINEUP_ID + self.players_per_lineup * self.SIZE_PLAYER) * self.entries.count()", "def data_size(self, data_size):\n self._data_size = data_size", "def get_data_size(self):\n\n\tif self.data:\n\t return self.data.size\n\telif se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fechando a porta no sistema
def closeGate(self): print("tentando fechar a porta") self.com.disable() print('+--------------------------------+') print('| Porta fechada |') print('+--------------------------------+')
[ "def velocidade_porta(self): # Testar este metodo.\r\n porta, velocidade = args\r\n if \"usb\" in porta:\r\n if velocidade:\r\n ## Retorna \"0\" se executado com sucesso\r\n status = subprocess.call(\r\n \"stty -F /dev/ttyUSB0 speed {0}\".format(ve...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
receive message size is the width of the message type(size) = int return the message received
def receiveMessage(self,size): self.messageReceived = self.com.getData(size) print('+--------------------------------+') print('| Mensagem Recebida |') print('+--------------------------------+') print(self.messageReceived)
[ "def recv_size(s, size):\n print 'Receive data in fixed size mode'\n reply = s.recv(size)\n print reply", "def receive_message(self):\n\n msg_len_bytes = self.receive(struct.calcsize(\"<I\"))\n if not msg_len_bytes:\n return None\n\n msg_len, = struct.unpack(\"<I\", msg_le...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the information in /proc/cpuinfo as a dictionary in the following
def cpuinfo(): cpu_info = OrderedDict() procinfo = OrderedDict() nprocs = 0 with open('/proc/cpuinfo') as cpuinfo_file: for line in cpuinfo_file: if not line.strip(): # end of one processor cpu_info["proc{!s}".format(nprocs)] = procinfo ...
[ "def cpu_info():\n \n with open(Path.proc_cpuinfo()) as f:\n cpuinfo = {'processor_count': 0}\n for line in f:\n if ':' in line:\n fields = line.replace('\\t', '').strip().split(': ')\n # count processores and filter out core specific items\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks existence (runnability) of plymouth in the target system. True if plymouth exists in the target, False otherwise
def detect_plymouth(): # Used to only check existence of path /usr/bin/plymouth in target isPlymouth = target_env_call(["sh", "-c", "which plymouth"]) debug("which plymouth exit code: {!s}".format(isPlymouth)) return isPlymouth == 0
[ "def hasPokemon(self):\r\n return self.trainer.hasPokemon()", "def can_exist_outside_of_game(self):\n return True", "def check_game_finished(self):\r\n for player in self.players:\r\n if player.own_cards():\r\n return False\r\n return True", "def has_playe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calls routine with given parameters to modify '/etc/mkinitcpio.conf'.
def run(): partitions = libcalamares.globalstorage.value("partitions") root_mount_point = libcalamares.globalstorage.value("rootMountPoint") if not partitions: libcalamares.utils.warning("partitions is empty, {!s}".format(partitions)) return (_("Configuration Error"), _("No ...
[ "def finalize_configuration():\n sudo(\"/usr/share/mdadm/mkconf > /etc/mdadm/mdadm.conf\")\n sudo(\"update-initramfs -u\")", "def bootstrap():\n validate_configurator_version()\n\n # put new mkinitcpio.conf in place\n run(\"mv /etc/mkinitcpio.conf.pacnew /etc/mkinitcpio.conf\")\n sed(\"/etc/mkin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the mesh object lists is a list of [data.DisplayList, texture] objects holding the 3d rendering of the mesh pos must be a threepart tuple representing the position of the mesh rotation must be a threepart tuple representing the rotation of the mesh verts is a list of vertices in the mesh scale must be a number o...
def __init__(self, lists, pos=(0,0,0), rotation=(0,0,0), verts=[], scale=1, colorize=(1,1,1,1)): view.require_init() self.gl_lists = lists self.pos = pos self.rotation = rotation self.verts = verts self.scale = scale se...
[ "def create_mesh(self):\n print(\"create_mesh\")\n faces = self.get_faces()\n print(\"num faces: {}\".format(len(faces)))\n\n # TODO: perform face filtering to remove long edges in Z direction\n # filtered_faces = self.get_filtered_faces(faces)\n # print(\"num filtered face...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a copy of the mesh, sharing the same data.DisplayList
def copy(self): return BasicMesh(self.gl_lists, list(self.pos), list(self.rotation), list(self.verts), self.scale, list(self.colorize))
[ "def copy(self):\n newVertices = [v.copy() for v in self.vertices]\n return face(newVertices)", "def get_mesh(self):\n return self.mesh", "def mesh(self):\n return self._mesh", "def get_open3d_mesh(self):", "def new_mesh_set(self, all_meshes):\n if isinstance(all_meshes, M...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Render the mesh camera must be None if the camera the scene is using
def render(self, camera=None): glPushMatrix() x,y,z = self.pos glTranslatef(x,y,-z) a, b, c = self.rotation glRotatef(a, 1, 0, 0) glRotatef(b, 0, 1, 0) glRotatef(c, 0, 0, 1) try: glScalef(*self.scale) except: glSc...
[ "def render_scene( self, camera ):\r\n projection = camera.view_matrix.matrix\r\n model_view = camera.model_view\r\n\r\n # bind our diffuse texture\r\n glActiveTexture( GL_TEXTURE0 )\r\n self.texture.bind()\r\n\r\n # iterate through our renderables\r\n for node, fram...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resets the database to a healthy state by any means necessary. Tries to delete the file, or flush all tables, then runs the migrations from scratch. It now checks if the file exists. This will throw a PermissionError if the user has the DB open in another program.
def reset_db(name, fail_ok=True): print("Deleting", db_path(name)) close_old_connections() delete_failed = False if os.path.exists(db_path(name)): # your database is corrupted and must be destroyed connections[name].close() try: # or you could http://stackoverflow.com/a/2450...
[ "def reset_db(self):\n self.time.unfreeze()\n self.rollback()\n\n if not self._restore_state or not self.is_dirty():\n return\n\n new_snapshot = create_database_snapshot(self._conn)\n raise errors.DatabaseIsDirtyError.from_snapshots(self._restore_state,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
exports specified tasks to Things3 for Mac
def export2Things3(self, taskObjs): # append all task names to link, so Things3 knows # which tasks (more than one) to add for i in taskObjs: if taskObjs == None: print(col.FAIL + "Failed exporting to Things. Things3Helper didn't receive appropriate data." + col.ENDC) lin...
[ "def discover_tasks(app):\n\n task_arguments.add_argument(\n \"preload-defaults-from-site\",\n type=str,\n required=False,\n default=\"\",\n choices=preload_defaults_from_site_choices,\n help=\"Select site within environment to load defaults from, argument format is <env...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Open and read an Excel file
def open_file(path): book = xlrd.open_workbook(path) # print number of sheets #print book.nsheets # print sheet names #print book.sheet_names() # get the first worksheet first_sheet = book.sheet_by_index(0) # read a row #print first_sheet.row_values(0) # read a cell cell = fi...
[ "def open_file(path):\n book = xlrd.open_workbook(path)\n\n # print number of sheets\n print\n book.nsheets\n\n # print sheet names\n print\n book.sheet_names()\n\n # get the first worksheet\n first_sheet = book.sheet_by_index(0)\n\n # read a row\n print\n first_sheet.row_values(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decorator to check for masked arrays. Check that the first argument to a function is a masked array. If not, convert it into one.
def check_mask(f): def wrapper(*args, **kwargs): data = args[0] try: mask = data.mask except AttributeError: data = np.ma.array(data, mask=np.zeros(data.shape, dtype=np.bool)) mask = data.mask args = list(args) args[0] = data ...
[ "def _mask_array(mask, *args):\n invalid = ~mask # True if invalid\n args_masked = []\n for arg in args:\n if arg.size > 1 and arg.shape != invalid.shape:\n raise ValueError('Shape mismatch between mask and array.')\n arg_masked = arg.astype(np.float64)\n if arg.size == 1:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Apply SumThreshold method This function applies a set ofmoving averages to the data along both time and frequency axes, then checks if the output are above a threshold. This is the basic technique used in AOFlagger's algorithm.
def sum_threshold(data, plot_progress=False, verbose=False): thr_f = params.thr_f thr_t = params.thr_t scales = params.scales rho = params.rho mask = np.copy(data.mask) thr1_f = thr_f thr1_t = thr_t # do first stage of flagging: mask_f = np.greater_equal(np.abs(data-...
[ "def WAMP(self, windowed_data, threshold):\n \n # wamp=0 \n \n # for i in range(len(windowed_data)): \n # if abs(windowed_data[i]-windowed_data[i+1])>threshold:\n # wamp=wamp+1; \n fs = 200\n n = windowed_data.shape[0]\n\n wamp = n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Flag anything above or below absolute thresholds. First pass for horrific data.
def flag_absolute(data): data.mask = np.logical_or(data.mask, data > params.thr_max) data.mask = np.logical_or(data.mask, data < params.thr_min) return data.mask
[ "def hard_thresholding(data, level):\n return data * (np.abs(data) >= level)", "def apply_thresholding(x):\n return x > threshold_otsu(x)", "def is_alertworthy(self):\n return (not healthdb.util.isNaN(self.zscore)) and self.zscore < 0 and (\n healthdb.util.isNaN(self.percentile) or (self.per...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Alternate DTV flagger for spectrometer data. This function uses the constrastin power between the DTV band edges (outer 0.25 MHz) and the DTV band centers (inner 4.5 MHz) to identify DTV flares.
def do_dtv_flagging2(data, freqs): mask = data.mask*1 dtv_times = [] for ledge in (54, 60, 66, 76, 82): uedge = ledge + 6 band = np.where( (freqs>=ledge) & (freqs<=uedge) )[0] trns = np.where( (freqs>=ledge+0.25) & (freqs<=uedge-0.25) )[0] empt = np.where( ((freqs>...
[ "def fourier_analysis(self, tolerance, max_iter, t_laser_ON, t_max, dt, eval_energy=False):\n epsilon, C0, energy_per_step, delta_per_step = self.solve_TIHF(tolerance=tolerance, max_iter=max_iter, print_ON=False)\n C1, time1, overlap1, dipole1, energy1 = self.solve_TDHF(0, dt, t_laser_ON, C0, eval_ove...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
RFI Flagging routine for LEDA data
def rfi_flag(data, freqs=None): masks = Masks() # Record any nans masks.add("nan_mask", np.isnan(data)) if params.do_sum_threshold: try: to_flag except NameError: bpass = estimate_bandpass(data) to_flag = data / bpass to_fla...
[ "def ledFlashRapidly(ledPinNumber):", "def aspcapflag(aspcapfield) :\n\n parambitmask=bitmask.ParamBitMask()\n aspcapbitmask=bitmask.AspcapBitMask()\n\n gd=np.where((aspcapfield['ASPCAPFLAG'] & aspcapbitmask.getval('NO_ASPCAP_RESULT') ==0) &\n (aspcapfield['ASPCAPFLAG'] & aspcapbitmask.get...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an offspring obtained by applying crossover to the two given chromosomes, chrom1 and chrom2. If the crossover occurs at a random index i, then the offspring is created
def crossover(self, chrom1, chrom2): pass
[ "def _create_offspring(self):\n parents = self._select_parents()\n offspring = self._crossover(*parents)\n if (random.uniform(0, 1) < self.mutation_rate):\n self._mutate(offspring)\n return offspring", "def crossover(self, old_gen, Pc):\n new_gen = copy.deepcopy(old_g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the fitness value of the given chrom
def fitness_fn(self, chrom): pass
[ "def calculateFitness(self,chromosome):\n\t\tif self.fitness_external_data:\n\t\t\treturn self.fitness_func(chromosome, *(self.fitness_external_data))\n\t\telse:\n\t\t\treturn self.fitness_func(chromosome)", "def fitness_func(gene):\n vals = [84, 12, 55, 66, 68, 43]\n index = population.index(gene)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the version tuple as a string, e.g. for (0, 10, 7), return '0.10.7'.
def get_version(version_tuple): return ".".join(map(str, version_tuple))
[ "def _version_tuple_to_string(version):\n return \".\".join(list(map(str, version)))", "def get_version(version_tuple):\n return '.'.join(map(str, version_tuple))", "def get_version():\n return \".\".join(map(str, VERSION))", "def get_version():\r\n return '.'.join((str(each) for each in VERSION[:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if the currently stored steps are valid with respect to a given proximity class
def is_step_allowed(self, proximity_class, condition_on_grid=None): return proximity_class.is_step_allowed(self.arr_new_steps, self.pos_x, self.pos_y, self.pos_z, condition_on_grid=condition_on_grid)
[ "def check_step(step):\n assert isinstance(step, list), \"Step must be a list\"\n assert (len(step) == 3 or len(step) == 4), \\\n \"Step must be a list of length 3 or 4 (to include temporary values)\"\n assert isinstance(step[0], type), (\n \"The first element of the step ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the position of the selected agents using coordinates of the graph vertex the agent is currently on.
def set_position_based_on_graph(self, arr_selected_agent, use_radius=True, agent_position_attribute='position', graph_coord_x_attribute='coord_x', graph_coord_y_attribute='coord_y', graph_coord_z_attribute='coord...
[ "def set_new_location(self, xPos, yPos):", "def set_agent_loc(self, agent, r, c):\n assert (0 <= r < self.size[0]) and (0 <= c < self.size[1])\n i = agent.idx\n # If the agent is currently on the board...\n if self._agent_locs[i] is not None:\n curr_r, curr_c = self._agent_l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the directions of the selected agents in the direction of the north pole (coordinates X et Y are 0.). Agents located at the north or south pole have their initial direction set to (1., 0., 0.).
def set_direction_to_north(self, arr_selected_agents): arr_selected_agents = np.array(arr_selected_agents, dtype=bool) pos_x = np.array(self.df_population['coord_x'], dtype=np.float) pos_y = np.array(self.df_population['coord_y'], dtype=np.float) pos_z = np.array(self.df_population['coo...
[ "def set_direction_von_mises(self, arr_selected_agents, kappa):\n arr_selected_agents = np.array(arr_selected_agents, dtype=bool)\n\n pos_x = np.array(self.df_population['coord_x'], dtype=np.float)\n pos_y = np.array(self.df_population['coord_y'], dtype=np.float)\n pos_z = np.array(self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the direction of the selected agents by deviating their current direction by an angle given by von mises distribution.
def set_direction_von_mises(self, arr_selected_agents, kappa): arr_selected_agents = np.array(arr_selected_agents, dtype=bool) pos_x = np.array(self.df_population['coord_x'], dtype=np.float) pos_y = np.array(self.df_population['coord_y'], dtype=np.float) pos_z = np.array(self.df_populat...
[ "def set_direction_to_north(self, arr_selected_agents):\n arr_selected_agents = np.array(arr_selected_agents, dtype=bool)\n\n pos_x = np.array(self.df_population['coord_x'], dtype=np.float)\n pos_y = np.array(self.df_population['coord_y'], dtype=np.float)\n pos_z = np.array(self.df_popul...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Propose a new step for the selected agents, following their current direction with a step length given by a Gamma distribution.
def propose_step_gamma_law(self, arr_selected_agents, k, theta): gamma_sample = np.random.gamma(k, theta, size=(arr_selected_agents.sum(),)) arr_selected_agents = np.array(arr_selected_agents) pos_x = np.array(self.df_population['coord_x'], dtype=np.float) pos_y = np.array(self.df_popu...
[ "def GAStep(self):\n\n self.updateMatingPool()\n self.newGeneration()", "def propose_step(self, occupancy):\n return self._rng.choice(self._mcushers, p=self._p).propose_step(occupancy)", "def Step(self, settings):\n\n super(Grasshopper, self).Step(settings)\n\n if self.ship.an...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds the standard deviation of a list of column values Arguments
def column_stdev(column_values, mean): try: stdev = math.sqrt( sum([(mean-x)**2 for x in column_values]) / len(column_values)) except ZeroDivisionError: print("Column is empty, cannot perform calculation", file=sys.stderr) sys.exit(1) return stdev
[ "def stdev(headers, data):\n\tcolumn_matrix=data.get_data(headers)\n\tmean_values=column_matrix.std(0)\n\tstd_values=mean_values.tolist()\n\treturn std_values", "def std(list_val):\n return st.stdev(list_val)", "def stdev(inlist):\n return math.sqrt(var(inlist))", "def stdev(items):\n return Series.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes lagcrp for a given recall list
def lagcrp(rec, lstlen): def check_pair(a, b): if (a>0 and b>0) and (a!=b): return True else: return False def compute_actual(rec, lstlen): arr=pd.Series(data=np.zeros((lstlen)*2), index=list(range(-lstlen,0)...
[ "def _lags_num(self):\r\n \r\n r_new = np.zeros(10)\r\n # Step 1\r\n L = 1\r\n while True:\r\n\r\n # Step 2\r\n augmented = self.augmentation(L, self.data1.copy())\r\n\r\n # Step 3\r\n _, s_fault, _ = np.linalg.svd(augmented)\r\n\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a List of all args in settings.txt file
def init(): args = [] with open("settings.txt", "r") as reader: for line in reader: args.append(line) return args
[ "def extract_args(config_file):", "def get_args() -> DefaultArguments:\n from mscxyz import settings\n\n return getattr(settings, \"args\")", "def args(self):\n return self.args_parser.parse_args()", "def _list_settings(self, settings=None):\n if settings == None:\n settings = f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a single item without mix_results. Iterate through all data processors to prepare model inputs. The data processors are organized first by modalities and then by models.
def _load_item(self, idx): ret = dict() try: for group_id, per_processors_group in enumerate(self.processors): per_sample_features = get_per_sample_features( modality_features=getattr(self, f"modality_features_{group_id}"), modality_typ...
[ "def process_item(self, item):\n return item", "def process(cls, data):\n\n model_list = []\n\n # iterate over formatted data from API call\n for item in data:\n\n # instantiate model with one row of data\n model_object = cls(item)\n\n # iterate over mo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate global coordinate of mosaic image and local coordinate of cropped subimage.
def _mosaic_combine( self, loc: str, center_position_xy: Sequence[float], img_shape_wh: Sequence[int] ) -> Tuple[Tuple[int], Tuple[int]]: assert loc in ("top_left", "top_right", "bottom_left", "bottom_right") if loc == "top_left": # index0 to top left part of image x1...
[ "def _mosaic_combine(self, loc, center_position_xy, img_shape_wh):\n\n assert loc in ('top_left', 'top_right', 'bottom_left', 'bottom_right')\n if loc == 'top_left':\n # index0 to top left part of image\n x1, y1, x2, y2 = max(center_position_xy[0] - img_shape_wh[0], 0), \\\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructor for creating the custom column. Usage is the same as normal Column, however, a 'mapper_key' is required.
def __init__( self, *args, mapper_key: typing.Optional[str] = None, transform: typing.Optional[typing.Callable] = None, **kwargs, ): super(CustomColumn, self).__init__(*args, **kwargs) self.mapper_key = mapper_key self.transform = transform
[ "def col_mapper(self):\n return self._col_mapper", "def __init__(self, input_column, output_column):\n super().__init__([input_column], output_column)", "def __init__(self, input_column):\n \n super().__init__([input_column], \"{0}_hashcount\".format(input_column))", "def __init__(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test API on creating a bucketlist (POST Request)
def test_bucketlist_create(self): res = self.client().post('/bucketlist', data=self.bucketlist) self.assertEqual(res.status_code, 201) self.assertIn('Go to vacation', str(res.data))
[ "def test_create_bucketlist(self):\n bucketlist = {'title': 'Swimming'}\n response = self.client.post(\n '/bucketlists/', data=json.dumps(bucketlist), headers=self.get_header())\n self.assertEqual(response.status_code, 201)\n self.assertIn(\"Swimming - bucketlist has been adde...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test API to get all data in bucketlist (GET Request)
def test_api_get_all_bucketlists(self): res = self.client().post('/bucketlist', data=self.bucketlist) self.assertEqual(res.status_code, 201) res = self.client().get('/bucketlist') self.assertEqual(res.status_code, 200) self.assertIn('Go to vacation', str(res.data))
[ "def test_user_can_get_list_of_buckets(self):\n with self.client:\n response = self.client.get(\n '/bucketlists/',\n headers=dict(Authorization='Bearer ' + self.get_user_token())\n )\n data = json.loads(response.data.decode())\n self.a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test API to get bucketlist by id
def test_api_get_bucketlist_by_id(self): res_post = self.client().post('/bucketlist', data=self.bucketlist) self.assertEqual(res_post.status_code, 201) res_in_json = json.loads(res_post.data.decode('UTF-8').replace("'", "\"")) res = self.client().get(f"/bucketlist/{res_in_json['id']}") ...
[ "def test_bucket_by_id_is_returned_on_get_request(self):\n with self.client:\n token = self.get_user_token()\n # Create a Bucket\n response = self.client.post(\n '/bucketlists',\n data=json.dumps(dict(name='Travel')),\n headers=dic...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test API to get bucketlist by id when id does not exist
def test_api_get_bucketlist_by_id_not_exist(self): res = self.client().get(f"/bucketlist/99") self.assertEqual(res.status_code, 404)
[ "def test_no_bucket_returned_by_given_id(self):\n with self.client:\n token = self.get_user_token()\n\n response = self.client.get(\n '/bucketlists/1',\n headers=dict(Authorization='Bearer ' + token)\n )\n data = json.loads(response.da...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test API to edit bucketlist (PUT Request)
def test_api_edit_bucketlist(self): res_post = self.client().post('/bucketlist', data={'name': 'Wake up, Eat, Code, Sleep & Repeat'}) self.assertEqual(res_post.status_code, 201) res_post_in_json = json.loads(res_post.data.decode('UTF-8').replace("'", "\"")) id = res_post_in_json['id'] ...
[ "def test_edit_bucketlist(self):\n post_data = self.post_a_bucket()\n self.assertEqual(post_data.status_code, 201)\n result_of_put_method = self.client().put(\n '/bucketlists/1',\n headers=dict(Authorization='Bearer '\n + self.token()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test API to delete bucketlist (DELETE Request)
def test_api_delete_bucketlist(self): res_post = self.client().post('/bucketlist', data={'name': "Don't forget to exercise"}) self.assertEqual(res_post.status_code, 201) res_post_in_json = json.loads(res_post.data.decode('UTF-8')) id = res_post_in_json['id'] res_delete = self.cl...
[ "def test_delete_bucketlist(self):\n post_data = self.post_a_bucket()\n self.assertEqual(post_data.status_code, 201)\n result_of_delete_method = self.client().delete('/bucketlists/1',\n headers=dict(Authorization='Bearer '\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Piecewise Polynomial Coefficients for a PCHIP (Piecewise Cubic Hermite Interpolating Polynomial)
def pchip_coeffs(X, Y): # Suppress the divide by zero and invalid arguments warnings that appear # for the `numba.guvectorize`d function, though not for the `numba.njit`ed # function. The PCHIP algorithm is guaranteed to not divide by zero. # https://github.com/numba/numba/issues/4793#issuecomment-623...
[ "def polynomial_approximation_coefficients(f, dilatation_factor=50, polynomial_degree=25,\n bound=1, convertToTensor=True):\n p,_ = chebyshev_approximation(f, dilatation_factor, polynomial_degree, bound, convertToTensor)\n\n return Polynomial.cast(p).coef", "def poly...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Coefficients for a single PCHIP when the data may contain NaNs Inputs and outputs are as for `pchip_coeffs`, but `X` and `Y` both 1D arrays of length `n`, and so `Yppc` is a 2D array of size `(n, 4)`.
def pchip_coeffs_1(X, Y): # Find k = index to first valid data site, and # K such that K - 1 = index to last valid data site in contiguous range # of valid data after index k. k, K = valid_range_1_two(X, Y) return _pchip_coeffs_1(X, Y, k, K)
[ "def pchip_coeffs(X, Y):\n\n # Suppress the divide by zero and invalid arguments warnings that appear\n # for the `numba.guvectorize`d function, though not for the `numba.njit`ed\n # function. The PCHIP algorithm is guaranteed to not divide by zero.\n # https://github.com/numba/numba/issues/4793#issuec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
rotates a word from given index onwards
def rotate(s, index): # we'll have to split the list from index so that we can only rotate the charaters starting after index left = s[:index] right = s[index:] # shift each character to the left # "abcd" => "bcda" rotated = right[1:] #rotated.append(right[0]) rotated += right[0] # merged the rotated...
[ "def rotate_right(word, n):\n pass", "def rotate_word(s,i):\n new_string = ''\n for letter in s:\n new_string += chr(ord(letter)+i)\n return new_string", "def rotate(string, n):\n\n # removes characters from left if n positive and right if n negative\n # and put them into the oposite si...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove reserved keys from records.
def clean_record(self): _dict = { key: value for (key, value) in self.record.items() if not key in BAMBOO_RESERVED_KEYS } return remove_mongo_reserved_keys(_dict)
[ "def filter_keys(self, row, whitelist):\n for key, value in row.items():\n if not key in whitelist:\n del row[key]", "def remove_unnecessary_keys(self):\n arguments_to_remove = self.arguments_to_remove()\n for key in arguments_to_remove:\n print(F'Removing...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the first row matching `query` and `select` from MongoDB.
def find_one(cls, query, select=None, as_dict=False): record = cls.collection.find_one(query, select) return record if as_dict else cls(record)
[ "def find_one(self, collection, query):\n obj = getattr(self.db, collection)\n result = obj.find_one(query)\n return result", "def fetch_one(q, *params):\n db = Database()\n db.cur.execute(q, params)\n ret = db.cur.fetchone()\n db.con.close()\n return ret", "def test_select_o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Call unset with the spec `query` the unset document `unset_query`.
def unset(cls, query, unset_query): cls.collection.update(query, {"$unset": unset_query}, multi=True)
[ "def unset_queries(self, *args):\n for k in args:\n self._query_dict.pop(k, None)", "def _clean_query(self, query):\n for object_query in query:\n filters = object_query.get(\"filters\", {}).get(\"expression\")\n self._clean_filters(filters)\n self._macro_expand_object_query(ob...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Instantiate with data in `record`.
def __init__(self, record=None): self.record = record
[ "def __init__(self, record):\n self.record = record", "def Create(cls, connection, record):\n raise NotImplementedError", "def _from_db_record(cls, record):\n kwargs = {\n 'id': record.id,\n 'name': record.name,\n 'user': record.user,\n 'project': rec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perist the state of the current instance to `STATE_PENDING`
def pending(self): self.update({self.STATE: self.STATE_PENDING})
[ "def pending(self):\n self.state = Step.State.PENDING", "def pending(self, pending):\n\n self._pending = pending", "def is_pending(self):\n return self.type_id == STATE_PENDING", "def update_active(self):\n self.state = WAITING", "def pending(self):\n return self._pending"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perist the state of the current instance to `STATE_READY`
def ready(self): self.update({self.STATE: self.STATE_READY})
[ "def _ready(cls):\n sync_call(cls.ready)", "def update_ready(self):\n self._ready = self.ready", "def handle_ready(self):\r\n self._is_ready.set()", "def mark_ready(self):\n self.ready = True\n self._update_last()", "def set_ready(self):\n if self.game.has_started()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save `record` in this model's collection. Save the record in the model instance's collection and set the internal record of this instance to the passed in record.
def save(self, record): self.collection.insert(record) self.record = record return self
[ "def save_record(self,record:ArxivRecord) -> None:\n self._save_record(record)", "def update(self, record):\n record = dict_for_mongo(record)\n id_dict = {'_id': self.record['_id']}\n self.collection.update(id_dict, {'$set': record})\n\n # Set record to the latest record from th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the current instance with `record`. Update the current model instance based on its `_id`, set it to the passed in `record`.
def update(self, record): record = dict_for_mongo(record) id_dict = {'_id': self.record['_id']} self.collection.update(id_dict, {'$set': record}) # Set record to the latest record from the database self.record = self.__class__.collection.find_one(id_dict)
[ "def save(self, record):\n self.collection.insert(record)\n self.record = record\n\n return self", "def update(self,record,**kw):\r\n # update indices\r\n _id = record[\"__id__\"]\r\n for indx in self.indices.keys():\r\n if indx in kw.keys():\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enviem informacio d'error amb l'hora
def print_if_error(cadena): print(time.strftime("%H:%M:%S ERROR => ") + cadena)
[ "def msjError(self, mensaje):\n print \"[\" + strftime(\"%H:%M:%S\") + \"] ERROR: \" + mensaje\n exit(0)", "def estimacionError(this,tolerancia=1,clase='energia',avance=100,puntosGauss=1000,analitica=None,danalitica=None,tipo='he'):\n if tipo =='he':\n if not analitica == None and ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Al rebre un ALIVE_INF, busca l'equip i mira si esta REGISTERED o ALIVE i si esta tot correcte per enviar ALIVE_ACK
def control_manteniment_comunicacio(data, sock, address, equips, dades_serv): for equip in equips: if equip['nom'].__eq__(data[1:6]) and equip['mac'].__eq__(data[8:20]) and equip['estat'].__eq__('DISCONNECTED'): enviar_alive_rej(sock, address, 'Equip no registrat al sistema.') elif equip...
[ "def testExpiredVisaTender(self):\n self.setupTransaction()\n checkout.pay_card(card_name='Expired_Visa', verify=False)\n eMsg = checkout.read_message_box(timeout=10)\n if (eMsg):\n checkout.click_message_box_key(\"OK\")\n if \"Expired\" not in eMsg:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mira si el client esta registrat, tupla format per Boolean i el nom de l'equip ('' en cas negatiu)
def es_client_registrat(data_tcp, equips): for equip in equips: if equip['nom'].__eq__(data_tcp[1:6]) and equip['mac'].__eq__(data_tcp[8:20]): return True, equip['nom'] return False, ''
[ "def info(int,user):\n\tj=IsRegister(user)\n\tif j[0] == True:\n\t\tif int == 1:\n\t\t\ti=arrays.DB_user[j[1]][4]\n\t\t\tif i[1] == \"connected\":\n\t\t\t\treturn [True,\"connected\"]\n\t\t\telse:\n\t\t\t\treturn [False,\"disconnected\"]\n\t\tif int == 2:\n\t\t\treturn arrays.DB_user[j[1]][1]\n\t\tif int == 3:\n\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Crea paquets amb pdu de TCP buits del tipus i amb les dades que vulguem
def create_empty_pack_tcp(type, data): camps = ['', '', '', ''] llargada_camps = (7, 13, 7, 50) index_camps = 0 for llargada in llargada_camps: camps[index_camps] = camps[index_camps].zfill(llargada) index_camps += 1 return struct.pack('c7s13s7s150s', chr(type), '', '', '', data)
[ "def _tcp_reassemble(self, number, src_addr, dst_addr, tcp):\n \n pld = tcp.message[tcp.header_len : tcp.header_len + tcp.segement_len]\n src_socket = (src_addr, tcp.src_port)\n dst_socket = (dst_addr, tcp.dst_port)\n sockets = (src_socket, dst_socket)\n\n def debug_c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Envia el paquet SEND_REJ
def enviar_send_rej(sock): pack = create_empty_pack_tcp(0x23, 'Dades de l\'equip incorrectes') print_if_debug(DEBUG, 'Enviat ' + to_str_dades_udp(pack)) sock.send(pack)
[ "def enviar_mensaje(self, mensaje):\n\t\tself.CONEXION.send(mensaje.encode())", "def sendBuffer():\n dislin.sendbf()", "def _enviar_comando(self, comando, leer_respuesta=True):\n cmd_len = len(comando)\n cmd_len_bytes = cmd_len / 2\n if cmd_len % 2 != 0:\n raise TAGError('Long...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Envia el GET_NACK amb el motiu
def enviar_get_nack(sock): pack = create_empty_pack_tcp(0x32, 'Dades addicionals de l\'equip incorrectes') print_if_debug(DEBUG, 'Enviat ' + to_str_dades_udp(pack)) sock.send(pack)
[ "def handle_nak(self):", "def test_fetch_nack(self):\n self.ICNRepo.start_repo()\n content = self.fetch.fetch_data(Name(\"/test/data/f4\"))\n self.assertEqual(content, \"Received Nack: \" + NackReason.NO_CONTENT.value)", "def get_offline_msg(self):\n self.get(\"GetOfflineMessages\",'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mira si existeix nom_equip.cfg, en cas afirmatiu envia l'ack, en cas negatiu envia rej
def enviar_get_ack(dades, sock, nom_equip, aleatori): try: open(nom_equip + '.cfg', 'r') data = struct.pack('c7s13s7s150s', chr(0x31), dades['Nom'], dades['MAC'], aleatori, nom_equip + '.cfg') print_if_debug(DEBUG, 'Enviat ' + to_str_dades_udp(data)) sock.send(data) return no...
[ "def _check_config(self):", "def save_equip():\n my_file_config = DnDConfig()\n equip_file = my_file_config.equip_file()\n\n equipEntry = equipmentBox.get(\"1.0\", 'end-1c')\n\n with open(equip_file, \"r+\") as write_equip_file:\n write_equip_file.truncate()\n write_equip_file.write(equi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sample n unique transitions from this replay buffer.
def sample(self, n): raise NotImplementedError
[ "def sample_transition_batch(self):\n return next(self._replay)", "def make_transition_probs(self):\n n = len(self.speakers) # TODO why this line ???\n transitions = np.random.randint(5, size=(n, n)) + 1\n transitions += transitions.transpose()\n for i in range(0, math.floor(n / 2)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sample n unique (sub)episodes from this replay buffer.
def sample_episodes(self, n_episodes, max_len=None): raise NotImplementedError
[ "def sample(self, n):\n raise NotImplementedError", "def sample(self, n):\n idx = np.random.randint(0, len(self.memory), size=n)\n return [self.memory[i] for i in idx]", "def sample_without_replacement(self, n=100):\n np.random.shuffle(self.logs)\n output = []\n for i i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests task timeout exceeded.
def test_timeout(self, mocker, mock_timedelta): tid = 289466 site = "mysite" exception_response = self.generate_task_dictionary( tid, state="started", completed=None ) responses = [{"json": exception_response}] url = ( "https://cloudapi.acquia.c...
[ "def test_timeout(self, fake_time):\n fake_task = MagicMock()\n fake_task.info.completeTime = None\n fake_task.info.error = None\n fake_task.info.result = 'woot'\n\n with self.assertRaises(RuntimeError):\n task_lib.consume_task(fake_task, timeout=2)", "def test_task_t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
call fn n times with args in n is an int; if n is float, repeat up to n seconds; return min, avg, and max times
def timedcalls(n, fn, *args): if isinstance(n, int): times = [timedcall(fn, *args)[0] for _ in xrange(n)] elif isinstance(n, float): timer, times = 0.0, [] while timer < n: times.append(timedcall(fn, *args)[0]) timer += times[-1] return min(times), average(t...
[ "def time_it(function, arg_gen, n, graph = False):\n times = []\n for i in range(n):\n args = arg_gen()\n t0 = clock()\n function(args)\n delta = clock() - t0\n times.append(delta)\n if graph:\n x, y, mean = [], [], times[0]\n for i in range(n-1):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the initialization of Commands plugin.
def test_commands_initialization(bot): plugin = Commands(bot) assert isinstance(plugin, Commands) assert plugin.bot == bot
[ "def test_commands(self):\n pass", "def test_arg_parser_init(self):\n args = self.parser.parse_args(['init'])\n self.assertEqual(args.command, 'init')", "def test_plugin_initialize(self):\n p = PluginCustom()\n self.assertEqual('youpie', p.toto)", "def commands_init(bot: Bot...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the horoscope command.
def test_horoscope(mock_session_get, sign, expected, bot): data = {'horoscope': expected} request = asynctest.Mock(json=asynctest.CoroutineMock(side_effect=[data])) mock_session_get.return_value.__aenter__.return_value = request mask = IrcString('nickname!@192.168.0.100') channel = IrcString('#melec...
[ "def test_cli_query_command(no_auth):\n # Not Implemented yet\n assert True", "def test_commands(self):\n pass", "def test_cli_fix():\n assert Cli is Cl", "def testTableExistsAndUsedBySearchHelp(self):\n self.assertTrue(os.path.exists(cli_tree.CliTreePath()))\n # Make basic assertion tha...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the greeting command.
def test_greeting(bot): mask = IrcString('nickname!@192.168.0.100') channel = IrcString('#meleca') args = { '<nick>': 'nickname', '<message>': 'Hello there.' } data = { 'channel': channel.replace('#', ''), 'nick': args.get('<nick>'), 'options': '\n'.join(['Hey...
[ "def test_greeting(self):\r\n self.assertEqual(greet_by_name('Dani'), 'Hello, Mark!')", "def test_greeting(self):\n self.assertEqual(self.test_npc.greet(), f\"{self.test_npc_name.title()}: Hi!, my name is {self.test_npc_name.title()}!\")", "def greeting():\n print('hello world')", "def test_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the greeting command when error occur.
def test_greeting_raising_exception(bot): bot.dataset['greetings'].upsert.side_effect = ValueError() mask = IrcString('nickname!@192.168.0.100') channel = IrcString('#meleca') args = { '<nick>': 'nickname', '<message>': 'Hello there.' } plugin = Commands(bot) async def test(...
[ "def test_greeting(bot):\n mask = IrcString('nickname!@192.168.0.100')\n channel = IrcString('#meleca')\n args = {\n '<nick>': 'nickname',\n '<message>': 'Hello there.'\n }\n data = {\n 'channel': channel.replace('#', ''),\n 'nick': args.get('<nick>'),\n 'options': ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the joke command.
def test_joke(mock_session_get, subject, joke, expected, bot): request = asynctest.Mock(json=asynctest.CoroutineMock(side_effect=[joke])) mock_session_get.return_value.__aenter__.return_value = request mask = IrcString('nickname!@192.168.0.100') channel = IrcString('#meleca') args = {'<subject>': su...
[ "def main(args=None):\n click.echo()\n click.echo(get_a_random_joke())\n click.echo()\n\n return 0", "async def joke(message):\n return random.choice(jokes)", "def get_joke(name):", "def main():\n joke_util = JokeUtility()\n for i in xrange(7):\n print \"{}. \".format(i + 1) + joke...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the cebolate command.
def test_cebolate(bot): mask = IrcString('nickname!@192.168.0.100') channel = IrcString('#meleca') args = {'<message>': ['CORRECT', 'answer']} plugin = Commands(bot) async def test(): response = await plugin.cebolate(mask, channel, args) assert response == 'COLLECT answel' async...
[ "def test(contracts):\n test_command(contracts)", "def testCasCommand(self):\n self.assertEqual(None, self.msTest.getCASCommand(\"abc123\"),\n \"\\\"abc123\\\" was not a valid computer algebra system in the list, but\\\nour machine settings instance returned it as one.\")\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Added a file logger to the root
def add_file_handler_to_root(file_name): formatter = logging.Formatter('%(asctime)-15s:' + logging.BASIC_FORMAT) file_handler = logging.FileHandler(file_name) file_handler.setFormatter(formatter) root_logger = logging.getLogger() root_logger.addHandler(file_handler)
[ "def setup_fileLogger(self):\n try:\n self._filelogger = logging.getLogger('chatlogfile')\n handler = TimedRotatingFileHandler(self._file_name, when=self._file_rotation_rate, encoding=\"UTF-8\")\n handler.setFormatter(logging.Formatter('%(asctime)s\\t%(message)s', '%y-%m-%d %...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test instantiation of base metadata object
def test_base_metadata(self): base_meta = BaseMetadata(api_client=self.IDS_SYS_CLIENT) self.assertIsNotNone(base_meta) self.assertEqual(base_meta._api_client, self.IDS_SYS_CLIENT)
[ "def test_meta_data_is_not_inherited(self):", "def test_meta_base_metadata_param(self):\n name = 'idsvc.basemeta'\n meta = { 'name': name }\n base_meta = BaseMetadata(api_client=self.IDS_SYS_CLIENT, meta=meta)\n # base_meta.meta will return null values that we did not specifiy\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test value parameter to base metadata constructor
def test_value_base_metadata_param(self): value = { 'color': 'blue' } base_meta = BaseMetadata(api_client=self.IDS_SYS_CLIENT, value=value) self.assertEqual(base_meta.value, value)
[ "def __init__(self, value, should_prepare=True, prepare_with=None):\r\n self.value = value\r\n self.should_prepare = should_prepare\r\n self.prepare_with = prepare_with", "def __init__(self, value):\n\n self.value = value", "def __init__(self, type, value):\n self.type = type\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test meta parameter to base metadata constructor
def test_meta_base_metadata_param(self): name = 'idsvc.basemeta' meta = { 'name': name } base_meta = BaseMetadata(api_client=self.IDS_SYS_CLIENT, meta=meta) # base_meta.meta will return null values that we did not specifiy # so we need to test if meta is a subset of base_meta.met...
[ "def test_meta_class_init_arg(self):\n k = MyKlass()\n self.assertEqual(MyMeta_Init_Arg['cls'], MyKlass)\n self.assertEqual(MyMeta_Init_Arg['name'], 'MyKlass')\n self.assertEqual(MyMeta_Init_Arg['bases'], (object,))\n self.assertTrue('foo' in MyMeta_Init_Arg['dct'].keys())\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test name attribute in base metadata object
def test_name_attribute_in_base_metadata(self): name = 'idsvc.basemeta' meta = { 'name': name } base_meta = BaseMetadata(api_client=self.IDS_SYS_CLIENT, meta=meta) self.assertEqual(base_meta.name, meta['name'])
[ "def test_name_attr(self):\n n = Place()\n self.assertTrue(hasattr(n, \"name\"))\n self.assertEqual(n.name, \"\")", "def test_attribute_name(self):\n m1 = State()\n self.assertTrue(hasattr(m1, \"name\"))\n self.assertEqual(m1.name, \"\")", "def test_name(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reusable method for saving a base metadata object
def save_base_metadata(self): value = { 'color': 'blue' } meta = { 'value': value } base_meta = BaseMetadata(api_client=self.IDS_SYS_CLIENT, meta=meta) base_meta.save() self.assertIsNotNone(base_meta.uuid) self.assertTrue(all([item in base_meta.meta.items() for item in me...
[ "def test_save_base_metadata(self):\n\n self.save_base_metadata()\n\n # cleanup\n\n self.delete_base_metadata()", "def save_info(base):\r\n _info = open(base.info_name,'wb')\r\n fields = []\r\n for k in base.field_names:\r\n if isinstance(base.fields[k],base.__class__):\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test saving a base metadata object
def test_save_base_metadata(self): self.save_base_metadata() # cleanup self.delete_base_metadata()
[ "def test_edit_base_metadata(self):\n\n # start out by creating some metadata\n\n base_meta_object_a = self.save_base_metadata()\n\n # load the same metadata object again from agave\n\n base_meta_object_b = BaseMetadata(api_client=self.IDS_SYS_CLIENT, uuid=base_meta_object_a.uuid)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test saving with value but without 'meta'
def test_save_with_value_no_meta(self): value = { 'color': 'blue' } base_meta = BaseMetadata(api_client=self.IDS_SYS_CLIENT, value=value) base_meta.save() self.assertIsNotNone(base_meta.uuid) self.assertTrue(all(item in base_meta.value.items() for item in value.items())) ...
[ "def save_without_setting_canon(self, *args, **kwargs):\n super(DocumentSetFieldEntry, self).save(*args, **kwargs)", "def test_save(self, mock_storage):\n instance = BaseModel()\n old_value_created = instance.created_at\n old_value_update = instance.updated_at\n instance.save()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test editing a base metadata object
def test_edit_base_metadata(self): # start out by creating some metadata base_meta_object_a = self.save_base_metadata() # load the same metadata object again from agave base_meta_object_b = BaseMetadata(api_client=self.IDS_SYS_CLIENT, uuid=base_meta_object_a.uuid) base_meta_o...
[ "def test_modify_metadata(self):\n pass", "def test_update_metadata(self):\n pass", "def test_update_metadata1(self):\n pass", "def test_update_metadata_by_attribute(self):\n pass", "def test_metadata(self):\n self.assertEquals(self.testObject.metadata, {})", "def test_p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete all metadata with name = 'idsvc.basemeta'
def delete_base_metadata(self): # get a list of basemetadata objects response = BaseMetadata.list(self.IDS_SYS_CLIENT) # we will delete any and all metadata with name = 'idsvc.basemeta' for mo in response: mo.delete() # check delete, list metadata with name = 'id...
[ "def test_delete_base_metadata(self):\n\n # start out by creating some metadata\n\n self.save_base_metadata()\n\n # delete all metadata with name = 'idsvc.basemeta'\n\n self.delete_base_metadata()", "def test_delete_metadata(self):\n pass", "def delete_metadata(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test deleting a base metadata object
def test_delete_base_metadata(self): # start out by creating some metadata self.save_base_metadata() # delete all metadata with name = 'idsvc.basemeta' self.delete_base_metadata()
[ "def test_delete_metadata(self):\n pass", "def test_data_object_del(self):\n pass", "def delete_base_metadata(self):\n\n # get a list of basemetadata objects\n\n response = BaseMetadata.list(self.IDS_SYS_CLIENT)\n\n # we will delete any and all metadata with name = 'idsvc.base...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a few metadata objects with associations, and test to see that model returns appropriate associations between objects
def test_associations(self): oj = {} if self.DEBUG: print "Create A" # create a a = self.save_base_metadata() oj[a.uuid] = 'A' if self.DEBUG: print "Create B, point B to A" # create b, point b to a b = self.save_base_metadata(...
[ "def test_instance(self):\n self.assertEqual(True, type(self.Test.defined_associations['things']) is pyperry.association.HasMany)", "def test_defined_associations(self):\n self.assertEqual(True, len(self.Test.defined_associations) > 0)", "def test_instance(self):\n self.assertEqual(True, ty...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Main entry point. Waits until the protocol should start and then runs the Hydrand protocol. returns True if the protocol was succesfully executed for NUM_ROUNDS
def run(self): self.logger.info(f"THIS IS NODE: {self.ID}") self.logger.info("starting node") self.startup() self.logger.info("startup completed") while not self.shutdown_requested and self.round < NUM_ROUNDS: self._run_round() self.shutdown() self.l...
[ "def main():\n print(\"Welcome to the Cryptography Suite!\")\n run_suite()\n while should_continue():\n run_suite()\n print(\"Goodbye!\")", "def main():\n print(\"Welcome to the Cryptography Suite!\")\n run_suite()\n while should_continue():\n run_suite()\n print(\"Goodbye!\")...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wrapper for _run_round, used for single stepping execution in tests only.
def run_round(self): self._running = True self._run_round() self._running = False
[ "def simulate(self):\n self.round += 1", "def next_round(self):\n pass", "def run(self, step: str = None) -> None:\n return super().run(step=step)", "def run():\n step = 0\n while traci.simulation.getMinExpectedNumber() > 0:\n traci.simulationStep()\n step+=1\n trac...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
helper function rn(Dx) to recursively compute the set of recovered nodes from the view of a dataset
def _recovered_nodes(self, x: int): if x == 0: return set() Dx = self.datasets[x] assert Dx is not None xprev = Dx.prev_round_idx if xprev == x - 1: # no recovery certificates return self._recovered_nodes(xprev) return self._recovered_n...
[ "def descendants(G, x):\n return set(nx.dfs_preorder_nodes(G, x)) - {x}", "def _dfs(self, node, feed_dict):\n if node.parent is None:\n # We are in a leaf\n if not node in feed_dict:\n raise RuntimeError(\"Some source op don't have provided values !\")\n \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Trys to process the next message from the message queue. All past message at the beginning of the queue are skipped. If the next message is for some future round and phase, it is not processed and this call returns False. Otherwise, the next message is removed from the queue and processed, True is returned.
def process_message(self): while True: if not self.next_message: return False # check if next message is in the past, and drop it if (self.next_message.round, self.next_message.phase) < (self.round, self.phase): (self.logger.debug if self.is_l...
[ "def next_message(self):\n while self.queue.consuming:\n yield self.queue.channel._consume_message()", "def process(self, next_byte) -> bool:\r\n\r\n # Received Message Structures:\r\n # '#B25500' + payload bytes + '\\r\\n'\r\n # '#U00' + payload bytes + '\\r\\n'\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Processes a receive propose message from some node. The outer message signature has already been verified, but the other signatures and all messageinternal checks are performed in this function. This includes the check if the sender is actually leader of the current round.
def process_propose(self, msg: ProposeMessage): dataset = msg.dataset if self.verify_revealed_secret(dataset.revealed_secret): self.revealed_secrets[self.round] = dataset.revealed_secret self.compute_beacon(msg.dataset.revealed_secret) else: self.flag_adversa...
[ "def process_message(self):\n while True:\n if not self.next_message:\n return False\n\n # check if next message is in the past, and drop it\n if (self.next_message.round, self.next_message.phase) < (self.round, self.phase):\n (self.logger.debug ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks the validity of an incomming message prior to deserialization. Raises a ValueError if any of the checks fail.
def verify_raw_message(self, msg: bytes): if not (MIN_MESSAGE_SIZE < len(msg) < MAX_MESSAGE_SIZE): raise ValueError("Invalid message size!") msg_type = get_message_type(msg) # yields a ValueError on invalid type msg_sender = get_message_sender(msg) # yields a ValueError if sender ...
[ "def validate(self):\n if self.data.Header.PacketType != type(self).TYPE:\n raise BadPeer(\"bad packet type: \", self.data.Header.PacketType)\n #TODO: test data 0xdeadbeef should be changed to other value to pass this validation\n #if self.data.Time > 0x7fffffff:\n # raise ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if the given revealed secret can successfully be verified against the value the leader previously committed itself to. The check also fails if the leader previously did not send the ProposeMessage to this node.
def verify_revealed_secret(self, revealed_secret: Scalar): r = self.prev_round_with_same_leader if r: dataset = self.datasets[r] if dataset: proof = dataset.proof else: proof = NODE_INFOS[self.leader].initial_proof return proof is not ...
[ "def verify_secret(secret: str, known_hash: bytes, known_salt: bytes) -> bool:\n unknown_bytes = secret.encode(SECRET_ENCODING)\n unknown_hash = hash_secret_raw(unknown_bytes, known_salt, **CRYPTO_PARAMS)\n\n return unknown_hash == known_hash", "def check_secret(self, client_secret):\n encrypted =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the current virtual time as continously increasing float. Before protocol start this value is negative. At the start of the 1st round this value is 1.0. At the middle of round 5 this value is ~5.5. At the end of round 5 this value is 5.99.
def virtual_time(self): return (_time.time() - PROTOCOL_START_TIME) / ROUND_DURATION
[ "def virtual_round(self):\n return math.ceil(self.virtual_time())", "def __float__(self):\n return self.sec + self.nsec / 10.0e9", "def getTimeToNextFrameDraw(self):\r\n try:\r\n rt = (self._next_frame_sec - 1.0/self._retracerate) - self._video_track_clock.getTime()\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the most recent round number in which the current leader was previously leader.
def prev_round_with_same_leader(self): for r in range(self.round - 1, 0, -1): if self.leaders[r] == self.leader: return r return None
[ "def get_current_round(self) -> int:\n return self.get_game_history().current_turn", "def latest(self):\n return self.scores[-1:][0]", "def latest(self):\n return self.scores[-1]", "def get_current_turn(self):\n return self.turns.latest('number')", "def get_latest(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Increments the internal round number and phase. Must be called at to start a new round, including the protocol start itself (round 0 > round 1). Also updates the internal times for round starts and ends to compute timeouts correctly. Extends rounds based lists by one None element.
def advance_round(self): self._round += 1 self._phase = Phase.Propose self._t_round_start += ROUND_DURATION self._t_round_end = self._t_round_start + ROUND_DURATION self._t_ack_phase_start = self._t_round_start + PROPOSE_PHASE_DURATION self._t_vote_phase_start = self._t_a...
[ "def _increment_round_number():\n store.round += 1", "def start_new_round(self):\n try:\n if self.round_counter >= 3*len(self.players):\n self.end_game()\n elif self.player_draw_ind == -1:\n self.end_game()\n else:\n self.roun...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If a new phase is specified, the current phase is updated to match the given phase. Otherwise, the phase is updated to the next phase if the current timeout was exceeded. Return True if the phase was changed and False otherwise.
def update_phase(self, new_phase: Optional[Phase] = None): if new_phase is None: if self._phase != Phase.Vote and self.next_timeout() == 0: self._phase = Phase(self._phase + 1) self.logger.info(f"PHASE CHANGED, now in: round=%d, phase=%s", self.round, self.phase) ...
[ "def _check_phase(self):\n age: datetime.timedelta = utcnow() - self._start\n\n # Uses integer division to calculate the expected phase. We start in\n # Phase 0, so until [_phase_length] seconds have passed, this will\n # not resolve to 1.\n expected_phase: int = age.seconds // se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the round number the node is operating in according to the current virtual time. As long as the syncroncy assumption is fulfilled, virtual_round <= round is ensured.
def virtual_round(self): return math.ceil(self.virtual_time())
[ "def get_round() -> int:\n return store.round", "def round_num(self) -> int:\n return self._round_num", "def getRound(self):\n\n status = self.getStatus()\n return status['round']", "def get_current_round(self) -> int:\n return self.get_game_history().current_turn", "def next_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the number of (fractional) seconds to wait until a change to the next protocol phase should happen. Typically used in the main message receive loop, to ensure progress when no messages are received. Returns at most config.MAX_TIMEOUT to allow for proper termination (keep alive tick).
def next_timeout(self): if self.phase == Phase.Propose: timeout = max(self._t_ack_phase_start - self.actual_time(), 0) elif self.phase == Phase.Acknowledge: timeout = max(self._t_vote_phase_start - self.actual_time(), 0) else: timeout = max(self._t_round_end -...
[ "def _probe_wait_time(self):\n r = self.probe_cycle_time / float(len(self.servers)) #self.probe_cycle_time=5\n r = max(.25, r) # Cap it at four per second\n return r", "def getReadyCheckTimeout(self):\n return self.ready_timeout / 1000", "def timeOut(self):\n return (sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize publisher socket to broadcast messages to all other nodes.
def connect(self): assert self.listening assert not self.connected ctx = zmq.Context.instance() port = NODE_INFOS[self.ID].port self._send_socket = ctx.socket(zmq.PUB) self._send_socket.bind(f"tcp://*:{port}") self.connected = True
[ "def init_socket(self):\n self.context = zmq.Context.instance()\n self.socket = self.context.socket(zmq.SUB)\n\n self.socket.setsockopt(zmq.SUBSCRIBE, self.topic.encode(\"utf-8\"))\n self.socket.connect(self.sub_url)", "def initialize(self):\n logger.info('Websockets Sender init...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the next message from the message queue without removing it.
def next_message(self) -> Optional[MessageQueueItem]: if self._message_queue: return self._message_queue[0] return None
[ "def get_next_message(self, timeout=None):\n try:\n return self._message_queue.get(timeout=timeout)\n except Queue.Empty:\n return None", "def pop_next_message(self):\n messages = self._msq_queue.receive_messages(\n AttributeNames=['All'],\n Message...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the next message from the message queue and removes it from the queue.
def dequeue_message(self) -> MessageQueueItem: return heapq.heappop(self._message_queue)
[ "def pop_message(self, tag):\n if self.new_messages_number(tag):\n return heapq.heappop(self._message_queue[tag])[-1]\n raise threadprop.NoMessageThreadError(\"no messages with tag '{}'\".format(tag))", "def dequeue_msg(self):\n dst, key = self.mqueue.popleft()\n dst.receive_msg(key...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes the next message from the message queue.
def drop_message(self): heapq.heappop(self._message_queue)
[ "def dequeue_msg(self):\n dst, key = self.mqueue.popleft()\n dst.receive_msg(key)", "def remove_message(self, msg):\n with self.message_lock:\n if msg not in self.messages:\n raise ValueError(f'{msg.msg_type} was not found in '\n 'the list of ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wait for a new incomming message or a timeout, whichever comes first. If a message is received, preprocessing checks (i.e. msg size, type, ...) are performed. If a message is considered valid it is added to the message queue and True is returned. If a timeout occurres False is returned. If any of the message preprocess...
def receive_message(self, timeout: Optional[float] = None) -> bool: self.logger.debug("waiting for incomming message (timeout=%f seconds)", timeout) message_bytes = self.receive_bytes(timeout) if not message_bytes: self.logger.debug("message receive timeout") return False...
[ "def wait_for_message(\n self, message_predicate=lambda m: True, seconds_to_wait=5\n ):\n start_time = time.time()\n poll_time = seconds_to_wait / 100\n while True:\n try:\n message = self._message_q.get...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot GAIM climate and assim VTEC versus JASON using at least two 'gc' files. First file is usually climate file, and rest are assim files.
def plotVtecAndJasonTracks(gtcFiles, outFile=None, names=None, makeFigure=True, show=False, **options): ensureItems(options, {'title': 'GAIM vs. JASON for '+gtcFiles[0], \ 'xlabel': 'Geographic Latitude (deg)', 'ylabel': 'VTEC (TECU)'}) if 'show' in options: show = True ...
[ "def fig_1(geo_file,os_file,mob_temporal_file,save_dir):\r\n ### Load Data\r\n # Get Geographic Data\r\n gdf1 = gpd.read_file(geo_file)\r\n gdf2 = gpd.read_file(os_file)\r\n norm = colors.Normalize(vmin=gdf1['Mobility P'].min(), vmax=gdf1['Mobility P'].max())\r\n cbar = plt.cm.ScalarMappable(norm=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CASSANDRA9748 CASSANDRA8084 Test that it's possible to connect over the broadcast_address when listen_on_broadcast_address=true and that GossipingPropertyFileSnitch reconnect via listen_address when prefer_local=true
def test_prefer_local_reconnect_on_listen_address(self): NODE1_LISTEN_ADDRESS = '127.0.0.1' NODE1_BROADCAST_ADDRESS = '127.0.0.3' NODE2_LISTEN_ADDRESS = '127.0.0.2' NODE2_BROADCAST_ADDRESS = '127.0.0.4' STORAGE_PORT = 7000 cluster = self.cluster cluster.popula...
[ "def test_broadcast(self):\n if _debug: TestSimple._debug(\"test_broadcast\")\n\n # create a network\n tnet = TNetwork()\n\n # make a PDU from node 1 to node 2\n pdu_data = xtob('dead.beef')\n pdu = PDU(pdu_data, source=tnet.td.address, destination=LocalBroadcast())\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function returns the residual amount on a receivable or payable account.move.line. By default, it returns an amount in the currency of this journal entry (maybe different of the company currency), but if you pass 'residual_in_company_currency' = True in the context then the returned amount will be in company curre...
def _amount_residual(self, cr, uid, ids, field_names, args, context=None): res = {} if context is None: context = {} cur_obj = self.pool.get('res.currency') for move_line in self.browse(cr, uid, ids, context=context): res[move_line.id] = { 'amount_...
[ "def _l10_mx_edi_prepare_advance_refund_fields(self):\n self.ensure_one()\n adv_amount = 0.0\n partial_amount = 0.0\n reverse_lines = self.env['account.move.line']\n partial_line = reverse_lines\n domain = self._l10n_mx_edi_get_advance_aml_domain()\n related_advs = s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }