query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Inserts multiple new bids in the order book (assumes that the order book AND the new_bids list are sorted) | def insertBids(previous_bids, received_bids):
new_bids = []
while len(previous_bids) > 0 and len(received_bids) > 0:
bid = None
if Decimal(previous_bids[0][0]) > Decimal(received_bids[0][0]):
bid = previous_bids.pop(0)
elif Decimal(previous_bids[0][0]) < Decimal(received_bids[0][0]):
bid =... | [
"def add_books(cursor, order, old_order):\n books = str.split(old_order['books'], \"&&\") # a list of all the book IDs\n for book_id in books:\n cursor.execute(\"SELECT * FROM `books` WHERE `key`=%s\" % book_id)\n old_books = cursor.fetchall()\n assert len(old_books) == 1 # ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Populate paths with lengths in database | def postPathLengths(map_area):
paths = Path.query.filter(Path.map_area==map_area).all()
for path in paths:
start = Node.query.filter_by(id=path.start).first()
end = Node.query.filter_by(id=path.end).first()
# get the length of the two side of the paths
avg_length = calculatePath... | [
"def total_length(self):\n # YOUR CODE HERE\n return sum([path.total_length for path in self.subpaths])",
"def calculateWireLenght(path_list):\n\n total_length = 0\n for path in path_list:\n total_length += len(path)\n return total_length",
"def gen_path(cell):\n cell.tmp_path =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a database according to schema in JSON format. | def create_db(db, schema_json):
with open(schema_json) as of:
schema = json.load(of, object_pairs_hook=OrderedDict)
# OrderedDict so that tables are created in the order specified,
# allowing foreign keys to reference previously defined tables
for table_name, columns in schema.items():
... | [
"def main(db_path, schema_json):\n create_db(db_path, schema_json)",
"def create(self, schema=\"{}\", **kwargs):\n if isinstance(schema, basestring):\n strschema = schema\n schema = json.loads(schema)\n else:\n strschema = json.dumps(schema)\n Draft4Validat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a database from a schema and populate it with CSV/JSON data. | def main(db_path, schema_json):
create_db(db_path, schema_json) | [
"def create_db(db, schema_json):\n with open(schema_json) as of:\n schema = json.load(of, object_pairs_hook=OrderedDict)\n # OrderedDict so that tables are created in the order specified,\n # allowing foreign keys to reference previously defined tables\n\n for table_name, columns in schem... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
verify that, once send() is called, a tenant has been setup | def test_tenant_setup_celery(self):
class interceptor(mock.Mock):
tenant = None
def send(self, *kw, **args):
self.tenant = properties.tenant
msg = interceptor()
tenant = mock.Mock()
tenant.client_name = 'mock-tenant'
_send_celery_mail(m... | [
"def test_tenant_setup_celery_reset(self):\n msg = mock.Mock()\n tenant = mock.Mock()\n tenant.client_name = 'mock-tenant'\n\n _send_celery_mail(msg, tenant, send=False)\n\n self.assertFalse(hasattr(properties, 'tenant'))\n self.assertEqual(properties.tenant_properties, {})... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
after _send_celery_mail finishes, the tenant should be cleared again | def test_tenant_setup_celery_reset(self):
msg = mock.Mock()
tenant = mock.Mock()
tenant.client_name = 'mock-tenant'
_send_celery_mail(msg, tenant, send=False)
self.assertFalse(hasattr(properties, 'tenant'))
self.assertEqual(properties.tenant_properties, {}) | [
"def clear_celery_result(self):\n if self.has_celery_result:\n self._celery_result.forget()",
"def test_tenant_setup_celery(self):\n\n class interceptor(mock.Mock):\n tenant = None\n\n def send(self, *kw, **args):\n self.tenant = properties.tenant\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handles a success in payment. If the order is paidoff, sends success, else return page to pay remaining. | def _onSuccess(self, controller):
if controller.order.paid_in_full:
controller.cart.empty()
for item in controller.order.orderitem_set.all():
if item.product.is_subscription:
item.completed = True
item.save()
try:... | [
"def ui_redirect_success(self, order: Order = None) -> HttpResponse:\n ui_return_url = self.extract_ui_return_url()\n if ui_return_url:\n return self._redirect_to_ui(\n ui_return_url, \"success\", order, path=\"/payment-result\"\n )\n else:\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
| Ground Truth | Forehand Backhand Serve Forehand num_FF num_BF num_SF Backhand num_FB num_BB num_SB Serve num_FS num_BS num_SS No_action num_FN num_BN num_SN | def show_eval_class_level(num_BB, num_BF, num_BS, num_BN, num_FB, num_FF, num_FS, num_FN, num_SB, num_SF, num_SS, num_SN):
print("************************************************")
print(" | Ground Truth | ")
print(" Forehand Backhand Serve ")
print("F... | [
"def exact_successes(nflips: int, nheads: int) -> float:\r\n\tpass",
"def formationFlying(): ### PENDING\n\tpass",
"def test():\n sf = \"6C 7C 8C 9C TC\".split() # Straight Flush\n sf1 = \"6C 7C 8C 9C TC\".split() # Straight Flush\n sf2 = \"6D 7D 8D 9D TD\".split() # Straight Flush\n fk = \"9D 9H 9S... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
anothet_minute [числовой] Количество минут на номера других оператора home_minute [числовой] Количество минут на номера домашнего оператора sms [числовой] Количество смс internet [числовой] Количество интернетасоединения speed_internet [числовой] Скорость интернетсоединения cost [числовой] Стоимость тарифа transition_n... | def __init__(self, anothet_minute: int, home_minute: int,
sms: int, internet: str, speed_internet: str, cost: str, transition_number: str,
changelog: Changelog):
self.anothet_minute = anothet_minute
self.home_minute = home_minute
self.sms = sms
sel... | [
"def horario():\n print(\"Los horarios de la pelicula son : 10:30a.m, 1:30 p.m, 4.50p.m\")",
"def __call__(self, hours=None, minutes=None, ampm=None ):\r\n if ampm != None:\r\n assert hours >= 1 and hours <= 12, \"AM/PM time selection, but given hours are not between 1 and 12\"\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove Key from a Key Value pair Can be performed on Dictionary or Json key value string | def remove(kv_data, key):
if isinstance(kv_data, str):
kv_data = loads(kv_data) # Turn into Dictionary
try:
del kv_data[key]
except NameError:
print(key, " does not exists in key value pair.")
kv_data = dumps(kv_data)
else:
print("Provide a Json Ke... | [
"def remove(key):",
"def remove_dict_key(dict_in: dict, key: str):\n new_dict = dict_in.copy()\n new_dict.pop(key, None)\n return new_dict",
"def _remove_key(obj: Any, key_to_remove: str) -> Any:\n if isinstance(obj, dict):\n for key in list(obj.keys()):\n if key == key... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If JSON Key Value, Value contains this value | def contains_value(kv_json, value):
if isinstance(kv_json, str):
kv_dict = loads(kv_json)
for key in kv_dict:
if kv_dict[key] == value: # Found value in dictionary
return True
return False
else:
print("Provide A JSON Key Value String") | [
"def json_key_contains(key, value, json_response_list):\n for item in json_response_list:\n if item[key] == value:\n return True\n return False",
"def __is_key_in_json(self, key=str, json_dict=json):\n if key in json_dict:\n # noinspection PyUnresolvedReferences\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
from all the information provided by the ONCat template, we are only interested by the following infos [name, path and units]. We isolate those into the template_information dictionary | def isolate_relevant_information(self):
def get_formula(oncat_formula):
"""will need to go from something like
"${value/10e11}`"
to something more pythonic
"{value/10e11}"""
regular_expression = r'\$(?P<formula>.+)\`'
m = re.se... | [
"def parse_template(self):\n for line in self.raw_template.split(\"\\n\"):\n line = line.strip()\n if line.startswith('#m3'):\n key, val = line[3:].strip().split('=', 1)\n key = key.strip()\n val = val.strip()\n self.variables[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Using the ONCat template to create projection used by oncat to return full information | def create_oncat_projection_from_template(with_location=False,
template={}):
projection = []
if with_location:
projection = ['location']
nbr_columns = len(template)
for _col in np.arange(nbr_columns):
projection.appe... | [
"def describe(self, template='projection_default.txt', engine='default'):\n raise NotImplementedError",
"def export_template_geo(self):",
"def parse_projection(self, header): # pragma: no cover\n pass",
"def get_filtered_collection_string( self, taxon_name_list ):\n if self.format == 'ne... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Applies selected activation function to intermediate output. | def apply_activation(intermediate_output, intermediate_activation):
if intermediate_activation is None:
return intermediate_output
if intermediate_activation == 'gelu':
intermediate_output = nn.gelu(intermediate_output)
elif intermediate_activation == 'relu':
intermediate_output = nn.relu(intermediat... | [
"def activation(self, summatory_activation):\n # Этот метод необходимо реализовать\n \n return self.activation_function(summatory_activation)",
"def _apply_activation(self, r):\n\n # In case no activation function was chosen\n if self.activation is None:\n return r\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns TF Bert config.. | def get_tf_config(config_path):
return modeling.BertConfig.from_json_file(config_path).__dict__ | [
"def create_config(config_dir: str) -> configs.BertConfig:\n with tf.io.gfile.GFile(config_dir) as config_file:\n bert_config = json.load(config_file)\n return configs.BertConfig(**bert_config)",
"def get_config():\n return CONFIG",
"def get_config_template(self) -> cconfig.Config:",
"def get_config(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return tf mlperf model parameters in a dictionary format. Use get_tf_model_variables if using kerasBERT checkpoint. This function works | def get_mlperf_model_variables(config_path, init_checkpoint):
# Load saved model configuration
bert_config = modeling.BertConfig.from_json_file(config_path)
seq_length = bert_config.max_position_embeddings
tf_variables = {}
max_predictions_per_seq = 76
# Generate BERT TF model and initiate variable update ... | [
"def convert_mlperf_param_dict_to_jax(tf_params, emb_dim, num_heads):\n jax_params = {}\n # mapping between mlperf model and JAX model\n # works for model in //third_party/tensorflow_models/mlperf/models/rough/bert\n tf_key_to_jax_key = [\n ('cls/seq_relationship/', 'classification/predictions_transform_lo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert TF BERT model config to be compatible with JAX BERT model. | def convert_tf_config_to_jax_bert(config):
unnecessary_keys = ['initializer_range', 'backward_compatible',
'embedding_size']
for key in unnecessary_keys:
if key in config:
config.pop(key)
# change TF parameter names to match JAX parameter names
mapping = {
'attention_dropo... | [
"def get_tf_config(config_path):\n return modeling.BertConfig.from_json_file(config_path).__dict__",
"def convert_from_config(config):\n\n if isinstance(config, str):\n yamlConfig = parse_yaml_config(config)\n else:\n yamlConfig = config\n\n model = None\n if 'OnnxModel' in yamlConfig:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modify TF mlperf model parameter dict to be compatible with JAX parameter dict. Convert parameter names in tf_params to match JAX parameter names and create a nested dictionary of parameters for each layer in the model using `/` in each key as a delimeter. This function uses mlperf model naming convention. Use convert_... | def convert_mlperf_param_dict_to_jax(tf_params, emb_dim, num_heads):
jax_params = {}
# mapping between mlperf model and JAX model
# works for model in //third_party/tensorflow_models/mlperf/models/rough/bert
tf_key_to_jax_key = [
('cls/seq_relationship/', 'classification/predictions_transform_logits/'),
... | [
"def convert_tf_param_dict_to_jax(tf_params):\n jax_params = {}\n tf_key_to_jax_key = [\n ('embeddings/layer_norm', 'embeddings_layer_norm'),\n ('transformer/layer', 'encoder_layer'), ('embeddings:0', 'embedding'),\n (':0', ''), ('beta', 'bias'), ('gamma', 'scale'),\n ('position_embedding/', '... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modify TF parameter dict to be compatible with JAX parameter dict. Convert parameter names in tf_params to match JAX parameter names and create a nested dictionary of parameters for each layer in the model using `/` in each key as a delimeter. | def convert_tf_param_dict_to_jax(tf_params):
jax_params = {}
tf_key_to_jax_key = [
('embeddings/layer_norm', 'embeddings_layer_norm'),
('transformer/layer', 'encoder_layer'), ('embeddings:0', 'embedding'),
(':0', ''), ('beta', 'bias'), ('gamma', 'scale'),
('position_embedding/', 'position_em... | [
"def convert_mlperf_param_dict_to_jax(tf_params, emb_dim, num_heads):\n jax_params = {}\n # mapping between mlperf model and JAX model\n # works for model in //third_party/tensorflow_models/mlperf/models/rough/bert\n tf_key_to_jax_key = [\n ('cls/seq_relationship/', 'classification/predictions_transform_lo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
>>> get_comparison_value('AS KS QS JS TS'.split())[1] 'Royal Flush' >>> get_comparison_value('KS QS JS TS 9S'.split())[1] 'Straight Flush' >>> get_comparison_value('8S 8C 8D 8H 3S'.split())[1] 'Four of a Kind' >>> get_comparison_value('8S 8C 8D 3H 3S'.split())[1] 'Full House' >>> get_comparison_value('2S QS JS TS 9S'.s... | def get_comparison_value(hand):
suits = set(get_suit(card) for card in hand)
values = set(get_value(card) for card in hand)
is_flush = len(suits) == 1
is_straight = (len(values) == 5 and
min(values) + 4 == max(values))
kinds = get_kinds(hand)
kind_counts = [k.count for k in kinds]
i... | [
"def strcmp(s1, s2):\n i = 0\n if s1 > s2:\n return 1\n elif s1 == s2:\n return 0\n else:\n return -1",
"def testWinkler(self): # - - - - - - - - - - - - - - - - - - - - - - - - - -\n\n for pair in self.string_pairs:\n\n approx_str_value = stringcmp.winkler(pair[0],pair[1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the transformation matrix from Galactic spherical to Magellanic Stream coordinates. | def galactic_to_MS():
return MS_MATRIX | [
"def MS_to_galactic():\n return matrix_transpose(MS_MATRIX)",
"def get_shower_trans_matrix (azimuth,altitude):\n\n cos_z = sin(altitude)\n sin_z = cos(altitude)\n cos_az = cos(azimuth)\n sin_az = sin(azimuth)\n\n trans = np.zeros([3,3])\n trans[0][0] = cos_z*cos_az\n trans[1][0] = sin_az\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the transformation matrix from Magellanic Stream coordinates to spherical Galactic. | def MS_to_galactic():
return matrix_transpose(MS_MATRIX) | [
"def galactic_to_MS():\n return MS_MATRIX",
"def spherical_coordinate_conversion_matrix(vector):\n r = ( (vector[0]**2) + (vector[1]**2) + (vector[2]**2) )**(1/2)\n theta = math.atan( ( (vector[0]**2) + (vector[1]**2) )**(1/2)/vector[2] )\n phi = math.atan(vector[1]/vector[0])\n atom_pos_spherical ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add the ``request.raven`` method and configure the `ravenjs` panel. | def includeme(config, get_raven=None, panel=None):
# Compose.
if get_raven is None: #pragma: no cover
get_raven = get_raven_client
if panel is None: #pragma: no cover
panel = raven_js_panel
# Unpack.
settings = config.registry.settings
# Provide the client as ``req... | [
"def includeme(config):\n\n settings = config.registry.settings\n if 'zipkin.collector' not in settings:\n import logging\n logging.getLogger(__name__).warn('The plugin zipkin.binding.pyramid'\n 'is active but not configured. '\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loading model weights and meta information from cfg and checkpoint. Subclasses could override this method to load extra meta information from ``checkpoint`` and ``cfg`` to model. | def _load_weights_to_model(self, model: nn.Module,
checkpoint: Optional[dict],
cfg: Optional[ConfigType]) -> None:
if checkpoint is not None:
_load_checkpoint_to_model(model, checkpoint)
else:
warnings.warn('Checkpoint... | [
"def load_model(self, ckpt_name=\"best_model.pth\"):\n path = \"/\".join(ckpt_name.split(\"/\")[:-1])\n chkpt = torch.load(ckpt_name)\n self.start_epoch = chkpt['epoch']\n self.best_metric = chkpt['best_metric']\n\n # fix the DataParallel caused problem with keys names\n if... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize the ``collate_fn`` with the given config. The returned ``collate_fn`` will be used to collate the batch data. | def _init_collate(self, cfg: ConfigType) -> Callable:
try:
with FUNCTIONS.switch_scope_and_registry(self.scope) as registry:
collate_fn = registry.get(cfg.test_dataloader.collate_fn)
except AttributeError:
collate_fn = pseudo_collate
return collate_fn # t... | [
"def collate_fn(self, collate_fn: Callable) -> \"BaseDataset\":\n self._collate_fn = collate_fn\n return self",
"def build_collate_fn(\n cls, args: argparse.Namespace, train: bool\n ) -> Callable[[Sequence[Dict[str, np.ndarray]]], Dict[str, torch.Tensor]]:\n raise NotImplementedErro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List models defined in metafile of corresponding packages. | def list_models(scope: Optional[str] = None, patterns: str = r'.*'):
matched_models = []
if scope is None:
default_scope = DefaultScope.get_current_instance()
assert default_scope is not None, (
'scope should be initialized if you want '
'to load c... | [
"def list_available_models():\n models = []\n # For each directory in PYTHONPATH\n paths = [p for p in sys.path if os.path.isdir(p)]\n for site_package_dir in paths:\n # For each module\n modules = [os.path.join(site_package_dir, m) for m in os.listdir(site_package_dir)]\n modules =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
By this save method we create user and make a relationship with contact model and secoud depend on conatc type. | def save(self,commit=True):
instance = super(ClientSignupForm, self).save(commit=False)
if commit:
instance.username = self.cleaned_data['email']
instance.is_active = False
instance.save()
contact = Client.objects.create(first_name=self.cleaned_data['first... | [
"def __save_contact_information(self):\n try:\n ContactInformation.objects.create(user=self.user, **self.contact_info)\n except:\n pass",
"def users_create():",
"def save(self):\n \n self.email = self.email.lower()\n\n if self.user_id:\n # upda... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Must preserve data used at construction. Specifically for default averaging/length adjustments. averaging/length adjustments recalculate the underlying data | def _original_data(self, data: np.ndarray):
if self._raw_data is None:
self._raw_data = data | [
"def __update(self):\n self.length = len(self.data)\n self.mean = self.__calc_mean()\n self.median = self.__calc_median()\n self.variance = self.__calc_var()\n self.standev = self.__calc_stdv()",
"def rescale_data(self):\n self.set_data(self.raw_data, self.raw_subset_data... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fully refresh the underlying visual. | def _refresh(self):
self._need_display_update = True
self._update() | [
"def redraw(self):\n self.vispy_viewer.canvas.update()",
"def _refreshGraphics(self):\n self._model.autorangeSpectrum()\n self._ui.alignmentsceneviewerwidget.paintGL()",
"def update_visual(self):\n # Should be overidden in a subclass\n pass",
"def refresh(self):\n\t\tself.wi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates list of mesh vertices and triangles from a list of vectors | def _generate_meshes(self, vectors, width):
centers = np.repeat(vectors, 2, axis=0)
offsets = segment_normal(vectors[::2, :], vectors[1::2, :])
offsets = np.repeat(offsets, 4, axis=0)
signs = np.ones((len(offsets), 2))
signs[::2] = -1
offsets = offsets*signs
vert... | [
"def vertices(tri, vertex_list):\n dim = len(vertex_list[0])\n p = numpy.zeros((3, dim))\n for j in range(3):\n p[j] = vertex_list[tri[j]]\n return p",
"def extract_triangles(mesh, materials_list):\n tri_list = []\n do_uv = bool(mesh.tessface_uv_textures)\n\n for mat in materials_list:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the view given the indices to slice with. | def _set_view_slice(self, indices):
vertices = self._mesh_vertices
faces = self._mesh_triangles
if len(faces) == 0:
self._node.set_data(vertices=None, faces=None)
else:
self._node.set_data(vertices=vertices[:, ::-1], faces=faces,
... | [
"def _set_view_slice(self, indices):\n z_order = self.data._mesh.triangles_z_order\n faces = self.data._mesh.triangles[z_order]\n colors = self.data._mesh.triangles_colors[z_order]\n vertices = self.data._mesh.vertices[:, ::-1]\n if len(faces) == 0:\n self._node._subvis... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Utilities for spatio temporal analysis zed.uchicago.edu Fit dataproc with specified grid parameters and create timeseries for date boundaries specified by INIT, THRESHOLD, and END which do not have to match the arguments first input to the dataproc | def fit(self,grid=None,INIT=None,END=None,THRESHOLD=None,csvPREF='TS'):
if INIT is not None:
self._INIT=INIT
if END is not None:
self._END=END
if grid is not None:
self._grid=grid
assert(self._END is not None)
assert(self._coord1 in self._gri... | [
"def manipulate_data(ds, var, predef_clim, predef_trnd, trn_yrs, all_yrs, \n apply_latw=True, apply_detrending=True, dropna=True):\n\n \n if((var=='SD')|(var=='sd')|(var=='snowc')): \n ds[var] = ds[var].where(ds[var]>=0, other=0.0)\n ds[var] = ds[var].where(ds[var]==0, other=1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Utility function zed.uchicago.edu Converts list into string separated by dashes or empty string if input list is not list or is empty | def stringify(List):
if List is None:
return ''
if not List:
return ''
return '-'.join(str(elem) for elem in List) | [
"def list_to_string(in_list):\n if not in_list:\n return \"[]\"\n else:\n return \"\\n- \" + \"\\n- \".join(in_list)",
"def human_list(_list) -> str:\n last_item = _list.pop()\n result = \", \".join(_list)\n return \"%s or %s\" % (result, last_item)",
"def list_to_str( L ):\n if le... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Utilities for storing and manipulating XPFSA models inferred by XGenESeSS zed.uchicago.edu Calculates the distance between all models and stores them under the distance key of each model; modifies instance in place No I/O | def augmentDistance(self):
for key,value in self._models.iteritems():
src=[float(i) for i in value['src'].replace('#',' ').split()]
tgt=[float(i) for i in value['tgt'].replace('#',' ').split()]
dist = haversine((np.mean(src[0:2]),np.mean(src[2:])),
... | [
"def TrainGCM(self):\n # First, present the instances to the model one by one.\n # Next, estimate the model response.\n # Then forget and re-estimate\n pass",
"def fit(self, graph, instances):\n if self.wl:\n graph.weisfeiler_lehman(iterations=self.wl_iterations)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Path of the directory that stores all the instances. | def instance_dir(self):
return os.path.join(self.basedir, self.yml['instdir']) | [
"def _InstanceDir(cls, instance_name):\n return utils.PathJoin(cls._ROOT_DIR, instance_name)",
"def getInstDir(self):\n\n return os.path.join(self.configDir, self.instName.name.lower())",
"def store_path(self):\n return path.join(env.store_home, self._store_path)",
"def path(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Collects all successful runs and optionally parses their output. | def collect_successful_results(self, parse_fn=None):
def successful_runs(verbose=False):
for run in self.discover_all_runs():
finished = os.access(run.output_file_path('status'), os.F_OK)
if not finished:
if verbose:
print("Skipping unfinished run {}/{}[{}]".format(run.experiment.name,
... | [
"def collect_successful_results(self, parse_fn):\n\n\t\tres = [ ]\n\t\tfor run in self.discover_all_runs():\n\t\t\texp = run.experiment\n\t\t\tfinished = os.access(run.output_file_path('status'), os.F_OK)\n\t\t\tif not finished:\n\t\t\t\tprint(\"Skipping unfinished run {}/{}[{}]\".format(run.experiment.name,\n\t\t\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Exports experiments based on their status. | def export_experiments(self, included_statuses=None):
experiment_list = []
if included_statuses is not None:
for run in self.discover_all_runs():
status = run.get_status()
if status in included_statuses:
experiment_list.append((
run.experiment.name,
tuple(variant.name for variant in run... | [
"def phases_export(self):\n for idx, phase in enumerate(self.phases[:-1]):\n trans_op = False\n # only export if the phase has a transform operator on the dataset\n # otherwise all stats will be saved in the tabular object\n for task in phase:\n if i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
devbuilds only have a source directory instead of a repo and clone directory | def source_dir(self):
assert self.revision.is_dev_build
rev = self._get_dev_build_suffix()
return os.path.join(self._cfg.basedir, 'develop', self.name + rev) | [
"def install_dev_env(url, branch=None):\n startdir = os.getcwd()\n \n # make sure we don't clobber an existing repo\n if os.path.exists('OpenMDAO-Framework'):\n print \"Directory OpenMDAO-Framework already exists\"\n sys.exit(-1)\n\n if url.endswith('.git'): # clone the git repo\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the correlation coefficients between columns. Displays them in descending order of their absolute values. | def correlation(data, method, caption):
columns = list(data)
coefficients = data.astype(float).corr(method=method)
results = []
for i in range(len(columns)):
for j in range(i + 1, len(columns)):
coefficient = coefficients[columns[i]][columns[j]]
results.append((
... | [
"def print_correlations(results,columns):\n header, rows = results \n name2idx = indices(header)\n cols = zip(*rows)\n for i,n1 in enumerate(columns):\n for j,n2 in enumerate(columns):\n if j>=i: break\n v1 = map(float,cols[name2idx[n1]])\n v2 = map(float,cols[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate new UUIDs for all rows in a table | def assign_uuids(
model: Any, session: Session, batch_size: int = DEFAULT_BATCH_SIZE
) -> None:
bind = op.get_bind()
table_name = model.__tablename__
count = session.query(model).count()
# silently skip if the table is empty (suitable for db initialization)
if count == 0:
return
sta... | [
"def _generate_UUID():\n new_id = uuid1().hex\n while Participant.objects.filter(uuid=new_id).exists():\n new_id = uuid1().hex\n return new_id",
"def __generate_unique_id(df, \n columns_to_generate_id = ['id', 'created_at', 'last_login'], \n output_colum... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If param == 0, sets turn angle to default value. Converts current position angle from radians to degrees. Converts negative angles to positive. COntinues to turn left until the current distance to the goal is greater than the previous distance, meaning that the goal has been passed. | def left(self, param):
global estop_flag, move_state
#If input angle is zero, set angle to default
if param:
angle = param
else:
angle = riu.default_angle
signal.alarm(0) #Disable timer interrupt for the duration of the movement
#safely grab current yaw
with self.move_state_lock:
current_yaw = (... | [
"def right(self, param):\n\t\tglobal estop_flag, move_state\n\t\t#If input angle is zero, set angle to default\n\t\tif param:\n\t\t\tangle = param\n\t\telse:\n\t\t\tangle = riu.default_angle\n\n\t\tsignal.alarm(0) #Disable timer interrupt for the duration of the movement\n\t\t#safely grab current yaw\n\t\twith self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If param == 0, sets turn angle to default value. Converts current position angle from radians to degrees. Converts negative angles to positive. COntinues to turn left until the current distance to the goal is greater than the previous distance, meaning that the goal has been passed. | def right(self, param):
global estop_flag, move_state
#If input angle is zero, set angle to default
if param:
angle = param
else:
angle = riu.default_angle
signal.alarm(0) #Disable timer interrupt for the duration of the movement
#safely grab current yaw
with self.move_state_lock:
current_yaw = ... | [
"def left(self, param):\n\t\tglobal estop_flag, move_state\n\t\t#If input angle is zero, set angle to default\n\t\tif param:\n\t\t\tangle = param\n\t\telse:\n\t\t\tangle = riu.default_angle\n\n\t\tsignal.alarm(0) #Disable timer interrupt for the duration of the movement\n\t\t#safely grab current yaw\n\t\twith self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calls linear_move. If no parameter, defaults to default_dist | def forward(self, param):
if param:
self.linear_move(param * .3048)
else:
self.linear_move(riu.default_dist * .3048) | [
"def linear_move(self, initial_position, final_position):\n if any(initial_position - final_position):\n # The desired position is not the actual position (would make a 'divide by zero' error otherwise)\n\n # Compute directional vector\n dir_vector = final_position - initial_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks the tracking variable updated by the tracker callback. If no correction is needed, sends a linear twist message. If correction is needed, sends a left or right angular twist as appropriate. Acquires a lock on the move state to update its position. Checks for estop every cycle. Disables ready messages for duratio... | def linear_track(self, dist):
global estop_flag, move_state
#Disable timer interrupt, reset halfway flag, set target distance
signal.alarm(0)
halfway_flag = False
#Set starting position
with self.move_state_lock:
start_x, start_y, start_z = move_state['x'], move_state['y'], move_state['z']
#Set curr... | [
"def linear_move(self, dist):\n\t\tglobal estop_flag, move_state\n\t\tsignal.alarm(0) #Disable timer interrupt for the duration of the movement\n\t\thalfway_flag = False\n\t\t\n\t\twith self.move_state_lock:\n\t\t\tstart_x, start_y, start_z = move_state['x'], move_state['y'], move_state['z']\n\t\tcurrent_x = start_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Moves the robot a distance equal to dist. Checks for estop on each iteration. Publishes a Done message after completion and a Half message when the current distance is equal to half of the goal distance. | def linear_move(self, dist):
global estop_flag, move_state
signal.alarm(0) #Disable timer interrupt for the duration of the movement
halfway_flag = False
with self.move_state_lock:
start_x, start_y, start_z = move_state['x'], move_state['y'], move_state['z']
current_x = start_x
current_y = start_y
c... | [
"def drive(self, distance, tolerance=0.0, tolerance_step=0.5,\n max_attempts=10, avoid_targets=True, avoid_home=False,\n use_waypoints=True):\n self.cur_loc = self.swarmie.get_odom_location()\n start = self.cur_loc.get_pose()\n\n goal = Point()\n goal.x = start.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clean the distributed compute pipeline. | def cleanup():
dist.destroy_process_group() | [
"def cleanup(self):\n with hide(\"output\", \"warnings\", \"running\"):\n self.stop_all()\n self._execute_standard(\"rm -rf {model_repo}\".format(model_repo=MODEL_REPO))\n self._execute_root(\"docker rmi --force $(docker images -q)\", warn_only=True)\n self._execut... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reset all OATH data. This action will delete all accounts and restore factory settings for the OATH application on the YubiKey. | def reset(ctx, force):
force or click.confirm(
"WARNING! This will delete all stored OATH accounts and restore factory "
"settings. Proceed?",
abort=True,
err=True,
)
session = ctx.obj["session"]
click.echo("Resetting OATH data...")
old_id = session.device_id
se... | [
"def reset(ctx):\n\n controller = ctx.obj['controller']\n click.echo('Resetting OATH data...')\n old_id = controller.id\n controller.reset()\n\n settings = ctx.obj['settings']\n keys = settings.setdefault('keys', {})\n if old_id in keys:\n del keys[old_id]\n settings.write()\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Manage and use OATH accounts. | def accounts(): | [
"def open_account():\n print(\"\\n\")\n print(messages.open_account)\n u_id = pyip.inputInt(\"Id: \", greaterThan=0)\n name = pyip.inputCustom(raiseNameError, prompt=\"Name: \")\n address = pyip.inputCustom(raiseAddressError, prompt=\"Address: \")\n email = pyip.inputEmail(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate codes. Generate codes from OATH accounts stored on the YubiKey. Provide a query string to match one or more specific accounts. Accounts of type HOTP, or those that require touch, requre a single match to be triggered. | def code(ctx, show_hidden, query, single, password, remember):
_init_session(ctx, password, remember)
session = ctx.obj["session"]
entries = session.calculate_all()
creds = _search(entries.keys(), query, show_hidden)
if len(creds) == 1:
cred = creds[0]
code = entries[cred]
... | [
"def code(ctx, show_hidden, query, single):\n\n ensure_validated(ctx)\n\n controller = ctx.obj['controller']\n creds = [(cr, c)\n for (cr, c) in controller.calculate_all()\n if show_hidden or not cr.is_hidden\n ]\n\n creds = _search(creds, query)\n\n if len(creds) ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Rename an account (requires YubiKey 5.3 or later). \b QUERY a query to match a single account (as shown in "list") | def rename(ctx, query, name, force, password, remember):
_init_session(ctx, password, remember)
session = ctx.obj["session"]
creds = session.list_credentials()
hits = _search(creds, query, True)
if len(hits) == 0:
click.echo("No matches, nothing to be done.")
elif len(hits) == 1:
... | [
"def change_name(change_account):\n change_data(change_account, changed_data='name')",
"def userRenamed(self, oldname, newname):\n # Send messasge to Server bot.\n self.data_in(text=\"\", type=\"renamed\", oldname=oldname, newname=newname)",
"def change_username(self, accountid, oldusername, ne... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if link_id is in a valid format. | def isLinkIdFormatValid(link_id):
if linkable.LINK_ID_REGEX.match(link_id):
return True
return False | [
"def cleanLinkID(link_id):\n if not validate.isLinkIdFormatValid(link_id):\n raise forms.ValidationError(\n DEF_INVALID_LINK_ID % link_id, code=_INVALID_CODE)",
"def is_valid_id(id_):\n if not re.match(r'^[%A-Za-z0-9_.\\\\\\-~]*$', id_):\n return False\n return True",
"def valid_id(id):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if scope_path is in a valid format. | def isScopePathFormatValid(scope_path):
if linkable.SCOPE_PATH_REGEX.match(scope_path):
return True
return False | [
"def is_valid(self, path) -> bool:\n file = pathlib.Path(path)\n return (file.is_file() and file.suffix == \".csv\") # does this work?",
"def _verify_scope(self, scope, client_id):\n\n # Malformed scope requesting validation of more than one affiliation type\n requested_affiliations =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch latest crease xml from animation publish folder... | def _crease_XML_latest_publish(self, tk, templateFile = '', id = '', shotNum = ''):
debug(app = self.app, method = '_crease_XML_latest_publish', message = 'Looking for crease xml now...', verbose = False)
getCreaseXMLPublishFolder = tk.paths_from_template( templateFile, {'Step' : 'Anm', 'id' : id, 'Shot' : shot... | [
"def extractAnimationsFromXar( strFilename ):\n print( \"INF: extractAnimationFromXar: parsing '%s'\" % strFilename );\n allAnims = dict();\n xar = xml.dom.minidom.parse( strFilename );\n choregrapheNode = xar.childNodes[0]; # first is \"ChoregrapheProject\"\n strXarVersion = choregrapheNode.getAttri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Exposing a tool to help push the ocean into the right location based off the FX published fluid containers fluids_hrc | def _setOceanLocation(self):
## If the fluids_hrc exists
if cmds.objExists('fluids_hrc'):
if cmds.objExists('ocean_srf'):
cmds.connectAttr('fluids_hrc.translateX', 'ocean_srf.translateX', f = True)
cmds.connectAttr('fluids_hrc.translateZ', 'ocean_srf.translateZ', f = True)
else:
cmds.warnin... | [
"def _setOceanLocation():\n\t## If the fluids_hrc exists\n\tif cmds.objExists('fluids_hrc'):\n\t\tif cmds.objExists('ocean_srf'):\n\t\t\tcmds.connectAttr('fluids_hrc.translateX', 'ocean_srf.translateX', f = True)\n\t\t\tcmds.connectAttr('fluids_hrc.translateZ', 'ocean_srf.translateZ', f = True)\n\t\telse:\n\t\t\tcm... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return if the selected digits from start in the number are a palindrome | def is_number_palindrome(number, digits, start):
number = str((number // 10**start) % 10**digits).zfill(digits)
return is_palindrome(number) | [
"def is_number_palindrome(number, digits, start):\n number = str((number // 10**start) % 10**digits).rjust(digits, \"0\")\n return is_palindrome(number)",
"def is_palindrom(number):\n number = str(number)\n return number == number[::-1]",
"def is_palindrome(number):\r\n str_input = str(number)\r\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get all the tag combinations possible for a tree of length n | def get_all_tag_seq(self, n):
tags = list(product(self.tags, repeat=n))
return tags | [
"def enum_nestings(trees, data):\n\n rs = (itertools.combinations(vs,l) for l in range(len(trees)))",
"def EnumerateAllBinaryTrees(n):\n if n == 0:\n yield []\n for i in xrange(n):\n for left_child in EnumerateAllBinaryTrees(i):\n for right_child in EnumerateAllBinaryTrees(n - i - 1):\n yie... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get index of a tag sequence m in self.tags | def get_tag_index(self, m):
return self.tags.index(m) | [
"def index(self, tag):\n return self.tags.index(tag)",
"def index_in_tag(self):\n if hasattr(self, '_m_index_in_tag'):\n return self._m_index_in_tag if hasattr(self, '_m_index_in_tag') else None\n\n self._m_index_in_tag = (self.tag - 35)\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given two tags and a label, return the psi factor of the two tag sequences | def get_psi_score(self, psi, pos1, pos2, lab, m1, m2):
i, j = self.get_tag_index(m1), self.get_tag_index(m2)
return psi[pos1, pos2, lab, i, j] | [
"def _psi_function(share1, share2):\n return (share1 - share2) * math.log(share1/share2)",
"def get_emissions_probability(label_matches, given_tag, given_word, tag_counts):\r\n\tlookup_tuple = (given_word, given_tag)\r\n\tword_tag_frequency = label_matches.get(lookup_tuple, 0)\r\n\ttag_frequency = tag_counts[g... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the gradient of the log probability for a given tree with respect to the psi and phi parameters | def dlog_prob(self, T, pos, m, psi, phi=tr.Tensor()):
if phi.size() == tr.Size([0]):
phi = self.create_phi(T, pos, m)
dpsi_score = self.dlog_score(T, pos, m, psi)
dpsi_Z = self.dlogZ(T, pos, psi, phi)
return dpsi_score - dpsi_Z | [
"def grad_log(self, X):\n # \"\"\"\n # Evaluate the gradients (with respect to the input) of the log density at\n # each of the n points in X. This is the score function.\n\n # X: n x d numpy array.\n XB = np.dot(X, self.B)\n Y = 0.5*XB + self.c\n E2y = np.exp(2*Y)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns beat info as string | def Beat_disp(self):
return ' '.join(str(x+self.offset) for x in self.beats) | [
"def as_str(self) -> str:\n info_str = ''\n for key, value in self.fig_info.items():\n info_str += f'{key} : {value}\\n'\n\n # add timestamp\n res = datetime.utcnow().isoformat(timespec='seconds')\n info_str += f'created : {res}'\n\n return info_str",
"def get_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Team members' stats page for app | def team_members_stats(request):
username = request.session.get('username', False)
profile = request.session.get('profile', False)
if (username):
context = {'username': username, 'profile': profile}
return render(request, 'MedTAG_sket_dock_App/index.html', context)
else:
return ... | [
"def get_tournament_stats(self):",
"def info():\n print 'Loading info page'\n\n team_list = datastore.get_all_teams(engine)\n\n return render_template('info.html', rows=team_list)",
"def report_members_stats(request, template_name='reports/membership_stats.html'):\n summary, total = get_membership_s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This view returns the current session parameters | def get_session_params(request):
json_resp = {}
usecase = request.session.get('usecase',None)
language = request.session.get('language',None)
institute = request.session.get('institute',None)
annotation = request.session.get('mode',None)
team_member = request.session.get('team_member',None)
... | [
"def parameters():\n return render_template(\n 'parameters.html',\n title= \"Pi-Lapse\",\n year=datetime.now().year,\n )",
"def myCurrentSetting(self):\n paramDict = self.getCurrentSetting()\n return paramDict",
"def request_vars(self):",
"def get_params(self):\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This view handles the GET and POST requestes for LABELS ANNOTATION ACTION | def annotationlabel(request,action=None):
username = request.session['username']
mode1 = request.session['mode']
auto_required = request.GET.get('ns_id', None)
mode = NameSpace.objects.get(ns_id=mode1)
# print('mode',mode1)
usecase = request.session['usecase']
# language = request.GET.get(... | [
"def post_label():\n label_id = dao.set_label(id=str(uuid.uuid4()),\n name=request.json['name'],\n fields=request.json['fields'])\n\n return jsonify(dao.get_label(label_id))",
"def search_labels(request):\n client = ApiClient()\n query_term = req... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This view handles the GET AND POST requests to insert, delete, get concepts. | def contains(request, action=None):
username = request.session.get('username', False)
mode1 = request.session.get('mode', False)
mode = NameSpace.objects.get(ns_id=mode1)
error_json = {"Error": "No user authenticated"}
if (username):
response_json = {}
if request.method == 'GET':
... | [
"def post(self):\n\n app.logger.info('Received request for Concept creation')\n\n return post_concept_handler.handle_request(dict(request.form))",
"def post(self, request):\n log.debug(\"site.post: %r\"%(request.POST.lists()))\n\n collections = request.POST.getlist(\"select\", [])\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This view returns the list of reports associated to a single use_case, institute and language | def get_reports(request):
inst = request.GET.get('institute',None)
use = request.GET.get('usec',None)
print(use)
lang = request.GET.get('lang',None)
batch = request.GET.get('batch',None)
all = request.GET.get('all',None)
actual_report = request.GET.get('actual_report',None)
if all == 'a... | [
"def training_report_view(request, application_slug):\n return training_report(request, application_slug, attach=False)",
"def analysis_results_listing(request,option=None):\n\n if option == \"csv\":\n return generate_analysis_results_csv(request)\n return generate_analysis_results_jtable(request,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This view checks whether the configuration files the user inserted are well formed and returns the response | def check_input_files(request):
reports = []
labels = []
pubmedfiles = []
concepts = []
type1 = request.POST.get('type',None)
username = request.POST.get('username',None)
# email = request.POST.get('email',None)
password = request.POST.get('password',None)
for filename, file in requ... | [
"def check_conf_files(self):\n pass",
"def validate_config():\n\n # diff/sync settings, not including templates (see below)\n nori.setting_check_list('action', ['diff', 'sync'])\n nori.setting_check_type('reverse', bool)\n nori.setting_check_type('bidir', bool)\n nori.setting_check_callbacks... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This view checks whether the files inserted by the user to update the configuration are well formed | def check_files_for_update(request):
reports = []
pubmedfiles = []
labels = []
concepts = []
type1 = request.POST.get('type',None)
for filename, file in request.FILES.items():
if filename.startswith('reports'):
reports.append(file)
if filename.startswith('pubmed'):
... | [
"def check_edited_configuration_part(self):\n if (self.edit_mode):\n sheet=self.wb.sheets()[0]\n configuration_names=sheet.col_values(0,0,7) # names in the configuration (country, co_code, year,etc.). i.e. first column\n configuration_values=sheet.col_values(1,0,7) # values o... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This view returns the list of all the distinct keys present in the json reports. This view is called during configuration | def get_keys(request):
keys=[]
reports = Report.objects.all().exclude(institute = 'PUBMED')
for report in reports:
json_rep = report.report_json
for el in json_rep.keys():
if el not in keys:
keys.append(el)
json_resp = {'keys':keys}
return JsonResponse(js... | [
"def AllKeys(self) -> _n_0_t_1[str]:",
"def list_keys(self):\r\n return self.data.keys()",
"def api_sshkeys_list():\n return jsonify(export.collect_all_keys())",
"def distinct(self, key):\n return self.database.command({'distinct': self.name,\n 'key': key}... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This view returns ALL the ground truths to be downloaded. This view can be called only by the admin and the ground truths returned are those of ALL the users in the platform | def download_all_ground_truths(request):
json_resp = {}
json_resp['ground_truth'] = []
cursor = connection.cursor()
mode = request.GET.get('gt_mode',None)
if mode is None:
human = NameSpace.objects.get(ns_id = 'Human')
robot = NameSpace.objects.get(ns_id = 'Robot')
gt_human ... | [
"def get_user_ground_truth(request):\n\n user = request.GET.get('user',None)\n action = request.GET.get('action',None)\n mode = request.GET.get('mode',None)\n report = request.GET.get('report',None)\n language = request.GET.get('language',request.session['language'])\n mode_obj = NameSpace.objects... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This view returns the key files of BioC mentions and linking. | def download_key_files(request):
workpath = os.path.dirname(os.path.abspath(__file__)) # Returns the Path your .py file is in
path = os.path.join(workpath, './static/BioC/linking.key')
path1 = os.path.join(workpath, './static/BioC/mention.key')
ment = request.GET.get('type_key',None)
if ment == 'm... | [
"def take_auth_data():\n home = str(Path.home())\n path_to_keys = '/Documents/twitter/keys/'\n\n files = [f for f in listdir(home+path_to_keys) if '.DS' not in f]\n\n tokens = []\n for f in files:\n with open(home+path_to_keys+f, 'r') as lines:\n ln = lines.readline().replace(\" \",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This view returns the last ground truth created by the user for the session's parameters | def get_last_gt(request):
username = request.session['username']
mode1 = request.session['mode']
mode = NameSpace.objects.get(ns_id=mode1)
language = request.session['language']
usecase = request.session['usecase']
institute = request.session['institute']
batch = request.session['batch']
... | [
"def get_user_ground_truth(request):\n\n user = request.GET.get('user',None)\n action = request.GET.get('action',None)\n mode = request.GET.get('mode',None)\n report = request.GET.get('report',None)\n language = request.GET.get('language',request.session['language'])\n mode_obj = NameSpace.objects... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This view returns for each key of the json report required its text, the indexes of the start and stop chars in the json report string and the number of words that compose the fields to annotate. | def report_start_end(request):
report = request.GET.get('report_id')
lang = request.GET.get('language',None)
usecase = request.session['usecase']
data = get_fields_from_json()
json_keys_to_display = data['fields']
json_keys_to_display.extend(['journal','authors','year','volume'])
json_keys_... | [
"def count(json, index, word_list, index_words, word_count, dic):\n c = word_count\n if index_words >= len(word_list):\n return\n if index >= len(json):\n return count(json, 0, word_list, index_words + 1, 0, dic)\n c = [x for x in json[index][\"data\"][\"title\"].lower().split()].count(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This view returns the fields to display and annotate. If the annotation mode is automatic the fields to annotate are those the concepts and mentions have been extracted from. The fields are returned to give the user the chance to update the fields she wants to display/annotate in MANUAL CONFIGURATION. | def get_fields(request):
json_resp = {}
json_resp['fields'] = []
json_resp['fields_to_ann'] = []
all = request.GET.get('all',None)
workpath = os.path.dirname(os.path.abspath(__file__)) # Returns the Path your .py file is in
auto_request = request.GET.get('ns_id', None)
report = request.GET... | [
"def get_fields_to_show(self):\r\n\r\n return [self[f] for f in extra_fields]",
"def test_annotation_field(self):\n # Unauthenticated user should get 403 response.\n request = factory.get(\"/\", {}, format=\"json\")\n response: HttpResponse = self.annotationfield_viewset(request)\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This view creates the HttpResponse object with the CSV examples files, these are the examples the user can download. | def download_examples(request):
file_required = request.GET.get('token',None)
path = ''
workpath = os.path.dirname(os.path.abspath(__file__)) # Returns the Path your .py file is in
if file_required == 'reports':
path = os.path.join(workpath, './static/examples/report.csv')
elif file_requi... | [
"def csv_download_view(request):\n logging.info(\" CSV file download is working\")\n now = datetime.now()\n timestamp = now.strftime(\"%Y_%m_%d\")\n response = HttpResponse(content_type='text/csv')\n response['Content-Disposition'] = 'attachment; filename=\"results_' + \\\n GLOBAL_VARIABLE.get... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This view creates the HttpResponse object with the appropriate CSV header, these are the templates the user can download. | def download_templates(request):
file_required = request.GET.get('token',None)
path = ''
workpath = os.path.dirname(os.path.abspath(__file__)) # Returns the Path your .py file is in
if file_required == 'reports':
path = os.path.join(workpath, './static/templates/report.csv')
elif file_re... | [
"def get_cvs_template(self, request, *args, **kwargs):\n response = HttpResponse(content_type='text/csv')\n\n csv_file_name = \"template_controls.csv\"\n response[\"Content-Disposition\"] = 'attachment; filename=\"{}\"'.format(csv_file_name)\n writer = csv.writer(response)\n write... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This view returns the list of all the keys found in report files (other than institute,usecase,id_report,language) the admin has just inserted to update the database (only the keys that have never been detected before are returned). | def get_keys_from_csv_update(request):
reports = []
json_resp = {}
for filename, file in request.FILES.items():
if filename.startswith('reports'):
reports.append(file)
elif filename.startswith('pubmed'):
reports.append(file)
keys,uses = get_keys_csv_update(repor... | [
"def get_keys(request):\n\n keys=[]\n reports = Report.objects.all().exclude(institute = 'PUBMED')\n for report in reports:\n json_rep = report.report_json\n for el in json_rep.keys():\n if el not in keys:\n keys.append(el)\n json_resp = {'keys':keys}\n return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This view returns the groundtruth associated to a specific user,action,report | def get_user_ground_truth(request):
user = request.GET.get('user',None)
action = request.GET.get('action',None)
mode = request.GET.get('mode',None)
report = request.GET.get('report',None)
language = request.GET.get('language',request.session['language'])
mode_obj = NameSpace.objects.get(ns_id=m... | [
"def download_all_ground_truths(request):\n\n json_resp = {}\n json_resp['ground_truth'] = []\n cursor = connection.cursor()\n mode = request.GET.get('gt_mode',None)\n if mode is None:\n human = NameSpace.objects.get(ns_id = 'Human')\n robot = NameSpace.objects.get(ns_id = 'Robot')\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This view returns the list of batches associated to a use case | def get_batch_list(request):
json_resp = {}
json_resp['batch_list'] = []
usecase = request.GET.get('usecase',None)
# print(usecase)
if usecase is None:
batch = Report.objects.all().exclude(institute='PUBMED').values('batch')
else:
use_obj = UseCase.objects.get(name=usecase)
... | [
"def view_batches(request):\n\n template = 'batch_list.html'\n\n context = {\n 'invalid_due_date': request.GET.get('invalid_due_date')\n }\n\n try:\n get_batches(request, context)\n except Exception as e:\n context['error'] = '{} {}'.format(e, traceback.format_exc())\n\n # TOD... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This view returns the list of batches associated to a use case which have english language | def get_auto_anno_batch_list(request):
json_resp = {}
usecase = request.GET.get('usecase')
# print(usecase)
use_obj = UseCase.objects.get(name=usecase)
json_resp['batch_list'] = []
languages = ['English','english']
batch = Report.objects.filter(name=use_obj,language__in = languages).exclude... | [
"def get_auto_anno_PUBMED_batch_list(request):\n\n json_resp = {}\n usecase = request.GET.get('usecase')\n # print(usecase)\n languages = ['English', 'english']\n use_obj = UseCase.objects.get(name=usecase)\n json_resp['batch_list'] = []\n batch = Report.objects.filter(name=use_obj,language__in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This view returns the list of batches associated to a PUBMED use case | def get_PUBMED_batch_list(request):
json_resp = {}
usecase = request.GET.get('usecase')
# print(usecase)
use_obj = UseCase.objects.get(name=usecase)
json_resp['batch_list'] = []
batch = Report.objects.filter(name=use_obj,institute = 'PUBMED').values('batch')
for el in batch:
if el['... | [
"def view_batches(request):\n\n template = 'batch_list.html'\n\n context = {\n 'invalid_due_date': request.GET.get('invalid_due_date')\n }\n\n try:\n get_batches(request, context)\n except Exception as e:\n context['error'] = '{} {}'.format(e, traceback.format_exc())\n\n # TOD... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This view returns the list of batches associated to a PUBMED use case in english language | def get_auto_anno_PUBMED_batch_list(request):
json_resp = {}
usecase = request.GET.get('usecase')
# print(usecase)
languages = ['English', 'english']
use_obj = UseCase.objects.get(name=usecase)
json_resp['batch_list'] = []
batch = Report.objects.filter(name=use_obj,language__in = languages,... | [
"def get_PUBMED_batch_list(request):\n\n json_resp = {}\n usecase = request.GET.get('usecase')\n # print(usecase)\n use_obj = UseCase.objects.get(name=usecase)\n json_resp['batch_list'] = []\n batch = Report.objects.filter(name=use_obj,institute = 'PUBMED').values('batch')\n for el in batch:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This view handles the download of one or more reports' groundtruths (including the GT majority vote based. | def download_all_reports(request):
request_body_json = json.loads(request.body)
report_list = request_body_json['report_list']
mode = request_body_json['format']
action = request_body_json['action']
annot = request_body_json['annotation_mode']
if annot == 'Manual':
annot = 'Human'
... | [
"def download_all_ground_truths(request):\n\n json_resp = {}\n json_resp['ground_truth'] = []\n cursor = connection.cursor()\n mode = request.GET.get('gt_mode',None)\n if mode is None:\n human = NameSpace.objects.get(ns_id = 'Human')\n robot = NameSpace.objects.get(ns_id = 'Robot')\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This view returns the usecases which have not nor exa labels nor exa concepts | def get_uses_missing_exa(request):
use_to_ret = {}
use_to_ret['labels_present'] = []
use_to_ret['concepts_present'] = []
use_to_ret['labels_missing'] = []
use_to_ret['concepts_missing'] = []
uses = ['colon','uterine cervix','lung']
for el in uses:
usecase = UseCase.objects.get(name=... | [
"def all_included_use_cases(self):\n raise NotImplementedError(\n 'operation all_included_use_cases(...) not yet implemented')",
"def test_returns_all_studies_with_no_query(self):\n url = self.get_url()\n response = self.client.get(url)\n pks = get_autocomplete_view_ids(resp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This view returns the languages available for a report | def get_report_translations(request):
id_report = request.GET.get('id_report',None)
if id_report is not None:
languages = []
lang = Report.objects.filter(id_report = id_report)
for el in lang:
if el.language not in languages:
languages.append(el.language)
... | [
"def languages(self):\r\n url = '{0}/{1}'.format(self.get_url(), 'languages')\r\n\r\n return http.Request('GET', url), parsers.parse_json",
"def wikiLanguages():\n return languages",
"def get_langs():\r\n temp = \"\"\r\n translate_client = translate.Client()\r\n for i in translate_clie... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This view returns return the usecases of medtag reports | def medtag_reports(request):
json_resp = {}
json_resp['usecase'] = []
reps = Report.objects.all()
for r in reps:
if not r.id_report.startswith('PUBMED_') and not str(r.name_id) in json_resp['usecase']:
json_resp['usecase'].append(str(r.name_id))
return JsonResponse(json_resp) | [
"def summary(request, tag=''):\n if tag:\n if tag.startswith(\"@\"):\n target = Target.objects.get(id=tag[1:])\n summaries_by_value, consfield_summaries = target.getSummaries()\n elif tag.startswith(\"~\"):\n # TODO: is there a sensible analogous summary for users,\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This view returns return the usecases of pubmed reports | def pubmed_reports(request):
json_resp = {}
json_resp['usecase'] = []
reps = Report.objects.all()
for r in reps:
if r.id_report.startswith('PUBMED_') and not str(r.name_id) in json_resp['usecase']:
json_resp['usecase'].append(str(r.name_id))
return JsonResponse(json_resp) | [
"def summaryView(request):\n\n alert_errors = []\n alert_infos = []\n alert_filters = []\n\n runs = get_runs_from_request_filters(\n request, alert_errors, alert_infos, alert_filters\n )\n\n summary = SummaryReport(runs)\n\n context = {\n \"refs\": summary.reference_runs(),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the fuzz target of |benchmark| | def get_fuzz_target(benchmark):
# Do this because of OSS-Fuzz-on-demand.
# TODO(metzman): Use classes to mock a benchmark config for
# OSS_FUZZ_ON_DEMAND.
return benchmark_config.get_config(benchmark).get(
'fuzz_target', environment.get('FUZZ_TARGET')) | [
"def get_fuzzer_benchmark_key(fuzzer: str, benchmark: str):\n return fuzzer + ' ' + benchmark",
"def _get_fuzzer_path(target_list, fuzzer_name):\n fuzzer_filename = environment.get_executable_filename(fuzzer_name)\n for path in target_list:\n if os.path.basename(path) == fuzzer_filename:\n return pat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the project of |benchmark| | def get_project(benchmark):
return benchmark_config.get_config(benchmark)['project'] | [
"def benchmark_profile(self):\n cb_bin = os.path.join(bin_path, 'compilebench')\n desc = \"benchmark\"\n test_name = \"compilebench_{0}\".format(to_safe_name(desc))\n test = TestProfile(\n name=test_name,\n desc=desc,\n test_path=self.test_path,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the type of |benchmark| | def get_type(benchmark):
# TODO(metzman): Use classes to mock a benchmark config for
# OSS_FUZZ_ON_DEMAND.
default_value = os.getenv('EXPERIMENT_TYPE', BenchmarkType.CODE.value)
return benchmark_config.get_config(benchmark).get('type', default_value) | [
"def test_get_default_type(_):\n assert benchmark_utils.get_type('benchmark') == 'code'",
"def validate_type(benchmark):\n benchmark_type = get_type(benchmark)\n if benchmark_type not in BENCHMARK_TYPE_STRS:\n logs.error('%s has an invalid benchmark type %s, must be one of %s',\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the URL of the docker runner image for fuzzing the benchmark with fuzzer. | def get_runner_image_url(experiment, benchmark, fuzzer, docker_registry):
tag = 'latest' if environment.get('LOCAL_EXPERIMENT') else experiment
return f'{docker_registry}/runners/{fuzzer}/{benchmark}:{tag}' | [
"def get_builder_image_url(benchmark, fuzzer, docker_registry):\n return f'{docker_registry}/builders/{fuzzer}/{benchmark}'",
"def test_get_runner_image_url(benchmark, expected_url, oss_fuzz_benchmark):\n assert benchmark_utils.get_runner_image_url('experiment', benchmark,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the URL of the docker builder image for fuzzing the benchmark with fuzzer. | def get_builder_image_url(benchmark, fuzzer, docker_registry):
return f'{docker_registry}/builders/{fuzzer}/{benchmark}' | [
"def get_runner_image_url(experiment, benchmark, fuzzer, docker_registry):\n tag = 'latest' if environment.get('LOCAL_EXPERIMENT') else experiment\n return f'{docker_registry}/runners/{fuzzer}/{benchmark}:{tag}'",
"def test_get_runner_image_url(benchmark, expected_url, oss_fuzz_benchmark):\n assert bench... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if |benchmark| is a valid fuzzbench benchmark name. | def validate_name(benchmark):
if VALID_BENCHMARK_REGEX.match(benchmark) is None:
logs.error('%s does not conform to %s pattern.', benchmark,
VALID_BENCHMARK_REGEX.pattern)
return False
return True | [
"def validate(benchmark):\n if not validate_name(benchmark):\n return False\n\n if benchmark not in get_all_benchmarks():\n logs.error('%s must have a benchmark.yaml.', benchmark)\n return False\n\n # Validate config file can be parsed.\n try:\n get_fuzz_target(benchmark)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if |benchmark| has a valid type. | def validate_type(benchmark):
benchmark_type = get_type(benchmark)
if benchmark_type not in BENCHMARK_TYPE_STRS:
logs.error('%s has an invalid benchmark type %s, must be one of %s',
benchmark, benchmark_type, BENCHMARK_TYPE_STRS)
return False
return True | [
"def test_validate_type_invalid(_):\n assert not benchmark_utils.validate_type('benchmark')",
"def validate(benchmark):\n if not validate_name(benchmark):\n return False\n\n if benchmark not in get_all_benchmarks():\n logs.error('%s must have a benchmark.yaml.', benchmark)\n return F... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if |benchmark| is a valid fuzzbench benchmark. | def validate(benchmark):
if not validate_name(benchmark):
return False
if benchmark not in get_all_benchmarks():
logs.error('%s must have a benchmark.yaml.', benchmark)
return False
# Validate config file can be parsed.
try:
get_fuzz_target(benchmark)
except yaml.pa... | [
"def validate_type(benchmark):\n benchmark_type = get_type(benchmark)\n if benchmark_type not in BENCHMARK_TYPE_STRS:\n logs.error('%s has an invalid benchmark type %s, must be one of %s',\n benchmark, benchmark_type, BENCHMARK_TYPE_STRS)\n return False\n return True",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the list of all benchmarks. | def get_all_benchmarks():
all_benchmarks = []
for benchmark in os.listdir(BENCHMARKS_DIR):
benchmark_path = os.path.join(BENCHMARKS_DIR, benchmark)
if os.path.isfile(os.path.join(benchmark_path, 'benchmark.yaml')):
all_benchmarks.append(benchmark)
return sorted(all_benchmarks) | [
"def list_benchers():\n print_registry_items(BENCHERS)",
"def benchmarks(self):\n return BenchmarkApi(\n repository=BenchmarkRepository(con=self.con),\n backend=self.backend,\n urls=self.urls\n )",
"def run_all(self):\n runs = []\n for run in self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the list of all coverage benchmarks. | def get_coverage_benchmarks():
return [
benchmark for benchmark in get_all_benchmarks()
if get_type(benchmark) == BenchmarkType.CODE.value
] | [
"def get_all_benchmarks():\n all_benchmarks = []\n for benchmark in os.listdir(BENCHMARKS_DIR):\n benchmark_path = os.path.join(BENCHMARKS_DIR, benchmark)\n if os.path.isfile(os.path.join(benchmark_path, 'benchmark.yaml')):\n all_benchmarks.append(benchmark)\n return sorted(all_ben... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the list of standard bug benchmarks. | def get_bug_benchmarks():
return [
benchmark for benchmark in get_all_benchmarks()
if get_type(benchmark) == BenchmarkType.BUG.value
] | [
"def list_benchers():\n print_registry_items(BENCHERS)",
"def get_all_benchmarks():\n all_benchmarks = []\n for benchmark in os.listdir(BENCHMARKS_DIR):\n benchmark_path = os.path.join(BENCHMARKS_DIR, benchmark)\n if os.path.isfile(os.path.join(benchmark_path, 'benchmark.yaml')):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if |benchmark| is written in C/C++. | def is_cpp(benchmark):
return get_language(benchmark) == 'c++' | [
"def _c_optimizations_required():\n pure_env = os.environ.get('PURE_PYTHON')\n require_c = pure_env == \"0\"\n return require_c",
"def _should_attempt_c_optimizations():\n if PYPY:\n return False\n\n if _c_optimizations_required():\n return True\n return not _c_optimizations_ignore... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns |benchmarks| with only benchmarks written in C/C++. | def exclude_non_cpp(benchmarks):
return [benchmark for benchmark in benchmarks if is_cpp(benchmark)] | [
"def get_coverage_benchmarks():\n return [\n benchmark for benchmark in get_all_benchmarks()\n if get_type(benchmark) == BenchmarkType.CODE.value\n ]",
"def get_bug_benchmarks():\n return [\n benchmark for benchmark in get_all_benchmarks()\n if get_type(benchmark) == Benchmark... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the prorgamming language the benchmark was written in. | def get_language(benchmark):
config = benchmark_config.get_config(benchmark)
return config.get('language', 'c++') | [
"def programming_language(self) -> str:\n return self.random.choice(PROGRAMMING_LANGS)",
"def language():\n return random.choice(get_dictionary('languages')).strip()",
"def get_language_string(self) -> str:\n return f\"[L] {CST.get_text('LANGUAGE')}\"",
"def language():\n\n\texpect(\"language... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |