query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Gets the current explain_level
def _get_explain_level(self): self._validate_explain_level() if self.explain_level == "auto": if self._get_mode() == "Explain": return 2 if self._get_mode() == "Perform": return 1 if self._get_mode() == "Compete": return...
[ "def help_explain(self):\n print(EXPLAIN)", "def expert_level(self) -> int:\n return self._expert_level", "def getLevel(self):\n return _libsbml.ASTBasePlugin_getLevel(self)", "def verbose_level(self):\n return self._verbose_level", "def ColorfulPyPrint_current_verbose_level():\r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the current features_selection
def _get_features_selection(self): self._validate_features_selection() if self.features_selection == "auto": if self._get_mode() == "Explain": return False if self._get_mode() == "Perform": return True if self._get_mode() == "Compete": ...
[ "def selected_feature(self):\n return self._selected_feature", "def GetSelection(self):\r\n\r\n return self._current", "def getSelection(self): # real signature unknown; restored from __doc__\r\n pass", "def get_selection(self):\r\n return self.value", "def active_selection():\r\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the current start_random_models
def _get_start_random_models(self): self._validate_start_random_models() if self.start_random_models == "auto": if self._get_mode() == "Explain": return 1 if self._get_mode() == "Perform": return 5 if self._get_mode() == "Compete": ...
[ "def get_start_maybe_randomised(self):\n if self.randomise:\n return random.uniform(0, self.start)\n else:\n return self.start\n # return (random.uniform(0, self.start) if self.random else self.start)", "def generate_nnmodels(self):\n return []", "def get_random...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the current hill_climbing_steps
def _get_hill_climbing_steps(self): self._validate_hill_climbing_steps() if self.hill_climbing_steps == "auto": if self._get_mode() == "Explain": return 0 if self._get_mode() == "Perform": return 2 if self._get_mode() == "Compete": ...
[ "def getSteps( self ):\n\n return self.adb.get( 'steps' )", "def start_steps(self):\n return self._start_steps[:]", "def bootstrap_steps(self):\n return self._bootstrap_steps", "def get_workflow_steps(self):\n return self._data_dict[self.KEY_WF_ST...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the current top_models_to_improve
def _get_top_models_to_improve(self): self._validate_top_models_to_improve() if self.top_models_to_improve == "auto": if self._get_mode() == "Explain": return 0 if self._get_mode() == "Perform": return 2 if self._get_mode() == "Compete"...
[ "def getTopModel(self):\n top = self.model\n while top.parent is not None:\n top = top.parent\n return top", "def best_model(self):\n return self.best_model_wts", "def top(self):", "def get_best_known_model(self) -> Tuple[Optional[Path], int]:\n return self._get_f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the current boost_on_errors
def _get_boost_on_errors(self): self._validate_boost_on_errors() if self.boost_on_errors == "auto": val = self._get_validation_strategy() if val.get("validation_type", "") == "custom": return False if self._get_mode() == "Explain": retu...
[ "def on_errors(self):\n return self._on_errors", "def get_errors(self):\n return {'loss': self.loss.data[0]}", "def import_errors(self):\n return self._import_errors", "def get_script_errors(self):\r\n return self._script_errors", "def error(self):\n try:\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the current kmeans_features
def _get_kmeans_features(self): self._validate_kmeans_features() if self.kmeans_features == "auto": if self._get_mode() == "Explain": return False if self._get_mode() == "Perform": return False if self._get_mode() == "Compete": ...
[ "def k_means(self):\n raise NotImplementedError()", "def get_features(self):\n return self.features", "def get_features(self):\n if self.strokes is False:\n print('Isolating strokes')\n self.isolate_strokes()\n # List of features to use (sm1 omitted because alwa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the current max_single_prediction_time
def _get_max_single_prediction_time(self): self._validate_max_single_prediction_time() if self.max_single_prediction_time is None: if self._get_mode() == "Perform": return 0.5 # prediction time should be under 0.5 second return None else: retu...
[ "def max_time(self):\n #{{{ function to return time of last sample\n\n if self.maxtime == -1:\n return stock.now()\n\n return self.maxtime", "def max_time(self):\n return self.time[np.argmax(self.flux)]", "def max_time(self) -> float:\r\n if(len(self.operations_by_name)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the current optuna_time_budget
def _get_optuna_time_budget(self): self._validate_optuna_time_budget() if self.optuna_time_budget is None: if self._get_mode() == "Optuna": return 3600 return None else: if self._get_mode() != "Optuna": # use only for mode Optu...
[ "def budget(self):\n return self._budget", "def get_current_goal(self):\n if self.agenda is None or len(self.agenda) == 0:\n return None\n return self.agenda[0]", "def get_best_time():\n return best_reaction_time", "def lagtime(self):\n return self._tau", "def getSe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the current optuna_init_params
def _get_optuna_init_params(self): self._validate_optuna_init_params() if self._get_mode() != "Optuna": # use only for mode Optuna return {} return deepcopy(self.optuna_init_params)
[ "def getInitParams(self):\n paramDict = Distribution.getInitParams(self)\n paramDict['mapping'] = self.mapping\n paramDict['values'] = self.values\n return paramDict", "def init_params(self):\n self.params = {p.title: p for p in\n chain(self.session.shared_params.values(),...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the current optuna_verbose
def _get_optuna_verbose(self): self._validate_optuna_verbose() # use only for mode Optuna if self._get_mode() != "Optuna": return True return deepcopy(self.optuna_verbose)
[ "def isVerbose(self):\n return self.opts.verbose", "def is_verbose(self):\n return self._verbose", "def verbose():\n return Verbose.level()", "def getVerboseLevel(self):\n return self.__verboseLevel", "def verbose_level(self):\n return self._verbose_level", "def ColorfulPyPr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the current n_jobs
def _get_n_jobs(self): self._validate_n_jobs() return deepcopy(self.n_jobs)
[ "def get_n_jobs(self):\n return self.n_jobs", "def get_num_jobs(self):\n return self._config.get_num_jobs()", "def effective_n_jobs(n_jobs=-1):\n if n_jobs == 1:\n return 1\n\n backend, backend_n_jobs = get_active_backend()\n if n_jobs is None:\n n_jobs = backend_n_jobs\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the current random_state
def _get_random_state(self): self._validate_random_state() return deepcopy(self.random_state)
[ "def random_state(self):\n return self._random.get_state()", "def random_state(self):\n return self.__random_state", "def random_state(self):\n return self._distribution.random_state", "def get_state():\n return torch.get_rng_state(), random.getstate(), np.random.get_state()", "def r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the fairness metric
def _get_fairness_metric(self): self._validate_fairness_metric() if self.fairness_metric == "auto": if self._get_ml_task() == BINARY_CLASSIFICATION: return "demographic_parity_ratio" if self._get_ml_task() == REGRESSION: return "group_loss_ratio" ...
[ "def _get_fairness_threshold(self):\n if self.fairness_threshold == \"auto\":\n if self._get_ml_task() in [\n BINARY_CLASSIFICATION,\n MULTICLASS_CLASSIFICATION,\n ]:\n thresholds = {\n \"demographic_parity_difference\": 0....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the fairness threshold
def _get_fairness_threshold(self): if self.fairness_threshold == "auto": if self._get_ml_task() in [ BINARY_CLASSIFICATION, MULTICLASS_CLASSIFICATION, ]: thresholds = { "demographic_parity_difference": 0.1, ...
[ "def threshold(self) -> float:\n return pulumi.get(self, \"threshold\")", "def get_best_threshold(ensemble_model):\n train_gen, val_gen = get_generators()\n\n # Add metrics\n ensemble_model.compile(loss='binary_crossentropy', optimizer=get_optimizer(), metrics=get_metric(scan=True))\n preds_tes...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets privileged groups for fair training
def _get_privileged_groups(self): if self.privileged_groups == "auto": return [] else: return deepcopy(self.privileged_groups)
[ "def _get_underprivileged_groups(self):\n if self.underprivileged_groups == \"auto\":\n return []\n else:\n return deepcopy(self.underprivileged_groups)", "def test_aws_service_api_security_groups_get(self):\n pass", "def test_get_groups(self):\n pass", "def g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets underprivileged groups for fair training
def _get_underprivileged_groups(self): if self.underprivileged_groups == "auto": return [] else: return deepcopy(self.underprivileged_groups)
[ "def _get_privileged_groups(self):\n if self.privileged_groups == \"auto\":\n return []\n else:\n return deepcopy(self.privileged_groups)", "def test_aws_service_api_security_groups_get(self):\n pass", "def test_get_groups(self):\n pass", "def _identify_groups...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Download log files from remote machines on local machine via ssh
def __download_via_ssh(cls, request, local_path): hosts = request.POST.getlist('hosts[]') logs = request.POST.getlist('logs[]') if not os.path.exists(local_path): os.makedirs(local_path) for host_name in hosts: host_object = Host.objects.get(host_name=host_name) ...
[ "def get_logs():\n get(remote_path=\"/tmp/log_extracts.tar.gz\",\n local_path=\"/logs/new_log.tar.gz\")", "def PullLogs(ssh, log_files, download_folder):\n for log_file in log_files:\n target_file = os.path.join(download_folder, os.path.basename(log_file))\n ssh.ScpPullFile(log_file, ta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make an hashable representation of an object for hashlib
def hashable(obj): return bytes(str(obj), "utf-8")
[ "def hashable(obj):\n if not obj.__hash__:\n return str(obj)\n return obj", "def hash(obj):\n \n import hashlib\n import pickle\n \n sha = hashlib.sha256()\n sha.update(pickle.dumps(obj))\n \n return sha.hexdigest()", "def hash_object(cls, serialized_obj):\n hash_byte...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure row data is valid This currently just checks that 2D arrays match the variable components.
def validate_row(row): subkeys = [INDEP, DEP] for subkey in subkeys: for k, v in row[subkey].items(): if v is None: continue if np.ndim(v) > 1: assert np.ndim(v) == 2 if 1 not in np.shape(v): assert isinstance(k,...
[ "def valid_data(self):\n return len(self.input_row_positions) > 1", "def validate(self, row):\n raise NotImplementedError", "def _check_input_data(self, data):\n\n if not isinstance(data, np.ndarray):\n raise TypeError('Input data must be a numpy array.')", "def validate_matrix...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a dictionary of dependent data
def add_dict(self, indep, dep): dfull = {IND: len(self), INDEP: indep.copy(), DEP: dep} validate_row(dfull) check_objects(dfull) if settings.CONVERT_SCALAR_ARRAYS: scalarise(dfull) if settings.PRINT_UPDATES: print(self.show([dfull])) self.append(df...
[ "def add_dict(dictionary, context_name):", "def addDependent(location):", "def __add__(self, dt:DictTensor)->DictTensor:\n assert dt.device()==self.device()\n for k in dt.keys():\n assert not k in self.variables, (\n \"variable \" + k + \" already exists in the DictTensor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of dictionaries that only contain values for keys
def exclusively(self, keys, lst=None): minimal = self.minimal() if lst is None else lst def make_exclusive(d, keys): dct = {} for k in keys: if k in d: dct[k] = d[k] else: dct[k] = -999 return dc...
[ "def filter_dictionary(dictionary, keys):\n return {key: dictionary[key] for key in dictionary if key in keys}", "def minidict(self):\n return {k: v for k, v in self.dict().items() if v is not None}", "def filter_keys_out(items, keys):\n for key, value in items.items():\n if key in keys:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merge this Box with one or more other Box instances
def merge(self, box, in_place=True): if in_place: self._merge(box) else: base = self.copy() base._merge(box) return base
[ "def merge(self, other_box_list):\n self.boxes.append(other_box_list.boxes)\n self.filter()", "def merge(self, other):\n # merge containers with the same name\n for container in self._container_child_containers:\n lookup = {obj.name: obj for obj in getattr(self, container)}\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return unique key values
def unique(self, key, lst=None): d = self.find(key, lst) vals = set(d.values()) return sorted(list(vals))
[ "def unique_values(self):\n for key in self.metadb.unique_values():\n yield key, self.datadb[key]", "def distinct(self, key):\n return self.database.command({'distinct': self.name,\n 'key': key})['values']", "def unique_keys(self) -> List[str]:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The set methods must raise a ComponentsErrorEx in case of wrong mode
def test_wrong_mode(self): self.assertRaises(ComponentErrorsEx, self.dp.setRewindingMode, 'FOO')
[ "def setControlMode(self,mode,*args,**kwargs):\n raise NotImplementedError()", "def magic_xmode(self,parameter_s = ''):\n\n new_mode = parameter_s.strip().capitalize()\n try:\n self.InteractiveTB.set_mode(mode = new_mode)\n print 'Exception reporting mode:',self.Interact...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
collect docker logs from servers $ command is $ log_collector.py
def main(): global tar_file_descr help_msg = 'Usage: log_collector.py <all | host1[,host2,host3...]>' hosts = [] if len(sys.argv) == 2: if '-h' == sys.argv[1] or '--help' == sys.argv[1]: print(help_msg) sys.exit(0) elif 'all' == sys.argv[1]: # get log...
[ "def collect():\n try:\n return subprocess.check_output([\n 'sudo', '/opt/tinypilot-privileged/scripts/collect-debug-logs', '-q'\n ])\n except subprocess.CalledProcessError as e:\n raise LogCollectionScriptFailedError(str(e)) from e", "def __get_docker_logs(self, containers):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read in labels from digitStruct.mat file to create a dict of image file name and corresponding labels
def read_labels(digitstruct_file): labels = dict() for dsObj in tdqm(yieldNextDigitStruct(digitstruct_file), ncols=50): image_labels = [] for bbox in dsObj.bboxList: image_labels.append(bbox.label) labels[dsObj.name] = image_labels return labels
[ "def _get_imagenet_as_dict(self):\n real_file_path = os.path.realpath(self.map_file)\n if not os.path.exists(real_file_path):\n raise IOError(\"map file {} not exists\".format(self.map_file))\n\n label_dict = {}\n with open(real_file_path) as fp:\n line = fp.readlin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Construct a heap from a list of elements with priorities. Each element of the list must be in the form (Item, Priority).
def construct_heap(self, elems): for e in elems: self.n += 1 self.A.append(e) self.pos[e[0]] = self.n for i in range(self.n // 2, 0, -1): self.combine(i)
[ "def priority_queue():\n class PriorityElement:\n def __init__(self, value, weight):\n self.value = value\n self.weight = weight\n\n def __lt__(self, other):\n return self.weight < other.weight\n\n # The following will produce the exact same results\n priority...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inserts the element elem with priority prio.
def insert(self, elem, prio): self.n += 1 self.A.append( (e,w) ) self.pos[e] = self.n i = self.n p = i // 2 self.insert_loop(i, p)
[ "def change_priority(self, elem, prio):\n pos = self.pos[elem]\n currPrio = self.A[pos][1]\n self.A[pos] = (elem, prio)\n if self.cmpFn(prio, currPrio):\n self.insert_loop(pos, pos // 2) # Up heapify\n else:\n self.combine(pos) # Down heapify", "def inser...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Changes the priority of the element elem to prio.
def change_priority(self, elem, prio): pos = self.pos[elem] currPrio = self.A[pos][1] self.A[pos] = (elem, prio) if self.cmpFn(prio, currPrio): self.insert_loop(pos, pos // 2) # Up heapify else: self.combine(pos) # Down heapify
[ "def reprioritize(self, priority, element):\r\n if element not in self.element_finder:\r\n raise ValueError(\"No such element in the priority queue.\")\r\n entry = self.element_finder[element]\r\n self.add_element(priority, element, entry[1])\r\n entry[1] = self.INVALID", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the priority of an element.
def get_priority(self, elem): pos = self.pos[elem] return self.A[pos][1]
[ "def getpriority(self, name):\n\t\tif name not in self:\n\t\t\treturn None\n\t\treturn self.attributes[name].priority", "def priority(node):\n return node.priority", "def get_priority(self, item):\n try:\n return self.set[item][0]\n except KeyError:\n print(\"Can't get...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transcodes a file src to a file dest.
def transcode(self, src: Path, dest: Path) -> None: pass
[ "def copyFile( src, dest ):\n\tinFile = open( src, 'r' )\n\toutFile = open( dest, 'w' )\n\tfor line in inFile:\n\t\toutFile.write( line )\n\toutFile.close()\n\tinFile.close()", "def compressFile(source, target):\n data = cake.filesys.readFile(source)\n try:\n data = zlib.compress(data, 1)\n except zlib.erro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes an integer below 1001 and converts it into english text. Ignore spaces and hyphens as the instructions require.
def int2text(integer): # Numbers 1-99 are handled by simply looking up words in the special_case # dictionary. if integer < 100: return digit2text(integer) elif integer < 1000: # If exactly some hundred, then just return the word for the hundred's # place and the word 'hundred' ...
[ "def english(number):\r\n if number == 0:\r\n return 'zero'\r\n word = ''\r\n for step in itertools.count():\r\n number, rest = divmod(number, 1000)\r\n word = format_num(en3(rest), step) + word\r\n if number == 0:\r\n return word.strip()", "def num_to_thaiword(numb...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Solves [a]{b} = {x} by Gauss elimination.
def gaussElimin(a,b): a=float64(a) b=float64(b) n=len(b) x=zeros((n,1),dtype=float) for k in range(n-1): for i in range(k+1,n): l=float(a[i][k])/a[k][k] a[i][k]=0 for j in range(k+1,n): a[i][j]=a[i][j]-l*a[k][j] b[i]=b[i]-l*b[k] x[n-1]=float(b[n-1])/a[n-1][n-1] ...
[ "def gauss(A, b):\n n = len(A)\n\n A, b = forward_elimination(A, b, n)\n return back_substitution(A, b, n)", "def gaussian_elimination(A, b):\n n = len(b)\n # Join A and b\n ab = np.c_[A,b]\n # Gaussian Elimination\n for i in range(n-1):\n if ab[i,i] == 0:\n raise ZeroDiv...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Solves [L][U]{x} = b, where [a] = [L\U] is the matrix returned from LUdecomp.
def LUsolve(a,b): b=float64(b) n=len(b) LU=LUdecomp(a) y=zeros((n,1)) x=zeros((n,1)) y[0]=b[0] for i in range(1,n): sum=b[i] for j in range(i): sum=sum-LU[i][j]*y[j] y[i]=sum x[n-1]=float(y[n-1])/LU[n-1][n-1] for i in range(n-2,-1,-1): sum=y[i] ...
[ "def LUsolve(B, Y):\n\n n = len(B)\n U = np.zeros_like(B)\n L = np.identity(n)\n\n for i in range(n):\n for j in range(i):\n L[i,j] = B[i,j]\n \n for k in range(i, n):\n U[i,k] = B[i,k]\n\n LL = np.concatenate((L, Y), axis=1)\n Z = forward_substitute(LL)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a Octave ResNet26 model.
def pre_act_oct_resnet26(pretrained=False, **kwargs): model = PreActOctResNet(Bottleneck, [2, 2, 2, 2], **kwargs) return model
[ "def create_embedding_net():\n # This is a resnet50 base model\n resnet_model = models.resnet50(pretrained=True)\n\n # Now modify the network layers\n resnet_model.fc = Identity()\n resnet_model.avgpool = Identity() \n #print(resnet_model)\n\n return resnet_model", "def resnet10(shortcut_t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a Octave ResNet200 model.
def pre_act_oct_resnet200(pretrained=False, **kwargs): model = PreActOctResNet(Bottleneck, [3, 24, 36, 3], **kwargs) return model
[ "def resnet10(**kwargs):\n model = ResNet(BasicBlock, [1, 1, 1, 1], **kwargs)\n return model", "def create_embedding_net():\n # This is a resnet50 base model\n resnet_model = models.resnet50(pretrained=True)\n\n # Now modify the network layers\n resnet_model.fc = Identity()\n resnet_model.avg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The standard size of a tile sprite in 2D screen space.
def tile_size_2d(self): return 32.0, 32.0
[ "def tile_size(self):\n return self._tile_size", "def tile_size(self) -> int:\n return self._tile_size", "def get_tile_size(self) -> int:\n return self.tile_size.spin.value()", "def _get_tile_size() -> int:\n return octree_config['octree']['tile_size'] if octree_config else 256", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Using the Command_Handler from command module to handle command.
def usingHandler(self, cmd): self.command_handler.handle_command(cmd) while msg_queue.empty() is False: self.writeresponse(msg_queue.get())
[ "def mod_command_handler(self, cmd, args):\n self.command_handler_params = (cmd, args) # for inspection\n return bundy.config.create_answer(0)", "def handle(self, command):\n fn = \"handle_{}\".format(command)\n try:\n self.commands[fn](self)\n except KeyError:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Target method used by monitor thread, which polls vbmc status every 3s. If vbmc stops, ipmiconsole will stop.
def monitor(instance="default"): global logger_ic while True: try: with open("{}/{}/.{}-bmc.pid".format( config.infrasim_home, instance, instance), "r") as f: pid = f.readline().strip() if not os.path.exists("/proc/{}".format(pid)): ...
[ "def bitmessage_monitor(self):\n while True:\n now = time.time()\n if self.timer_check_bm_alive < now:\n while self.timer_check_bm_alive < now:\n self.timer_check_bm_alive += 10\n lf = LF()\n if (not self.is_restarting_bitm...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Stop ipmiconsole of target instance specified by its name
def stop(instance="default"): global logger_ic logger_ic = infrasim_log.get_logger(LoggerType.ipmi_console.value, instance) try: file_ipmi_console_pid = "{}/{}/.ipmi_console.pid".\ format(config.infrasim_home, instance) with open(file_ipmi_console_pid, "r") as f: pid...
[ "def stop(self):\n self.scion_sh('stop')", "def stop_single(self, name):\n logger.debug('Stopping module \"%s\"', name)\n self.modules[name].stop()\n logger.debug('Module \"%s\" stopped', name)", "def stop_notebook_instance(NotebookInstanceName=None):\n pass", "def _stop_instanc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a handle to the Ceph Cluster.
def connect(ceph_config_file, timeout = CEPH_TIMEOUT): handle = rados.Rados(conffile = ceph_config_file) LOGGER.info("librados version: " + str(handle.version())) LOGGER.info("Attempting to connect to: " + str(handle.conf_get('mon initial members'))) handle.connect() #timeout shoudl be...
[ "def host_cluster_create(context, values):\n return IMPL.host_cluster_create(context, values)", "def create_cluster():\n config = get_kube_config()\n command = CLUSTER_CREATE_COMMAND.replace('\\n','').format(cluster_name=config['cluster_name'],\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gather ceph monitor information
def get_monitor_info(handle, timeout): mon_info = dict() mon_info['stat'] = ceph_mon_command(handle, 'mon stat' , timeout) mon_info['dump'] = ceph_mon_command(handle, 'mon dump' , timeout) mon_info['map'] = ceph_mon_command(handle, 'mon getmap' , timeout) mon_info['metadata'] = c...
[ "async def get_monitor_data(self):\n json = await self._api_call(\"app/monitors/%s/overview\" % self.sense_monitor_id)\n if \"monitor_overview\" in json and \"monitor\" in json[\"monitor_overview\"]:\n self._monitor = json[\"monitor_overview\"][\"monitor\"]\n return self._monitor", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GAther ceph device information
def get_device_info(handle, timeout): device_info = dict() device_info['ls'] = ceph_mon_command(handle, 'device ls', timeout) return device_info
[ "def device_info(self) -> dict[str, any]:\n return system_info(self.hacs)", "def device_info(self) -> dict:\n return self._device_info", "def DeviceInfo(self): \n \n self.is_attached = self.spatial.isAttached()\n self.device_name = self.spatial.getDeviceName()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gather ceph manager information
def get_manager_info(handle, timeout): mgr_info = dict() mgr_info['ls-modules'] = ceph_mon_command(handle, 'mgr module ls', timeout) mgr_info['dump'] = ceph_mon_command(handle, 'mgr dump' , timeout) mgr_info['metadata'] = ceph_mon_command(handle, 'mgr metadata' , timeout) return mgr_info
[ "def manager_info(self, manager):\n _, body = self.request('/v1.1/managers/active/%s' % manager, 'GET')\n return body", "def get_monitor_info(handle, timeout):\n mon_info = dict()\n mon_info['stat'] = ceph_mon_command(handle, 'mon stat' , timeout)\n mon_info['dump'] = ceph_mon_co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure that graveyard_removal.py correctly removes the graveyard from an h5m file.
def test_default_graveyard_removal(): os.system("python svalinn_tools/graveyard_removal.py " + test_file_path + test_file) size = os.path.getsize(test_file[:-4] + "_no_grave.h5m") assert size == 5748780
[ "def remove_group(self):\n try:\n with open_hdf5(self.file_name, mode=\"a\") as hdf_file:\n del hdf_file[self.h5_path]\n except KeyError:\n pass", "def test_print_graveyard_removal(capfd):\n os.system(\"python svalinn_tools/graveyard_removal.py \" + test_file_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure that graveyard_removal.py prints the correct entity handle for the graveyard volume.
def test_print_graveyard_removal(capfd): os.system("python svalinn_tools/graveyard_removal.py " + test_file_path + test_file + " -p") out, err = capfd.readouterr() assert ("12682136550675318127" in out) == True
[ "def test_delete_volume(self):\n ctxt = context.get_admin_context()\n extra_specs = {}\n type_ref = volume_types.create(ctxt, 'hgst-1', extra_specs)\n volume = {'id': '1', 'name': 'volume1',\n 'display_name': '',\n 'volume_type_id': type_ref['id'],\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate the regex patterns, but only partially while the user is still typing. Because the 'from' pattern will be where the user specifies captures, changing it also requires revalidating the substitution pattern. However if the user is still typing (as opposed to hitting enter to complete the input) we do the minimal...
def validateRegexFields(self, complete=False): # Assume the patterns aren't valid. self.m_validFromRe = False self.m_validPatterns = False ### Validate the 'from' pattern # regexCtl = self.m_reFromCtl subsCtl = self.m_reToCtl regex, subs = regexCtl.V...
[ "def onTextChange(self, event):\n\n self.validateRegexFields(complete=False)\n event.Skip()", "def onHitEnterInFrom(self, event):\n\n self.validateRegexFields(complete=True)\n if self.m_validFromRe:\n self.m_reToCtl.SetFocus()", "def validate_data(self):\n for patte...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Uses the list of filesondisk and the regex patterns to build a list of what the directory will look like if we renamed the files. Because we're justusing a simple text list, we use symbols to show the user which filenames would change and whether they would produce any duplicates, substituting "." with "\1.txt".
def populateFileList(self): self.m_fileList.SetForegroundColour(wx.NullColour) # We'll need to track which file names are modified and which # file names duped. applicable, dupes = set(), set() if not self.m_validPatterns: # Regex's don't compile yet, just use the ...
[ "def mark_files(self,postfix):\n dk = self.cand.keys()\n dk.sort() # sort by date...\n dk.reverse() # .. and reverse so latest comes first\n res = \"\"\n for k in dk:\n fn = self.cand[k].name\n pfn = os.path.join(self.dir,fn)\n fnnew = fn + postfix\n pfnnew = os....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When the user hits 'enter' in the 'from' field.
def onHitEnterInFrom(self, event): self.validateRegexFields(complete=True) if self.m_validFromRe: self.m_reToCtl.SetFocus()
[ "def pressed_enter(self):\n pass", "def hit_enter():\n keyboard.press_and_release('Enter')", "def enter(self):\n\t\tself.actionObject().key_down(Keys.ENTER).key_up(Keys.ENTER).perform()", "def enterKey_cb(widget, dialog):\n dialog.response(gtk.RESPONSE_ACCEPT)", "def enter_press_log_watcher(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When the user modifies the content of either regex field.
def onTextChange(self, event): self.validateRegexFields(complete=False) event.Skip()
[ "def to_field(self, **kwargs):\n if self.regex:\n if not 'regex' in self.field_args:\n self.field_args = self.field_args + ('regex', )\n self.field_klass = forms.RegexField\n return super(StringSetting, self).to_field(**kwargs)", "def get_regex_mismatch_error_tex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the updated log_conf, taking into account new log files present on the instance as well as modifications made to the corresponding logentries host.
def update_instance_conf(log_paths, log_conf): log_client = LogClient.Client(account_key) instance_id, config = get_ssh_config(env.host) if log_conf is None and len(log_paths)>0: print 'log_conf is None' log_conf = create_host_logs(log_client,instance_id,log_paths) elif log_conf...
[ "def update_config(update):\n global _config\n new_config = copy.deepcopy(_config)\n _update_dict_recursive(new_config, update)\n logging.config.dictConfig(new_config)\n _configure_ulog_bridge()\n _config = new_config", "def update_log_config(self, monitor_name, log_config):\n pass", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a distribution, given by the list p_list, returns the entropy of the distribution.
def entropy(p_list): assert len(p_list) > 0 E = 0.0 for p in p_list: if p == 0.0: continue E += p*math.log(p) return E
[ "def entropy(p):\n h = 0\n\n # TODO -- Calculate entropy value in nats for probability distribution `p`\n for x in p:\n h -= p[x] * math.log(p[x])\n\n return h", "def entropy_of_a_list(values):\n counts = Counter(values).values()\n total = float(sum(counts))\n probabilities = [val / to...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For a list of dictionaries mapping values to counts, returns a cost used for DT splitting that is optimal at 0. Currently uses the negative of information gain.
def split_cost(label_count_list): return -split_information_gain(label_count_list) #this cost value is the misclassification error. return split_misclassification_error(label_count_list)
[ "def cost(foods, foods_used):\n cost = 0.00\n for i, count in foods_used.items():\n cost += (foods[i]['serving_cost'] * count)\n return cost", "def cost_fun(self, specs_dict: Dict[str, float]) -> float:\n cost = 0\n for spec in self.spec_range.keys():\n penalty = self.comp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a list of values and associated labels, optimizes the best split threshold z where dividing the values into z has the lowest split cost. Returns a pair (z,cost) where cost is the split_cost of the threshold z. If nonelabels is given, this indicates the labels of missing values that must be passed down to both sub...
def best_split(values,labels,nonelabels=None): assert len(values) >= 2 assert len(values) == len(labels) N = len(values) ilist = sorted((v,l) for (v,l) in zip(values,labels)) leftcount = defaultdict(int) rightcount = defaultdict(int) for v,l in ilist: rightcount[l] += 1 bestindex...
[ "def split_cost(label_count_list):\n return -split_information_gain(label_count_list)\n #this cost value is the misclassification error.\n return split_misclassification_error(label_count_list)", "def pick_best_split(self,db,labels,ids,features=None):\n idlabels = [labels[id] for id in ids]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Looks up the leaf node corresponding to the given entry. Does not handle missing values.
def lookup(self,entry): if self.type == 'v': return self v = entry[self.feature] assert v != None if self.type == 's': c = None try: c = self.children[v] except KeyError: #print "Unseen value for feature",sel...
[ "def build_node_from_entry(self, entry):\n if entry is None:\n mess = \"Object browser entry expected, %s found\" % entry\n raise ValueError(mess)\n node = Node(self.sstd, self.sbld, entry)\n sobj = node.get_sobj()\n if sobj.GetID() == sobj.GetFatherComponent().GetI...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a indexed database db, a list of labels (one for each id), and a list of ids to test, sets this node to the best label.
def pick_best_label(self,db,labels,ids): self.type = 'v' if len(labels) > 0: self.value = vote([labels[id] for id in ids]) else: self.value = None return
[ "def learn(self,db,labels):\n self.keys = db.keys[:]\n labelindex = -1\n if isinstance(labels,str):\n labelindex = db.keys.index(labels)\n assert labelindex >= 0,\"label does not exist in database keys\"\n labels = db.get_column(labelindex)\n elif isinsta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given an index database db, a list of labels (one for each id), and a list of ids to train on, computes the optimal split value. It modifies this node to have the optimal split type and value, and then returns the quality of the split as computed by the split_cost function. If features != None, it is a list of availabl...
def pick_best_split(self,db,labels,ids,features=None): idlabels = [labels[id] for id in ids] if misclassification_error(idlabels) == 0: #base case: no misclassifications self.type = 'v' self.value = idlabels[0] return 0 best = None bestCost...
[ "def __get_split_feature(self, data_set, target_feature, tree_features):\n\n if self.__criterion == 'entropy':\n feature_gains = {feature: self.__gain(data_set, feature, target_feature) for (feature) in tree_features}\n split_feature = max(feature_gains, key=feature_gains.get)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Learns from a Database instance. Each entry is given a label.
def learn(self,db,labels): self.keys = db.keys[:] labelindex = -1 if isinstance(labels,str): labelindex = db.keys.index(labels) assert labelindex >= 0,"label does not exist in database keys" labels = db.get_column(labelindex) elif isinstance(labels,int...
[ "def save_data_to_db(labelled):\n add_query = sqlite3.connect(DB_PATH).cursor()\n add_query.execute(\n \"CREATE TABLE IF NOT EXISTS labels(text TEXT, label TEXT, score FLOAT)\")\n for entry in labelled:\n add_query.execute(\"\"\"INSERT INTO labels(text,label,score) VALUES(?,?,?)\"\"\",\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a indexed database, greedily and recursively learns the split value for the subtree of the indicated node. Return value is the number of mistakes made by the decision tree. Missing values are handled properly as indicating a 'don't care' value that gets passed down to both sides of the tree.
def greedy_learn(self,node,db,labels,ids): if node.depth >= self.maxdepth or len(ids) <= self.minexamples: #terminate recursion node.pick_best_label(db,labels,ids) err = misclassification_error([labels[id] for id in ids]) if err > 0: print "Reached...
[ "def count_splits_on_tree(self, tree):\n if self.taxon_set is None:\n self.taxon_set = tree.taxon_set\n else:\n assert tree.taxon_set is self.taxon_set\n self.total_trees_counted += 1\n if not self.ignore_node_ages:\n tree.calc_node_ages()\n for sp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Identifies the list of example indices that would follow the decision tree to node.
def identify_examples(self,db,labels,node): path = [] while node.parent != None: nkey = None for (k,c) in node.parent().children.iteritems(): if c is node: nkey = k break assert nkey != None path.appe...
[ "def indices(self):", "def list_indices(self):", "def target_nodes_indexes(self) -> _TargetNodes:\n return self.__target_nodes_indexes", "def reference_nodes_idx(self) -> Dict[str, torch.Tensor]:\n return self.node_idx_references", "def getResultIdx(self):\n return [ element.idx for ele...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Same as greedy learn, but with a maximum number of nodes. Rather than a DFS, this uses a priority queue that at each step splits the node with the maximum improvement in misclassification error. At most maxnodes are in the resulting tree, and the depth is limited to maxdepth. Returns the total number of misclassificati...
def greedy_learn_search(self,db,labels): queue = PriorityQueue() dolowmem = (self.lowmem == True) numidsets = 0 root_ids = range(len(labels)) queue.push((self.root,root_ids),len(labels)) numnodes = 1 deepest = 0 err = 0 while len(queue) > 0 and num...
[ "def max_node_count(self) -> int:\n return pulumi.get(self, \"max_node_count\")", "def node_count_max(self) -> int:\n return int(self.graph_tuple_stats.node_count_max or 0)", "def max_nodes(self):\n return self._max_nodes", "def max_nodes(self) -> int:\n return pulumi.get(self, \"max_n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes the list. If entries is given, this initializes the entries of the list. If memoized = True, any lazy evaluated entries are saved after their first evaluation.
def __init__(self,entries=None,memoized=False): if entries is not None: self.entries = entries[:] else: self.entries = [] self.memoized = memoized
[ "def __init__(self, contents=()):\n self._data = [self._Item(k, v) for k, v in contents]\n if self._data:\n self._heapify()", "def __init__(self, entries=None):\n ## Mark the start timestamp:\n self._started_at = datetime.datetime.now()\n self._finished_at = None\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the template tag js_settings
def test_js_settings(mocker, rf): mocker.patch( "mitxpro.templatetags.js_interop.get_js_settings", return_value={"data": "value"}, ) request = rf.get("/") context = Context({"request": request}) template = Template(("{% load js_interop %}" "{% js_settings %}")) rendered_templat...
[ "def jssettings(self):\n self.update()\n return \"var %s = %s\" % (self.js_var_settings_name,\n json.dumps(self.settings))", "def test_jssettings(self):\n settings_fullpath = os.path.join(dirs.get_main_js_dir(), \"mediabrute-settings.js\")\n \n i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function computes the fundamental matrix by computing the SVD of Ax = 0 ; 8point algorithm
def computeFundamentalMatrix(pts1, pts2): A = np.empty((8, 9)) for i in range(len(pts1)-1): x1 = pts1[i][0] x2 = pts2[i][0] y1 = pts1[i][1] y2 = pts2[i][1] A[i] = np.array([x1 * x2, x2 * y1, x2, y2 * x1, y2 * y1, y2, x1, y...
[ "def svd0(A):\n M,N = A.shape\n if M>N: return sla.svd(A, full_matrices=True)\n else: return sla.svd(A, full_matrices=False)", "def _nullSpaceBasis(A):\n if A.any():\n U, s, Vh = la.svd(A)\n vecs = np.array([])\n toAppend = A.shape[1] - s.size\n s = np.append(s, zeros((1, toApp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Leverages the 8point algorithm and implement RANSAC algorithm to find the inliers and the best fundamental matrix
def getInlierRANSAC(pts1, pts2): # global finalFundamentalMatrix iterations = 50 threshold = 0.01 max_count = 0 n = len(pts1) finalFundamentalMatrix = np.zeros((3, 3)) for i in range(iterations): count = 0 idx = random.sample(range(n - 1), 8) left_pts = pts1[idx] ...
[ "def evaluation(result, reference, verbose=0):\n # get column signals\n Ar = reference[0].copy()\n Sr = reference[1].T.copy()\n noise = reference[2].T.copy()\n Ae = result[0]\n Se = result[1].T\n r = Sr.shape[1]\n # set nan values to 0\n Ar[np.isnan(Ar)] = 0\n Sr[np.isnan(Sr)] = 0\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function computes the essential matrix from the fundamental matrix. The E matrix is defined in normalized image coordinates
def getEssentialMatrix(K, F): E = np.dot(K.T, np.dot(F, K)) u, s, v = np.linalg.svd(E) # We correct the singular values of the E matrix s_new = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 0]]).reshape(3, 3) final_E = np.dot(u, np.dot(s_new, v)) return final_E
[ "def calc_eigendecomp(self):\n self.evals, self.evecs = np.linalg.eigh(self.sub_matrix)", "def energyMatrix(image):\n gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)\n sobelX = cv.Sobel(gray, cv.CV_64F,1,0)\n sobelY = cv.Sobel(gray, cv.CV_64F,0,1)\n engMatrix = np.abs(sobelX) + np.abs(sobelY)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given the essential matrix, we derive the camera position and orientation
def ExtractCameraPose(E): u, s, v = np.linalg.svd(E, full_matrices=True) w = np.array([[0, -1, 0], [1, 0, 0], [0, 0, 1]]).reshape(3, 3) c1 = u[:, 2].reshape(3, 1) r1 = np.dot(np.dot(u, w), v).reshape(3, 3) c2 = -u[:, 2].reshape(3, 1) r2 = np.dot(np.dot(u, w), ...
[ "def get_camera_orientation(self):\n\n # Create the vector from the camera to the robot\n vector_x = self.robot_x - self.camera_x\n vector_y = self.robot_y - self.camera_y\n vector_z = self.robot_z - self.camera_z\n\n # Calculate yaw and pitch from this vector\n yaw = math....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function returns the extrinsic parameter matrix
def getExtrinsicParameter(K, R, C): t = np.dot(-R, C) homogeneous_matrix = np.hstack((R.reshape(3, 3), t)) extrinsic_parameter = np.dot(K, homogeneous_matrix) return extrinsic_parameter
[ "def get_extM(self):\n ext_mat = np.array([\n [0, 1, 0],\n [0, 0, 1],\n [1, 0, 0]]) @ np.hstack((self.R.T, -self.R.T @ self.T)) # extrinsic matrix (rows re-aligned)\n return ext_mat", "def get_model_parameters(self):\n return np.atleast_2d(self.cost_model.get_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
removes all Hydrogen atoms from instance
def remove_hydrogens(self) -> None: for cid, c in self: for rid, r in c: for aid, a in r: if a.element == 'H': print('removing H at %s' % aid) r.remove_atom(a)
[ "def delete(self):\n del self.shx.atoms[self.index]", "def strip(self):\n types = [type(self.strip),\n type(self.values),\n type(self.__ne__),\n type(self.__class__)]\n\n for attr in dir(self):\n if not type(getattr(self, attr)) in ty...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
collect a set of residues with memb_z within [15, 15]
def memb_residues(pdb: MyPDB) -> list(): result = [] for ch in pdb.chains.values(): for res in ch.values(): if res.memb_z is not None: result.append(res) return result
[ "def residues(atoms):\n residues = dict([ [j,[]] for j in set([i['resid'] for i in atoms]) ])\n for i in range(len(atoms)):\n residues[atoms[i]['resid']].append(i)\n return residues", "def getLigandNbrs(resids: List[Residue], struct:Structure)->List[ResidueDict]:\n\n ns = NeighborSearch(list...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes indicating root Python module. The application will look for all `Resource` classes defined in the given root module.
def __init__(self, root): self._root = root if not self.get_resources(): raise Exception('Your application has no Resource.')
[ "def initAll(cls):\n for dir in os.environ['MODULEPATH'].split(':'):\n if not os.path.exists(dir):\n continue\n for subdir in os.listdir(dir):\n subdirPath = \"%s/%s\" % (dir, subdir)\n if not os.path.isdir(subdirPath):\n continue\n for file in os.listdir(subdirPath...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unnormalize a given image.
def unnormalize(self, image, transpose=False): return unnormalize(image, self.mean, self.std, transpose)
[ "def normalise(image):", "def reverse_normalize(image):\n\n reverse = transforms.Normalize(mean=[-0.485 / 0.229, -0.456 / 0.224, -0.406 / 0.255],\n std=[1 / 0.229, 1 / 0.224, 1 / 0.255])\n return reverse(image)", "def inverse_normalize(img):\n if opt.caffe_pretrain:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle imbalanced dataset through sampler.
def create_class_imbalance_sampler(self): count = [0] * len(self.classes) for item in self.train_data.imgs: count[item[1]] += 1 weight_per_class = [0.] * len(self.classes) for i in range(len(self.classes)): weight_per_class[i] = float(sum(count)) / float(...
[ "def balanced_sampling(dat: pd.DataFrame, logger=None):\n if logger == None:\n logging.basicConfig(\n level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n logger = logging.getLogger(__name__)\n \n \n # upsampling\n logger.info('Start balanced s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the selected locale from user settings.
def get_locale(): setting = Setting.query.filter(Setting.name == 'default_language').first() if setting is not None: return setting.value # Return default language when none found return 'en'
[ "def _get_locale(self):\n context = self.context\n locales = {\n 'en': 'en_GB',\n 'de': 'de_DE'\n }\n language = context.language if context.language else 'en'\n return locales.get(language)", "def _get_user_locale():\n if 'Windows' in platform.system():...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decodes a Base58Check encoded key.
def from_b58check(key): return HDKey.from_bytes(base58.b58decode_check(key))[0]
[ "def base58_decode(v: bytes) -> bytes:\n try:\n prefix_len = next(\n len(encoding[2])\n for encoding in base58_encodings\n if len(v) == encoding[1] and v.startswith(encoding[0])\n )\n except StopIteration:\n raise ValueError('Invalid encoding, prefix or le...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates either a HDPrivateKey or HDPublicKey from the underlying bytes.
def from_bytes(b): if len(b) < 78: raise ValueError("b must be at least 78 bytes long.") version = int.from_bytes(b[:4], 'big') depth = b[4] parent_fingerprint = b[5:9] index = int.from_bytes(b[9:13], 'big') chain_code = b[13:45] key_bytes = b[45:78] ...
[ "def generate_ecdh_key_pair() -> tuple[X25519PrivateKey, bytes]:\n private_key = X25519PrivateKey.generate()\n public_key_raw = private_key.public_key().public_bytes(\n serialization.Encoding.Raw, serialization.PublicFormat.Raw\n )\n return private_key, public_key_raw", "def decode_public_key(b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Whether or not this is a hardened node. Hardened nodes are those with indices >= 0x80000000.
def hardened(self): # A hardened key is a key with index >= 2 ** 31, so # we check that the MSB of a uint32 is set. return self.index & 0x80000000
[ "def isItFreeNode(self):\n for c in self.children:\n if c:\n return False\n return True", "def is_dedicated_node(self):\n return self.is_node() and not self.is_master()", "def has_extra_nodes(self):\n return (self.n_edge_nod + self.n_face_nod + self.n_bu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the key's fingerprint, which is the first 4 bytes of its identifier.
def fingerprint(self): return self.identifier[:4]
[ "def key_fingerprint(self):\n return self._key_fingerprint", "def fingerprint(public_key):\r\n\r\n return hashlib.new('ripemd160', hashlib.sha256(public_key).digest()).digest()[:4]", "def fingerprint(self, key):\n base64_pub = self.base64_pub_encode(key)\n return SHA256.new(base64_pub.en...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get inventory list from config files builds a NetworkRunner inventory object and a mac_map dictionary according to ansible inventory file yaml definition
def __init__(self): self.inventory = {} self.mac_map = {} for conffile in CONF.config_file: # parse each config file sections = {} parser = cfg.ConfigParser(conffile, sections) try: parser.parse() except IOError as e: ...
[ "def main():\n with open('group_vars/all.yaml', 'r') as file:\n config = yaml.safe_load(file)\n\n if not os.path.exists('host_vars'):\n os.makedirs('host_vars')\n\n nso_ip = config['nso']['ip']\n username = config['nso']['username']\n password = config['nso']['password']\n nso = NSO(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for get_liveness Get job service liveness
def test_get_liveness(self): response = self.client.open('/api/v1//liveness', method='GET', content_type='application/json') self.assert200(response, "Response body is : " + response.data.decode('utf-8'))
[ "def test_liveness(client):\n response = client.get(api_route_for(\"liveness\"))\n assert response.status_code == 200\n json_data = get_json_from_response(response)\n assert json_data == {}", "def test_get_refresh_job_status(self):\n pass", "def liveness():\n return jsonify({}), 200", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for get_readiness Get job service readiness
def test_get_readiness(self): response = self.client.open('/api/v1//readiness', method='GET', content_type='application/json') self.assert200(response, "Response body is : " + response.data.decode('utf-8'))
[ "def test_get_refresh_job_status(self):\n pass", "def readiness():\n return run_health_check()", "def test_readiness(client):\n response = client.get(api_route_for(\"readiness\"))\n assert response.status_code == 200\n json_data = get_json_from_response(response)\n assert json_data == {}",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
=============================================================== save_obj(obj, saved_name ) =============================================================== this function is used to save any python object to your hard desk
def save_obj(obj, saved_name ): with open( saved_name + '.pkl', 'wb') as f: pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
[ "def saveObject(obj):\r\n\r\n name = QtWidgets.QFileDialog.getSaveFileName(mw,'Save File','New SDE.sde',\r\n 'SDE-file *.sde')\r\n name = name[0]\r\n name = name.split('/')[-1]\r\n print(\"Save, name: \",name)\r\n with open(name,'wb') as output:\r\n pickle.dump(obj, output, -1)", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
=============================================================== load_obj(saved_name) =============================================================== this function is used to save any python object to your hard desk
def load_obj(saved_name): with open( saved_name + '.pkl', 'rb') as f: return pickle.load(f)
[ "def save_obj(obj, saved_name ):\n with open( saved_name + '.pkl', 'wb') as f:\n pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)", "def pickle_object(obj, name):\n with open(name+\".pkl\", 'wb') as f:\n pickle.dump(obj, f)", "def load_obj(name):\n with open('../../data/' + name + '.pkl', 'rb...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
=========================================================== DateFormatedSQL(x) =========================================================== this function converts the the date read from a list to a datetime format
def DateFormatedSQL(x): x=[i[0] for i in x] x1=[] for i in x: if len(i)==19: x1.append(datetime.datetime(int(i[:4]),int(i[5:7]),int(i[8:10]),int(i[11:13]),int(i[14:16]),int(i[17:18]) )) # elif len(i)==13: # x1.append(datetime.datetime(int(i[:4]),int(i[5:7]),int(i[8...
[ "def mapillary_to_sql_date(date):\r\n date_sql = date[:10] + \" \" + date[11:13] + \":\" + date[14:16] + \":\" + date[17:]\r\n return date_sql", "def change_format_from_input_to_datetime(list_d_t_t):\n data_output = []\n\n for row in list_d_t_t:\n data_output.append([datetime.datetime.strptime(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
=========================================================== dateformated(x) =========================================================== this function converts the the date read from a list to a datetime format
def DateFormated(x): x1=[] for i in x: if len(i)==19: x1.append(datetime.datetime(int(i[:4]),int(i[5:7]),int(i[8:10]),int(i[11:13]),int(i[14:16]),int(i[17:18]) )) # elif len(i)==13: # x1.append(datetime.datetime(int(i[:4]),int(i[5:7]),int(i[8:10]),int(i[11:13]),int(0),...
[ "def change_format_from_input_to_datetime(list_d_t_t):\n data_output = []\n\n for row in list_d_t_t:\n data_output.append([datetime.datetime.strptime(row[0] + \" \" + row[1], \"%Y-%m-%d %H:%M:%S\"),\n datetime.datetime.strptime(row[0] + \" \" + row[2], \"%Y-%m-%d %H:%M:%S\")]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if a record exists matching the service pattern with the current host's ip
def record_exists(route53_zone, service_name, ip): # Match records belonging to the service for particular service and # environment. match_regex = "{}\d+\.{}\.?".format(service_name, route53_zone.name) for record in route53_zone.get_records(): match = re.match(match_regex, record.name) ...
[ "def _record_exists(self, cusip, dt):\n where_str = \"(cusip == '{}') & (as_of_date == {})\"\n if not isinstance(dt,int):\n dt = time.mktime(dt.timetuple())\n p_data = self.pools_table.read_where(where_str.format(cusip, dt))\n return p_data.shape[0] > 0", "def check_if_ip_ex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates record with record_name and ip; updates record if it already exists with different ip does nothing if record already exists with same ip
def upsert_record(route53_zone, record_name, ip): # Only upsert the dns record if it doesn't resolve to us. try: record_ip = socket.gethostbyname(record_name) except socket.error: # Ignore if we can't connect to the host pass else: if ip == record_ip: return ...
[ "def _update_record(self, record_name, ip):\n if ((not hasattr(self, '_current_zone')) or (not self._current_zone)) or ((not hasattr(self, '_new_zone_version_number')) or (not self._new_zone_version_number)):\n raise GandiApiException(\"Can't update record, no cloned zone available.\")\n \n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new EC2 instance with specific parameters SecurityGroup (sg) and KeyPair (key) have to be previously created (see cassandgo initSG and cassandgo initKP)
def createInstance(ec2,ami,nb_nodes,placement,instance_type,key,sg,user_data=None): reservation = ec2.run_instances(ami,min_count=nb_nodes,max_count=nb_nodes,placement = placement,key_name=key,security_groups=[sg],instance_type=instance_type,user_data=user_data) instance = reservation.instances[0] return i...
[ "def create_instance(ami, sg_name):\n instance = None\n ec2 = boto3.resource('ec2',region_name=\"us-east-1\")\n # TODO: Create an EC2 instance\n # Wait for the instance to enter the running state\n # Reload the instance attributes\n\n try:\n instance = ec2.create_instances(\n ImageId...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List all instances for a specific region and zone
def listInstancesRegionZone(region,zone): print "-"*80 print "# Region :",region," Zone", zone print "-"*80 instances = getInstancesRegionZone(region,zone) if instances: for instance in instances: print "[",instance.ami_launch_index,"]",instance.ip_address," (",instance.private_ip_address,") ",instance.insta...
[ "def instances_by_region(aws_region=config.AWS_AWS_REGION):\n instances = _get_instances(aws_region)\n formatter = InstanceFormatter(instances)\n formatter.display()", "def get_instances(self, region):\n try:\n conn = ec2.connect_to_region(region, **self.credentials)\n region...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create all Cassandra security groups in all regions
def createAllSG(): for info in conf_HVM: ec2 = boto.ec2.connect_to_region(info['region']+'-'+info['zone']) createSG(ec2,'SG-Cassandra-'+info['region']+'-'+info['zone'],CASSANDRA_RULES)
[ "def _create_allow_all_security_group(self):\n pass", "def create_auth_groups ():\n auth_group_list = ['Cores', 'Coords', 'Vols', 'Super-Coords']\n for auth_group_name in auth_group_list:\n create_auth_group (auth_group_name)\n print 'Group %s created' %(auth_group_name)", "def create...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create all key pairs in all regions
def createAllKP(): if not os.path.exists(keysDir): os.makedirs(keysDir) for info in conf_HVM: keyName = 'Key-'+info['region']+'-'+info['zone'] try: os.remove(keysDir+'/'+keyName+'.pem') except OSError: pass print "Key creation :",keyName ec2 = boto.ec2.connect_to_region(info['region']+'-'+info['zone...
[ "def createAllSG():\n\tfor info in conf_HVM:\n\t\tec2 = boto.ec2.connect_to_region(info['region']+'-'+info['zone'])\n\t\tcreateSG(ec2,'SG-Cassandra-'+info['region']+'-'+info['zone'],CASSANDRA_RULES)", "def setup_space_keys(cls):\n if cls.KEYS:\n return\n\n from pkg_resources import iter_e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Interpret for left != right
def _op_ne(self, left: Any, right: Any) -> BoolOrIter: out = self._op_eq(left, right) if isinstance(out, (numpy.ndarray, Series)): neout = ~out # neout[pandas.isna(out)] = numpy.nan return neout # out is always a numpy.ndarray return not out # pragma:...
[ "def nexact(cls, lhs, rhs):\n return lhs != rhs", "def match_LR(left,right):\n\n if left[1] == right[3][::-1]:\n return True\n\n return False", "def __ne__(self, other):\n return tf.math.not_equal(self._ordinals, other.ordinal())", "def same_level(left, right):\n for i in range(min(l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recycle left right operands to each other
def _recycle_left_right(left: Any, right: Any) -> Tuple: try: left = recycle_value(left, length_of(right)) except DataUnrecyclable: right = recycle_value(right, length_of(left)) return left, right
[ "def right_func(self, left):\n if self.right is None:\n if self.left is None:\n new = copy(self)\n new.left = left\n return new\n else:\n raise SyntaxError(\"Infix operator already has its \"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the sparsity penalty on network activations combined as a sum
def get_sparsity_penalty(nnet, inputs, sparsity, mode="mean", deterministic=False): assert mode in ("mean", "l1") rho = sparsity penalty = 0 eps = 0.0001 # for numerical stability for layer in nnet.all_layers: if layer.isactivation: activation = lasa...
[ "def sparsity_penalty(rbm, hidden_units, v0_vmap, target):\n # complete units lists\n hidden_units = rbm.complete_units_list(hidden_units)\n \n # complete the supplied vmap\n v0_vmap = rbm.complete_vmap(v0_vmap)\n \n hidden_vmap = rbm.mean_field(hidden_units, v0_vmap)\n\n penalty_terms = []\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the offset to balance the polynomial parameters possible by the bias terms of the network.
def get_bias_offset(nnet): offset = 0 L = len(nnet.trainable_layers) for l in range(L-1): layer = nnet.trainable_layers[l] if layer.b is not None: W_prod = T.eye(int(layer.b.shape.eval()[0])) for k in range(1, L-1): W_prod = T.dot(nnet.trainable_la...
[ "def _get_bias(self) -> JTensor:\n p = self.params\n b = self.local_theta().b\n if p.forget_gate_bias != 0.0:\n b = b + self.get_adjustment()\n\n return b", "def get_bias(self):", "def getbias(x, bias):\n return x / ((1.0 / bias - 2.0) * (1.0 - x) + 1.0 + 1e-6)", "def GetBiasVector(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create a OCSVM loss for network given in argument with rho=1 fixed
def compile_update_ocsvm_rho_fixed(nnet, inputs, targets): floatX = Cfg.floatX C = Cfg.C nu = Cfg.nu if len(nnet.all_layers) > 1: feature_layer = nnet.all_layers[-2] else: feature_layer = nnet.input_layer final_layer = nnet.ocsvm_layer trainable_params = lasagne.layers.get_...
[ "def loss_creator(config):\n return torch.nn.BCELoss()", "def heteroscedastic_loss(network, params, x):\n\n pred_mean, pred_var = network(x)\n logvar = tf.reduce_sum(0.5 * tf.math.log(pred_var), axis=-1)\n squared_error = tf.reduce_sum(0.5 * tf.math.square(params - pred_mean) / pred_var, axis=-1)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create a SVDD loss for network given in argument
def compile_update_svdd(nnet, inputs, targets): floatX = Cfg.floatX B = Cfg.B C = Cfg.C nu = Cfg.nu # initialize R if nnet.R_init > 0: nnet.Rvar = shared(floatX(nnet.R_init), name="R") else: nnet.Rvar = shared(floatX(1), name="R") # initialization with R=1 # Loss ...
[ "def tv_loss(x, name='tv_loss'):\n raise NotImplementedError(\"Please use tensorflow total_variation loss.\")", "def loss_der(network_y, real_y):\n return (network_y - real_y)", "def train_loss(wb_vect, unflattener):\n wb_struct = unflattener(wb_vect)\n n_graphs = 100\n\n samp_graphs, samp_inputs...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create autoencoder Theano update for network given in argument
def create_autoencoder(nnet): floatX = Cfg.floatX B = Cfg.ae_B C = Cfg.ae_C ndim = nnet.data._X_train.ndim if ndim == 2: inputs = T.matrix('inputs') elif ndim == 4: inputs = T.tensor4('inputs') final_layer = nnet.all_layers[-1] # Backpropagation trainable_params =...
[ "def build_full_conv_autoencoder():\n input_img = Input(shape=(84, 84, 3))\n\n x = Convolution2D(48, 8, 8, activation='relu', border_mode='same', name='c1')(input_img)\n x = MaxPooling2D((2, 2), border_mode='same')(x)\n x = Convolution2D(32, 4, 4, activation='relu', border_mode='same', name='c2')(x)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests gotoField if there is a mismatch between MCP and guider.
def test_goto_field_cartridge_mismatch(self): sopTester.updateModel('guider', TestHelper.guiderState['bossLoaded']) mcpState = TestHelper.mcpState['boss_science'] mcpState.update({'instrumentNum': [15]}) sopTester.updateModel('mcp', mcpState) cmdState = self.actorState.gotoFie...
[ "def field_reached(self):\r\n try:\r\n if abs(self.actual_field - self.goto_field) < 0.0001:\r\n return True\r\n else:\r\n return False\r\n except Exception,e:\r\n log(\"Couldn't determine if field reached!\",e)\r\n return False...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }