query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Return a dictionary of crime categories and sum of crimes. | def get_crimes_by_category(self):
result = {}
for crime in self.crimes:
cat_name = crime.category.category_name
if cat_name in result:
result[cat_name] += 1
else:
result[cat_name] = 1
return result | [
"def sum_crimes(cs:CrimeStatistics)-> int:\n # return 0 # stub\n #template from atomic\n crimes_total = (cs.violent_crimes+cs.property_crimes+cs.arson)\n return crimes_total",
"def get_coordinates_by_category(self):\n\n result = {}\n for crime in self.crimes:\n cat_name = crim... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a dictionary of crime categories and list of coordinates. | def get_coordinates_by_category(self):
result = {}
for crime in self.crimes:
cat_name = crime.category.category_name.strip()
if cat_name in result:
result[cat_name].append((crime.latitude, crime.longitude))
else:
result[cat_name] = [(c... | [
"def get_crimes_by_category(self):\n\n result = {}\n for crime in self.crimes:\n cat_name = crime.category.category_name\n if cat_name in result:\n result[cat_name] += 1\n else:\n result[cat_name] = 1\n \n return resu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return the route id | def get_route_id(self):
return self.route_id | [
"def GetID(self):\n return self.Route_ID",
"def express_route_id(self) -> str:\n return pulumi.get(self, \"express_route_id\")",
"def RouteID(self):\n route_id = self.SR\n if self.RRT:\n route_id += self.RRT\n if self.RRQ:\n route_id += self.RRQ\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make causal mask used for bidirectional selfattention. | def _make_causal_mask(
input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
):
bsz, tgt_len = input_ids_shape
mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
mask_cond = torch.arange(mask.size(-1), device=device)
mask.mas... | [
"def _gen_cmask(self):\n self.mask_images = gen_coron_mask(self)",
"def causal_mask(input_t: JTensor) -> JTensor:\n assert (input_t.dtype == jnp.float32 or\n input_t.dtype == jnp.bfloat16), input_t.dtype\n large_negative_number = _get_large_negative_number(input_t.dtype)\n t = input_t.shape[1]\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Rotates half the hidden dims of the input. | def rotate_half(x):
x1 = x[..., : x.shape[-1] // 2]
x2 = x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=-1) | [
"def rotate_half(x):\n x1 = x[..., : x.shape[-1] // 2].clone()\n x2 = x[..., x.shape[-1] // 2 :].clone()\n return torch.cat((-x2, x1), dim=-1)",
"def _fix_dimension(self, rot: tf.Tensor) -> tf.Tensor:\n even_n = [i for i in range(0, self.circuit_model.nqubit * 2, 2)]\n odd_n = [i for i in r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a gaussian random number | def _get_gaussian_random(self):
u1 = generateRandom()
u2 = generateRandom()
if u1 < 1e-6:
u1 = 1e-6
return sqrt(-2 * log(u1)) * cos(2 * pi * u2) | [
"def gaussian_samp(self):\n s = sample()\n rand = np.random.normal(np.zeros(self.values.shape[0]), 0.5)\n for p in range(rand.shape[0]):\n s.c[p]=min(max(int(self.c[p]+0.5+rand[p]),0),self.max[p]-1)\n return s",
"def gauss(self, sigma):\n return np.random.normal(loc=0... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the displacement texture, storing the 3D Displacement in the RGB channels | def get_displacement_texture(self):
return self.displacement_tex | [
"def make_gradient(img):\n color_array = np.mean(pygame.surfarray.pixels3d(pygame.image.load(img)), axis=1)\n return ColorGradient(color_array)",
"def rgb_image(self):\n z3 = self.z[:,:,newaxis]\n return z3 * self.c",
"def gen3DTexture(self):\n\t\tif self.texture3d_name == 0:\n\t\t\tdata_cop... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the normal texture, storing the normal in world space in the RGB channels | def get_normal_texture(self):
return self.normal_tex | [
"def normal(self):\n normal = np.array(\n [\n self.center[0],\n self.center[1],\n self.center[2]-1,\n self.center[3],\n ]\n )\n return normal",
"def world_normal_images(self):\n if not hasattr(self, '_world_n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert (rows, cols) raster row and column indices to geographic coordinates based on the affine transformation of the raster. | def rowcol_to_xy(rows, cols, affine):
# make it a 3x3 matrix
aff_array = numpy.array(affine).reshape((3, 3))
# check that rows amd cols are indeed 1-D vectors
rows = validate.is_vector(rows)
cols = validate.is_vector(cols)
# filler
layers = numpy.ones_like(rows)
vector = numpy.array([... | [
"def __affine_geo_transformation(x, y, gtr):\n\n # https://gdal.org/user/raster_data_model.html#affine-geotransform\n # Affine transformation rewritten for rasterio:\n gtr_x = gtr[2] + (x + 0.5) * gtr[0] + (y + 0.5) * gtr[1]\n gtr_y = gtr[5] + (x + 0.5) * gtr[3] + (y + 0.5) * gtr[4]\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert (x, y) coordinates to raster column and row indices based on the affine transformation of the raster. | def xy_to_rowcol(x, y, affine):
# affine might be an Affine object, might be 3x3 array or
# 9-element vector. Let's first make damn sure is a 9-element
# vector
aff_array = numpy.array(affine).reshape(9)
# now be damn sure we have an Affine object, and reverse it to
# go from coordinates to ind... | [
"def pixel2coord(self, x, y):\n # NEED TO CHANGE TO USE INVERSE TRANSFORM COEFFS\n # partly taken from Sean Gillies \"affine.py\"\n a,b,c,d,e,f = self.coordspace_transform\n det = a*e - b*d\n idet = 1 / float(det)\n ra = e * idet\n rb = -b * idet\n rd = -d * i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
gets api credentials using keyring returns a list [user name, password] | def get_credentials(service_name="dataforSeo", uname="matteo.jriva@gmail.com"):
pw = keyring.get_password(service_name, uname)
return [uname, pw] | [
"def GetCreds():\n\n _username = input(\"Router username: \")\n _password = getpass(\"Password for {}: \".format(_username))\n return [_username, _password]",
"def get_username_and_password():\n\n user_credentials = dict()\n user_credentials['username'] = GAMEBENCH_CONFIG['username']\n user_cred... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
checks connection with api by verifying error codes and number of tasks between post_data/requests and response | def check_api_connection(post_data, response) -> list:
# check status code
if response['status_code'] != 20000:
raise ConnectionError(f"Status code is not ok: {response['status_message']}")
# check
id_list = []
for a, b in zip(post_data.values(), response['tasks']):
if a['keyword'] !... | [
"def check_error(failure):\n failure.trap(ConnectionRefusedError, ResponseNeverReceived)\n return False",
"def test_too_many_requests_details(self):\n setup_routing(self.edr_api_app, func=response_code)\n setup_routing(self.edr_api_app, path='/1.0/subjects/2842335', fun... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert an object serialization that was generated by the object serializer into a vocabulary handle. | def deserialize(self, descriptor: Dict, data: List) -> ObjectHandle:
return VocabularyHandle(
values=set(data),
name=descriptor['name'],
namespace=descriptor['namespace'],
label=descriptor.get('label'),
description=descriptor.get('description')
... | [
"def test_serialize_vocabulary():\n # Serialize minimal vocabulary handle.\n v = VocabularyHandle(values={'A', 'B', 'C'}, name='my_vocab')\n doc, data = VocabularyFactory().serialize(v)\n vocab = VocabularyFactory().deserialize(descriptor=doc, data=data)\n assert vocab.name == 'my_vocab'\n assert ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the mewe estimator for misspecified models Inputs | def mewe_misspecified(M,N,m,n,target):
output = []
for k in tqdm(range(0,M)):
# Allocate space for output
mewe_store = np.zeros((len(n),target['thetadim']))
mewe_runtimes = np.zeros(len(n))
mewe_evals = np.zeros(len(n))
# generate all observations and sets of randomness to be used
if targe... | [
"def MetabolicEP(b, S, D, KK, KB, unc_rvLoc, unc_rvVar, priorLoc, priorVar, conLoc, \n conVar, lbs, ubs, factor, mseThreshold = 1e-06, minVar = 1e-50, maxVar = 1e50, \n damp = 0.7, maxIter = 2000, GPU = True, returnCovar = False, Device = 0, \n trackFit = False, modelName = '', **params):\n if trackFit ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initiates the report object attached to the flowcell and sequencing run but not attached to any pipelines as of yet. | def __init__(self,config,key=int(-1),flowcell=None,seq_run=None,base_output_dir=None,process_name='flowcell_reports',**kwargs):
if not flowcell is None:
GenericProcess.__init__(self,config,key=key,process_name=process_name,**kwargs)
if base_output_dir == None:
self.base_o... | [
"def __init__(self) -> None:\n self._report_data = None",
"def init_report(self, report):\n report.text('warning', 'init_report() not implemented for this class.')",
"def start(self):\n self._CreateReportLinkIfNeccessary()\n shell.ShellCommand.start(self)",
"def initialize_report(output_di... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Connects the report with a pipeline by recoding the pipeline key and pipeline obj_type in a string. | def __add_pipeline__(self,pipeline):
if not re.search('Pipeline',pipeline.obj_type):
raise Exception("Trying to add non-pipeline key to flowcell statistics reports")
if not self.pipelines is None:
self.pipelines += ';'
self.pipelines += str(pipeline.key) + ":" + pipel... | [
"def format(self, pipeline):\n pipeline = pipeline.data\n if not pipeline or '__Header__' not in pipeline or pipeline['__Header__']['__Type__'] != 'CellProfiler':\n # wrong pipeline type\n return None \n return json_to_cellprofiler(pipeline)",
"def pipeline_id(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Uses the pipelines string stored in self to generate a list of pipeline objects. | def __current_pipeline_list__(self,mockdb):
pipelines = []
if self.pipelines is None:
return pipelines
pipelines_dict = self.pipelines.split(';')
for d in pipelines_dict:
pipeline_key, obj_type = d.split(':')
try:
pipeline = mockdb[obj_type].objects[... | [
"def pipelines(self) -> list:\n if not self._pipelines:\n if \"pipelines\" not in self._pipeline_definition:\n raise ValueError(\"Pipeline is missing 'pipelines' field.\")\n elif len(self._pipeline_definition[\"pipelines\"]) == 0:\n raise ValueError(\"Pipel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of sample keys associated with pipelines that have completed. | def __completed_samples_list__(self,mockdb):
sample_keys = []
for pipeline in self.__current_pipeline_list__(mockdb):
if pipeline.__is_complete__():
sample_keys.append(pipeline.sample_key)
return sample_keys | [
"def expected_log_keys(learner: adaptive.BaseLearner) -> list[str]:\n # Check if the result contains the expected keys\n expected_keys = [\n \"elapsed_time\",\n \"overhead\",\n \"npoints\",\n \"cpu_usage\",\n \"mem_usage\",\n ]\n if not _at_least_adaptive_version(\"0.1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks the number of completed samples and generates reports based on this number and what has been previously reported. Return True only if a new report object is initialized. | def __generate_reports__(self,configs,mockdb):
sample_keys = self.__completed_samples_list__(mockdb)
n = len(sample_keys)
numbers = configs['pipeline'].get('Flowcell_reports','numbers').split(',')
numbers.sort(key=int,reverse=True)
flowcell = mockdb['Flowcell'].__get__(configs['s... | [
"def has_report(self):\n return self.report is not None",
"def can_generate_report(self) -> bool:\n can_generate = True\n list_of_lines = [self.version, self.environment]\n for line in list_of_lines:\n can_generate &= not line.text() == \"\"\n list_of_plains = [self.d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fills the qsub file from a template. Since not all information is archived in the parent object, the function also gets additional information on the fly for the qsub file. | def __fill_qsub_file__(self,configs):
template_file= os.path.join(configs['system'].get('Common_directories','template'),configs['pipeline'].get('Template_files','flowcell_report'))
dictionary = {}
for k,v in self.__dict__.iteritems():
dictionary.update({k:str(v)})
dictionary... | [
"def __fill_template__(self,template_file,output_fname):\n dictionary = {}\n for k,v in self.__dict__.iteritems():\n if k == 'sample_key':\n try:\n int(v)\n new_sample_key = \"Sample_\" + str(v)\n dictionary.update({k:n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Simple test to check that raw target data does NOT leak during validation. | def test_for_leakage(self):
src, trg = next(iter(self.validation_loader))
trg_mem = trg.clone().detach()
result = greedy_decode(self.model, src, 20, trg)
self.assertNotEqual(result[0, 1, 0], trg_mem[0, 1, 0])
self.assertEqual(result[0, 1, 1], trg_mem[0, 1, 1])
self.assert... | [
"def testCheckSourceCopyOperation_FailContainsData(self):\n payload_checker = checker.PayloadChecker(self.MockPayload())\n self.assertRaises(PayloadError, payload_checker._CheckSourceCopyOperation,\n 134, 0, 0, 'foo')",
"def test_clean_data_short():\n with pytest.raises(AssertionErro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper to clear workers. | def clear_workers(self):
# seems sometimes that workers will cause
# print "calling destructor"
# first set the exit flag for each of the workers.
for worker in self.workers:
worker.no_exit = False
# next clear the queue, the workers might be waiting to add data to
... | [
"def __del__(self):\n for worker in self.workers:\n try:\n worker.delete()\n except Exception, ex:\n pass\n\n self.workers = []\n\n return",
"def reset_workers(self, workers):\n for obj_ref, ev in self._tasks.copy().items():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
listens for incoming data. calls the callback when EOL character is received or nothing more received after frame_interval delay. | def __listener__(self):
frame_interval = 0.1
str_list = []
c = ''
while True:
with Timeout(frame_interval, False):
while True:
try:
c = self.ser.read()
except:
self.ser.clo... | [
"def data_handler(self, sender, data):\n logger.debug(\"RX DATA: {0}\".format(data))\n\n # For each new character, call its handler and add to buffer if any\n for byte in data:\n append = self.char_handler(byte)\n if append is not None:\n self.char_buf.appen... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run depth first search from the start page to a specified depth (n) | def depth_first_search(self, start_page: str, n: int = 1):
url = name_to_url(start_page)
i = self.add_node(WikiNode(url, 0))
stack = deque()
stack.append(i)
while stack:
nd = self.nodes[stack.pop()]
if nd.level > n:
continue
fo... | [
"def depth_scan(self, start, criteria):\n return depth_scan(graph=self, start=start, criteria=criteria)",
"def depth_first_traversal(self, start):\n return self.recursive_dft(start, [])",
"def depth_first_traversal(self, start, end, visit, seen=None):\n\n if seen is None:\n seen ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the average kullback leiber divergences of multiple univariate gaussian distributions. K(P1,…Pk) = 1/(k(k−1)) ∑_[k_(i,j)=1] DKL(Pi||Pj) (Andrea Sgarro, Informational divergence and the dissimilarity of probability distributions.) expects the distributions along axis 0, and samples along axis 1. Output is red... | def average_dkl(mu, std):
## clip log
log_std = np.log(std)
log_std = np.clip(log_std, -100, 1e8)
assert len(mu.shape)>=2 and len(log_std.shape)>=2
num_models = len(mu)
d_kl = None
for i in range(num_models):
for j in range(num_models):
if d_kl is None:
d_... | [
"def _kld_gauss(self, mean_1, std_1, mean_2, std_2):\n kld_element = (2 * torch.log(std_2) - 2 * torch.log(std_1) + (std_1.pow(2) + (mean_1 - mean_2).pow(2)) / std_2.pow(2) - 1)\n return\t0.5 * torch.sum(kld_element)",
"def kl_divergence(self, post_logits, post_samples, is_training=True):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the median kullback leiber divergences of multiple univariate gaussian distributions. K(P1,…Pk) = 1/(k(k−1)) ∑_[k_(i,j)=1] DKL(Pi||Pj) (Andrea Sgarro, Informational divergence and the dissimilarity of probability distributions.) expects the distributions along axis 0, and samples along axis 1. Output is redu... | def median_dkl(mu, std):
## clip log
log_std = np.log(std)
log_std = np.clip(log_std, -100, 1e8)
assert len(mu.shape)>=2 and len(log_std.shape)>=2
num_models = len(mu)
d_kl = np.zeros(shape=(num_models*(num_models-1),) + mu.shape[1:])
n = 0
for i in range(num_models):
for j in r... | [
"def gmm_clustering(X, K):\n\n # Initialization:\n pi = []\n mu = []\n cov = []\n for k in range(K):\n pi.append(1.0 / K)\n mu.append(list(np.random.normal(0, 0.5, 2)))\n temp_cov = np.random.normal(0, 0.5, (2, 2))\n temp_cov = np.matmul(temp_cov, np.transpose(temp_cov))\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Caches current values of this scaler. | def cache(self):
self.cached_mu = self.mu.eval()
self.cached_var = self.var.eval()
self.cached_count = self.count.eval() | [
"def cache(self):\n self.cached_mu = self.mu.eval()\n self.cached_sigma = self.sigma.eval()",
"def _cache_values(self):\n width = self.width.current\n center = self.horizontal.current\n\n # If center would need to be rounded, increase the width by 1 to make a smoother fade betwe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads values from the cache | def load_cache(self):
self.mu.load(self.cached_mu)
self.var.load(self.cached_var)
self.count.load(self.cached_count) | [
"def load_cache(self):\n self.mu.load(self.cached_mu)\n self.sigma.load(self.cached_sigma)",
"def _load_cache(self):\n logger.debug(\"Loading coherence data for %s from cache\", self.w1)\n\n assert self.variant_unit is None, \"Cannot load from cache once variant_unit has been set\"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run spark job that will associate vendor's users (loaded from REST API) with our users (loaded from MySQL) | def run(sc, logger):
start = time.time()
# Spark SQL Context
sqlContext = sql.context.SQLContext(sc)
# 1) Practices - Small table so no need to partition it, could even broadcast across all executors
# Spark SQL JDBC Options: https://spark.apache.org/docs/latest/sql-data-sources-jdbc.html
prac... | [
"def myjob(spark: SparkSession, **kwargs):\n df = spark.read.csv(\"spark-data/climatewatch-usemissions.csv\")\n\n df.show()",
"def main():\n sc = pyspark.SparkContext(conf=sparkConf())\n sql = pyspark.SQLContext(sc)\n args = parse_args()\n cleanOutputDir(args.output)\n users = os.listdir(args... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
DB Table (user) RDD | def getUsersRDD(sqlContext):
# Currently the id field ranges from '0' to '1000000'.
# To avoid loading it all in memory, partition on the id field (100 partitions, about 10k records per partition).
# Also setting fetch size to 10,000 to avoid multiple database calls per partition.
# All records from a s... | [
"def getPracticesRDD(sqlContext):\n from db import *\n return sqlContext \\\n .read \\\n .format(\"jdbc\") \\\n .options(\n driver=driver,\n url=url,\n dbtable=\"user_practice\",\n user=user,\n password=password\n ) \\\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
DB Table (user_practice) RDD | def getPracticesRDD(sqlContext):
from db import *
return sqlContext \
.read \
.format("jdbc") \
.options(
driver=driver,
url=url,
dbtable="user_practice",
user=user,
password=password
) \
.load() \
.rdd \... | [
"def getUsersRDD(sqlContext):\n # Currently the id field ranges from '0' to '1000000'.\n # To avoid loading it all in memory, partition on the id field (100 partitions, about 10k records per partition).\n # Also setting fetch size to 10,000 to avoid multiple database calls per partition.\n # All records... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modify cherrypy.response status, headers, and body to represent self. CherryPy uses this internally, but you can also use it to create an HTTPRedirect object and set its output without raising the exception. | def set_response(self):
import cherrypy
response = cherrypy.response
response.status = status = self.status
if status in (300, 301, 302, 303, 307):
response.headers['Content-Type'] = "text/html"
# "The ... URI SHOULD be given by the Location field
... | [
"def set_response(self):\r\n import cherrypy\r\n \r\n response = cherrypy.response\r\n \r\n clean_headers(self.status)\r\n \r\n # In all cases, finalize will be called after this method,\r\n # so don't bother cleaning up response values here.\r\n respon... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove any headers which should not apply to an error response. | def clean_headers(status):
import cherrypy
response = cherrypy.response
# Remove headers which applied to the original content,
# but do not apply to the error page.
respheaders = response.headers
for key in ["Accept-Ranges", "Age", "ETag", "Location", "Retry-After",
... | [
"def DeleteResponseHeader(self, name):\n assert name.islower()\n self._wpr_response.original_headers = \\\n [x for x in self._wpr_response.original_headers if x[0].lower() != name]",
"def get204(self):\n bad = ('content-length', 'content-type')\n for h in bad:\n bottle.respon... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modify cherrypy.response status, headers, and body to represent self. CherryPy uses this internally, but you can also use it to create an HTTPError object and set its output without raising the exception. | def set_response(self):
import cherrypy
response = cherrypy.response
clean_headers(self.status)
# In all cases, finalize will be called after this method,
# so don't bother cleaning up response values here.
response.status = self.status... | [
"def __init__(self, reponse):\n self.response = ResponseException\n super(ResponseException, self).__init__('received {} HTTP response'.format(response.status_code))",
"def set_response(self):\r\n import cherrypy\r\n response = cherrypy.response\r\n response.status = status = se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return an HTML page, containing a pretty error response. status should be an int or a str. kwargs will be interpolated into the page template. | def get_error_page(status, **kwargs):
import cherrypy
try:
code, reason, message = _http.valid_status(status)
except ValueError, x:
raise cherrypy.HTTPError(500, x.args[0])
# We can't use setdefault here, because some
# callers send None for kwarg values.
if k... | [
"def _error_page(request, status):\n return jingo.render(request, '%d.html' % status, status=status)",
"def error_page(request, template, status=None):\n return render(request, '%d.html' % template, status=(status or template))",
"def _error(self, request, status, headers={}, prefix_template_path=False, *... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return exc (or sys.exc_info if None), formatted. | def format_exc(exc=None):
if exc is None:
exc = _exc_info()
if exc == (None, None, None):
return ""
import traceback
return "".join(traceback.format_exception(*exc)) | [
"def format_exc():\n\n return '\\n'.join(traceback.format_exc().split('\\n')[-4:-1])",
"def format_exc():\n from traceback import format_exc\n return format_exc().decode('utf-8', 'surrogateescape')",
"def _FormatException(exc):\n return ''.join(traceback.format_exception_only(type(exc), exc))"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Produce status, headers, body for a critical error. Returns a triple without calling any other questionable functions, so it should be as errorfree as possible. Call it from an HTTP server if you get errors outside of the request. If extrabody is None, a friendly but rather unhelpful error message is set in the body. I... | def bare_error(extrabody=None):
# The whole point of this function is to be a last line-of-defense
# in handling errors. That is, it must not raise any errors itself;
# it cannot be allowed to fail. Therefore, don't add to it!
# In particular, don't call any other CP functions.
body... | [
"def reqErr(failure, request):\n request.setHeader(\"Content-Type\", \"application/json\")\n if failure.check(MatrixRestError) is not None:\n request.setResponseCode(failure.value.httpStatus)\n request.write(dict_to_json_bytes({'errcode': failure.value.errcode, 'error': failure.v... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Called when an interest for the specified name is recieved | def onInterest(self, prefix, interest, transport, registeredPrefixId):
interestName = interest.getName()
data = Data(interestName)
data.setContent("Hello, " + interestName.toUri())
hourMilliseconds = 3600 * 1000
data.getMetaInfo().setFreshnessPeriod(hourMilliseconds)
s... | [
"def interest(self, interest):\n self._interest = interest",
"def interest(self, interest):\n\n self._interest = interest",
"def on_callback_myname(self, pubsub, topic, value):\n raise NotImplementedError()",
"async def on_interest(self, param: InterestParam, app_param: Optional[BinaryStr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Called when forwarder can't register prefix | def onRegisterFailed(self, prefix):
dump("Register failed for prefix", prefix.toUri())
self.isDone = True | [
"def route_rejected(self, prefix, next_hop, as_path):",
"def register_prefix(prefix, namespace):",
"def add_prefix(self, prefix, uri):\n root = self.wsdl.root\n mapped = root.resolvePrefix(prefix, None)\n if mapped is None:\n root.addPrefix(prefix, uri)\n return\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns default metadata of type ``name``, where ``name`` is one of "tree_sequence", "edge", "site", "mutation", "mutation_list_entry", "node", "individual", or "population". | def default_slim_metadata(name):
if name == "tree_sequence":
out = {
"SLiM" : {
"model_type" : "nonWF",
"cycle" : 1,
"tick" : 1,
"file_version" : slim_file_version,
"spatial_dimensionality" : "",
... | [
"def FetchMetadataDefault(cls, name):\n try:\n url = 'http://metadata/computeMetadata/v1/instance/attributes/%s' % name\n return HttpGet(url, headers={'Metadata-Flavor': 'Google'})\n except urllib2.HTTPError:\n raise ValueError('Metadata key \"%s\" not found' % name)",
"def get_or_create_medd... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests whether the tree sequence or table collection provided is the current SLiM file format or not. If not, use `pyslim.update( )` to bring it up to date. | def is_current_version(ts, _warn=False):
out = (
isinstance(ts.metadata, dict)
and
('SLiM' in ts.metadata)
and
(ts.metadata['SLiM']['file_version'] == slim_file_version)
)
if _warn and not out:
warnings.warn(
"This tree sequence is not the curr... | [
"def update_tables(tables):\n # First we ensure we can find the file format version number\n # in top-level metadata. Then we proceed to fix up the tables as necessary.\n if not (isinstance(tables.metadata, dict) and 'SLiM' in tables.metadata):\n # Old versions kept information in provenance, not to... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update tables produced by a previous verion of SLiM to the current file version. Modifies the tables in place. | def update_tables(tables):
# First we ensure we can find the file format version number
# in top-level metadata. Then we proceed to fix up the tables as necessary.
if not (isinstance(tables.metadata, dict) and 'SLiM' in tables.metadata):
# Old versions kept information in provenance, not top-level m... | [
"def _db_upgrade_data_tables(self, q, old_version):\n pass",
"def schema_update_script(self, version):",
"def callUpdateTable(self):\r\n self.updateTable()",
"def update_table_in_file(table, source_file):\n with open(source_file, 'r') as source, \\\n tempfile.NamedTemporaryFile('w', dele... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Uses a dictionary to convert a DNA sequence into the complement strand. C G, T A | def fast_complement(dna):
str = ''
dict = {'C':'G','G':'C','A':'T','T':'A'}
for char in dna:
if char == 'C' or char == 'G' or char == 'T' or char == 'A':
str = str + dict[char]
else :
str = 'invalid character entered, please check the input'
break
retu... | [
"def fast_complement(dna):\n dictionary = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'}\n compliment = ''.join([dictionary[element] for element in dna])\n return compliment",
"def complement_dna(dnaSeq):\n #The complement rule is \"A\" to \"T\", \"T\" to \"A\", \"C\" to \"G\", \"G\" to \"C\". \n if dnaS... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes the interval of characters from a string or list inclusively, 0 based | def remove_interval(s, start, stop):
#s[:start] will get the string from start of string to 'start'->value stored in start
#s[stop:] will get the string from 'stop'->value stored in the stop to end of the string
temp_list = s[:start] + s[stop+1:]
return temp_list | [
"def remove_interval(s, start, stop):\n result = s[:start] + s[stop+1:]\n return result",
"def anything_but_range(*args:List[str]) -> str:\n return range(*args, negate=True)",
"def remove_4s_every_other_in_between(seq):\n seq_copy = seq [4:-4:2]\n return seq_copy",
"def anything_but_chars(*args... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates all kmers of size k for a string s and store them in a set | def kmer_set(s, k):
kmer = set([])
n = len(s)
#n-k+1 is the available range of values or probablities.
for x in range(0, n - k + 1):
kmer.add(s[x:x + k])
return kmer | [
"def get_kmers(s, k):\n kmers = set()\n for i in range(len(s) - k +1):\n kmers.add(s[i:i+k])\n return kmers",
"def kmer_set(s, k):\n kmerset = set()\n strlength = len(s)\n tempstr = strlength - k + 1\n for element in range(0, tempstr):\n kmerset.add(s[element:element + k])\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates all kmers of size k for a string s and store them in a dictionary with the kmer(string) as the key and the number of occurances of the kmer as the value(int). | def kmer_dict(s, k):
kmer = {}
#calculating the length as n.
n = len(s)
for x in range(0, n - k + 1):
#checking if the entry alread in the dictionary kmer
if s[x:x+k] in kmer:
#if the entry is available then increament 1
kmer[s[x:x + k]] += 1
else:
... | [
"def kmer_dict(s, k):\n kmerdictionary = {}\n strlength = len(s)\n tempstr = strlength - k + 1\n for element in range(0, tempstr):\n str = s[element:element + k]\n if str not in kmerdictionary:\n kmerdictionary[str] = 0\n kmerdictionary[str] = kmerdictionary[str]+1\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prints the FIRST 10 lines of a file | def head(file_name):
#from itertools import islice
with open('../test_files/' + file_name, 'r') as infile:
list = infile.readlines()
#printing the 1st 10 lines
print('list of first 10 lines',list[:10]) | [
"def head_of_file(file_name, lines=10):\n try:\n f = open(file_name, 'rU')\n except(IOError):\n print 'file(%s) not exist' % (file_name)\n\n for x in xrange(1, lines + 1):\n try:\n print f.readline(),\n except(EOFError):\n break\n f.close()",
"def head... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prints the LAST 10 lines of a file | def tail(file_name):
with open('../test_files/' + file_name, 'r') as infile:
list = infile.readlines()
#calculating the last 10 lines using len(list)-10:len(list)
print('list of last 10 lines',list[len(list)-10:len(list)]) | [
"def tail(file_name):\n f = open(file_name)\n file_content = f.readlines()\n new_list = file_content[-10:]\n for p in new_list:\n print(p)\n return",
"def file_tail(filename, n):\n result = ''\n with open(filename, 'r') as f:\n for line in (f.readlines()[-n:]):\n resu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prints the even numbered lines of a file | def print_even(file_name):
with open('../test_files/' + file_name, 'r') as infile:
#initialising 1 to 1 so that it evaluate from line 1
i = 1
for x in infile.readlines():
#performing operation to find the even number entry
if i%2 == 0:
#actual printing... | [
"def print_even(file_name):\n f = open(file_name)\n file_content = f.readlines()\n new_list = file_content[1::2]\n for i in new_list:\n print(i)\n return",
"def display_enumerated_lines(filename):",
"def display_num_lines(n, f):\r\n fo = open(f, \"r\")\r\n for i, txt in enumerate(fo)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads in a CSV file and returns a list of values belonging to the column specified | def get_csv_column(file_name, column):
list = []
with open('../test_files/' + file_name, 'r') as infile:
for x in infile.readlines():
x = x.replace('\n', '')
# splitting based on ',' that are encountered in csv files.
#column-1 because the range start from 0 , so if u... | [
"def values_of_col(csvf,col_name,sepchar=' '):\n\tcol_values=[]\n\twith open(csvf,'rb') as f:\n\t\treader=csv.reader(f,delimiter=sepchar)\n\t\tcsv_list=list(reader)\n\t\theader_row=csv_list[0]\t\t\n\t\tcol_name_index=header_row.index(col_name)\n\t\tfor row in csv_list:\n\t\t\tcol_values.append(row[col_name_index])\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads in a FASTA file and returns a list of only the sequences | def fasta_seqs(file_name):
list = []
with open('../test_files/' + file_name, 'r') as infile:
text = infile.read()
seqs = text.split('>')
for seq in seqs:
try:
x = seq.split('\n', 1)
# sequence will be stored in x[1], and i am removing nextline ... | [
"def readFromFile():\n sequences = []\n line_idx = 0\n with open('sequence.fasta') as f:\n content = f.read()\n for line in content.splitlines():\n if line_idx % 2 == 0:\n line_idx += 1\n continue\n else:\n line_idx += 1\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads in a FASTA file and returns a list of only the headers (Lines that start with ">") | def fasta_headers(file_name):
list = []
with open('../test_files/' + file_name, 'r') as infile:
text = infile.read()
seqs = text.split('>')
for seq in seqs:
try:
x = seq.split('\n', 1)
if x[0] != '':
#x[0] contains only head... | [
"def fasta_headers(file_name):\n with open(file_name, 'r') as infile:\n text = infile.read()\n seqs = text.split('>')[1:]\n header = []\n for seq in seqs:\n try:\n x = seq.split('\\n', 1)\n header.append(x[0])\n except:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads in a FASTQ file and writes it to a new FASTA file. This definition should also keep the same file name and change the extension to from .fastq to .fasta if new_name is not specified. | def fastq_to_fasta(file_name, new_name=None):
if(file_name.endswith('.fastq')):
with open('../test_files/' + file_name, 'r') as infile:
text = infile.read()
if new_name == None:
f = open('../test_files/'+file_name.split('.')[0]+'.fasta','w+')
print('Ne... | [
"def fastq_to_fasta(file_name, new_name=None):\n if file_name.endswith('.fastq'):\n if new_name is None:\n fasta_file = file_name.replace('.fastq','.fasta')\n else:\n fasta_file = new_name\n try:\n with open(file_name, 'r') as infile:\n text = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates a list of all 6 possible reading frames for a given strand of DNA | def reading_frames(dna):
#the 6 types are as follows
# the actual string and the reverse complement
list = []
#this is the actual string
list.append(dna)
#this is the reverse complement of the string
# done reusing the fastcomplement() method that was already available.
#others are done ... | [
"def reading_frames(dna):\n\n reading_frames = []\n\n reading_frames.append(dna)\n reading_frames.append(dna[1:-2])\n reading_frames.append(dna[2:-1])\n\n dictionary = {'C': 'G', 'T': 'A','A': 'T','G': 'C'}\n rev = reversed(dna)\n reverse_compli = ''.join([dictionary[element] for element in rev... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
fetches instruction from ROM, increases IP and returns instruction | def fetch_instruction(self) -> dict:
instruction = self.__ROM.read(self.regs["ip"].read())
self.regs["ip"].inc()
return self.disassembler.decode_instruction(instruction) | [
"def fetch_execute(self):\n\n op_code = self.mem.read(self.reg.ip)\n self.reg.ip_inc()\n addr = self.mem.read(self.reg.ip)\n self.reg.ip_inc()\n\n # Execute the instruction on addr.\n self.op_codes[op_code.num](addr)",
"def fetch(self):\n\n self.executing_opcode = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets book statuses from the dim_book_statuses table. | def get_book_statuses() -> list:
return data.get_book_statuses() | [
"def statuses(self):\n return self._get_paged(\"statuses\")",
"def get_statuses(self, board_id, *args, **kwargs):\n endpoint_url = '{}/{}/statuses'.format(self.ENDPOINT_BOARDS, board_id)\n return self.fetch_resource(endpoint_url, should_page=True,\n *args, **... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
compute the LR1 closure of items | def closure(items, ruleSet, terminals):
I = copy.deepcopy(items)
added = 1
while added:
added = 0
#for each item [A -> alpha . B Beta, a] in I (result)
for item in I:
if item.pointAtEnd(): continue
A = item.lhs
alpha = item.rhs[:item.dotPos]
... | [
"def visititems(self, func: Callable) -> None:",
"def _build_item_closure(itemset, productionset):\r\n #For every item inside current itemset, if we have the following rule:\r\n # xxx <cursor><nonterminalSymbol> xxx append every rule from self._productionruleset that begins with that NonTerminalSymbol\r\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
find targetSet in C | def fullIndex(C, targetSet):
for i in range(len(C)):
if not fullCmpSets(C[i], targetSet):
return i
raise 'OhShit', "couldn't find %s\n%s" % (targetSet, C[4]) | [
"def LocateSet(self, target):\n for i, set_ in enumerate(self.__sets):\n if target in set_:\n return i\n raise Exception(\"Value not found!\")",
"def getInSet(label, cfg, outSets):\n return set().union(*(outSets[p.name] for p in cfg.predecessors(label)))",
"def getSets... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate an LR(1) state table | def generateStateTable(C, ruleSet, terminals, indexFunc):
#initialize the state dictionary
stateDict = {}
for i in range(len(C)):
stateDict[i] = {}
gotoDict = {}
for i in range(len(C)):
gotoDict[i] = {}
#compute the states
for state in range(len(C)):
for item in... | [
"def generate_table(self):\n states = self.get_canonical_collection()\n # self.print_canonical_collection(states)\n table = [{} for _ in range(len(states))]\n\n for index in range(len(states)):\n state = states[index]\n first_rule_cnt = 0\n second_rule_cn... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print the invoice and mark it as sent, so that we can see more easily the next step of the workflow This Method overrides the one in the original invoice class | def invoice_print(self):
self.ensure_one()
self.sent = True
return self.env['report'].get_action(self, 'ferrua_report.report_invoice') | [
"def invoice_print(self):\n account_invoice_obj = self.env['account.invoice']\n account_invoice_obj.add_print_count(self)\n assert len(self) == 1, 'This option should only be used for a single id at a time.'\n self.sent = True\n return self.env['report'].get_action(self, 'jakc_acc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the retrieval system. For each input in image_ids, generate a list of IDs returned for that image. | def test(label_dict, image_ids, args):
log_header('Starting image retrieval preparations')
queries = []
if args.test_image is not None:
queries.append(args.test_image)
else:
logging.info('Generating random test queries')
number_of_images = len(image_ids)
# Generate r... | [
"def test_train_image_ids(self):\n existing_image_ids = []\n for info_dict in self.train_info_dicts:\n image_id = info_dict[constant.detectron.IMAGE_ID_KEY]\n with self.subTest(image_id=image_id):\n if image_id not in existing_image_ids:\n existi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Square 32 < n < 99 | def square(n: int) -> int:
return int(n ** 2) | [
"def square(n):\r\n return n*n",
"def sqrncube(n=0) :\r\n return n**2 , n**3",
"def square_root(n): # Big squares\n if n < (1<<50): return int(n**0.5)\n r = 1 << ((n.bit_length() + 1) >> 1)\n while True:\n num = (r+n//r) >> 1\n if num >= r:\n return r\n r = num",
"def mak... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pentagonal 26 < n < 81 | def pentagonal(n: int) -> int:
return int(n * (3 * n - 1) / 2) | [
"def pentagonal(n):\n return n*(3*n-1)/2",
"def pentagonal(n):\n return (n * ((3 * n) - 1)) / 2",
"def is_pentagonal(n):\r\n if ((1+(24*n+1)**0.5) / 6)%1 == 0:\r\n return True\r\n return False",
"def pentagon(n) -> int:\n\n return (n * (3 * n - 1)) // 2",
"def isPantagonal(n):\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Hexagonal 23 < n < 70 | def hexagonal(n: int) -> int:
return int(n * (2 * n - 1)) | [
"def is_hexagonal(n):\n return (1 + math.sqrt(1 + 8 * n)) % 4 == 0",
"def hexagonal(n):\n return n*(2*n-1)",
"def hexagonal_number(n):\n return n * (2 * n - 1)",
"def ishexagonal(H):\n from gmpy2 import is_square, sqrt\n sq = 1 + 8*H\n return is_square(sq) and int(sqrt(sq)+1) % 4 == 0",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Heptagonal 21 < n < 63 | def heptagonal(n: int) -> int:
return int(n * (5 * n - 3) / 2) | [
"def hexagonal(n):\n return n*(2*n-1)",
"def hexagonal(n: int) -> int:\n return int(n * (2 * n - 1))",
"def formHn(n,min,max,N):\n pas = abs((max-min)/N)\n x = min\n result = np.array([])\n \n for i in range(0,N):\n result = np.append(result,H(n,x))\n x += pas \n return r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Octagonal 19 < n < 58 | def octagonal(n: int) -> int:
return int(n * (3 * n - 2)) | [
"def hexagonal(n):\n return n*(2*n-1)",
"def hexagonal_number(n):\n return n * (2 * n - 1)",
"def hexagonal(n: int) -> int:\n return int(n * (2 * n - 1))",
"def make_zernike_indexes(self):\n zernike_n_m = []\n for n in range(10):\n for m in range(n+1):\n if (m+... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
computes the number of zernike coefficients given the radial polynomial order/level n. | def zernike_num_coeff(n):
if not (n>=0):
print('Input parameter must be >= 0')
raise AssertionError()
return sum(xrange(n+1)) + n+1 | [
"def _getZc(n):\n # An extra trial is required for low counts, due to the fact\n # that there is higher variance in the calculated deviation.\n extra = 1\n\n vFree = n - 1\n zc = 1.96\n if vFree > 15:\n # Normal distribution, and enoug... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to compute the Zernike polynomial (n, m) given a grid of radial coordinates rho and azimuthal coordinates phi. >>> zernike(3,5, 0.12345, 1.0) 0.0073082282475042991 | def zernike_poly(m, n, rho, phi):
if (m > 0): return zernike_rad(m, n, rho) * np.cos(m * phi)
if (m < 0): return zernike_rad(-m, n, rho) * np.sin(-m * phi)
return zernike_rad(0, n, rho) | [
"def _zernike(m, n, rho, phi):\n if (m > 0): return _zernike_rad(m, n, rho) * np.cos(m * phi)\n if (m < 0): return _zernike_rad(-m, n, rho) * np.sin(-m * phi)\n return _zernike_rad(0, n, rho)",
"def calculate_zernike(self, rho, phi, y, n, m):\n pass",
"def zernike(m, n, rho, phi):\n if (m > 0... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create an unit disk and convert to rho, phi and and masking the grid. | def unit_disk(imgSize):
# src = np.nan_to_num(imgsrc)
if not (imgSize > 0):
print('Nside must be > 0')
raise AssertionError()
nx = imgSize #, ny = src.shape
grid = (np.indices((nx, nx), dtype=np.float) - nx/2) / (nx*1./2) # create unit grid [-1,1]
grid_rho, gr... | [
"def _disk(radius):\n\n coords = np.arange(-round(radius,0), round(radius,0)+1)\n X, Y = np.meshgrid(coords, coords)\n disk_out = 1*np.array((X**2 + Y**2) < (radius+0.5)**2)\n # round improves behavior with irrational radii\n return(disk_out)",
"def getDenFileOf(raw_data_file):\n # read and ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Truncate the coefficients upto the given threshold | def truncate(coeffs, threshold=99):
sortedindex = np.argsort(np.abs(coeffs))[::-1]
Ncoeff = coeffs.shape[-1]
cutoff = np.int(np.round(Ncoeff*threshold/100.))
# print "Keeping %2.0f %% (N=%s) of the biggest coefficients"%(threshold,cutoff)
coeffs_trunc = coeffs.copy() ... | [
"def threshold_wcoeffs(coeffs,threshold,mode='soft'):\n from copy import deepcopy\n coeffs_new=deepcopy(coeffs)\n\n # threshold all the detialed coeffs [1:], but not the approximate [1]\n coeffs_new[1:] = map (lambda x: pywt.threshold(x,threshold,mode=mode),\n coeffs[1:])\n\n return coeffs_new",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reconstruct a model image from the coeffcicients | def reconstruct_image(imgsrc, nlevels, trunc_threshold=None):
coeffs = zernike_basis_n_coeffs(imgsrc, nlevels, return_basis=False)
if trunc_threshold is not None:
coeffs = truncate(coeffs, threshold=trunc_threshold)
# Generate (rho, phi) grids and masking grid
grid_rho, grid_phi, grid_mask = unit_disk(img... | [
"def constructModel(bvals,coeffs,xc,size):\n model_img=np.dot(bvals,coeffs)\n model_img=np.reshape(model_img,size)\n return model_img",
"def reconstruct_image(pic, psi_vec, u_evecs, num_pcs=None):\n\n # extract the number of eigen vectors that will be used\n if num_pcs: \n final_evecs = u_ev... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k') 2Dpolynomials Computes 2 indices (n,m) to specify Zernike functions, starting from the top, shifts to the left and then right. | def zernike_visuo__pyramid(zbasis, n, m, nlevels, figsize=(12, 12), cmap='jet', fontsize=20, colorbar_labelsize=10):
cmap = plt.get_cmap('%s' %cmap)
index = 0
if not (nlevels>=0):
print('Input parameter must be >= 0')
raise AssertionError()
axlist = []
if (nle... | [
"def unittest_plotzernikes(degree=10):\n coefs = warpcoefs()\n import matplotlib.pyplot as plt\n import time\n x = numpy.arange(-1,1.0001,0.005)\n y = numpy.arange(-1,1.0001,0.005)\n x,y = numpy.meshgrid(x,y)\n dont = x**2+y**2>1\n for n in range(0,degree):\n for m in range(-n,n+1,2):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a dummy Supervisor structure and start a global patch. | def setUp(self):
from supvisors.plugin import expand_faults
self.supervisor = DummySupervisor()
# add a global patch
self.supvisors_patcher = patch('supvisors.rpcinterface.Supvisors')
self.mocked_supvisors = self.supvisors_patcher.start()
self.mocked_supvisors.return_valu... | [
"def supervisor_start():\n log('start supervisor', green)\n sudo('/etc/init.d/supervisor start')",
"def start_stubs(_scenario):\r\n for name, service in SERVICES.iteritems():\r\n fake_server = service['class'](port_num=service['port'])\r\n setattr(world, name, fake_server)",
"def setup_su... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the get_api_version RPC. | def test_api_version(self):
from supvisors.rpcinterface import API_VERSION, RPCInterface
# create RPC instance
rpc = RPCInterface(self.supervisor)
self.assertEqual(API_VERSION, rpc.get_api_version()) | [
"def test_get_oapi_version(self):\n pass",
"def test_version_endpoint(client):\n response = client.get('/version')\n data = json.loads(response.data)\n \n assert response.status_code == 200\n assert data['api_version'] == api.__version__\n assert data['models_version'] == hr.__version__",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the get_supvisors_state RPC. | def test_supvisors_state(self):
from supvisors.rpcinterface import RPCInterface
# prepare context
self.supervisor.supvisors.fsm.serial.return_value = 'RUNNING'
# create RPC instance
rpc = RPCInterface(self.supervisor)
self.assertEqual('RUNNING', rpc.get_supvisors_state()) | [
"def test_check_state(self):\n from supvisors.rpcinterface import RPCInterface\n # prepare context\n self.supervisor.supvisors.fsm.state = 1\n # create RPC instance\n rpc = RPCInterface(self.supervisor)\n # test there is no exception when internal state is in list\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the get_master_address RPC. | def test_master_address(self):
from supvisors.rpcinterface import RPCInterface
# prepare context
self.supervisor.supvisors.context.master_address = '10.0.0.1'
# create RPC instance
rpc = RPCInterface(self.supervisor)
self.assertEqual('10.0.0.1', rpc.get_master_address()) | [
"def test_client_address_retrieve(self):\n pass",
"def test_testnet_get_address_info(self):\n pass",
"def test_retrieve_address(self):\n pass",
"def test_address_info(self):\n from supvisors.rpcinterface import RPCInterface\n # prepare context\n self.supervisor.supvis... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the get_strategies RPC. | def test_strategies(self):
from supvisors.rpcinterface import RPCInterface
# prepare context
self.supervisor.supvisors.options.auto_fence = True
self.supervisor.supvisors.options.conciliation_strategy = 1
self.supervisor.supvisors.options.starting_strategy = 2
# create RP... | [
"def test_get_scenario(self):\n pass",
"def list_active_strategies():\n response = houston.get(\"/zipline/trade\")\n\n houston.raise_for_status_with_json(response)\n return response.json()",
"def test_get_scenarios(self):\n pass",
"def test_feature_multiStrategies_a_enabled(unleash_clie... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the get_address_info RPC. | def test_address_info(self):
from supvisors.rpcinterface import RPCInterface
# prepare context
self.supervisor.supvisors.context.addresses = {
'10.0.0.1': Mock(**{'serial.return_value': 'address_info'})}
# create RPC instance
rpc = RPCInterface(self.supervisor)
... | [
"def test_testnet_get_address_info(self):\n pass",
"def test_retrieve_address(self):\n pass",
"def test_client_address_retrieve(self):\n pass",
"def rpc_getaddressinfo(self, address: str) -> dict:\n return self._call_command([\"getaddressinfo\", address])",
"def test_get_order_ad... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the get_all_addresses_info RPC. | def test_all_addresses_info(self):
from supvisors.rpcinterface import RPCInterface
# prepare context
self.supervisor.supvisors.context.addresses = {
'10.0.0.1': Mock(**{'serial.return_value': 'address_info_1'}),
'10.0.0.2': Mock(**{'serial.return_value': 'address_info_2'}... | [
"def test_testnet_get_address_info(self):\n pass",
"def test_list_address(self):\n pass",
"def test_address_info(self):\n from supvisors.rpcinterface import RPCInterface\n # prepare context\n self.supervisor.supvisors.context.addresses = {\n '10.0.0.1': Mock(**{'ser... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the get_application_info RPC. | def test_application_info(self, mocked_serial, mocked_check):
from supvisors.rpcinterface import RPCInterface
# create RPC instance
rpc = RPCInterface(self.supervisor)
# test RPC call
self.assertEqual({'name': 'appli'}, rpc.get_application_info('dummy'))
self.assertEqual(... | [
"def test_get_application_information(self):\n pass",
"def test_get_application(self):\n from supvisors.rpcinterface import RPCInterface\n # prepare context\n self.supervisor.supvisors.context.applications = {\n 'appli_1': 'first application'}\n # create RPC instance\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the get_all_applications_info RPC. | def test_all_applications_info(self, mocked_get, mocked_check):
from supvisors.rpcinterface import RPCInterface
# prepare context
self.supervisor.supvisors.context.applications = {
'dummy_1': None, 'dummy_2': None}
# create RPC instance
rpc = RPCInterface(self.supervi... | [
"def test_get_application_information(self):\n pass",
"def test_get_organization_applications(self):\n pass",
"def test_get_application(self):\n from supvisors.rpcinterface import RPCInterface\n # prepare context\n self.supervisor.supvisors.context.applications = {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the get_process_info RPC. | def test_process_info(self, mocked_get, mocked_check):
from supvisors.rpcinterface import RPCInterface
# create RPC instance
rpc = RPCInterface(self.supervisor)
# test first RPC call with process namespec
self.assertEqual([{'name': 'proc'}], rpc.get_process_info('appli:proc'))
... | [
"def test_get_process(self):\n from supvisors.rpcinterface import RPCInterface\n # prepare context\n self.supervisor.supvisors.context.processes = {\n 'proc_1': 'first process'}\n # create RPC instance\n rpc = RPCInterface(self.supervisor)\n # test with known app... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the get_all_process_info RPC. | def test_all_process_info(self, mocked_check):
from supvisors.rpcinterface import RPCInterface
# prepare context
self.supervisor.supvisors.context.processes = {
'proc_1': Mock(**{'serial.return_value': {'name': 'proc_1'}}),
'proc_2': Mock(**{'serial.return_value': {'name'... | [
"def test_process_info(self, mocked_get, mocked_check):\n from supvisors.rpcinterface import RPCInterface\n # create RPC instance\n rpc = RPCInterface(self.supervisor)\n # test first RPC call with process namespec\n self.assertEqual([{'name': 'proc'}], rpc.get_process_info('appli:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the get_application_rules RPC. | def test_application_rules(self, mocked_get, mocked_check):
from supvisors.rpcinterface import RPCInterface
# create RPC instance
rpc = RPCInterface(self.supervisor)
# test RPC call with aplpication name
self.assertDictEqual(rpc.get_application_rules('appli'),
{'appl... | [
"def test_get_canary_results_by_application_using_get(self):\n pass",
"def test_get_organization_applications(self):\n pass",
"def test_process_rules(self, mocked_rules, mocked_get, mocked_check):\n from supvisors.rpcinterface import RPCInterface\n # create RPC instance\n rpc ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the get_process_rules RPC. | def test_process_rules(self, mocked_rules, mocked_get, mocked_check):
from supvisors.rpcinterface import RPCInterface
# create RPC instance
rpc = RPCInterface(self.supervisor)
# test first RPC call with process namespec
self.assertEqual([{'start': 1}], rpc.get_process_rules('appl... | [
"def test_application_rules(self, mocked_get, mocked_check):\n from supvisors.rpcinterface import RPCInterface\n # create RPC instance\n rpc = RPCInterface(self.supervisor)\n # test RPC call with aplpication name\n self.assertDictEqual(rpc.get_application_rules('appli'), \n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the get_conflicts RPC. | def test_conflicts(self, mocked_check):
from supvisors.rpcinterface import RPCInterface
# prepare context
self.supervisor.supvisors.context.processes = {
'proc_1': Mock(**{'conflicting.return_value': True,
'serial.return_value': {'name': 'proc_1'}}),
'proc... | [
"def test_militaryconflicts_get(self):\n query_string = [('label', 'label_example'),\n ('page', 1),\n ('per_page', 100)]\n headers = { \n 'Accept': 'application/json',\n }\n response = self.client.open(\n '/v0.0.1/milita... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the start_application RPC. | def test_start_application(self, mocked_check):
from supvisors.rpcinterface import RPCInterface
from supvisors.ttypes import ApplicationStates
# prepare context
self.supervisor.supvisors.context.applications = {'appli_1': Mock()}
# get patches
mocked_start = self.supervis... | [
"def test_run_app(self):\n\n self.run_app()\n self.assertGoodExitCode()",
"def test_application_start():\n\n process = subprocess.Popen(['python', 'runserver.py'],\n stderr=subprocess.STDOUT,\n stdout=subprocess.PIPE)\n\n assert process.pid\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the stop_application RPC. | def test_stop_application(self, mocked_check):
from supvisors.rpcinterface import RPCInterface
from supvisors.ttypes import ApplicationStates
# prepare context
self.supervisor.supvisors.context.applications = {'appli_1': Mock()}
# get patches
mocked_stop = self.supervisor... | [
"def test_stop():\n with patch.dict(monit.__salt__, {\"cmd.retcode\": MagicMock(return_value=False)}):\n assert monit.stop(\"name\")",
"def test_v1_stop(self):\n pass",
"def stopApplication(appName, servers):\n for server in servers:\n appManager = AdminControl.queryNames(\"type=Application... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the start_args RPC. | def test_start_args(self, mocked_check, mocked_proc):
from supvisors.rpcinterface import RPCInterface
# prepare context
info_source = self.supervisor.supvisors.info_source
info_source.update_extra_args.side_effect = KeyError
info_source.supervisor_rpc_interface.startProcess.side_... | [
"def assert_server_process_start_called_with(self, **args):",
"def test_start_from_args_no_args():\n log = conlog.start()\n log.info('Testing')",
"def start(self, args = []):\n pass",
"def start_test_run(self):",
"def test_v1_start(self):\n pass",
"def test_start_from_args_simple_args(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the start_process RPC. | def test_start_process(self, mocked_check):
from supvisors.rpcinterface import RPCInterface
# get patches
mocked_start = self.supervisor.supvisors.starter.start_process
mocked_progress = self.supervisor.supvisors.starter.in_progress
# create RPC instance
rpc = RPCInterfac... | [
"def test_startProcess(self):\r\n self.pm.addProcess(\"foo\", [\"foo\"])\r\n self.pm.startProcess(\"foo\")\r\n self.assertIsInstance(self.pm.protocols[\"foo\"], LoggingProtocol)\r\n self.assertIn(\"foo\", self.pm.timeStarted.keys())",
"def test_startProcessAlreadyStarted(self):\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the stop_process RPC. | def test_stop_process(self, mocked_check):
from supvisors.rpcinterface import RPCInterface
# get patches
mocked_stop = self.supervisor.supvisors.stopper.stop_process
mocked_progress = self.supervisor.supvisors.stopper.in_progress
# create RPC instance
rpc = RPCInterface(s... | [
"def test_stop():\n with patch.dict(monit.__salt__, {\"cmd.retcode\": MagicMock(return_value=False)}):\n assert monit.stop(\"name\")",
"def test_stopProcessForcedKill(self):\r\n self.pm.startService()\r\n self.pm.addProcess(\"foo\", [\"foo\"])\r\n self.assertIn(\"foo\", self.pm.prot... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the restart_process RPC. | def test_restart_process(self, mocked_check, mocked_stop, mocked_start):
from supvisors.rpcinterface import RPCInterface
# create RPC instance
rpc = RPCInterface(self.supervisor)
# test RPC call with sub-RPC calls return a direct result
mocked_stop.return_value = True
moc... | [
"def test_restart(self, mocked_check):\n from supvisors.rpcinterface import RPCInterface\n # create RPC instance\n rpc = RPCInterface(self.supervisor)\n # test RPC call\n self.assertTrue(rpc.restart())\n self.assertEqual([call()], mocked_check.call_args_list)\n self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the restart RPC. | def test_restart(self, mocked_check):
from supvisors.rpcinterface import RPCInterface
# create RPC instance
rpc = RPCInterface(self.supervisor)
# test RPC call
self.assertTrue(rpc.restart())
self.assertEqual([call()], mocked_check.call_args_list)
self.assertEqual(... | [
"def test_v1_restart(self):\n pass",
"def test_v1alpha3_restart(self):\n pass",
"def test_restart():\n with patch.dict(monit.__salt__, {\"cmd.retcode\": MagicMock(return_value=False)}):\n assert monit.restart(\"name\")",
"def test_restart_case(self):\r\n result = self.create_res... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the shutdown RPC. | def test_shutdown(self, mocked_check):
from supvisors.rpcinterface import RPCInterface
# create RPC instance
rpc = RPCInterface(self.supervisor)
# test RPC call
self.assertTrue(rpc.shutdown())
self.assertEqual([call()], mocked_check.call_args_list)
self.assertEqua... | [
"def test_cons_shutdown(self):\n\n body = {\n 'force': False,\n }\n\n # the function to be tested:\n resp = self.urihandler.post(\n self.hmc, '/api/console/operations/shutdown', body, True, True)\n\n assert not self.hmc.enabled\n assert resp is None",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the _check_state utility. | def test_check_state(self):
from supvisors.rpcinterface import RPCInterface
# prepare context
self.supervisor.supvisors.fsm.state = 1
# create RPC instance
rpc = RPCInterface(self.supervisor)
# test there is no exception when internal state is in list
rpc._check_s... | [
"def checkState(self):",
"def check_test_state(self):\n\n self.metadata[\"result\"][\"state\"] = \"FAIL\"\n\n if self.metadata[\"result\"][\"returncode\"] == 0:\n self.metadata[\"result\"][\"state\"] = \"PASS\"\n\n # if status is defined in Buildspec, then check for returncode and ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the _check_operating_conciliation utility. | def test_check_operating_conciliation(self):
from supvisors.rpcinterface import RPCInterface
# create RPC instance
rpc = RPCInterface(self.supervisor)
# test the call to _check_state
with patch.object(rpc, '_check_state') as mocked_check:
rpc._check_operating_concilia... | [
"def test_check_operating(self):\n from supvisors.rpcinterface import RPCInterface\n # create RPC instance\n rpc = RPCInterface(self.supervisor)\n # test the call to _check_state\n with patch.object(rpc, '_check_state') as mocked_check:\n rpc._check_operating()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the _check_operating utility. | def test_check_operating(self):
from supvisors.rpcinterface import RPCInterface
# create RPC instance
rpc = RPCInterface(self.supervisor)
# test the call to _check_state
with patch.object(rpc, '_check_state') as mocked_check:
rpc._check_operating()
self.as... | [
"def test_guest_os(self):\n self.check_guest_os()",
"def test_check_system_python_api(self):\n\n errors, successes = check_system.check_system()\n self.assertTrue(len(errors) + len(successes) >= 4)",
"def test_check_module(self) -> None:\n check_module(\"os\")",
"def test_check_ope... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the _check_conciliation utility. | def test_check_conciliation(self):
from supvisors.rpcinterface import RPCInterface
# create RPC instance
rpc = RPCInterface(self.supervisor)
# test the call to _check_state
with patch.object(rpc, '_check_state') as mocked_check:
rpc._check_conciliation()
s... | [
"def _check_conciliation_auto(self):\n # create the conflicts\n self._create_database_conflicts()\n # cannot check using XML-RPC as conciliation will be triggered\n # automatically so check only the Supvisors state transitions\n event = self._get_next_supvisors_event()\n se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the _get_application utility. | def test_get_application(self):
from supvisors.rpcinterface import RPCInterface
# prepare context
self.supervisor.supvisors.context.applications = {
'appli_1': 'first application'}
# create RPC instance
rpc = RPCInterface(self.supervisor)
# test with known app... | [
"def test_get_application_information(self):\n pass",
"def test_duo_application_get(self):\n pass",
"def test_get_app(self):\n # Try to fetch a non-existing app\n with self.assertRaises(LookupError):\n get_app('dummy_app')\n # Fetch the demo app and evaluate it\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the _get_process utility. | def test_get_process(self):
from supvisors.rpcinterface import RPCInterface
# prepare context
self.supervisor.supvisors.context.processes = {
'proc_1': 'first process'}
# create RPC instance
rpc = RPCInterface(self.supervisor)
# test with known application
... | [
"def test_process_id():\n output = sh.process_id()\n assert isinstance(output, int) and output > 0",
"def test_find_processes_matches_cmdline(self, test_system_status):\n num_procs_found = len(test_system_status.system_status.find_processes_by_name(\n test_system_status.mocked_proc_name\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |