query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Abstract method for updating the search space. Must override. Tuners are advised to support updating search space at runtime. If a tuner can only set search space once before generating first hyperparameters, it should explicitly document this behaviour.
def update_search_space(self, search_space): raise NotImplementedError('Tuner: update_search_space not implemented')
[ "def update_search_space(self, search_space):\n logger.info('update search space %s', search_space)\n assert self.search_space is None\n self.search_space = search_space\n\n for _, val in search_space.items():\n if val['_type'] != 'layer_choice' and val['_type'] != 'input_choi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
By default the nested modules are not imported automatically. Call this function if you would like to import them all. This may be useful for autocompletion in interactive mode.
def import_all(): import theory
[ "def import_sub_modules(self):\n try:\n for package in self.package_list:\n Utils.import_utils.import_submodules(package)\n except ImportError, err:\n print_error(\"{0} : \\n\".format(str(err)))\n print_error('unexpected error: {0}'.format(traceback.form...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
u""" 例子: 1. 检测车型: >>> model_slug(u'马自达马自达3星骋1.6 手动 舒适型 2011款') u'\\u9a6c\\u81ea\\u8fbe3\\u661f\\u9a8b' >>> model_slug(u'test2两厢') u'2' >>> model_slug(u'test3三厢') u'3' >>> model_slug(u'test2') u'2' >>> model_slug(u'标致307 Cross') u'307 Cross' >>> model_slug(u'1235656') u'56' >>> model_slug(u'奇瑞旗云22011款1.5手动基本型') u'\\u65d...
def model_slug(value): # if value.startswith(u'检测车型'): # value = value.strip(u'检测车型:') # return value.split('-')[1] # value = re.sub(u'-.厢', '', value.rstrip('-')) # if ' ' in value: # values = value.split() # if re.search(ur'^\d+\.\d+[LT]?', values[1]) or re.search(ur'^-?\d{4}款?', ...
[ "def slugify_model(model: models.Model, content: str) -> str:\n slug_candidate = slug_original = slugify(content)\n\n for i in itertools.count(1):\n if not model.objects.filter(slug=slug_candidate).exists():\n break\n slug_candidate = '{}-{}'.format(slug_original, i)\n\n return slu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reset domain_list, origin_list, caching_list, service_name and flavor_id to its default value.
def reset_defaults(self): self.domain_list = [{"domain": "mywebsite%s.com" % uuid.uuid1()}] self.origin_list = [{"origin": "mywebsite1.com", "port": 443, "ssl": False}] self.caching_list = [{"name": "default", "ttl": 3600}, ...
[ "def reset(self):\n self.manager.delete_all()\n for name, val in DEFAULT_SETTINGS.items():\n val['name'] = name\n val['default_value'] = val['value']\n self.manager.from_dict(val)", "def reset(self):\n for var in self.var_list:\n var.value = None\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create invalid_json like [[[[[[[[[[[[[test]]]]]]]]]]]]]
def create_invalid_json(self, length): str = "" str += "[" * length str += "\"test\"" str += "]" * length return str
[ "def test_circular_nested(self):\n obj = {}\n obj[\"list\"] = [{\"obj\": obj}]\n with self.assertRaises(orjson.JSONEncodeError):\n orjson.dumps(obj)", "def test_validation_error_json():\n error = ValidationError(\n type=\"Syntax Error\",\n data={\"data\": [1, 2, 3]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
zip the data using gzip format
def data_zip(self, data): stringio = StringIO.StringIO() gzip_file = gzip.GzipFile(fileobj=stringio, mode='wb') gzip_file.write(data) gzip_file.close() return stringio.getvalue()
[ "def __unzip(self, data):\n compressed = StringIO.StringIO(data)\n gzipper = gzip.GzipFile(fileobj=compressed)\n return gzipper.read()", "def compress(self, data):\n\n compress = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, +15) \n compressed_data = compress.c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check whether it is possible to kill the application by creating a big malicious json blob.
def test_malicious_json_create_service(self): # create a payload with malicous json blob attack_string = self.create_malicious_json(900) headers = {"X-Auth-Token": self.client.auth_token, "X-Project-Id": self.client.project_id} kwargs = {"headers": headers, "data": att...
[ "def check_for_crashes(self):\n return False", "def _should_relaunch_killed_pod(evt_obj):\n return (\n evt_obj.status.container_statuses\n and evt_obj.status.container_statuses[0].state.terminated\n and evt_obj.status.container_statuses[0].state.terminated.exit_code\n == 137\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check whether it is possible to kill the application by creating a big malicious json blob with utf8 encoding.
def test_malicious_json_utf_8_create_service(self): # create a payload with malicous json blob attack_string = self.create_malicious_json(800) headers = {"X-Auth-Token": self.client.auth_token, "X-Project-Id": self.client.project_id} kwargs = {"headers": headers, "data...
[ "def test_bad_encoding(self, app, data_queues):\n body = b'{\"comment\": \"R\\xe9sum\\xe9 from 1990\", \"items\": []}'\n assert \"Résumé\" in body.decode(\"iso8859-1\")\n with pytest.raises(UnicodeDecodeError):\n body.decode(\"utf-8\")\n headers = {\"Content-Type\": \"applicat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check whether it is possible to kill the application by creating a big malicious json blob with utf16 encoding.
def test_malicious_json_utf_16_create_service(self): # create a payload with malicous json blob attack_string = self.create_malicious_json(400) headers = {"X-Auth-Token": self.client.auth_token, "X-Project-Id": self.client.project_id} kwargs = {"headers": headers, "dat...
[ "def testJsonFormatBinaryGarbage(self):\r\n out = six.StringIO()\r\n stats = {'garbage': '\\xc2\\xc2 ROAR!! \\0\\0'}\r\n formats.jsonFormat(out, statDict=stats)\r\n self.assertEquals(json.loads(out.getvalue()), {'garbage': six.u('\\xc2\\xc2 ROAR!! \\0\\0')})", "def check_for_crashes(self):\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check whether it is possible to kill the application by creating a big malicious json blob with gzip.
def test_malicious_json_gzip_create_service(self): # create a payload with malicious json blob attack_string = self.create_malicious_json(2500) headers = {"X-Auth-Token": self.client.auth_token, "X-Project-Id": self.client.project_id, "Content-Encoding": "gz...
[ "def test_gzip(handler,config):\r\n if not config.gzip:\r\n return False\r\n if not gzip_support:\r\n return False\r\n accept_encoding = handler.headers.get('accept-encoding','').split(',')\r\n accept_encoding = [ x.strip() for x in accept_encoding ]\r\n ctype = handler.resp_headers[\"C...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check whether it is possible to kill the application by creating a service with huge list of domains.
def test_dos_create_service_domain_list(self): # create a huge list of domain self.reset_defaults() for k in range(1, 30000): self.domain_list.append({"domain": "w.t%s.com" % k}) # send MAX_ATTEMPTS requests for k in range(1, self.MAX_ATTEMPTS): self.serv...
[ "def test_dos_list_service_huge_limit(self):\n # create a huge list of domain\n attack_string = \"1\" * 3500\n params = {\"limit\": attack_string, \"marker\": attack_string}\n resp = self.client.list_services(param=params)\n self.assertTrue(resp.status_code < 503)", "def check_s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check whether it is possible to kill the application by creating a service with huge list of origins.
def test_dos_create_service_origin_list(self): # create a huge list of domain self.reset_defaults() for k in range(1, 9000): self.origin_list.append({"origin": "m%s.com" % k, "port": 443, "ssl": False, ...
[ "def test_process_gone_on_ipsec_connection_delete(self):\n pass", "def killAll(controller=False):", "def test_delete_antivirus_servers(self):\n pass", "def _stop_proxies_if_needed(self) -> bool:\n all_node_ids = {node_id for node_id, _ in get_all_node_ids(self._gcs_client)}\n to_st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check whether it is possible to kill the application by creating a service with huge list rules within caching list.
def test_dos_create_service_caching_list_rules(self): # create a huge list of domain self.reset_defaults() for k in range(1, 15000): self.caching_list[1]["rules"].append( {"name": "i%s" % k, "request_url": "/index.htm"}) # send MAX_ATTEMPTS r...
[ "def ha_check_monit(self):\n self.env.revert_snapshot(\"deploy_ha\")\n for devops_node in self.env.nodes().slaves[3:5]:\n remote = self.fuel_web.get_ssh_for_node(devops_node.name)\n remote.execute(\"kill -9 `pgrep nova-compute`\")\n wait(\n lambda: len(r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check whether it is possible to kill the application by listing all services with a huge limit
def test_dos_list_service_huge_limit(self): # create a huge list of domain attack_string = "1" * 3500 params = {"limit": attack_string, "marker": attack_string} resp = self.client.list_services(param=params) self.assertTrue(resp.status_code < 503)
[ "def checkProcess(process_id, time_limit):\n # set an arbitrary time limit\n t_end = time.time() + 60 * time_limit\n while time.time() < t_end:\n if not is_process_running(process_id):\n print(\"process {0} terminated\".format(process_id))\n return\n\n # could be an external...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given the key of the external_issue return the external issue link.
def get_issue_url(self, key): raise NotImplementedError
[ "def getLinkedIssue(key):\n inwardIssues = []\n outwardIssues = []\n results = {}\n\n issue = cmc_jira.issue(key)\n for link in issue.fields.issuelinks:\n if hasattr(link, \"outwardIssue\"):\n outwardIssue = link.outwardIssue\n if checkLinkedTicket(outwardIssue):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Stores the last used field defaults on a perproject basis. This accepts a dict of values that will be filtered to keys returned by ``get_persisted_default_config_fields`` which will automatically be merged into the associated field config object as the default.
def store_issue_last_defaults(self, project_id, data): persisted_fields = self.get_persisted_default_config_fields() if not persisted_fields: return defaults = {k: v for k, v in six.iteritems(data) if k in persisted_fields} self.org_integration.config.update({ '...
[ "def _configure_defaults(self):\n values = {\n key: val\n for key, (desc, val) in WorkspaceConfiguration()\n .get_fields(only_defaults=True)\n .items()\n }\n self.set_meta(values)", "def populate_default_values(cls, new_kwargs: Dict) -> Dict:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create an issue via the provider's API and return the issue key, title and description. Should also handle API client exceptions and reraise as an IntegrationError (using the `message_from_error` helper).
def create_issue(self, data, **kwargs): raise NotImplementedError
[ "def create_issue(repo, issue, label, key):\n global debug\n print(\"..\",issue['title'])\n if repo and not debug:\n # print(\" .. Created ({title})\", title=issue['title'])\n body = issue_body(\n issue['body'], repo.default_branch, issue['location'], issue['context']\n )\n res = repo.create_i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes the external issue that has been linked via `get_issue`. Does anything needed after an issue has been linked, i.e. creating a comment for a linked issue.
def after_link_issue(self, external_issue, **kwargs): pass
[ "def add_gh_link(bug, pullreq):\n api_url = pullreq.get_url()\n html_url = apilink2htmlink(api_url)\n comments = bug.getcomments()\n for comment in comments:\n if html_url in comment.get(\"text\"):\n return\n comment = (\"Fix has submited, follow below link\"\n \" to s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the display name of the issue. This is not required but helpful for integrations whose external issue key does not match the disired display name.
def get_issue_display_name(self, external_issue): return ''
[ "def get_display_name(issue):\n\treturn issue.get('fields', {}).get('assignee', {}).get('displayName', '')", "def name(self):\n return self._github_issue.title", "def get_display_name(self) -> str:", "def display_name(self):\n if \"displayName\" in self._prop_dict:\n return self._prop...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper method for get_repository_choices Returns the choice for the default repo in a tuple to be added to the list of repository choices
def create_default_repo_choice(self, default_repo): return (default_repo, default_repo)
[ "def get_default_repo(self):\n for repo in self.get_repos():\n if self.get_safe(repo, 'default') and self.getboolean(repo, 'default'):\n return repo\n return False", "def get_default_repo(self):\n repos_json = self.client.get('/api2/default-repo').json()\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Propagate a sentry issue's assignee to a linked issue's assignee. If assign=True, we're assigning the issue. Otherwise, deassign.
def sync_assignee_outbound(self, external_issue, user, assign=True, **kwargs): raise NotImplementedError
[ "def issue_assign(self, issue, assignee=None):", "def assignee(self, assignee):\n\n self._assignee = assignee", "def assign_issue(self, issue, user):\n issue._github_issue.edit(assignee=user)", "def set_assignment(self, updates, original=None):\n if not original:\n original = {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return the current position in axis x
def get_pos_x(self): return self.__pos_x
[ "def get_x(self):\n return self.__x_position", "def pos_x(self) -> int:\n return self._pos_x", "def position(self):\n return self.x", "def getXPosition(self):\n return self._x", "def get_x(self):\n return self.coords[0]", "def getLeftX(self):\r\n return self.joy.g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return the current speed in axis x
def get_speed_x(self): return self.__speed_x
[ "def get_speed_x(self):\r\n return self.__X_speed", "def getX(self):\n return self.getAcceleration(self.Axes.kX)", "def speedup_x(self):\r\n new_speed = math.cos((self.__direction*math.pi)/180) + self.__X_speed\r\n self.__X_speed = new_speed", "def velocity_x(self):\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return the current speed in axis y
def get_speed_y(self): return self.__speed_y
[ "def get_speed_y(self):\r\n return self.__y_speed", "def getY(self):\n return self.getAcceleration(self.Axes.kY)", "def speedup_y(self):\r\n new_speed = math.sin((self.__direction*math.pi)/180) + self.__y_speed\r\n self.__y_speed = new_speed", "def verticalspeed(self):\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set new speed (new_speed) in axis x for the torpedo
def set_speed_x(self, new_speed): self.__speed_x = new_speed
[ "def set_speed(self, axis, speed):\r\n if axis == X:\r\n self.__x_speed = speed\r\n else:\r\n self.__y_speed = speed", "def set_speed_x(self, speed_x):\n self.__speed_x = speed_x", "def speedup_x(self):\r\n new_speed = math.cos((self.__direction*math.pi)/180) + ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set new speed (new_speed) in axis y for the torpedo
def set_speed_y(self, new_speed): self.__speed_y = new_speed
[ "def speedup_y(self):\r\n new_speed = math.sin((self.__direction*math.pi)/180) + self.__y_speed\r\n self.__y_speed = new_speed", "def set_speed_y(self, speed_y):\n self.__speed_y = speed_y", "def customize_torpedo_speed(self, current_gameboard, turn, new_speed):\n current_gameboard['...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set new position (new_pos) in axis x for the torpedo
def set_new_pos_in_x(self, new_pos): self.__pos_x = new_pos
[ "def moveXaxis(self):\r\n new_x = 0\r\n old_x = self.x\r\n # select direction\r\n if (random.random()<0.5):\r\n new_x = old_x + 1\r\n else:\r\n new_x = old_x - 1\r\n # check for boundaries\r\n if new_x < 0:\r\n new_x = 0\r\n if...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set new position (new_pos) in axis y for the torpedo
def set_new_pos_in_y(self, new_pos): self.__pos_y = new_pos
[ "def set_axis_y(self, new_axis_point):\r\n self.__y_axis = new_axis_point", "def set_ypos(self, pos):\n self.position[1] = pos", "def set_y(self, new_y):\r\n self.y = new_y", "def moveYaxis(self):\r\n new_y = 0\r\n old_y = self.y\r\n # select direction\r\n if (...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set the new number of lives (new_number_of_lives) of the torpedo
def set_lives(self, new_number_of_lives): self.__lives = new_number_of_lives
[ "def setLives(self, lives):\n assert type(lives) == int\n self._lives = lives", "def update_lives(self, amount):\n self.lives += amount", "def setLives(self,life):\n self._lives = life", "def setBossLives(self, lives):\n self._boss_lives = lives", "def set_tries(self,lives...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize the object with a placeholder value of 1.
def __init__(self) -> None: super().__init__() self.placeholder = 1.0
[ "def __init__(self, number=0):\n pass", "def __init__(self, int_value: int = 0):\n\n self._value = int_value", "def test_init_with_default_value(self):\n dim = Integer(\"yolo\", \"uniform\", -3, 10, default_value=2)\n\n assert type(dim.default_value) is int", "def __init__(self, i)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return an empty RequiredParameters object.
def _required_parameters(self) -> RequiredParameters: return RequiredParameters([])
[ "def null_required_fields(self):\n self._null_required_fields = {key for key in self.required_keys if self.get(key) is None}\n return self._null_required_fields", "def get_mandatory_param(self):\n mandatory_params = [k for k, v in self.validation_rule.get('fields').items()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return an empty DerivedParameterCollection.
def _get_derived_parameters(self) -> DerivedParameterCollection: return DerivedParameterCollection([])
[ "def empty_collection(self):\n raise NotImplementedError", "def remove_parameters(self):\n self.parameters = []", "def parameters(self):\n ps = super().parameters()\n exclude = set(self.estimator.parameters())\n ps = (p for p in ps if not p in exclude)\n return ps", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return an EmptyLikelihood object.
def empty_likelihood() -> EmptyLikelihood: return EmptyLikelihood()
[ "def empty_stats(cls):\n return cls(0, 0, 0)", "def empty():\n return nominat.Nominator([])", "def empty() -> ObservableBase:\n from ..operators.observable.empty import empty\n return empty()", "def zero_proximal(sigma=1.0):\n return ZeroOperator(self.domain)", "def nan(kl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize the ParameterizedLikelihood by reading the specificed sacc_filename value.
def __init__(self, params: NamedParameters): super().__init__() self.sacc_filename = params.get_string("sacc_filename")
[ "def __init__(self, generative_model, genomic_data, alphabet_file = None):\n GenerationProbability.__init__(self)\n PreprocessedParametersVJ.__init__(self, generative_model, genomic_data, alphabet_file)", "def __init__(self, generative_model, genomic_data, alphabet_file = None):\n GenerationP...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return an empty RequiredParameters object.
def _required_parameters(self) -> RequiredParameters: return RequiredParameters([])
[ "def null_required_fields(self):\n self._null_required_fields = {key for key in self.required_keys if self.get(key) is None}\n return self._null_required_fields", "def get_mandatory_param(self):\n mandatory_params = [k for k, v in self.validation_rule.get('fields').items()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return an empty DerivedParameterCollection.
def _get_derived_parameters(self) -> DerivedParameterCollection: return DerivedParameterCollection([])
[ "def empty_collection(self):\n raise NotImplementedError", "def remove_parameters(self):\n self.parameters = []", "def parameters(self):\n ps = super().parameters()\n exclude = set(self.estimator.parameters())\n ps = (p for p in ps if not p in exclude)\n return ps", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a ParameterizedLikelihood object.
def parameterized_likelihood(params: NamedParameters): return ParamaterizedLikelihood(params)
[ "def get_likelihood(self, discretized=False, state=None):\n if not hasattr(self, 'softmax'):\n self.generate_softmax()\n\n if self.softmax is not None:\n if state is not None:\n return self.softmax.probability(class_=self.softmax_class_label,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return an email Message object. This works like mboxutils.get_message, except it doesn't junk the headers if there's an error. Doing so would cause a headerless message to be written back out!
def get_message(obj): if isinstance(obj, email.Message.Message): return obj if hasattr(obj, "read"): obj = obj.read() try: msg = email.message_from_string(obj) except email.Errors.MessageParseError: msg = None return msg
[ "def get_message(obj):\n if isinstance(obj, email.Message.Message):\n return obj\n if hasattr(obj, \"read\"):\n obj = obj.read()\n try:\n msg = email.message_from_string(obj)\n except email.Errors.MessageParseError:\n headers = extract_headers(obj)\n obj = obj[len(head...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Train bayes with all messages from a maildir.
def maildir_train(h, path, is_spam, force, removetrained): if loud: print(" Reading %s as Maildir" % (path,)) import time import socket pid = os.getpid() host = socket.gethostname() counter = 0 trained = 0 for fn in os.listdir(path): cfn = os.path.join(path, fn) ...
[ "def mhdir_train(h, path, is_spam, force):\n if loud:\n print(\" Reading as MH mailbox\")\n import glob\n counter = 0\n trained = 0\n for fn in glob.glob(os.path.join(path, \"[0-9]*\")):\n counter += 1\n cfn = fn\n tfn = os.path.join(path, \"spambayes.tmp\")\n if l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Train bayes with a Unix mbox
def mbox_train(h, path, is_spam, force): if loud: print(" Reading as Unix mbox") import mailbox import fcntl f = file(path, "r+b") fcntl.flock(f, fcntl.LOCK_EX) mbox = mailbox.PortableUnixMailbox(f, get_message) outf = os.tmpfile() counter = 0 trained = 0 for msg in mbox...
[ "def mhdir_train(h, path, is_spam, force):\n if loud:\n print(\" Reading as MH mailbox\")\n import glob\n counter = 0\n trained = 0\n for fn in glob.glob(os.path.join(path, \"[0-9]*\")):\n counter += 1\n cfn = fn\n tfn = os.path.join(path, \"spambayes.tmp\")\n if l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Train bayes with an mh directory
def mhdir_train(h, path, is_spam, force): if loud: print(" Reading as MH mailbox") import glob counter = 0 trained = 0 for fn in glob.glob(os.path.join(path, "[0-9]*")): counter += 1 cfn = fn tfn = os.path.join(path, "spambayes.tmp") if loud and counter % 10 ...
[ "def train(self, trainfile):", "def maildir_train(h, path, is_spam, force, removetrained):\n if loud:\n print(\" Reading %s as Maildir\" % (path,))\n import time\n import socket\n pid = os.getpid()\n host = socket.gethostname()\n counter = 0\n trained = 0\n for fn in os.listdir(pat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Runt 1x de pool, dus alle combinaties van teams worden gespeeld. Na 1x spelen van de pool komt er een huidige score uit met welke teams welke punten hebben.
def run_one_pool(curr_pool, goals=False): curr_score = { "Ajax": 0, "Feyenoord": 0, "PSV": 0, "FC Utrecht": 0, "Willem II": 0 } for match in curr_pool: if curr_pool[match]: teamvsteam, chance = match, curr_pool[match] if not goals: ...
[ "def scoreTeams(curTeams, oppTeam, pokedex, league, minDistWanted):\n battleData, htmlData = loadBattleData(league)\n similarities = loadSims() \n \n #If not given an opponent team then simply randomly choose losers from the dataset to compare to.\n if len(oppTeam) == 0:\n picks = set([])\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Het draaien van de monte carlo machine speelt gewoon heel veel pools (de hoeveelheid runs). Na het spelen van een pool wordt de ranking van die partij toegevoegd aan de totale ranking. Als bijvoorbeeld ajax 10x eerste wordt, dan staat die 10x in de lijst van total_ranking[1]
def run_monte_carlo(runs, pool, goals=False): total_ranking = { 1: [], 2: [], 3: [], 4: [], 5: [] } for run in range(runs): if goals: curr_score = run_one_pool(pool, True) else: curr_score = run_one_pool(pool) total_rank...
[ "def get_total_ranking(self):\n output = 0\n for i in self.__ranking:\n output += i\n return output", "def mlbpowerrankings(self, irc, msg, args):\n \n url = self._b64decode('aHR0cDovL2VzcG4uZ28uY29tL21sYi9wb3dlcnJhbmtpbmdz')\n\n try:\n req = urllib2...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
compute truncate_div calculating data's truncate_div, res = floor(x / y) if x/y>0 else ceil(x/y)
def truncate_div_compute(input_x, input_y, output_x, kernel_name="truncate_div"): shape_list = broadcast_shapes( te.lang.cce.util.shape_to_list(input_x.shape), te.lang.cce.util.shape_to_list(input_y.shape), param_name_input1="input_x", param_name_input2="input_y") ...
[ "def ceil_div(x, y):\n return -(-x // y)", "def floor_division(x, y):\n return x // y", "def ceildiv(a, b):\n return - (-a // b)", "def floor_div(a, b):\r\n # see decorator for function body\r", "def safe_division(dividend, divisor):\n if divisor:\n return dividend / divisor\n else:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test alert policies .create() calls put with correct parameters
def test_create_success(self, mock_post): self.policies.create( name=self.policy_single_response['policy']['name'], incident_preference=self.policy_single_response['policy']['incident_preference'] ) mock_post.assert_called_once_with( url='https://api.newrelic...
[ "def test_alert_definition_update_integration_for_escalation_with_put(self):\n pass", "def test_update(self, mock_put):\n self.policies.update(id=333114, policy_update=self.policy_show_response)\n\n mock_put.assert_called_once_with(\n url='https://api.newrelic.com/v2/alert_policies...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test alert policies .update() calls put with correct parameters
def test_update_success(self, mock_put): self.policies.update( id=self.policy_single_response['policy']['id'], name=self.policy_single_response['policy']['name'], incident_preference=self.policy_single_response['policy']['incident_preference'] ) mock_put.asse...
[ "def test_update(self, mock_put):\n self.policies.update(id=333114, policy_update=self.policy_show_response)\n\n mock_put.assert_called_once_with(\n url='https://api.newrelic.com/v2/alert_policies/333114.json',\n headers=self.policies.headers,\n data=json.dumps(self.po...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test alert policies .delete() success
def test_delete_success(self, mock_delete): self.policies.delete(id=self.policy_single_response['policy']['id']) mock_delete.assert_called_once_with( url='https://api.newrelic.com/v2/alerts_policies/{0}.json'.format( self.policy_single_response['policy']['id'] )...
[ "def test_delete_alert(self):\n pass", "def test_alerts_delete(self):\n pass", "def test_undelete_alert(self):\n pass", "def test_alerts_alert_id_delete(self):\n pass", "def test_delete_alert_by_id(self):\n pass", "def test_delete_policy(self):\n pass", "def tes...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test alert policies .associate_with_notification_channel() calls put with correct parameters
def test_associate_with_notification_channel_success(self, mock_put): self.policies.associate_with_notification_channel( id=self.policy_single_response['policy']['id'], channel_id=self.channel_single_response['channel']['id'], ) mock_put.assert_called_once_with( ...
[ "def test_dissociate_from_notification_channel(self, mock_put):\n self.policies.associate_with_notification_channel(\n id=self.policy_single_response['policy']['id'],\n channel_id=self.channel_single_response['channel']['id'],\n )\n\n mock_put.assert_called_once_with(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test alert policies .associate_with_notification_channel() calls put with correct parameters
def test_dissociate_from_notification_channel(self, mock_put): self.policies.associate_with_notification_channel( id=self.policy_single_response['policy']['id'], channel_id=self.channel_single_response['channel']['id'], ) mock_put.assert_called_once_with( url...
[ "def test_associate_with_notification_channel_success(self, mock_put):\n self.policies.associate_with_notification_channel(\n id=self.policy_single_response['policy']['id'],\n channel_id=self.channel_single_response['channel']['id'],\n )\n\n mock_put.assert_called_once_wit...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a contact representing a publication coauthored by the ego to the ego network.
def add_publication(self, pub_id: int, timestamp: int, title: str, coauthors: List[str], contact_type="__all__"): if self.min_pub_date is None or timestamp >= self.min_pub_date: # standardize names, remove possible duplicates and wrong names, and remove ego if present std_coauth_names = ...
[ "def add_contact(self, contact):\n self.contacts.append(contact)", "def add_contact(contact):\n\tdb.insert_entry(contact)", "def add_contact(rep, contact):\n logger.write_log(\"add_contact\")\n number = contact[\"Numéro\"]\n rep[number] = contact", "def add_contact(self, contact):\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reset the function call count to zero.
def reset_count(self): self.count = 0
[ "def __reset_counter(self):\r\n self.__counter = 0", "def resetOperationCount():\n global _operationCount\n _countLock.acquire()\n try:\n _operationCount = 0\n finally:\n _countLock.release()", "def reset(self):\n Generic.reset(self)\n self.prev_run_time = self.p -...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the average execution time of a given function.
def time_function(function, runs=1, average=min): results = [None] * runs for i in range(runs): t0 = time.perf_counter() function() t1 = time.perf_counter() results[i] = t1 - t0 return average(results)
[ "def calculateRunTime(function, *args):\n startTime = time.time()\n result = function(*args)\n return time.time() - startTime, result", "def execution_time(function: Callable, args=tuple(), kwargs=dict()):\n start_time = time.time()\n function(*args, **kwargs)\n end_time = time.time()\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Query if a value is in an array via iterative linear search.
def linear_search_iterative(array, value): for elt in array: if compare(elt, value) == 0: return True return False
[ "def linear_search_recursive(array, value):\n # Base case for empty list\n n = len(array)\n if n == 0:\n return False\n\n # Recursive case\n if compare(array[0], value) == 0:\n return True\n else:\n return linear_search_recursive(array[1:], value)", "def in_array(self, f, el...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Query if a value is in an array via recursive linear search.
def linear_search_recursive(array, value): # Base case for empty list n = len(array) if n == 0: return False # Recursive case if compare(array[0], value) == 0: return True else: return linear_search_recursive(array[1:], value)
[ "def binary_search_recursive(array, value):\n # Base cases for empty or singular list\n n = len(array)\n if n == 0:\n return False\n elif n == 1:\n return compare(array[0], value) == 0\n\n # Recursive case\n middle = n // 2\n if compare(array[middle], value) == 0:\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Query if a value is in an array via recursive binary search.
def binary_search_recursive(array, value): # Base cases for empty or singular list n = len(array) if n == 0: return False elif n == 1: return compare(array[0], value) == 0 # Recursive case middle = n // 2 if compare(array[middle], value) == 0: return True elif co...
[ "def linear_search_recursive(array, value):\n # Base case for empty list\n n = len(array)\n if n == 0:\n return False\n\n # Recursive case\n if compare(array[0], value) == 0:\n return True\n else:\n return linear_search_recursive(array[1:], value)", "def find_array(sub, in_a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sort a list via hybrid recursive (topdown) mergesort. Delegates to insertion sort when n is less than or equal to some threshold.
def mergesort_recursive_hybrid(array, threshold=37): # Base case delegates to insertion sort n = len(array) if n <= threshold: return insertion_sort(array) # Recur on two halves of array and merge results mid = n // 2 return merge( mergesort_recursive(array[:mid]), merge...
[ "def Merge_Sort(numlist):\n\n\tif len(numlist) <= 1:\n\t\treturn numlist\n\t\n\tmid = len(numlist) // 2\n\tleft = Merge_Sort(numlist[:mid])\n\tright = Merge_Sort(numlist[mid:])\n\n\treturn Merge(left, right)", "def merge_sort(unsorted, threshold, reverse):\r\n length = len(unsorted)\r\n if length < 2:\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sort a list via hybrid iterative (bottomup) mergesort. Delegates to insertion sort when n is less than or equal to some threshold.
def mergesort_iterative_hybrid(array, threshold=37): n = len(array) result = array.copy() # Initial insertion sort pass for i in range(0, n, threshold): result[i:i+threshold] = insertion_sort(result[i:i+threshold]) # Merge runs of length threshold, 2*threshold, ... length = threshold ...
[ "def mergesort_recursive_hybrid(array, threshold=37):\n # Base case delegates to insertion sort\n n = len(array)\n if n <= threshold:\n return insertion_sort(array)\n\n # Recur on two halves of array and merge results\n mid = n // 2\n return merge(\n mergesort_recursive(array[:mid]),...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Siftup the last node (end1) in the given max heap.
def sift_up(heap, start, end): # Swap last node with parents until no longer greater. i = end - 1 heaped = False while i > start and not heaped: parent = (i - 1) // 2 if compare(heap[i], heap[parent]) > 0: heap[i], heap[parent] = heap[parent], heap[i] i = parent ...
[ "def _heappop_max(heap):\n lastelt = heap.pop() # raises appropriate IndexError if heap is empty\n if heap:\n returnitem = heap[0]\n heap[0] = lastelt\n _siftup_max(heap, 0)\n return returnitem\n return lastelt", "def heap_pop_max(heap):\n last = heap.pop()\n if heap:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shuffle a list by recursively pileshuffling each pile.
def recursive_pile_shuffle(array, n): # Base case for empty or singular list if len(array) < 2: return array # Pile-shuffle and recur on each of n piles piles = [array[i::n] for i in reversed(range(n))] result = [] for pile in piles: result += recursive_pile_shuffle(pile, n) ...
[ "def shuffleSites(myList):\n shuffle(myList)\n ctr = 0\n for x in myList:\n ctr += 1\n yield ctr, x", "def shuffle(L):\n return [L[i] for i in permutation(len(L))]", "def shuffle_list(list_: list):\n new_list = copy(list_)\n shuffle(new_list)\n return new_l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
OAuth2 compatible token login, get an access token for future requests
async def login_access_token( form_data: OAuth2PasswordRequestForm = Depends() ): user = await crud.user.authenticate( username=form_data.username, password=form_data.password ) if not user: raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail="Incorrect credentials") elif ...
[ "def login_oauth():\n state = {}\n authorize_handler = functools.partial(OAuthLoginHandler, state)\n authorize_server = BaseHTTPServer.HTTPServer((\"\", 0), authorize_handler)\n port = authorize_server.server_port\n callback_url = \"http://localhost:%i%s\" % (port, AUTHORIZED_URL)\n \n # Step 1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verify account using token.
async def verify_account( token: str = Form(...) ): email = await verify_register_token(token) if not email: raise HTTPException(status_code=400, detail="Invalid email verify token") record = await crud.user.get_by_email(email) if not record: raise HTTPException( stat...
[ "def verify_token(self, token):\n return False", "def verify_confirm_account_token(token):\n try:\n user_id = jwt.decode(token, app.config['ADMIN_PASSWORD'], algorithms=[\"HS256\"])['confirm_account']\n except BaseException as err:\n system_logging(err, exception=True)\n return N...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the number of frames in the trajectory in universe u, using teq as equilibration time and tsample as sampling time
def traj_nslice (u,teq,tsample) : # get the number of frames in the slice (http://stackoverflow.com/a/7223557) traj_slice = u.trajectory[teq::tsample] return sum(1 for _ in traj_slice)
[ "def get_num_frames(signal_length_samples, window_size_samples, hop_size_samples):\r\n o = window_size_samples - hop_size_samples\r\n \r\n return math.ceil((signal_length_samples - o)/(window_size_samples - o))", "def frameTimes(self):\n sr = self.sampleRate\n offset = self.activeOffset\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the Pearson correlation coefficient between the row sum of the given HiC matrix and the given ChIPseq profile.
def hic_chipseq_r2 (hic, chipseq) : hic_rowsum = np.sum(hic,axis=1)/float(np.sum(hic)) return np.corrcoef(hic_rowsum,chipseq)[0,1]**2
[ "def coreCorrelation(A,C):\n\tcMat = numpy.matrix(C)\n\tCij = numpy.multiply(cMat,cMat.transpose())\n\treturn pearsonr(A.flat,Cij.flat)", "def _pearsons_contingency_coefficient_compute(confmat: Tensor) ->Tensor:\n confmat = _drop_empty_rows_and_cols(confmat)\n cm_sum = confmat.sum()\n chi_squared = _comp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the relative proportion of contacts of the tracers with binding sites compared with nonbinding sites. As usual user should supply equilibration time, sampling time, and contact threshold value.
def contacts_with (sim,polymer_text,tracers_text,bindingsites_text,teq,tsample,threshold) : # select polymer, tracers, and binding sites polymer = sim.u.select_atoms (polymer_text) tracers = sim.u.select_atoms (tracers_text) bss = sim.u.select_atoms (bindingsites_text) # select binding site indices ...
[ "def _fraction_latency(self, users_distances):\n\n users_desired_latency = np.array(list(map(lambda a: self.services_desired_latency[a],\n self.users_services)))\n check = users_distances < users_desired_latency\n fraction = np.count_nonzero(chec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform a simple fit of the supplied timedependent MSD, using a linear regression of the logarithms of the values. User must supply the conversion factor from time to real time and from length to real length. Also, user
def fit_msd (msd,cutoff,delta_t,scale_l) : # prepare the values to fit: exclude the first value because it is zero t = np.arange(msd.size)*delta_t x = np.log(t[cutoff:]) y = np.log(msd[cutoff:]*scale_l**2) # perform fit to y = ax + b with their errors b,a,db,da = mbt.linear_regression (x,y,0.99)...
[ "def fit_model(train_ts_dis, data, init_prior = [.5,.5], bias = True, mode = \"biasmodel\"):\r\n if mode == \"biasmodel\":\r\n #Fitting Functions\r\n def bias_fitfunc(rp, tsb, df):\r\n init_prior = [.5,.5]\r\n model = BiasPredModel(train_ts_dis, init_prior, ts_bias = tsb, recu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the mean square displacement of the particles defined by 'particles_text' in simulation sim, using sampling tsample and equilibration time teq. Returns the matrix corresponding to the mean square displacement of each particle, along with a matrix corresponding to the variance in the estimate of this quantity.
def msd_t (sim,particles_text,teq,tsample) : u = sim.u particles = u.select_atoms (particles_text) nparticles = particles.n_atoms nslice = traj_nslice (u,teq,tsample) # initialize the matrix containing all the positions # of the particles at all the sampling frames particles_pos = np.zeros (...
[ "def msd_t(sim,particles_text,teq,tsample) :\n u = sim.u\n particles = u.select_atoms(particles_text)\n nparticles = particles.n_atoms\n nslice = traj_nslice (u,teq,tsample)\n # initialize the matrix containing all the positions\n # of the particles at all the sampling frames\n particles_pos = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the minimum distance between the atoms defined in sel1 and the atoms defined in sel2, as a function of time. Returns a matrix that contains the minimum distance for each atom defined in sel1. As usual user should supply equilibration time, sampling time, and contact threshold value.
def dmin_sel (sim,sel1_text,sel2_text,teq,tsample) : # define atom selections sel1 = sim.u.select_atoms (sel1_text) sel2 = sim.u.select_atoms (sel2_text) # get number of atoms in selection 1 natoms = sel1.n_atoms nslice = traj_nslice (sim.u,teq,tsample) dmin = np.zeros((natoms,nslice)) f...
[ "def minimum_subset_distance(D, limits1, limits2):\n score = numpy.ones( (limits1[1]) )\n for i in xrange(limits1[1]):\n for j in xrange(limits2[1]-limits2[0]):\n score[i] = min(score[i], D[i,j+limits2[0]-1])\n #print i, j, D[i,j+limits2[0]-1], score[i], min(score[i], D[i,j+limits...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the image index of all particles in simulation, at the frame 'frame_id'
def particle_images (sim,frame_id) : # get positions of all particles: define first the atom selection, then jump to # the user-requested trajectory frame, get the box dimensions (currently works # only for orthorhombic boxes, then calculate the image indices atoms = sim.u.select_atoms ('all') ts = ...
[ "def _get_frame_index(self, frame):\n if isinstance(frame, cf.CoordinateFrame):\n frame = frame.name\n #frame_names = [getattr(item[0], \"name\", item[0]) for item in self._pipeline]\n frame_names = [step.frame if isinstance(step.frame, str) else step.frame.name for step in self._pip...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For the simulation 'sim', calculate the matrix of binding events of the polymer and the tracers. Returns a contacts matrix of the shape (ntracers,nslice,npolymer).
def contacts_t (sim,polymer_text,tracer_text,teq,tsample,threshold) : u = sim.u polymer = u.select_atoms (polymer_text) tracers = u.select_atoms (tracer_text) ntracers = tracers.n_atoms npolymer = polymer.n_atoms nslice = mbt.traj_nslice(u,teq,tsample) C = np.zeros((ntracers,nslice,npolymer)...
[ "def contacts_with (sim,polymer_text,tracers_text,bindingsites_text,teq,tsample,threshold) :\n # select polymer, tracers, and binding sites\n polymer = sim.u.select_atoms (polymer_text)\n tracers = sim.u.select_atoms (tracers_text)\n bss = sim.u.select_atoms (bindingsites_text)\n # select binding sit...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the matrix of average intrapolymer distances. User must supply the parameters teq, tsample and threshold.
def distance_matrix (sim,polymer_text,teq,tsample,threshold=2.5) : u = sim.u polymer = u.select_atoms (polymer_text) N = polymer.n_atoms nslice = mbt.traj_nslice (u,teq,tsample) d = np.zeros((N,N)) for i,ts in enumerate(u.trajectory[teq::tsample]) : this_d = distance_array(polymer.positi...
[ "def calc_qavg(self, TRANGE = []):\n #put some variables in this namespace\n nebins=self.nebins\n nqbins=self.nqbins\n binenergy=self.binenergy\n binq=self.binq\n visits2d=self.visits2d\n logn_Eq=self.logn_Eq\n \n if len(TRANGE) == 0:\n NTEMP = 1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function does the complete analysis of the tracers in the simulation. It calculates the virtual HiC, virtual ChIPseq, KullbackLeibler divergence between the two profiles as a function of time, and coverage of the tracers.
def tracers_analysis (sim,polymer_text,tracer_text,teq,tsample,t_threshold,p_threshold) : # define DKL(t) vector nframes = traj_nslice(sim.u,teq,tsample) DKL_t = np.zeros(nframes) # define polymer and tracers polymer = sim.u.select_atoms(polymer_text) tracers = sim.u.select_atoms(tracer_text) ...
[ "def tracers_analysis (sim,polymer_text,tracer_text,teq,tsample,t_threshold,p_threshold) :\n # define DKL(t) vector\n nframes = traj_nslice(sim.u,teq,tsample)\n DKL_t = np.zeros(nframes)\n # define polymer and tracers\n polymer = sim.u.select_atoms(polymer_text)\n tracers = sim.u.select_atoms(trac...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the shape of an element x. If it is an element with a shape attribute, return it. If it is a list with more than one element, compute the shape by checking the len, and the shape of internal elements. In that case, the shape must be consistent. Finally, in other case return () as shape.
def get_shape(x): if isinstance(x, list) and len(x) > 0: shapes = [get_shape(subx) for subx in x] if any([s != shapes[0] for s in shapes[1:]]): raise ValueError('Parameter dimension not consistent: {}'.format(x)) return (len(x), ) + shapes[0] else: if hasattr(x, '_sha...
[ "def getShape(arr):\n if hasattr(arr, \"shape\"):\n return arr.shape\n elif type(arr) in (type(()), type([])):\n return (len(arr),)\n elif type(arr) in (type(1), type(1.)):\n return ()\n else:\n raise AttributeError(\"No attribute 'shape'\")", "def shape(x):\n if type(x)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the signatures results of the teacher in the given career for all the active exams.
def get_teacher_career_results(self, teacher, career): data = [] # Get the active exams of the career. exams = EvaluationsExam.objects.filter( type__exact=career.type, status="ACTIVE") # Get the results for each exam. for exam in exams: # Get the signat...
[ "def getTeachers():\n\ttry:\n\t\tteachers = []\n\n\t\t# cur_student is a list of the student's attributes\n\t\tcur_student = parseRequestVars(request.args['student'])\n\n\t\t# The Salesforce \"multipicklist\" type, which is the type of the instrument\n\t\t# is particularly tricky. Query results are filtered here in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the count for the current tab and the count for the conversations in all 4 tabs
def get_all_conversation_type_counts(survey_id, conversation_tab, business_id, category): logger.info( "Retrieving count of threads for all conversation tabs", survey_id=survey_id, conversation_tab=conversation_tab, business_id=business_id, category=category, ) respo...
[ "def _get_conversation_counts(business_id, conversation_tab, survey_id, category, all_conversation_types):\n params = _get_secure_message_threads_params(\n survey_id, business_id, conversation_tab, category, all_conversation_types\n )\n url = f'{current_app.config[\"SECURE_MESSAGE_URL\"]}/messages/c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the count of conversations based on the params
def _get_conversation_counts(business_id, conversation_tab, survey_id, category, all_conversation_types): params = _get_secure_message_threads_params( survey_id, business_id, conversation_tab, category, all_conversation_types ) url = f'{current_app.config["SECURE_MESSAGE_URL"]}/messages/count' r...
[ "def getNumberOfConversations(self):\n log_deprecated(\"Products.Ploneboard.content.PloneboardForum.\"\n \"PloneboardForum.getNumberOfConversations is \"\n \"deprecated in favor of Products.Ploneboard.browser.\"\n \"forum.ForumView.getNumberOf...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if message contains correct checksum
def _validate_checksum(self, msg: bytes) -> bool: return self._checksum(msg) == msg[8]
[ "def isvalid_checksum(message: bytes) -> bool:\r\n\r\n lenm = len(message)\r\n ckm = message[lenm - 2 : lenm]\r\n return ckm == UBXMessage.calc_checksum(message[2 : lenm - 2])", "def _verify_checksum(cls, raw_message):\n digest = cls._get_digest(raw_message)\n checksum = cls._ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Trigger zero calibration (0PPM for Z14, 400 PPM for Z19)
def zero_calibrationn(self): self.link.write(self._calibrateZeroSequence)
[ "def calibrate():\n F0ST = 3.6307805477010028e-09\n F0AB = 3.6307805477010029e-20\n #-- get calibrator\n wave,flux = get_calibrator(name='alpha_lyr')\n zp = filters.get_info()\n \n #-- calculate synthetic fluxes\n syn_flux = synthetic_flux(wave,flux,zp['photband'])\n syn_flux_fnu = synthe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The function finds the most common seeds for several lengths and calculated the emissions and transitions matrices for each seed.
def get_seeds(seqs): k_lengths = list(range(6, 20)) final_tuples = {} motifs_dic = {} # find most common seeds seeds = [find_motifs(seqs, k) for k in k_lengths] for i in k_lengths: motifs_dic[i] = seeds[i - 6][0:5] # calculate emissions and transitions global_possible_occurrenc...
[ "def search_mates(kmer_dict, sequence, kmer_size) :\n\n return [i[0] for i in Counter([ids for kmer in cut_kmer(sequence, kmer_size)\n if kmer in kmer_dict for ids in kmer_dict[kmer]]).most_common(8)]", "def clusterSeeds(seeds, l): \n \n # Code to complete - you are free to define other...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return if x == y, if eps is not None, return if abs(xy) <= eps
def all_equal(x, y, eps=None): if eps: return all([abs(i - j) <= eps for i, j in zip(x, y) if i is not None and j is not None]) return all([i == j for i, j in zip(x, y)])
[ "def realEqual(x,y,eps=10e-10):\n return abs(x-y) < eps", "def compare(x,y, eps=1e-6):\n return abs(x-y) < eps", "def withinEpsilon(x, y, epsilon):\n return abs(x - y) <= epsilon", "def equal(a, b, eps=1E-14):\r\n return abs(a - b) < eps", "def equal(a, b, eps=1E-14):\r\n return abs(a - b) < ep...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reduce product of x.
def product(x): return functools.reduce(lambda x, y: x * y, x)
[ "def prod(x):\n p = 1\n for n in x:\n p *= n\n return p", "def reduce_function(x):", "def product_reduce(list):\n \n return reduce(lambda x, y: x * y, list)", "def product(nums):\n return reduce(operator.mul, nums, 1)", "def prod(*args):\n return _reduce(lambda x, y: x.__rmul__(y),...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a `list` of `int` that represents a range of axes.
def ranged_axes(shape): return (-np.arange(1, len(shape) + 1)[::-1]).tolist() or -1
[ "def range() -> List[int]:\n pass", "def yield_spectral_range(self):\n return [min(self.x), max(self.x), len(self.x)]", "def limits(self):\n\n\t\treturn [\n\t\t\tmin(self.xvalues),\n\t\t\tmax(self.xvalues),\n\t\t\tmin(self.yvalues),\n\t\t\tmax(self.yvalues)]", "def _get_axes_numbers(self, axes):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Partition `zipped` into `num_steps`.
def partition(zipped, num_steps, allow_overflow=True): size = len(zipped) parts = [] for i in range(0, size, num_steps): end = i + num_steps if end >= size: parts.append(zip(*zipped[i:])) break elif allow_overflow: parts.append(zip(*zipped[i:end])) return parts
[ "def partition(iterable, n=2, step=None, fillvalue=_sentinel):\n step = step or n\n slices = (islice(iterable, start, None, step) for start in range(n))\n if fillvalue is _sentinel:\n return zip(*slices)\n else:\n return zip_longest(*slices, fillvalue=fillvalue)", "def get_chunks(num_ite...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pad or truncate a list `x` with the values `pad_value` and `maxlen`.
def list_pad_or_truncate(x, maxlen, pad_value=None): length = len(x) if maxlen > length: x += [pad_value] * (maxlen - length) elif maxlen < length: x = x[:maxlen] return x
[ "def pad_with_zero(list, max_length, pad_type):\n padded_list = pad_sequences(list, maxlen=max_length, padding=pad_type, truncating='post')\n return padded_list", "def pad_tokens(x, max_length, pad_token_id,\n truncate_from=\"left\",\n pad_from=\"left\"):\n assert truncate_fro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return list of rain fall for previous year
def precipitation(): last_date = session.query(Measurement.date).order_by(Measurement.date.desc()).first() last_year = dt.date(2017, 8, 23) - dt.timedelta(days=365) rain = session.query(Measurement.date, Measurement.prcp).\ filter(Measurement.date > last_year).\ order_by(Measurement.date...
[ "def get_forecast_regions(year, get_b_regions=False):\n\n if year == '2012-13':\n # varsling startet januar 2013\n region_ids = [106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129]\n elif year == '2013-14':\n # Svartisen ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create mode of given scale
def scale_to_mode(scale, transpose=0): # find mode scheme based on original scale l = scale[transpose:] # create complete 16-elements list of steps i = ceil((16 - len(l)) / 12) l += scale * i l = list(accumulate(l)) n = l[0] l = list(map(lambda x: x - n, l)) return l[:16]
[ "def scale_mode():\r\n pass", "def setScale(self, mode='ACC', scale=0):\r\n\t\tif mode.upper() == 'ACC':\r\n\t\t\treg = 0x1C\r\n\t\telif mode.upper() == 'GYR':\r\n\t\t\treg = 0x1B\t\t\r\n\t\telse:\r\n\t\t\treturn False\r\n\t\tcurrentVal = self.read(reg)\r\n\t\tcurrentVal = self.dec2BinList(currentVal)\r\n\t\ts...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
to_user ile olan conversationu al, eğer conversation yoksa yeni bir conversation oluştur
def user_chat(request, username): user = request.user to_user = get_object_or_404(User, username=username) if user == to_user: # @TODO: return a error (kendine mesaj atamazsın) return redirect('chat:chat_index') contact_user_qs = Contact.objects.filter(user=user, friend=to_user) co...
[ "def chat(api: tweepy.API, user: str):\n\n try:\n user = user.replace(\"@\", \"\")\n user = api.get_user(user)\n me = api.me()\n messages = api.list_direct_messages(count=100)\n for message in sorted(\n messages, key=lambda message: int(message.created_timestamp)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function is from the latest version of SCons to support older SCons version. Configure check for a specific program. Check whether program prog_name exists in path. If it is found, returns the path for it, otherwise returns None.
def CheckProg(context, prog_name): context.Message("Checking whether %s program exists..." % prog_name) path = context.env.WhereIs(prog_name) context.Result(bool(path)) return path
[ "def whereis(program):\n for path in os.environ.get('PATH', '').split(':'):\n if os.path.exists(os.path.join(path, program)) and not os.path.isdir(os.path.join(path, program)):\n return os.path.join(path, program)\n return None", "def _get_prog_path(env, key, name):\n\n # check if the u...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function is from SCons but extended with additional flags, e.g. the extra_libs. Another (more sophisticated) test for a library. Checks, if library and header is available for language (may be 'C' or 'CXX'). Call maybe be a valid expression _with_ a trailing ';'. As in CheckLib, we support library=None, to test if...
def CheckLibWithHeader(context, libs, header, language, call = None, extra_libs = None, autoadd = 1): prog_prefix, dummy = \ SCons.SConf.createIncludesFromHeaders(header, 0) if libs == []: libs = [None] if not SCons.Util.is_List(libs): libs = [l...
[ "def check_lib(self,\n funcname,\n library=None,\n includes=None,\n include_dirs=None,\n libraries=None,\n library_dirs=None,\n msg_add_libs=False):\n\n # hook to be sure we do the std stuff...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a playlist with a given name or raise NotFound.
def playlist(self, title): # noqa for item in self.playlists(): if item.title == title: return item raise NotFound('Invalid playlist title: %s' % title)
[ "def find_playlist(self, name):\n for playlist in self._playlists:\n# if playlist.special_kind.get() != _appscript.k.none:\n# continue\n if playlist.name.get() == name:\n return iTunes.Playlist(playlist)", "def getPlaylist(self,name):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List all active sessions.
def sessions(self): return utils.listItems(self, '/status/sessions')
[ "def list_sessions(self):\n return self.sessions.list_sessions()", "def list_sessions(self):\n return self.store.list()", "def get_sessions(self):\n\n return self.all_sessions", "def get_sessions_list():\n sessions = Session.query.all()\n result = sessions_schema.dump(sessions).data...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the use of a cache.
def _update_use(self, key): if (self._replace_pol == Cache.LRU): self.cache[key]= self.hashmap[key] if (self._replace_pol == Cache.LRU_S): self.cache[key] = self.hashmap[key]
[ "def update_cache(self):\n self.cache = self.movie_database.view()", "def set_cache(self, val):\n pass", "def use_cache(self, use_cache):\n self._use_cache = bool(use_cache)", "def _setCache(self, name, val): # TODO: remove me\n self.cached[name] = val", "def use_cache(self, use...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the name, arguments, and return type of the first function definition found in code. Arguments are returned as [(type, name), ...].
def parse_function_signature(code): m = re.search("^\s*" + re_func_decl + "\s*{", code, re.M) if m is None: print(code) raise Exception("Failed to parse function signature. " "Full code is printed above.") rtype, name, args = m.groups()[:3] if args == 'void' or ar...
[ "def find_functions(code):\n regex = \"^\\s*\" + re_func_decl + \"\\s*{\"\n \n funcs = []\n while True:\n m = re.search(regex, code, re.M)\n if m is None:\n return funcs\n \n rtype, name, args = m.groups()[:3]\n if args == 'void' or args.strip() == '':\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of (name, arguments, return type) for all function definition2 found in code. Arguments are returned as [(type, name), ...].
def find_functions(code): regex = "^\s*" + re_func_decl + "\s*{" funcs = [] while True: m = re.search(regex, code, re.M) if m is None: return funcs rtype, name, args = m.groups()[:3] if args == 'void' or args.strip() == '': args = [] ...
[ "def find_prototypes(code):\n\n prots = []\n lines = code.split('\\n')\n for line in lines:\n m = re.match(\"\\s*\" + re_func_prot, line)\n if m is not None:\n rtype, name, args = m.groups()[:3]\n if args == 'void' or args.strip() == '':\n args = []\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of signatures for each function prototype declared in code. Format is [(name, [args], rtype), ...].
def find_prototypes(code): prots = [] lines = code.split('\n') for line in lines: m = re.match("\s*" + re_func_prot, line) if m is not None: rtype, name, args = m.groups()[:3] if args == 'void' or args.strip() == '': args = [] else: ...
[ "def find_functions(code):\n regex = \"^\\s*\" + re_func_decl + \"\\s*{\"\n \n funcs = []\n while True:\n m = re.search(regex, code, re.M)\n if m is None:\n return funcs\n \n rtype, name, args = m.groups()[:3]\n if args == 'void' or args.strip() == '':\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of template variables found in code.
def find_template_variables(code): return re.findall(re_template_var, code)
[ "def _get_template_variables(template):\n src = templateEnv.loader.get_source(templateEnv, template)\n vars = meta.find_undeclared_variables(templateEnv.parse(src))\n return vars", "def vars(self) -> Optional[List[\"TemplateVariable\"]]:\n return self.__vars", "def variables(self):\n\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a function for generating trials for a model op. Infers the Python main module for the operation and returns the `gen_trials` function defined for that module. Raise `TypeError` if the operation does not use a Python main module (either explicitly with the `main` attribute or implicitly in the `exec` attribute.
def optimizer_trial_generator(model, op_name): try: module_name = _model_op_main(model, op_name) except ValueError as e: raise TypeError( f"could not get main module for {model.name}{op_name}: {e}" ) from None else: try: main_mod = importlib.import_mod...
[ "def hyperopt_trial(trial_name,\n trial_function,\n hyperopt_space,\n hyperopt_evals,\n snippets,\n **kwargs):\n exp_key = \"exp1\"\n\n with trial.run_trial(trial_name=trial_name,\n snippets=snipp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Looks for main module in exec spec for model op. Raises `ValueError` if exec spec is empty or not in the exepcted format.
def _op_main_for_exec(exec_): if not exec_: raise ValueError("exec spec not specified") m = re.search(r"-u?m ([^ ]+)", exec_) if not m: raise ValueError(f"unexpected exec spec: {exec_!r}") return m.group(1)
[ "def test_get_executable_details(self):\n pass", "def find_model_information_in_edi(parsed_edi_output, model_name):\n founded = [info for info in parsed_edi_output if info[0] == model_name]\n if not founded:\n raise Exception(f'Info about model {model_name} not found')\n\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a vignette for the package
def getVignette(self, packageUrl): cat = getToolByName(self.context, 'portal_catalog') results = cat.searchResults(portal_type='Vignette', path={'query': packageUrl}) if results: return results[0]
[ "def vignette(image, vignette_size=150):\n # height and width of the image\n height, width = image.shape[:2]\n # We will construct the vignette mask using Gaussian kernels\n # Construct a Gaussian kernel for x-direction\n kernel_x = cv2.getGaussianKernel(width, vignette_size)\n # Construct a Gauss...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function creates a new hdf5 file in the active directory taking as the sole argument a string name for the file.
def new_hdf5(new_filename): # handling input errors if not isinstance(new_filename, str): raise TypeError('Passed value of `filename` is not a string! Instead, it is: ' + str(type(new_filename))) # w- mode will create a file and fail if the file already exists hdf5 = h5py...
[ "def _create_file(self, filepath):\n folder, _filename = os.path.split(filepath)\n if not os.path.isdir(folder):\n os.makedirs(folder)\n file = h5py.File(filepath, 'a')\n return file", "def save_as_hdf5(self, filename):", "def _makeHDF5Txt(self):\n msg = self.asyncR...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function adds Raman calibration data to an existing hdf5 file. It uses the spectrafit.fit_data function to fit the data before saving the fit result and the raw data to the hdf5 file.
def add_calibration(hdf5_filename, data_filename, label=None): # handling input errors if not isinstance(hdf5_filename, str): raise TypeError('Passed value of `cal_filename` is not a string! Instead, it is: ' + str(type(hdf5_filename))) if not hdf5_filename.split('/')[-1].spl...
[ "def append_rates(path, detection_rate, formation_rate, merger_rate, redshifts, COMPAS, n_redshifts_detection,\n maxz=1., sensitivity=\"O1\", dco_type=\"BHBH\", mu0=0.035, muz=-0.23, sigma0=0.39, sigmaz=0., alpha=0.,\n append_binned_by_z = False, redshift_binsize=0.1):\n print('shape redshifts', np.shape(r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }