query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Test case for networking_project_network_list
def test_networking_project_network_list(self): pass
[ "def test_networking_project_netadp_list(self):\n pass", "def test_networking_project_network_service_list(self):\n pass", "def test_networking_project_network_get(self):\n pass", "def test_networking_project_network_event_list(self):\n pass", "def test_networking_project_network...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for networking_project_network_service_get
def test_networking_project_network_service_get(self): pass
[ "def test_networking_project_network_get(self):\n pass", "def test_networking_project_netadp_service_get(self):\n pass", "def test_networking_project_network_service_list(self):\n pass", "def test_networking_project_netadp_get(self):\n pass", "def test_networking_project_network_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for networking_project_network_service_list
def test_networking_project_network_service_list(self): pass
[ "def test_networking_project_netadp_service_list(self):\n pass", "def test_networking_project_network_list(self):\n pass", "def test_networking_project_network_service_get(self):\n pass", "def test_networking_project_netadp_list(self):\n pass", "def test_networking_project_networ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for networking_project_network_tag_create
def test_networking_project_network_tag_create(self): pass
[ "def test_networking_project_netadp_tag_create(self):\n pass", "def test_networking_project_network_tag_put(self):\n pass", "def test_networking_project_network_tag_get(self):\n pass", "def test_networking_project_network_create(self):\n pass", "def test_networking_project_networ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for networking_project_network_tag_delete
def test_networking_project_network_tag_delete(self): pass
[ "def test_networking_project_netadp_tag_delete(self):\n pass", "def test_networking_project_network_delete(self):\n pass", "def test_iam_project_tag_delete(self):\n pass", "def test_networking_project_netadp_delete(self):\n pass", "def test_delete_network(self):\n pass", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for networking_project_network_tag_get
def test_networking_project_network_tag_get(self): pass
[ "def test_networking_project_netadp_tag_get(self):\n pass", "def test_networking_project_network_tag_list(self):\n pass", "def test_networking_project_network_tag_create(self):\n pass", "def test_networking_project_network_get(self):\n pass", "def test_networking_project_network_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for networking_project_network_tag_list
def test_networking_project_network_tag_list(self): pass
[ "def test_networking_project_netadp_tag_list(self):\n pass", "def test_networking_project_network_tag_get(self):\n pass", "def test_networking_project_network_list(self):\n pass", "def test_networking_project_network_tag_create(self):\n pass", "def test_networking_project_netadp_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for networking_project_network_tag_put
def test_networking_project_network_tag_put(self): pass
[ "def test_networking_project_netadp_tag_put(self):\n pass", "def test_networking_project_network_tag_create(self):\n pass", "def test_networking_project_network_tag_get(self):\n pass", "def test_networking_project_network_tag_delete(self):\n pass", "def test_iam_project_tag_put(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for networking_project_network_update
def test_networking_project_network_update(self): pass
[ "def test_networking_project_netadp_update(self):\n pass", "def test_networking_project_network_get(self):\n pass", "def test_networking_project_network_create(self):\n pass", "def test_networking_project_network_list(self):\n pass", "def test_networking_project_network_tag_put(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate that required_cols are in self.frame
def validate(self): super().validate() frame = getattr(self, 'frame', None) if frame is None: raise ValueError('Missing columns %s since no frame' % ', '.join( self.required_cols)) cols = set(list(self.frame)) missing = sorted(self.required_cols - cols...
[ "def cols_valid(self,\n df: pd.DataFrame,\n req_cols: set) -> bool:\n missing_cols = req_cols.difference(df.columns)\n\n if len(missing_cols) > 0:\n logging.error(f\"{missing_cols} columns required but missing\")\n return False\n\n return Tru...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
read calibration file returns > dict calibration matrices as 44 numpy arrays
def read_calib_file(filename): calib = {} """calib1 = np.eye(4,4) calib1[0:3, 3] = [0.27, 0.0, -0.08] print(calib1) calib.append(calib1) calib2 = np.eye(4,4) calib2[0:3, 3] = [0.27, -0.51, -0.08] print(calib2) calib.append(calib2) calib3 = np.eye(4,4) calib3[0:3, 3] = [0.27...
[ "def parse_calibration(filename):\n calib = {}\n\n calib_file = open(filename)\n for line in calib_file:\n key, content = line.strip().split(\":\")\n values = [float(v) for v in content.strip().split()]\n\n pose = np.zeros((4, 4))\n pose[0, 0:4] = values[0:4]\n pose[1, 0:4] = values[4:8]\n pose...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse the model description string to a keras model builder.
def _parse_model(model: str, num_classes: int) -> Callable[[], tf.keras.Model]: if model == 'cnn': keras_model_builder = functools.partial( create_conv_dropout_model, num_classes=num_classes) elif model in ['resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152']: keras_model_builder = functool...
[ "def parse_biomodel(model_string):\n return ParsedBioModel.whole_input_grammar.parseString(model_string)[0]", "def parse_model(model_string):\n return ParsedModel.whole_input_grammar.parseString(model_string)[0]", "def to_model(description, start_rule=None):\n parse_tree = parse(description, start_rule...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load (unsplitted) EMNIST(like) clientdata from sql database.
def load_custom_emnist_client_data(sql_database: str) -> ClientData: if sql_database is None: raise ValueError('sql_database cannot be None.') return sql_client_data_utils.load_parsed_sql_client_data( sql_database, element_spec=_ELEMENT_SPEC)
[ "def load_custom_cifar_client_data(sql_database: str) -> ClientData:\n\n if sql_database is None:\n raise ValueError('sql_database cannot be None.')\n\n return sql_client_data_utils.load_parsed_sql_client_data(\n sql_database, element_spec=_ELEMENT_SPEC)", "def pull_data_from_db():\n base_data_url = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a preprocessing function for EMNIST client datasets.
def _create_preprocess_fn( num_epochs: int, batch_size: int, merge_case: bool, shuffle_buffer_size: int = emnist_dataset.MAX_CLIENT_DATASET_SIZE, use_cache: bool = True, use_prefetch: bool = True, ) -> Callable[[tf.data.Dataset], tf.data.Dataset]: @tf.function def merge_mapping(elem): or...
[ "def get_preprocess_fn(**preprocessing_kwargs):\n\n def _preprocess_fn(data):\n \"\"\"The preprocessing function that is returned.\"\"\"\n\n # Validate input\n if not isinstance(data, dict) or 'image' not in data:\n raise ValueError('Argument `data` must be a dictionary, '\n 'no...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Configuring federated runner spec.
def build_federated_runner_spec(self) -> training_specs.RunnerSpecFederated: task_spec = self._task_spec train_preprocess_fn = _create_preprocess_fn( num_epochs=task_spec.client_epochs_per_round, batch_size=task_spec.client_batch_size, merge_case=self._merge_case, use_cache=Tru...
[ "def build_federated_runner_spec(self) -> training_specs.RunnerSpecFederated:\n task_spec = self._task_spec\n\n train_preprocess_fn = _create_preprocess_fn(\n num_epochs=task_spec.client_epochs_per_round,\n batch_size=task_spec.client_batch_size,\n use_cache=True,\n use_prefetch=Tr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Configures federated training for the EMNIST character recognition task. This method will load and preprocess datasets and construct a model used for the task. It then uses `iterative_process_builder` to create an iterative process compatible with `tff.simulation.run_training_process`.
def configure_training_federated( task_spec: training_specs.TaskSpecFederated, *, # Caller passes below args by name. model: str = 'resnet18', only_digits: bool = False, merge_case: bool = False, ) -> training_specs.RunnerSpecFederated: return _EmnistCharacterTask( task_spec, model=mo...
[ "def train(training_environment):\n # Block until all host DNS lookups succeed. Relies on retrying dns_lookup.\n logger.info('Block until all host DNS lookups succeed.')\n for host in training_environment.hosts:\n _dns_lookup(host)\n\n _set_nccl_environment(training_environment.network_interface_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Configures centralized training for the EMNIST character recognition task.
def configure_training_centralized( task_spec: training_specs.TaskSpecCentralized, *, # Caller passes below args by name. model: str = 'resnet18', only_digits: bool = False, merge_case: bool = False, ) -> training_specs.RunnerSpecCentralized: return _EmnistCharacterTask( task_spec, mo...
[ "def set_training_parameters(\n self,\n config: ConfigDict,\n len_train: int,\n len_test: int,\n ):\n self.configure_steps(config, len_train, len_test)\n self.configure_reporting(config)\n self.configure_training_functions(config)", "def setup_train(self, deep_m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fit model that predicts return of credit
def fit_model(): global _HOME_OWNERSHIP _HOME_OWNERSHIP = {x: i for i, x in enumerate(["rent", "own", "mortgage", "other"])} df = pd.read_csv(os.path.join(settings.BASE_DIR, "LoanStats3a.csv"), skiprows=1).head(5000) df = df[df.apply(is_poor_coverage, axis=1)] df['year_issued'] = df.issue_d.apply(la...
[ "def fit_model(input_file):\n # read the data in and fit it. the values below are placeholder values\n data = np.genfromtxt(input_file, skip_header=1)\n X = data[:,:5] # feature columns \n y = data[:,5] # target label column (price)\n c = np.linalg.lstsq(X, y, rcond=None)[0] # least squares method\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Random rhythm and notes based on time
def randMelody(self, value, chord): self.randRhythm() self.randNotes(value, chord)
[ "def create_rand_notes(level, tempo_time):\n rand_note_dist = get_prop_level(level)\n\n # Get all possible notes for the level, and the PDF of probabilites for them to appear.\n sum = 0.0\n ids = []\n distribution = []\n for id, prob in rand_note_dist.items():\n ids.append(id)\n dist...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate random rhythm, based on chord It must have rhythm before
def randNotes(self, value, chord): aChord = mgChord(value, chord) self.data = [] for i in range(len(self.rhythm)): note = random.choice(aChord).copy() note.setDuration(self.rhythm[i]) self.data.append(note)
[ "def randMelody(self, value, chord):\n self.randRhythm()\n self.randNotes(value, chord)", "def get_rdm_note(chord, last_note):\r\n \r\n if random.randint(1,10) <= 6:\r\n # chord note\r\n return random.choice(CHORDS[chord]) \r\n else:\r\n # scale note \r\n n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the duration remain, within this bar list, values of rhythm int
def durationRemain(self, l=None): if l is None: l = self.rhythm full = float(self.time.upper)/self.time.lower s = 0 for i in range(len(l)): s += 1.0 / l[i] return full - s
[ "def get_dur(self):\n return [char.get_dur() for char in self.string]", "def getDuration(self):\n if self.getDot():\n return self.duration*1.5\n else:\n return self.duration", "def speaking_duration_with_pauses(self):\r\n objects = self.__get_objects()\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute MD5 hash of the data_path (dir or file) for data versioning.
def hash_data(data_path: Union[str, Path], chunk_size: int = 65536) -> str: if Path(data_path).is_dir(): hash = _hash_dir(data_path, chunk_size) elif Path(data_path).is_file(): hash = _hash_file(data_path, chunk_size) else: raise ValueError(f"{data_path} is neither directory nor file...
[ "def _md5sum(self, data):\n data = str(data)\n\n if os.path.isfile(data):\n try: \n f = open(data, 'rb')\n except:\n return 'ERROR: unable to open %s' % data\n temp1 = ''\n while True:\n d = f.read(8192)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a normalized complex data. If the data is a numpy data with complex, returns the absolute value. Else returns the input data.
def _normalizeComplex(data): if hasattr(data, "dtype"): isComplex = numpy.issubdtype(data.dtype, numpy.complexfloating) else: isComplex = isinstance(data, numbers.Complex) if isComplex: data = numpy.absolute(data) return data
[ "def complex_abs(data):\n assert data.size(-1) == 2\n return (data ** 2).sum(dim=-1).sqrt()", "def __complex__(self):\n return complex(self.__data)", "def complex_abs_sq(data):\n assert data.size(-1) == 2\n return (data ** 2).sum(dim=-1)", "def abs(data):\n return _make.abs(data)", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called when the widget of the view was created
def viewWidgetCreated(self, view, plot): return
[ "def create_widgets(self):", "def on_show_view(self):\n self.setup()", "def init_widget(self):\n raise NotImplementedError", "def widgetClicked(self):\n pass", "def init_widget(self):\n super(UiKitTextView, self).init_widget()\n self.init_text()", "def HandleViewCreated(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the data viewer hooks used by this view.
def getHooks(self): return self.__hooks
[ "def hooks(self):\n return tuple(self.__hooks.keys())", "def base_hooks(self):\n return self._base_hooks", "def get_doc_hooks():\n\tif not hasattr(local, \"doc_events_hooks\"):\n\t\thooks = get_hooks(\"doc_events\", {})\n\t\tout = {}\n\t\tfor key, value in hooks.items():\n\t\t\tif isinstance(key, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a default colormap.
def defaultColormap(self): colormap = None if self.__hooks is not None: colormap = self.__hooks.getColormap(self) if colormap is None: colormap = Colormap(name="viridis") return colormap
[ "def make_default():\n mpl.rcParams['image.cmap'] = 'maier'", "def load_default(cls):\n config = ShuffledHLSColormapConfig.builder().set(num_colors=36).build()\n return ShuffledHLSColormap(config)", "def default_cmap( self, range, **traits ):\n\n vrange = ( -256, 256 )\n\n _data =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a default color dialog.
def defaultColorDialog(self): dialog = None if self.__hooks is not None: dialog = self.__hooks.getColormapDialog(self) if dialog is None: dialog = ColormapDialog() dialog.setModal(False) return dialog
[ "def colorPickerDialog(self, current_color=None):\n\t\tcolor_dialog = QtWidgets.QColorDialog()\n\t\t#color_dialog.setOption(QtWidgets.QColorDialog.DontUseNativeDialog)\n\n\t\t# Set current colour\n\t\tif current_color is not None:\n\t\t\tcolor_dialog.setCurrentColor(current_color)\n\n\t\t# Only return a color if va...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the mode id
def modeId(self): return self.__modeId
[ "def _get_modeid(self):\n return self.__modeid", "def get_mode(self):\n return self.mode", "def __mode_modesetid(self, mode):\n\t\tfor key,val in self.ms_all.iteritems():\n\t\t\tix = val.index(mode)\n\t\t\tif ix is not None:\n\t\t\t\treturn key, ix", "def _mode_key(guild_id: int) -> str:\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the value of a custom axis
def setCustomAxisValue(self, name, value): pass
[ "def value_axis(self, value_axis):\n\n self.container['value_axis'] = value_axis", "def setAxis(self, *__args): # real signature unknown; restored from __doc__ with multiple overloads\n pass", "def setAxis(self,ax):\r\n self.axis = ax", "def setAxisValue(self, axis, value):\n if se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if the widget is already initialized.
def isWidgetInitialized(self): return self.__widget is not None
[ "def is_initialized(self):\n try:\n self.check_initialized()\n return True\n except Error:\n return False", "def initialized(cls):\n return hasattr(cls, \"_instance\") and cls._instance is not None", "def initialized_(self) -> bool:\n return hasattr(self, \"model_\")", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Format an iterable of slice objects
def __formatSlices(self, indices): if indices is None: return '' def formatSlice(slice_): start, stop, step = slice_.start, slice_.stop, slice_.step string = ('' if start is None else str(start)) + ':' if stop is not None: string += str(st...
[ "def pixelize_slice(item, wcs, _source='cube'):\n if isinstance(item, tuple):\n result = list(range(len(item)))\n for axis in range(len(item)):\n if isinstance(item[axis], slice):\n result[axis] = _convert_slice(item[axis], wcs,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build title from given selection information.
def titleForSelection(self, selection): if selection is None or selection.filename is None: return None else: directory, filename = os.path.split(selection.filename) try: slicing = self.__formatSlices(selection.slice) except Exception: ...
[ "def updateTitle(self):\n \n if len(self.selParams) == 0:\n self.title = 'Measure (Nothing)'\n elif len(self.selParams) == 1:\n self.title = 'Measure ' + self.selParams[0]\n elif len(self.selParams) == 2:\n self.title = 'Measure ' + self.selParams[0] + ',...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the data selection displayed by the view If called, it have to be called directly after `setData`.
def setDataSelection(self, selection): pass
[ "def update_view(self, selected):\n pass", "def selection_set(self, first, last=None):\n self.tk.call(self._w, 'selection', 'set', first, last)", "def showDataset(self):\n self.createDatasetWidget(self.currentIndex())", "def setData(self, data: DataDictBase) -> None:\n self.data = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns names of the expected axes of the view, according to the input data. A none value will disable the default axes selectior.
def axesNames(self, data, info): return []
[ "def axesnames(self):\n return self._axesnames", "def allAxes( mv ):\n if mv is None: return None\n return mv.getAxisList()", "def _getaxes(self):\n try:\n return [getattr(self.nxgroup,name) for name in _readaxes(self.axes)]\n except KeyError:\n return None", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the views that can be returned by `getMatchingViews`.
def getReachableViews(self): return [self]
[ "def getMatchingViews(self, data, info):\n raise NotImplementedError()", "def get_views(self):\n return self.get_info()['views']", "def getViews(self):\n return list(self.__views)", "def views(self):\n return self._views", "def getReachableViews(self):\n raise NotImplement...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the priority of using this view according to a data. `UNSUPPORTED` means this view can't display this data `1` means this view can display the data `100` means this view should be used for this data `1000` max value used by the views provided by silx ...
def getDataPriority(self, data, info): return DataView.UNSUPPORTED
[ "def __getBestView(self, data, info):\n if not self.isSupportedData(data, info):\n return None\n views = [(v.getCachedDataPriority(data, info), v) for v in self.__views.keys()]\n views = filter(lambda t: t[0] > DataView.UNSUPPORTED, views)\n views = sorted(views, key=lambda t:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns all views that can be reachable at on point. This method return any sub view provided (recursivly).
def getReachableViews(self): raise NotImplementedError()
[ "def getReachableViews(self):\n return [self]", "def get_views(self):\n return self.get_info()['views']", "def views(self):\n return self._views", "def getViews(self):\n return list(self.__views)", "def child_views(self):\n return self.children", "def getViews(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns sub views matching this data and info. This method return any sub view provided (recursivly).
def getMatchingViews(self, data, info): raise NotImplementedError()
[ "def subviews(self):\n return {}", "def child_views(self):\n return self.children", "def GetViews(pattern='.*'):\n return GetSubpictures(None, pattern)", "def _views(is_refresh: bool, current_path: str, session: ObjectExplorerSession, match_params: dict) -> List[NodeInfo]:\n is_system = is...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a new dataview to the available list.
def addView(self, dataView): hooks = self.getHooks() if hooks is not None: dataView.setHooks(hooks) self.__views[dataView] = None
[ "def addView(self, dataView):\n hooks = self.getHooks()\n if hooks is not None:\n dataView.setHooks(hooks)\n self.__views.append(dataView)", "def add_view(self, view):\n params = {\"view_id\": view.id, \"view_name\": view.name}\n change = SKETCH_CHANGE(\"STORY_ADD\", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the list of registered views
def getViews(self): return list(self.__views.keys())
[ "def getViews(self):\n return list(self.__views)", "def views(self):\n return self._views", "def get_views(self):\n return self.get_info()['views']", "def get_views(self):\n return self._get_types_from_default_ns(View)", "def list_views(self, cls):\n if isinstance(cls, str...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the best view according to priorities.
def __getBestView(self, data, info): if not self.isSupportedData(data, info): return None views = [(v.getCachedDataPriority(data, info), v) for v in self.__views.keys()] views = filter(lambda t: t[0] > DataView.UNSUPPORTED, views) views = sorted(views, key=lambda t: t[0], rev...
[ "def get_best_known_model(self) -> Tuple[Optional[Path], int]:\n return self._get_first_model(sort='total_score', desc=False)", "def get_best_solution(self):\n if not self.tours:\n raise Exception('No solution has been computed yet')\n scores = {s:get_cost(self.tours[s],self) for s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replace a data view with a custom view. Return True in case of success, False in case of failure.
def replaceView(self, modeId, newView): oldView = None for view in self.__views: if view.modeId() == modeId: oldView = view break elif isinstance(view, _CompositeDataView): # recurse hooks = self.getHooks() ...
[ "def replaceView(self, modeId, newView):\n oldView = None\n for iview, view in enumerate(self.__views):\n if view.modeId() == modeId:\n oldView = view\n break\n elif isinstance(view, CompositeDataView):\n # recurse\n hoo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a new dataview to the available list.
def addView(self, dataView): hooks = self.getHooks() if hooks is not None: dataView.setHooks(hooks) self.__views.append(dataView)
[ "def addView(self, dataView):\n hooks = self.getHooks()\n if hooks is not None:\n dataView.setHooks(hooks)\n self.__views[dataView] = None", "def add_view(self, view):\n params = {\"view_id\": view.id, \"view_name\": view.name}\n change = SKETCH_CHANGE(\"STORY_ADD\", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the list of registered views
def getViews(self): return list(self.__views)
[ "def getViews(self):\n return list(self.__views.keys())", "def views(self):\n return self._views", "def get_views(self):\n return self.get_info()['views']", "def get_views(self):\n return self._get_types_from_default_ns(View)", "def list_views(self, cls):\n if isinstance(c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replace a data view with a custom view. Return True in case of success, False in case of failure.
def replaceView(self, modeId, newView): oldView = None for iview, view in enumerate(self.__views): if view.modeId() == modeId: oldView = view break elif isinstance(view, CompositeDataView): # recurse hooks = self.get...
[ "def replaceView(self, modeId, newView):\n oldView = None\n for view in self.__views:\n if view.modeId() == modeId:\n oldView = view\n break\n elif isinstance(view, _CompositeDataView):\n # recurse\n hooks = self.getHook...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update used colormap according to nxdata's SILX_style
def _updateColormap(self, nxdata): cmap_norm = nxdata.plot_style.signal_scale_type if cmap_norm is not None: self.defaultColormap().setNormalization( 'log' if cmap_norm == 'log' else 'linear')
[ "def color(self, sids=None, sat=1):\n if sids == None: # init/overwrite self.colors\n nids = self.nids\n # uint8, single unit nids are 1-based:\n self.colors = CLUSTERCLRSRGB[nids % len(CLUSTERCLRSRGB) - 1] * sat\n # overwrite unclustered/multiunit points with GREY...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a new LogImg object to the logger.
def add_log_img(self, log_img_type): self.log_img_map[log_img_type] = LogImg(self.log_path, log_img_type)
[ "def log_image(self, name, step, img):\n self._experiment.send_image(name, step, img)", "def add_image(self, im):\n self.flist.append(im)\n self.n = len(self.flist)", "def log_image(self, image, name, epoch):\n wandb.log({name: [wandb.Image(image, caption=name)]}, step=epoch)", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get an existing log img object reference
def get_log_img_obj(self, log_img_type): if log_img_type in self.log_img_map: return self.log_img_map[log_img_type] else: msg = "error: log_img_type '{}' does not exist in the Logger object.\n".format(log_img_type) msg += "There are currently {} objects saved in the L...
[ "def getImage(cam):\n\n return cam.getImage()", "def get_image(self):\n return self.image", "def get_image(self, record) -> Images:\r\n\r\n raise Exception()", "def _get_image(image):\n return c.IMAGES.get(image,image)", "def _get_image_obj(self):\n images = self.conn.list_images(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check the validity of an AFM number (Greek VAT code). Check if input is a valid AFM number via its check digit (not if it is actually used). Return either True of False. Input should be given as a string. An integer, under certain conditions, could through an exception.
def check_afm(afm): if not isinstance(afm, str): raise TypeError( "check_afm()", "You should feed to this function only strings to avoid exceptions and errors! Aborting." ) if len(afm) == 11 and afm[:2].upper() == "EL": afm=afm[2:] if afm.isdigit() == True and len(afm) == 9: i, sums = 256, 0 fo...
[ "def CheckNumber(userInput):\n try:\n float(userInput)\n return True\n except(ValueError):\n return False", "def verify_amount(amount):\n if amount.isdigit():\n return True\n return False", "def check_one_digit():\n if tokenize_user_input[1].isdigit:\n return Tr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method trains the clustering network from scratch if there is no pretrained autoencoder, else it will load the existing pretrained autoencoder to retrieve the latent representation of the images to train the final clustering layer in the convolutional neural network.
def train(args): dataset = args.dataset ae_mode = args.mode train_input, train_labels = load_data(dataset, mode=ae_mode) num_clusters = len(np.unique(train_labels)) data_initialization = dataset_parameters[dataset]['data_initialization'] with_attention = args.attention interval_updation = da...
[ "def train(self):\n best_eval = 0\n\n try:\n for epoch in range(self.resume_epoch, self.args.epochs):\n self.epoch = epoch\n\n # Clustering\n if self.clustering and \\\n ((epoch % self.epochs_clustering == 0) or (self.args....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Picks the first connection based on the best three connections possible.
def pick_first_connection(self): self.best_connection = [] stations = list(self.grid.stations.values()) # add a first station to the track for station in stations: self.track = Track(f"greedy_track_{self.count}", self.grid) self.track.add_station(self.grid, sta...
[ "def choose_serial_connection(potential_connections):\n for connection in potential_connections:\n if os.path.exists(connection):\n return connection\n return None", "def get_connection(user1, user2):\n if user1.is_coach and user2.is_coachee:\n connection = Connection.objects.fil...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Picks the next station based on the three connections that produce the best score.
def pick_next_station(self, station): self.best_score = 0 stations = self.grid.stations # all connections of the last added added station lookahead_1 = self.grid.get_station(self.best_connection[1]).connections for la1 in lookahead_1.values(): next_station = la1[0]...
[ "def pick_first_connection(self):\n self.best_connection = []\n stations = list(self.grid.stations.values())\n\n # add a first station to the track \n for station in stations:\n self.track = Track(f\"greedy_track_{self.count}\", self.grid)\n self.track.add_station(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Predicts the sound class (0 > Kick, 1 > Snare) for a single sound using an XGBoost model
def predictSoundClass(sound, boostModel, sampleRate=44100, nCoeffs=32): sound = util.normalize(sound) mfcc = extractFeatures(sound, sampleRate, nCoeffs) mfcc = mfcc.reshape(1, len(mfcc)) dTest = xgb.DMatrix(mfcc) return boostModel.predict(dTest)
[ "def predictWithXgboost(self):\n #import xgboost as xgb\n #bst = xgb.Booster()\n #bst.load_model(self.modelsParam[\"model\"])\n pass", "def main_predict(config, x):\n\n # load the wav file\n # init model\n # run prediction", "def predict(x):\n\n scores = np.zeros(shape=(l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a amenity with id as amenity_id
def get_amenity(amenity_id): try: amenity = Amenity.get(Amenity.id == amenity_id) except Exception: return {'code': 404, 'msg': 'Amenity not found'}, 404 return amenity.to_dict(), 200
[ "def amenities_id(amenity_id):\n obj = storage.get('Amenity', amenity_id)\n if obj is None:\n abort(404)\n return jsonify(obj.to_dict())", "def amenity_by_id(amenity_id):\n\n fetched_obj = storage.get(\"Amenity\", str(amenity_id))\n\n if fetched_obj is None:\n abort(404)\n\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete amenity with id as amenity_id
def delete_amenity(amenity_id): try: amenity = Amenity.get(Amenity.id == amenity_id) except Exception: return {'code': 404, 'msg': 'Amenity not found'}, 404 amenity = Amenity.delete().where(Amenity.id == amenity_id) amenity.execute() res = {} res['code'] = 201 res['msg'] = "A...
[ "def amenitydelete(amenity_id):\n amenobj = storage.get(Amenity, amenity_id)\n if amenobj is None:\n abort(404)\n storage.delete(amenobj)\n storage.save()\n return (jsonify({}), 200)", "def delete_amenity(amenity_id=None):\n objects = storage.get('Amenity', amenity_id)\n if objects is ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete amenities with id as amenity_id and place with id as place_id
def delete_place_amenities(place_id, amenity_id): try: delete = PlaceAmenities.delete().where( PlaceAmenities.amenity == amenity_id, PlaceAmenities.place == place_id ) delete.execute() res = {} res['code'] = 200 res['msg'] = 'Amenity deleted su...
[ "def delete_amenity_to_a_place(place_id, amenity_id):\n place_obj = storage.get(Place, place_id)\n amenity_obj = storage.get(Amenity, amenity_id)\n if place_obj and amenity_obj:\n if amenity_obj in place_obj.amenities:\n place_obj.amenities.remove(amenity_obj)\n storage.save()\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a rate to convert the metric data to new unit, as below. value in old unit / rate = value in new unit
def get_conversion_rate(self, old_unit, new_unit): for i in [old_unit, new_unit]: if i not in self.units: raise Exception("Can't find unit %s in unitgroup '%s'" % (i, self.name)) return float(self.units[new_unit]) / float(self.units[old_unit])
[ "def _set_rate(self):\r\n interval = self.data.iloc[2, 0] - self.data.iloc[1, 0]\r\n self.rate = int(1 / interval)", "def conversion_rate(self, init, new_currency):\r\n\r\n curr = CurrencyRates()\r\n curr_conv_rate = curr.get_rate(init, new_currency)\r\n return curr_conv_rate", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the fields of a host data record in a list.
def get_host_data_fields(self): raise NotImplementedError
[ "def arcpy_get_field_objects(self):\r\n\t\tif __thou_shalt__.do_a_dry_run:\r\n\t\t\treturn []\r\n\t\treturn thou_shalt(\"Fetch field information from {}\".format(self.shortened_name_with_context()),\r\n\t\t\tlambda:arcpy.ListFields(str(self))\r\n\t\t)", "def getAllHostFields(self):\n if self.login(): \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the fields of a VM data record in a list.
def get_vm_data_fields(self): raise NotImplementedError
[ "def arcpy_get_field_objects(self):\r\n\t\tif __thou_shalt__.do_a_dry_run:\r\n\t\t\treturn []\r\n\t\treturn thou_shalt(\"Fetch field information from {}\".format(self.shortened_name_with_context()),\r\n\t\t\tlambda:arcpy.ListFields(str(self))\r\n\t\t)", "def get_record_fields():\n\tfields = ['RecordType', 'Record...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return data time information in a tuple.
def get_time_info(self): raise NotImplementedError
[ "def _get_timeTuple(self):\n return self.hour, self.minute, self.second", "def CopyToStatTimeTuple(self):\n if self._number_of_seconds is None:\n return None, None\n\n return self._number_of_seconds, self.milliseconds * 10000", "def get_data(self):\n return self.__times, self.__values",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return host output files in a tuple.
def get_host_outfiles(self): raise NotImplementedError
[ "def get_output_files(self):\n return self.__output_files", "def list_output_files(self):\r\n fname = self.__get_output_filename()\r\n return [fname] if fname else []", "def output_files(self):\n outs = [os.path.join(self.address.repo, self.address.path, x)\n for x in ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return VM output files in a tuple.
def get_vm_outfiles(self): raise NotImplementedError
[ "def list_output_files(self):\r\n fname = self.__get_output_filename()\r\n return [fname] if fname else []", "def output_files(self):\n outs = [os.path.join(self.address.repo, self.address.path, x)\n for x in self.params['outs']]\n return outs", "def get_output_files(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize a CSVFile object with a directory. The directory is CBTOOL experiment result directory generated by monextract command. It contains a few CSV files. Among those files, one contains host OS metric data, and another VM OS metric data.
def __init__(self, expdir): self.expdir = expdir self.expid = basename(expdir) self.host_csvfile = "%s/%s_%s.csv" % (expdir, self.HOST_FILE_PREFIX, self.expid) self.host_data = {} self.host_data_fields = [] self.host_outfiles...
[ "def __init__(self, target_dir='.'):\n super(CSVWriter, self).__init__()\n self.target_dir = os.path.abspath(os.path.expanduser(target_dir))\n self._files = {}\n self.csv = {}", "def __openAndInitCSVFile(self, modelInfo):\n # Get the base path and figure out the path of the report f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Implement DataSource.get_hosts() method. The returned host names are sorted in alphabetic order.
def get_hosts(self): return sorted(self.host_data.keys())
[ "def get_hosts(self):\n result = self._call_zabbix_method(\n method='host.get',\n params={'output': 'extend'}\n )\n\n return result", "def host_names(self):\n resp = self._cmd(uri = '/jenkins_hosts')\n names = []\n for item in resp.get('hosts'):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Implement DataSource.get_vms() method. VM names in CSV files are of "vm_" format. The returned VM names are sorted in integer id order.
def get_vms(self): vms = [v for v in self.vm_data.keys()] vms.sort(lambda x, y: cmp(int(x[3:]), int(y[3:]))) return vms
[ "def get_vmfilenames(self, directory):\n filenames = os.listdir(os.getcwd() + '\\\\' + directory)\n return [directory + '\\\\' + filename for filename in filenames if\n filename.endswith('.vm')]", "def getVMList(self):\n log.debug(\"Entering getVMList()...\")\n result = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse a datatime string and return seconds since epoch.
def parse_timestr(self, timestr): epoch = datetime.datetime(1970, 1, 1, 0, 0, 0, 0, tzutc()) return int((parsedate(timestr) - epoch).total_seconds())
[ "def datumToSeconds(timestr):\n return (datetime.datetime(int(timestr.split(\"-\")[0]), \n int(timestr.split(\"-\")[1]), \n int(timestr.split(\"-\")[2])) - datetime.datetime(1970,1,1)).total_seconds()", "def parse_timestamp(input_time: str) -> int:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot graph using information in graphinfo object.
def plot_graph(self, graphinfo): WIDTH = 450 HEIGHT = WIDTH * 0.55 opts = [] # Generate outfile name if not self.rrdfile: self.outfiles[graphinfo.name] = self.SKIPPED return logging.info("Plotting %s graph for %s" % (graphinfo.name, self.node)) ...
[ "def plot_graph(self) -> None:", "def plot_graph(self):\r\n x = []\r\n y = []\r\n\r\n for n in self.graph.get_all_v().values():\r\n if(n.get_pos() != None):\r\n x.append(n.get_pos().get_x())\r\n y.append(n.get_pos().get_y())\r\n else:\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A wrapper of rrdtool functions, with additional logging function.
def rrdtool_cmd(self, cmd, *args, **kwargs): fn_table = {"create": rrdtool.create, "update": rrdtool.update, "graph": rrdtool.graph} fn = fn_table[cmd] cmdline = "rrdtool %s %s" % (cmd, " ".join([i if isinstance(i, str) else " ".join(i) for i ...
[ "def logtool(ctx):", "def result_logger(fct):\n\n\t\tdef wrapper(*args, **kw):\n\t\t\tret = fct(*args, **kw)\n\t\t\tlogger.debug(\"%s %s %s return %s\" % (\n\t\t\t\targs[0].__class__.__name__,\n\t\t\t\targs[0].__class__.__module__[len('metric_'):],\n\t\t\t\tfct.__name__, ret))\n\t\t\treturn ret\n\n\t\treturn wrap...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Combine graphs for each host, each VM, and each type of graph. The function gets generated graphs from ds object, and combine them for each host, each VM, and each type of graph.
def combine_graphs(cls, ds, gr): topdir, file_prefix, outfiles = ds.get_allinone_outfiles() # For each host, combine all its graphs _, _, host_outfiles = ds.get_host_outfiles() for node in ds.get_hosts(): logging.info("Combining graphs for %s" % node) graphs = [...
[ "def graph_create(host, host_path):\n graphs = list()\n for name in dash_profile['graphs']:\n log.info(\" Graph: %s\" % name)\n graph = list()\n # Skip undefined graphs\n if name not in graphdef.keys():\n log.error(\"%s not found in graphdef.yml\" % name)\n c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set transparency to a color The function returns a new color code in RRGGBBAA format.
def alpha(cls, rgb_color, transparency): if transparency > 1: transparency = 1 elif transparency < 0: transparency = 0 return rgb_color + str(hex(int(254 * transparency)))[2:]
[ "def _set_transparency(self, transparency, elm):\n a = str(100 - transparency) + '196'\n \n alpha = OxmlElement('a:alpha')\n alpha.set('val', a)\n elm.srgbClr.append(alpha)", "def alpha_extend(color: C3I, alpha: int = 255) -> C4I:\n return (*color, alpha)", "def alpha_e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load config file and instantiate UnitGroup, Metric and Graph objects.
def initialize(config_file): config = Config(config_file) # Instantiate UnitGroup objects, based on definition in config file. ugregistry = {} for ugname, ugcfg in config["unit_groups"].items(): ugobj = UnitGroup(ugname) for unit, value in ugcfg.items(): ugobj.add(unit, val...
[ "def __init__(self, config):\n\n # First, figure out the real metric\n self.metric_name = config['real_metric']\n\n # Get the class and instantiate it\n cls = utils.import_class_or_module(self.metric_name)\n self.metric = cls(config)\n self.vtype = self.metric.vtype", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function checks if the username being entered exists in the text file. While taken usernames are being entered, the user is prompted for a new one. Only details with unique username are added to the text file.
def check_registration_details(username, password): contents = read_file() while ((username + '\n') in contents): print("Sorry! This username is taken..") username = get_username() password = get_password() add_details(username, password)
[ "def user_find(file):\n username1 = input(\"Enter your username: \")\n username = username1.lower()\n for row in file:\n if row[0] == username:\n print(\"\\n username found \" + username +\"\\n\")\n user_found = [row[0],row[1]]\n pass_check(user_found)\n g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the WoS ID and MAG ID from a paperinfo json file
def get_wos_id(path_to_json): data = json.loads(path_to_json.read_text()) return (data.get('wos_id'), data.get('mag_id'))
[ "def mp_info(mp_id):\r\n # pulling the json object from file\r\n j = get_mp_json_from_file(mp_id)\r\n\r\n votes = {}\r\n\r\n for item in j:\r\n if item.startswith('public_whip_dreammp'):\r\n\r\n key = item.replace('public_whip_dreammp', '')\r\n vote_id = re.findall(r'\\d+', ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get Genre element with list attr
def get_genres(type_: str, value_: str, page: int, step: int): genre = factory.get_elem_list(Genre, type_, value_, page, step) return genre
[ "def get_genre(id_genre):\n genre = factory.get_elem_solo(Genre, id_genre)\n return genre", "def find_genres(genre_dom, dom):\n # take the first genre and turn it into a string\n genre = str(genre_dom)[3:-1]\n\n # see if there are more genres to a movie\n next_genre = dom.find(\"div\", itemprop=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get Genre element with attrs
def get_genre(id_genre): genre = factory.get_elem_solo(Genre, id_genre) return genre
[ "def get_genres(type_: str, value_: str, page: int, step: int):\n genre = factory.get_elem_list(Genre, type_, value_, page, step)\n return genre", "def attr(html, name):\n return (None, html.find('input', attrs={'name': name})['value'])", "def get_attr(self, termid, attr):\n return self.G.node[t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get count genres by type and value
def count_genres(type_: str, value_=''): count = factory.get_elem_count(Genre, type_, value_) return count
[ "def get_count_genres(content) -> int:\n count = 0\n if content['type'] == 'by_song' or content['type'] == 'by_artist':\n count = __get_count_all_genre()\n elif content['type'] == 'search':\n count = __get_count_genre_search(content['value'])\n return count", "def __get_count_all_genre()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extracts and anaylzes the altitude from a raw telemetry string
def process_telemetry_string(telem, nichrome): telemFields = telem.split(",") try: # Check to make sure the string is actually the telemetry data. # This will have to be changed based on what you name your payload if re.match("\$\$\w{1,10}", telemFields[0]) != None: # The 6t...
[ "def get_altitude(self):\n self.degrees = self.altitude_encoder.get_degrees()\n self.tele_altitude = self.Calculations.convert_degrees( self.degrees)\n return self.tele_altitude", "def altitude(self):\r\n pressure = self.pressure # in Si units for hPascal\r\n return 44330 * (1.0...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sleeps forever, periodically forcing nichrome to stay low (deactivated)
def keepNichromeLow(nichrome): while True: loginfo("Deactivating nichrome again...") nichrome.deactivate() time.sleep(2)
[ "def lightsleep(time_ms: int, /) -> None:", "def lightleep(time_ms: int = None) -> None:", "def fuzz():\n if FUZZ:\n time.sleep(random.random())", "def ssleep():\n time.sleep(0.15);\n return", "def cool_off(self):\n\n #self.error_counter += 1\n t = 60\n print(f\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the telemetry file if it isn't there
def create_telemetry_file(): loginfo("Creating telem file if it doesn't exist...") with open(HAB_TELEM_FILE, "w"): pass
[ "def write_telemetry(self, telemetry):\n\n _id = telemetry['id']\n _type = telemetry['type']\n\n # If there is no log open for the current ID check to see if there is an existing (closed) log file, and open it.\n if _id not in self.open_logs:\n _search_string = os.path.join(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test wrapper function doify()
def test_doify(): def genfun(tymth, tock=0.0, **opts): tyme = yield(tock) assert inspect.isgeneratorfunction(genfun) gf0 = doing.doify(genfun, name='gf0', tock=0.25) gf1 = doing.doify(genfun, name='gf1', tock=0.125) assert inspect.isgeneratorfunction(gf0) assert inspect.isgeneratorfun...
[ "def test_do_return():\n\n @do\n def f():\n yield do_return(\"hello\")\n\n with warns(DeprecationWarning):\n assert perf(f()) == \"hello\"", "def test_wraps():\n print('func')", "def run(self, test, env):\n\n raise NotImplementedError", "def test_taskify_sets_name(self):\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test DoDoer class with tryDoer and always
def test_dodoer_always(): # create some TryDoers for doers doer0 = TryDoer(stop=1) doer1 = TryDoer(stop=2) doer2 = TryDoer(stop=3) doers = [doer0, doer1, doer2] tock = 1.0 dodoer = doing.DoDoer(tock=tock, doers=list(doers)) assert dodoer.tock == tock == 1.0 assert dodoer.doers == do...
[ "def test_exDo():\n doizeExDo = doing.doizeExDo\n assert inspect.isgeneratorfunction(doizeExDo)\n assert hasattr(doizeExDo, \"tock\")\n assert hasattr(doizeExDo, \"opts\")\n assert \"states\" in doizeExDo.opts\n assert doizeExDo.opts[\"states\"] == None\n doizeExDo.opts[\"states\"] = []\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test exDo generator function nonclass based
def test_exDo(): doizeExDo = doing.doizeExDo assert inspect.isgeneratorfunction(doizeExDo) assert hasattr(doizeExDo, "tock") assert hasattr(doizeExDo, "opts") assert "states" in doizeExDo.opts assert doizeExDo.opts["states"] == None doizeExDo.opts["states"] = [] tymist = tyming.Tymist(...
[ "def test_generator_inline(self):\n def test_odd(v):\n assert v % 2\n for i in range(0, 4):\n yield test_odd, i", "def test_base_not_hermitian_has_generator_false(self):\n op = Exp(qml.RX(1.23, 0), 1j)\n assert op.has_generator is False", "def te...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test trydo testing function example with break to normal exit
def test_trydo_break(): assert inspect.isgeneratorfunction(tryDo) assert hasattr(tryDo, "tock") assert hasattr(tryDo, "opts") tymist = tyming.Tymist(tock=0.125) assert tymist.tyme == 0.0 states = [] do = tryDo(tymth=tymist.tymen(), states=states, tock=0.25) assert inspect.isgenerator(d...
[ "def test_run_loop_success(self):\n found = False\n pyint = Interpreter(limit=15)\n try:\n pyint.run(code=BF_CODE_LOOP_TWICE)\n except SystemExit: \n found = True\n self.assertFalse(found)", "def test_retry_run(self):\n pass", "def RunAndDie(fun, *...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test trydo testing function example with close to force exit
def test_trydo_close(): tymist = tyming.Tymist(tock=0.125) assert tymist.tyme == 0.0 states = [] do = tryDo(tymth=tymist.tymen(), states=states, tock=0.25) assert inspect.isgenerator(do) result = do.send(None) assert result == 0 assert states == [State(tyme=0.0, context='enter', feed='D...
[ "def test_terminate_run(self):\n pass", "def test_close():\n try:\n cfg = config()\n js = rs.job.Service(cfg.job_service_url, cfg.session)\n js.close()\n js.get_url()\n assert False, \"Subsequent calls should fail after close()\"\n\n except rs.NotImplemented as ni:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test trydo testing function example with throw to force exit
def test_trydo_throw(): tymist = tyming.Tymist(tock=0.125) assert tymist.tyme == 0.0 states = [] do = tryDo(tymth=tymist.tymen(), states=states, tock=0.25) assert inspect.isgenerator(do) result = do.send(None) assert result == 0 assert states == [State(tyme=0.0, context='enter', feed='D...
[ "def _try(func):\n try:\n return func()\n except Exception as e:\n print_tb(e)\n raise e", "def test_exception():", "def test_retry_run(self):\n pass", "def RunAndDie(fun, *args):\n try:\n fun(*args)\n finally:\n sys.exit(1)", "def test_trydo_break():\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test ServerDoer ClientDoer classes
def test_server_client(): tock = 0.03125 ticks = 16 limit = ticks * tock doist = doing.Doist(tock=tock, real=True, limit=limit) assert doist.tyme == 0.0 # on next cycle assert doist.tock == tock == 0.03125 assert doist.real == True assert doist.limit == limit == 0.5 assert doist.do...
[ "def test_create_client(self):\n pass", "def test_get_client(self):\n pass", "def test_delete_client(self):\n pass", "def test_register_client(self):\n pass", "def test_echo_server_client():\n tock = 0.03125\n ticks = 16\n limit = ticks * tock\n doist = doing.Doist(t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test EchoServerDoer ClientDoer classes
def test_echo_server_client(): tock = 0.03125 ticks = 16 limit = ticks * tock doist = doing.Doist(tock=tock, real=True, limit=limit) assert doist.tyme == 0.0 # on next cycle assert doist.tock == tock == 0.03125 assert doist.real == True assert doist.limit == limit == 0.5 assert doi...
[ "def test_server_client():\n tock = 0.03125\n ticks = 16\n limit = ticks * tock\n doist = doing.Doist(tock=tock, real=True, limit=limit)\n assert doist.tyme == 0.0 # on next cycle\n assert doist.tock == tock == 0.03125\n assert doist.real == True\n assert doist.limit == limit == 0.5\n a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test EchoConsoleDoer class Must run in WindIDE with Debug I/O configured as external console
def test_echo_console(): port = os.ctermid() # default to console try: # check to see if running in external console fd = os.open(port, os.O_NONBLOCK | os.O_RDWR | os.O_NOCTTY) except OSError as ex: # maybe complain here return # not in external console else: os.close...
[ "def test_v1alpha3_console(self):\n pass", "def test_v1_console(self):\n pass", "def testing_console(self, print_func=None, input_func=None):\n if print_func:\n self._print = print_func\n if input_func:\n self._input = input_func\n self.play()", "def test_write_read_console_me...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Defines the null and alternative hypothesis.
def define_hypothesis(df, statistic, alternative, paired, alpha): paired_text = f"the {statistic} difference" if paired else f"difference in {statistic}" hypothesis = { 'two-sided_H0': f"{paired_text} equal to zero", 'two-sided_H1': f"{paired_text} not equal to zero", 'grea...
[ "def test_alternative(df, hypothesis, alternative='two-sided', alpha=0.05):\n df['H0'] = hypothesis[alternative + '_H0']\n df['H1'] = hypothesis[alternative + '_H1']\n formatted_alpha = round(alpha*100, 2)\n conclusion = 'There is no evidence' if df['p-val'][0] > alpha else 'There is evi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the hypothesis using the pvalue and adds the conclusion to the results DataFrame.
def test_alternative(df, hypothesis, alternative='two-sided', alpha=0.05): df['H0'] = hypothesis[alternative + '_H0'] df['H1'] = hypothesis[alternative + '_H1'] formatted_alpha = round(alpha*100, 2) conclusion = 'There is no evidence' if df['p-val'][0] > alpha else 'There is evidence' ...
[ "def test_find_p_value(self):\n \tself.assertEqual(find_p_value(df1), [1.0, 1.0, 0.6666666666666666])", "def define_hypothesis(df, statistic, alternative, paired, alpha):\n paired_text = f\"the {statistic} difference\" if paired else f\"difference in {statistic}\"\n hypothesis = {\n 'two...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called from the definition file with the definition of a condition. Receives the name of the condition and it's expression.
def AddCondition(self, name, expression): self.conditions[name] = expression
[ "def make_condition(self, name):\n pass", "def condition_expression(self, condition_expression):\n self._condition_expression = condition_expression", "def condition(self) -> global___Expression:", "def condition(self, condition):\n self._condition = condition", "def condition_name(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load the state machine definition file. In the definition file, which is based on the python syntax, the following variables and functions are defined.
def Load(self, filename): self.sm['state'] = self.AddState self.sm['condition'] = self.AddCondition exec(open(filename).read(), self.sm) self.name = self.sm['name'] if not self.name.isalnum(): raise Exception("State machine name must consist of only alphanumeric" "charac...
[ "def load_game_state(self, load_path : str) -> None:\n pass", "def load_old(file):\n\n machine = Turing_Machine(1,1)\n\n data = file.read()\n data = data.splitlines()\n\n nstates = len(data)\n nsymbols = 0\n\n for state in data:\n state = state.split()\n\n if nsymbols == 0:\n nsymbols = in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Used to get next row of either list of dicts or cursor
def get_next_row(table, names): if isinstance(table, list): if not table: return None, True else: return table.pop(0), False else: row = table.fetchone() if row is None: return None, True else: return dict(zip(names, row)),...
[ "def nextRow(self):\n\n # Update internal 'iterators'\n self._row_data = self._list_data[0]\n\n # Advance the row data once\n self._list_data = self._list_data[1:]\n\n return self.get('row')", "def next(self):\n\t\t#warnings.warn(\"DB-API extension cursor.next() used\", SyntaxWarning, 2)\n\t\ttry:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Used to find all rows in one table but not in another, not treating rows as distinct.
def unsorted_not_distinct(table1, table2, subset=False): only_in_table1 = [] if subset: # When subset, a row in table1 is not subset, # if its contains more instances of a row than table2 for row in table1: count1 = table1.count(row) count2 = table2.count(row) ...
[ "def setDifference(self, table2):\n results = set([])\n for rec in self.records:\n rec_tuple = tuple([v for (k, v) in rec.items()])\n results.add(rec_tuple)\n for rec in table2.records:\n rec_tuple = tuple([v for (k, v) in rec.items()])\n if rec_tuple...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Used to find all rows in one table but not in another.
def tab_unsorted(table1, table2, where_conditions, dw_rep): sql = \ " SELECT * " + \ " FROM " + table1 + \ " AS table1 " + \ " WHERE NOT EXISTS" \ " ( " + \ " SELECT NULL " + \ " FROM " + table2 + \ " AS table2 " + \ " WHERE " + " AND ".join(w...
[ "def anti_join(self, other: 'Table') -> 'Table':\n if len(other.key) == 0:\n raise ValueError('anti_join: cannot join with a table with no key')\n if len(other.key) > len(self.key) or any(t[0].dtype != t[1].dtype for t in zip(self.key.values(), other.key.values())):\n raise Value...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Does a subset comparison of two sorted tables
def subset_sorted_compare(actual, expected): # Get names of attributes names = [t[0] for t in actual.description] e_row, expected_empty = get_next_row(expected, names) if not expected_empty: result = None not in e_row.values() else: result = False actual_empty = False # Ru...
[ "def test_compare_rows(self):\n a = self.select_a\n b = self.select_b\n\n # A case we want to optimize.\n datatest.validate(a(a.fieldnames), a(a.fieldnames))\n\n # A case we want to optimize (using ordered intersection of fieldnames).\n common_fields = tuple(x for x in a.fi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate path, including query and fragment (aka anchor), for ``request`` using positional arguments ``args`` and keyword arguments ``kwargs``. Refer to corresponding router plugin for specific signature for positional and keyword arguments. Returns urlpath string. This does not include SCRIPT_NAME, netlocation and sch...
def urlpath( request, *args, **kwargs ):
[ "def _get_uri_from_request(request):\n uri = request.base_url\n if request.query_string:\n uri += '?' + request.query_string.decode('utf-8')\n return uri", "def url(path=None, **kw):\r\n if path is None:\r\n path = web.ctx.path\r\n if path.startswith(\"/\"):\r\n out = web.ctx.h...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Callback for asyncrhonous finish(). Means the response is sent and the request is forgotten. Chained call originating from
def onfinish( request ):
[ "def _finish_request(self, output, request):\n if output:\n request.write(output)\n request.finish()", "def deferred_response(response, request):\n request.write(simplejson.dumps(response))\n request.finish()", "def finished(self, reply):\n pass", "def _request_finished(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When the router finds that a resource (typically indicated by the requestURL) has multiple representations, where each representation is called a variant, it has to pick the best representation negotiated by the client. Negotiation is handled through attributes like mediatype, language, charset and contentencoding. ``r...
def negotiate( request, variants ):
[ "def test_content_type_negotiation(self):\n\t\tview = View()\n\t\tview.serializers = (\n\t\t\t('application/x-foo', FooSerializer()),\n\t\t\t('application/x-bar', BarSerializer())\n\t\t)\n\t\t\n\t\t# No accept header means the first serializer in the list\n\t\tcontent_type, result = view.serialize('', {})\n\t\tself...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use HTTP `headers` dictionary, to parse cookie name/value pairs, along with its metainformation, into Cookie Morsels. Get the cookie string from ``headers`` like,
def parse_cookies( headers ):
[ "def parse_cookie_header(header):\n attribs = (\n \"expires\",\n \"path\",\n \"domain\",\n \"version\",\n \"httponly\",\n \"secure\",\n \"comment\",\n \"max-age\",\n \"samesite\",\n )\n\n # Split into cookie(s); handles headers with multiple co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }