query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
When the user posts the find_org_to_create_account form, redirect to that page | def find_org_to_create_account(request):
if request.method != 'POST' or not request.POST.get('organization_slug'):
return HttpResponseRedirect(reverse('home'))
else:
org_slug = request.POST.get('organization_slug')
return HttpResponseRedirect(reverse('create_org_account', args=[org_slug]... | [
"def form_valid(self, form):\n # Redirect the user to the next step in the Member-creation process\n return HttpResponseRedirect(\n self.get_success_url(self.organization.slug, self.member.username)\n )",
"def create_organization():\n\n form = SQLFORM(db.organization)\n\n if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
df is a function of x_i, y_i, beta | def sgd_step(df, alpha, prev_beta, xy_i):
x_i, y_i = xy_i
gradient = df(x_i, y_i, prev_beta)
return [beta_j + alpha * df_j
for beta_j, df_j in zip(prev_beta, gradient)] | [
"def create_beta_posteriors(df):\n goods = df.num_matured - df.fpd\n df['alpha_p'] = df.alpha + df.fpd\n df['beta_p'] = df.beta + goods\n return df",
"def create_beta_priors(df):\n df['alpha'] = np.minimum(np.maximum((1 - df.expected) * np.power(df.expected, 2) / df.variance - df.expected, 0.1), 15... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the color of the mask at position. Using 2 bits as a color. | def get_color(mask: int, position: int):
return (mask >> (position << 1)) & 3 | [
"def mask_color(self):\n return self._mask_color",
"def GetOrFindMaskColour(*args, **kwargs):\n return _core_.Image_GetOrFindMaskColour(*args, **kwargs)",
"def set_color(mask: int, position: int, color: int):\n return mask | (color << (position << 1))",
"def get_color(self, point):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the color of the mask at position. Using 2 bits as a color. | def set_color(mask: int, position: int, color: int):
return mask | (color << (position << 1)) | [
"def get_color(mask: int, position: int):\n return (mask >> (position << 1)) & 3",
"def SetMaskColour(*args, **kwargs):\n return _gdi_.Bitmap_SetMaskColour(*args, **kwargs)",
"def SetMaskColour(*args, **kwargs):\n return _core_.Image_SetMaskColour(*args, **kwargs)",
"def SetMask(self,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a new ir.Set instance with given attributes. Absolutely all ir.Set instances must be created using this constructor. | def new_set(*, ctx: context.ContextLevel, **kwargs) -> irast.Set:
ir_set = irast.Set(**kwargs)
ctx.all_sets.append(ir_set)
return ir_set | [
"def newChemAtomSet(self, **attrlinks):\n return ChemAtomSet(self, **attrlinks)",
"def __init__(self, values=None):\n\n self.dict = {} # each instance of Set has its own dict property\n # which is what we'll use to track memnerships\n if values is not None:\n for ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a new ir.Set from another ir.Set. The new Set inherits source Set's scope, schema item, expression, and, if preserve_scope_ns is set, path_id. If preserve_scope_ns is False, the new Set's path_id will be namespaced with the currently active scope namespace. | def new_set_from_set(
ir_set: irast.Set, *,
preserve_scope_ns: bool=False,
path_id: typing.Optional[irast.PathId]=None,
stype: typing.Optional[s_types.Type]=None,
ctx: context.ContextLevel) -> irast.Set:
if path_id is None:
path_id = ir_set.path_id
if not preserve... | [
"def new_set(*, ctx: context.ContextLevel, **kwargs) -> irast.Set:\n ir_set = irast.Set(**kwargs)\n ctx.all_sets.append(ir_set)\n return ir_set",
"def copy_to_set(self) -> Set:\n return self.copy().flatten_to_set(modify=False)",
"def copy(self):\n newset = OrderedSet()\n newset.ite... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return ir.Set for a pointer defined as a computable. | def computable_ptr_set(
rptr: irast.Pointer, *,
unnest_fence: bool=False,
same_computable_scope: bool=False,
ctx: context.ContextLevel) -> irast.Set:
ptrcls = rptr.ptrcls
source_set = rptr.source
source_scls = source_set.stype
# process_view() may generate computable poin... | [
"def as_set(self):\n from ..sets import Union\n if len(self.free_symbols) == 1:\n return Union(*[arg.as_set() for arg in self.args])\n raise NotImplementedError('Sorry, Or.as_set has not yet been'\n ' implemented for multivariate'\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return founder and offspring subset of basename.ped containing only the markers in lcd lcd contains a sorted list of (chrom,offset,rs) for the common snps in all maps we need to keep genotypes all in the same column order | def subsetPed(basename="",lcdmap = [],faff='1', ofaff='2'):
mf = file('%s.map' % basename,'r').readlines()
lmap = [x.strip().split() for x in mf]
rscols = {} # lookup marker table
colrs = [] # lookup rs from column
for i,m in enumerate(lmap): # get columns to keep in the order we want them
... | [
"def mergePed(bnlist=[],faff=[],ofaff=[],newbasename='newped',fo=0):\r\n lcdmap = getLCD(bnlist) # list of chr,offset,rs for all snp common to all files\r\n print 'got %d lcd snps-%s' % (len(lcdmap),lcdmap[:5])\r\n cfped = []\r\n coped = []\r\n cfgeno = []\r\n cogeno = []\r\n allrsa = {}\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
take a list of basenames, get lcd and merge set founder affection according to faff flag and offspring according to ofaff flag | def mergePed(bnlist=[],faff=[],ofaff=[],newbasename='newped',fo=0):
lcdmap = getLCD(bnlist) # list of chr,offset,rs for all snp common to all files
print 'got %d lcd snps-%s' % (len(lcdmap),lcdmap[:5])
cfped = []
coped = []
cfgeno = []
cogeno = []
allrsa = {}
ignorers = {}
f... | [
"def subsetPed(basename=\"\",lcdmap = [],faff='1', ofaff='2'):\r\n mf = file('%s.map' % basename,'r').readlines()\r\n lmap = [x.strip().split() for x in mf]\r\n rscols = {} # lookup marker table\r\n colrs = [] # lookup rs from column\r\n for i,m in enumerate(lmap): # get columns to keep in the order ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test list secrets when not connected to any cluster. | def test_secrets_list_server_not_reachable():
message = "REANA client is not connected to any REANA cluster."
reana_token = "000000"
runner = CliRunner()
result = runner.invoke(cli, ["secrets-list", "-t", reana_token])
assert result.exit_code == 1
assert message in result.output | [
"def test_list_secrets(self):\n pass",
"def test_list_secrets(self):\n self.fail(\"test not implemented\")",
"async def list_secrets(self):\n pass",
"def test_read_namespaced_secret_list_secrets(self):\n pass",
"def test_secrets_list_server_no_token():\n message = \"Please pro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test list secrets when access token is not set. | def test_secrets_list_server_no_token():
message = "Please provide your access token"
env = {"REANA_SERVER_URL": "localhost"}
runner = CliRunner(env=env)
result = runner.invoke(cli, ["secrets-list"])
assert result.exit_code == 1
assert message in result.output | [
"def test_list_secrets(self):\n pass",
"def test_list_secrets(self):\n self.fail(\"test not implemented\")",
"def test_read_namespaced_secret_list_secrets(self):\n pass",
"def test_check_secrets(self):\n secrets.check_secrets([], argparse.Namespace())",
"def test_secrets_list_ser... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test adding secrets with wrong format. | def test_secrets_add_wrong_format(secret):
reana_token = "000000"
env = {"REANA_SERVER_URL": "localhost"}
runner = CliRunner(env=env)
message = 'For literal strings use "SECRET_NAME=VALUE" format'
result = runner.invoke(cli, ["secrets-add", "-t", reana_token, "--env", secret])
assert result.exi... | [
"def test_add_secret_key_value(self):\n pass",
"def test_check_secrets(self):\n secrets.check_secrets([], argparse.Namespace())",
"def test_list_secrets(self):\n pass",
"def test_create_secret(self):\n pass",
"def test_list_secrets(self):\n self.fail(\"test not implemented... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test adding secrets when they already exist. | def test_secrets_add_already_exist():
status_code = 409
reana_token = "000000"
env = {"REANA_SERVER_URL": "localhost"}
message = "One of the secrets already exists. No secrets were added."
mock_http_response = Mock(
status_code=status_code,
reason="Conflict",
json=Mock(return... | [
"def test_secret_exists(self):\n pass",
"def test_secret_exists_success(secret):\n secret.put(SECRET_STRING)\n assert secret.exists()",
"def test_add_secret_key_value(self):\n pass",
"def test_nonexisting_secret(self):\n assert docker.secret(\"NONEXISTING\", self.secrets_path) is No... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Optimized version of the generic paginate_query_across_partitioned_databases for case schedules queue_schedule_instances uses a lock to ensure that the same case_id cannot be queued within one hour of another instance The celery tasks handle_case_alert_schedule_instance and handle_case_timed_schedule_instance both use ... | def _paginate_query_across_partitioned_databases(model_class, q_expression, load_source):
from corehq.messaging.scheduling.scheduling_partitioned.models import (
CaseAlertScheduleInstance,
CaseTimedScheduleInstance,
)
if model_class not in (CaseAlertScheduleInstance, CaseTimedScheduleInstan... | [
"def schedule_fetch():\n for instance_group_manager in models.InstanceGroupManager.query():\n if instance_group_manager.url:\n if not utils.enqueue_task(\n '/internal/queues/fetch-instances',\n 'fetch-instances',\n params={\n 'key': instance_group_manager.key.urlsafe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method is used to terminate a job with the specified or a group of jobs job_id or job_name in a given cluster | def delete(cls, cluster, job, group=None):
try:
if group is not None:
# get the job ids from the db
arguments = {'cluster': cluster,
'group': group}
db_jobs = cls.cm.find('batchjob',
*... | [
"def stop_cluster(self, args):\n client = self.get_client()\n client.terminate_job_flows(JobFlowIds=[args['CLUSTERID']])\n\n return [{\"cm\": {\"cloud\": \"aws\",\n \"kind\": \"emr stop cluster request\",\n \"name\": args['CLUSTERID']},\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to set the tolerance. | def set_tolerance(self, tol):
self.tolerance = tol | [
"def setTolerance(self, tolerance = 0.001):\n \"\"\"tolerance: absolute tolerance value\"\"\"\n \n self.h.cvode.atol(tolerance)",
"def set_tolerance(self, value):\n\n self._tolerance = value",
"def set_tolerance(self, tol):\n self.precision = tol\n return",
"def set_t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to revert the direction of the current line. Returns | def revert(self):
reverted = Line(l=self)
reverted.direction *= -1.0
return reverted | [
"def fliped(self):\n return Line(self.end, self.start, self)",
"def revert(self, *args, **kwargs):",
"def _backup_line(self):\n if self._orig_line is None:\n self._orig_line = self._line",
"def reverseDirection(self):\n if self.extendedDirection == c.Directions.UP:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to get the abscissa of a point with respect to a line. The abscissa is 0 if the projection of the point and the projection of the frame origin on the line are the same point. | def get_abscissa(self, p):
return np.dot(p - self.zero, self.direction) | [
"def _line_x(line, y):\n p1 = line[0]\n p2 = line[1]\n if p2[0] == p1[0]:\n return p1[0]\n m = (p2[1] - p1[1]) / (p2[0] - p1[0])\n if m == 0:\n if p1[1] == y:\n return p1[0]\n return None\n x = p1[0] + (y - p1[1]) / m\n return x",
"def get_line_to(self, point):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the status code as per ttype and it's status_val | def get_status_code(self, ttype, status_val) -> str:
# get the status code from __status_code or __default_code
pass | [
"def status_type(self):\n return self._status_type",
"def ensure_status_value(status: T.Union[int, BaseStatusEnum]) -> int:\n if isinstance(status, BaseStatusEnum):\n return status.value\n else:\n return status",
"def get_status(self):\n if self.is_void:\n return u'v... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
To check if payload to be processed with this lambda | def apply_filter(self, payload: dict, ainfos) -> (dict, dict):
# check if needs to process by this lambda
pass | [
"def verify_payload():\n return True",
"def lambda_response_ok(response: dict) -> bool:\n # import pdb; pdb.set_trace()\n failed = response.get(\"FunctionError\")\n if failed:\n print(response[\"Payload\"].read().decode(\"utf-8\"), file=sys.stderr)\n return failed is None",
"def payloa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Use ansi code on 'string' if the output is the terminal of a not Windows platform | def isSpecial(ansiCode,string):
if IS_TERMINAL and not IS_WIN32: return ansiCode+string+ANSI_END
else: return string | [
"def ansi(self) -> str:\n # noinspection PyTypeChecker\n return str(self.read(), ANSI) # type: ignore",
"def ansi_sequence(self):\n codes = \";\".join(str(c) for c in self.ansi_codes)\n return f\"\\033[{codes}m\" if codes else \"\"",
"def ansi(key):\n global _ansi\n return _an... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sort list of TKey by their names ignoring the case | def keyListSort(keyList):
keyList.sort(key=lambda y: y.GetName().lower()) | [
"def sortCaseInsensitive(*args, **kwargs)->List[AnyStr]:\n pass",
"def sort_by_name(list_to_sort):\n return sorted(\n list_to_sort,\n key=lambda k: k['Name'].lower()\n )",
"def sortedNames(self):\n \n names = [(item.nicename, item.name) for item in self.values()]\n names.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sort list of tuple by their first elements ignoring the case | def tupleListSort(tupleList):
tupleList.sort(key=lambda y: y[0].lower()) | [
"def sort_case_sensitive(value: Tuple[str, Item]) -> str:\n return value[0]",
"def sort_case_insensitive(value: Tuple[str, Item]) -> str:\n return value[0].lower()",
"def sort_list_of_tuples(list):\n list.sort(key=lambda x: x[0])\n return list",
"def sortCaseInsensitive(*args, **kwargs)->List[AnyS... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Use sys.stdout.write to write the string with an indentation equal to indent and specifying the end character | def write(string,indent=0,end=""):
sys.stdout.write(" "*indent+string+end) | [
"def _indent_print(str, file, indent=4):\n # type: (six.text_type, TextIO, int) -> None\n file.write(\" \" * indent)\n print(str, file=file)",
"def maybePrintIndent(self):\n if self.lasttoken[0] != lex.Token.NEWLINE:\n return\n\n if len(self.lasttoken[1]) > 0:\n self.buffer.scopeline(\"__... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print informations given by keyList with a rools style choosen with optDict | def roolsPrint(keyList,optDict,indent=0):
if optDict['long'] or optDict['tree']: \
roolsPrintLongLs(keyList,optDict,indent)
else: roolsPrintSimpleLs(keyList,indent) | [
"def print_options(show_opts):\n select_dict = {}\n select_number = 1\n\n for key, value in show_opts.items():\n select_dict.update({str(select_number): key})\n description = value[0] if value[0] is not None else \"\"\n print(\"\\t{} - {}{}\".format(select_number, key, description))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a Producer queue instance | def getProducer():
# get the config and a producer
config = ecommerce.config.getConfig()
return ecommerce.queue.queue(config, queuePrefix) | [
"def get_queue():\n\n return multiprocessing.Queue()",
"def get_queue():\n watcher = Watcher()\n watcher.connect()\n queue = watcher.get_queue()\n return queue",
"def get_queue(self):\n return Queue(self.name, connection=self.connection, serializer=self.serializer)",
"def get(queue_n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the list of all entities of a given type from DB | def getEntityIds(type, subtype = None):
# get a cursor
conn = ecommerce.db.getConnection()
cursor = conn.cursor()
# decide the query to execute
if type not in entityQueries:
return [ ]
# execute the query
qparams = (type, )
if subtype is not None:
qparams ... | [
"def __get_entities(self, etype):\n r = fapi.get_entities(self.namespace, self.name,\n etype, self.api_url)\n fapi._check_response_code(r, 200)\n return [Entity(e['entityType'], e['name'], e['attributes'])\n for e in r.json()]",
"def getAll(self, ti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mark the entities modified before a specific date as processed | def mark_processed_entities(entity_type, max_date):
try:
# get a connection and cursor
conn = ecommerce.db.getConnection()
cursor = conn.cursor()
# execute the query
cursor.execute("""
UPDATE Stage0_Delta
SET F... | [
"def visitBefore(self, date):\n raise NotImplementedError()",
"def is_before(self,other_date):",
"def modified(self):\r\n\t\treturn self.last_modified > self.last_processed",
"def mark_as_processed(oea_msg_obj):\n oea_msg_obj.processed = timezone.now()\n oea_msg_obj.save()",
"def modified(self)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A generator that can be used to iterate over all of the message handlers that belong to this instance. | def iter_message_handlers(self):
for name in dir(self):
attr = getattr(self, name)
if isinstance(attr, MessageHandler):
yield attr | [
"def __iter__(self):\n for handlers in self._handlers.values():\n for h in handlers:\n yield h",
"def get_message_handlers(self):\n\t\treturn self.message_handlers",
"def get_message_handlers(self):\n return [\n (\"normal\", self.message),\n ]",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds the given service's message handlers to our managed message handlers. | def register_service(self, service):
for message_handler in service.iter_message_handlers():
self.message_handlers[message_handler.name] = message_handler | [
"def add_handlers(self, logger, handlers):\n for h in handlers:\n try:\n logger.addHandler(self.config['handlers'][h])\n except StandardError as e:\n raise ValueError('Unable to add handler %r: %s' % (h, e))",
"def register_websock_handlers(self, service,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Invokes the correct message handler for the given message. | def handle_message(self, sender, message):
self.logger.debug('handle_message(%r, %r)', sender, message.handler)
message_handler = self.message_handlers.get(message.handler)
if message_handler is None:
self.logger.warning("sender=%r, No handler found: '%s'",
... | [
"def handle_message(**payload):\n handler_instance = message.MessageHandler(payload)\n handler_instance.handle()",
"def _PushHandlerMessage(self, message):\n\n # We only accept messages of type MESSAGE.\n if message.type != rdf_flows.GrrMessage.Type.MESSAGE:\n raise ValueError(\"Unexpected messag... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert a time.struct_time as returned by feedparser into a | def _convert_struct_time_to_dt(stime):
return date.fromtimestamp(mktime(stime)) | [
"def time_struct_to_datetime(struct_time_object):\n return datetime.datetime(*struct_time_object[:6])",
"def _strptime_time(data_string, format=\"%a %b %d %H:%M:%S %Y\"):\n tt = _strptime(data_string, format)[0]\n return time.struct_time(tt[:time._STRUCT_TM_ITEMS])",
"def parse_time(block_time):\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Use feedparser to parse PyBites RSS feed. Return a list of Entry namedtuples (date = date, drop time part) | def get_feed_entries(feed=FEED) -> list:
f = feedparser.parse(feed)
entry_list = []
for entry in f.entries:
date = _convert_struct_time_to_dt(entry["published_parsed"])
title = entry["title"]
link = entry["link"]
tags = [tag["term"].lower() for tag in entry["tags"]]
... | [
"def get_feed_entries(feed=FEED):\n d = feedparser.parse(feed)\n entries = d.entries\n \n all_entries =[]\n for entry in entries:\n title = entry.title\n link = entry.link\n date = entry.published_parsed\n tags = entry.tags\n tags = [t.get('term').lower() for t in t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if search matches any tags as stored in the Entry namedtuple (case insensitive, only whole, not partial string matches). | def filter_entries_by_tag(search, entry) -> bool:
tags = entry.tags
search_words = search.strip().translate(str.maketrans("&|", " ")).split()
if "&" in search:
search_type = "AND"
else:
search_type = "OR"
for word in search_words:
if word.lower() in tags:
if se... | [
"def filter_entries_by_tag(search, entry):\n \n entry_tags = entry.tags\n if '&' in search:\n splits = search.split('&')\n\n return all(split.lower() in entry_tags for split in splits)\n elif '|' in search:\n splits = search.split('|')\n return any(split.lower() in entry_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gather the top 10 words by highest (descending) likelihoods for each class | def top10_likelihoods(likelihoods, vocab, classes):
resultDict = {}
for cls in classes:
results = []
for word in vocab:
results.append((word, likelihoods[cls][word]))
resultDict[cls] = results
# Sort and return top 10 for each class
for key in resultDict:
... | [
"def top10_odds_ratio(likelihoods, vocab, classes):\r\n results = []\r\n for word in vocab:\r\n highestOddsRatio = None\r\n for c1 in classes:\r\n for c2 in classes:\r\n # Skip self TODO: Is this right?\r\n # if c1 == c2:\r\n # continue... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gather the top 10 words by highest (descending) odds ratios | def top10_odds_ratio(likelihoods, vocab, classes):
results = []
for word in vocab:
highestOddsRatio = None
for c1 in classes:
for c2 in classes:
# Skip self TODO: Is this right?
# if c1 == c2:
# continue
odd... | [
"def display_top_n_words(total_count__of_words, n): # Considering n=10 here as specified in the requirements\n return sorted(total_count__of_words.items(), key=lambda i: i[1], reverse=True)[:n]",
"def top_words(filtered_words):\n\n fdist = FreqDist(filtered_words) #finds the words qrequency disctributi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Estimate the priors for a class | def calculate_priors(trainingLabels):
sum = 0
priors = {}
totalSamples = len(trainingLabels)
classes = set(trainingLabels)
for cls in classes:
numCls = len(filter(lambda x: x == cls, trainingLabels))
sum += numCls
priors[cls] = float(numCls) / float(totalSamples)
... | [
"def classProbs(observation, tree, classes):\n res = classify(observation, tree) #res = results\n total = sum(res.values())\n probs = []\n for c in classes:\n if c in res.keys():\n probs.append(float(res[c])/total)\n else:\n probs.append(0)\n return probs",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the likelihoods for multinomial | def calculate_likelihoods_multinomial(data, labels, vocab):
likelihoods = {}
counts = {}
words = {}
classes = set(labels)
vocabLen = len(vocab)
for cls in classes:
# Initialize
counts[cls] = {}
words[cls] = 0
# Perform counts
line = 0
for doc in da... | [
"def log_multinomial_coefficient(n, x):\n return gammaln(n + 1) - gammaln(x + 1).sum()",
"def log_marginal_likelihood(X_train,y_train,phi,tau=1.,Ve=1.e-10):",
"def multinomial_gen_log_prob(x, n, p):\n if n != 1:\n raise NotImplementedError()\n log_prob = np.sum(x * np.log(p))\n return log_prob\n # TOD... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract the known vocabulary from our training data | def get_vocab(trainingData):
return set(reduce(lambda x,y: x+y, map(lambda x: map(lambda y: y[0], x), trainingData), [])) | [
"def get_vocab(self):\n\n\t\tself.parse_transcript() \n\t\tself.purge_words()\n\t\tself.analyze_words()\n\t\tself.sort_word_analysis()",
"def get_vocab(self):\n return list(self.all_words.keys())",
"def test_get_transcription_vocabulary(self):\n pass",
"def get_vocab(self):\n return self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return elements from the iterable until it is exhausted. Then repeat the sequence indefinitely. cycle(seq) ==> seq[0], seq[1], ..., seq[n 1], seq[0], seq[1], ... | def cycle(seq, n=None):
if n is not None:
return Iter(_ncycle(n, seq))
return Iter(itertools.cycle(seq)) | [
"def cycle(iterator: Iterable[Any]) -> Iterable[Any]:\n while True:\n yield from iterator",
"def iter_sequence_infinite(seq):\n while True:\n for item in seq:\n yield item",
"def repeat(seq, n):\n for e in seq:\n for _ in range(n):\n yield e",
"def _seq():\n i = 0\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the object for the specified number of times. If not specified, returns the object endlessly. | def repeat(obj, times=None):
if times is None:
return Iter(itertools.repeat(obj))
return Iter(itertools.repeat(obj, times)) | [
"def repeat(self, count):\n return self.Sequence((self,) * count)",
"def repeater(at_least, timeout):\n timer = Timer(timeout)\n repeat = 0\n while repeat < at_least or timer.remaining():\n yield repeat\n repeat += 1",
"def repeat(fun, n):\n for i in range(n):\n yield fun... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make infinite calls to a function with the given arguments. End sequence if func() raises StopIteration. | def repeatedly(func, /, *args, **kwargs):
func = to_callable(func)
try:
while True:
yield func(*args, **kwargs)
except StopIteration as e:
yield from stop_seq(e) | [
"def iterate(func, x):\n while True:\n x = func(x)\n yield x",
"def iterate(func, start):\n while True:\n yield start\n start = func(start)",
"def iterate(f, x):\n while True:\n yield x\n x = f(x)",
"def iterate1(f, x):\n while True:\n yield x\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Invert a fold. Similar to iterate, but expects a function of seed > (seed', x). The second value of the tuple is included in the resulting sequence while the first is used to seed func in the next iteration. Stops iteration if func returns None or raise StopIteration. | def unfold(func, seed):
try:
elem = func(seed)
while elem is not None:
seed, x = elem
yield x
elem = func(seed)
except StopIteration as e:
yield from stop_seq(e) | [
"def foldr(func, iterable):\n return fold(func, reversed(iterable))",
"def flip(func):\n def flipped(*args):\n return func(*args[::-1])\n return flipped",
"def fold(iterable, func, base):\n acc = base\n for element in iterable:\n acc = func(acc, element)\n return acc",
"def fol... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create iterator from sequence of numbers. | def from_sequence(self, seq):
return Iter(self._from_sequence(seq)) | [
"def numeric_sequence_iteration(self) -> global___Statement.Iteration.NumericSequenceIteration:",
"def _seq():\n i = 0\n while True:\n yield i\n i += 1",
"def range(*args) -> \"Iter[int]\":\n return Iter(_range(*args))",
"def simple_seq(seq):\n for i in seq:\n yield i",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create iterator from slice object. | def from_slice(self, slice):
start = 0 if slice.start is None else slice.start
step = 1 if slice.step is None else slice.step
return self.count(start, step, stop=slice.step) | [
"def __iter__(self):\n return _IndexedComponent_slice_iter(self)",
"def islice(iterable, *args) -> \"Iter\":\n return Iter(itertools.islice(iterable, *args))",
"def from_sequence(self, seq):\n return Iter(self._from_sequence(seq))",
"def iter_slices(\n len_seq: int,\n chunk_size: int,\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a sequence of n evenly spaced numbers from a to b. | def evenly_spaced(self, a: Real, b: Real, n: int) -> Iter:
return Iter(_evenly_spaced(a, b, n)) | [
"def get_number_sequence(a: int, b: int) -> Iterable[int]:\n n = 0\n while True:\n yield n**2 + a*n + b\n n += 1",
"def distribute(N, b):\n return [div + mod for div, mod in izip_longest(repeat(N//b, b), repeat(1, N%b), fillvalue=0)]",
"def linspace(a,b,nsteps):\n ssize = float(b-a)/(n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert int to string without using builtin str() | def int_to_string(num):
if num < 0:
num, is_neg = -num, True
else:
is_neg = False
s = []
while num > 0:
s.append(chr(ord('0') + num%10))
num //= 10
return ('-' if is_neg else '') + ''.join(reversed(s)) | [
"def to_str(num: int) -> str:\n return str(num)",
"def int_to_str(source: int) -> str:\n return str(source)",
"def int_to_str(i):\n digits = '0123456789'\n if i == 0:\n return '0'\n result = ''\n while i > 0:\n result = digits[i%10] + result\n i = i//10\n return result",
"def _t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot a template over a detected stream, with picks corrected by lagcalc. | def plot_repicked(template, picks, det_stream, size=(10.5, 7.5), save=False,
savefile=None, title=False):
# _check_save_args(save, savefile)
fig, axes = plt.subplots(len(det_stream), 1, sharex=True, figsize=size)
if len(template) > 1:
axes = axes.ravel()
mintime = det_stream.so... | [
"def plotTemplate(self,ax=None):\n if self.templatefilename is None:\n return\n doshow = False\n if ax is None:\n doshow = True\n fig = figure()\n ax = fig.add_subplot(111)\n #ax.plot(self.sptemp.data,'k')\n ax.plot(self.sptemp.mpw,self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Carga tola la pila con strings | def cargaAutoStr(pila):
while not pila_llena(pila):
largo = random.randint(1, 15)
apilar(pila, randString(largo)) | [
"def extraccion_textos():\n global NOMBRE_ASIGNATURA1, NOMBRE_ASIGNATURA2\n global DESCRIPCION_ASIGNATURA1, DESCRIPCION_ASIGNATURA2\n global CAPITULOS_ASIGNATURA1, CAPITULOS_ASIGNATURA2\n\n NOMBRE_ASIGNATURA1 = obtener_nombre(ID_ASIGNATURA1)\n NOMBRE_ASIGNATURA2 = obtener_nombre(ID_ASIGNATURA2)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Devuelve elemento de la cima | def cima(pila):
return pila.datos[pila.tope] | [
"def elemento(self):\n try:\n nodo = self._lista._inicio\n\n count = 0\n\n while count != self._actual:\n nodo = nodo.getSiguiente()\n count += 1\n\n return nodo.getDato()\n\n except AttributeError:\n return self._lis... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Devuelve la pila invertida | def invertir(pila1):
pila2 = Pila()
while not pila_vacia(pila1):
apilar(pila2, desapilar(pila1))
return pila2 | [
"def scale_invert(self):",
"def modular_inverse(self):\n i = gmpy2.invert(self.c2, self.n)\n mx = pow(self.c1, self.a, self.n)\n my = pow(i, int(-self.b), self.n)\n self.m= mx * my % self.n",
"def __invert__(self):\n return BitBoard(~self.num)",
"def a_inv(self):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finalize the grades and print. Only for assessors. | def finalize(request, pk, version=0):
ts = get_timeslot()
if not hasattr(ts, 'resultoptions'):
raise PermissionDenied("Results menu is not yet visible.")
else:
if not get_timeslot().resultoptions.Visible:
raise PermissionDenied("Results menu is not yet visible.")
dstr = get_... | [
"def print_grades(self):\n for i in self._grades:\n print(f'Course name: \"{i}\", Letter grade: \"{self._grades[i]}\"')\n pass",
"def main():\n\n students = [\"Chris\", \"Jesse\", \"Sally\"]\n grades = [90, 80, 70]\n print_gradebook(students, grades)",
"def generate_gradelog(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List all aspects of a given grade category in the current timeslot | def list_aspects(request, pk):
category = get_object_or_404(GradeCategory, pk=pk)
aspects = GradeCategoryAspect.objects.filter(Category=category)
ts = get_timeslot()
return render(request, "results/list_aspects.html", {
"aspects": aspects,
'ts': ts,
'cat': category,
}) | [
"def get_category_averages(self):\n return [strand_analysis.get_category_average() for strand_analysis in self.strand_analyses.all()]",
"def attribute(category_name):",
"def list_all_cat_scores(self):\n\n categories = Category.objects.all()\n score_before = self.score\n output = {}\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a child config | def add(self, key, child_config):
self.__dict__[key] = child_config
child_config.root = self | [
"def register(self, child, name=None):\n if name is None:\n name = child.name\n if isinstance(child, ConfigValue):\n if name in self:\n raise KeyError('A child with this name already exists')\n self._values[name] = child\n elif isinstance(child, C... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Format strings using CONFIG object. This method uses python's builtin `str.format()` method. All root properties in CONFIG are passed in as kwargs. The properties lazy evaluate and recursively expand. | def format(self, value, key=None, **kwargs):
if not isinstance(value, str):
return value
# always format strings using the root so the full path is available
if self.root:
return self.root.format(value, key, **kwargs)
variables = CONFIG_VARIABLE_PATTERN.findall(... | [
"def recursively_update_config(config, string_formatting_dict):\n\n for k in _iterate_list_or_dict(config):\n v = config[k]\n if isinstance(v, dict) or isinstance(v, list):\n recursively_update_config(v, string_formatting_dict)\n else:\n if _key_in_string(v, string_form... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Directory where ixian is installed | def IXIAN(cls):
import ixian
return os.path.dirname(os.path.realpath(ixian.__file__)) | [
"def toilPackageDirPath():\n result = os.path.dirname(os.path.realpath(__file__))\n assert result.endswith('/toil')\n return result",
"def mitogen_lxc_path(self):",
"def get_install_dir(self):\n return EventGenerator.get_install_dir(self) + \"/madgraph5/src\"",
"def get_installdir(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Trova uno zero della funzione f tra i punti a e b, dove la f assume segno discorde. Il parametro opzionale toll indica la precisione con cui si vuole calcolare il valore dello zero | def bisezione(f,a,b,toll=10**-5):
m = (a+b)/2
f_m = f(m)
while abs(f_m) > toll:
if f(a)*f_m < 0:
b = m
elif f(b)*f_m < 0:
a = m
elif f_m == 0:
print("Trovata solzione esatta")
return m
else:
print("Metodo fallito")
... | [
"def valeur_approchee(f):\n (a, b) = f\n return round(a / b, 4)",
"def zero_force_func(v,t):\n return 0.0",
"def f(x0: float, x1: float) -> float:\n return 8 - (x0 - 2) ** 2 - (x1 - 2) ** 2",
"def _correct_p(self, f0, f1):\n return self.p * np.exp(self.dbeta * (f0 + f1) / 2)",
"def find_z... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Restituisce una lista con le sole frequenze con cui compaiono gli elementi nella lista/tupla l. Ad es. se l = (1,2,2,5,3,4,1,1), allora | def freq(l):
d = {}
for i in l:
if i in d:
d[i] += 1
else:
d[i] = 1
return list(d.values()) | [
"def tri_entiers(l):\n # première boucle, minimum, maximum\n m = l [0]\n M = l [0]\n for k in range(1,len(l)):\n if l [k] < m : m = l [k]\n if l [k] > M : M = l [k]\n \n # calcul du nombre d'occurrences\n p = [0 for i in range (m,M+1) ]\n for i in range (0, len (l)) :\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Restituisce la funzione di Mobius dei primi n numeri. Viene fornita la lista primes che deve contenere tutti i primi almeno fino a n, questa cosa per velocità non viene verificata, è a cura di chi utilizza la funzione!!! | def mobius(n,primes):
m = [0]*(n+1)
for p in primes:
for i in range(p, n+1, p):
m[i] += 1
for p in primes:
p_2 = p**2
for i in range(p_2, n+1, p_2):
m[i] = 0
for i in range(n+1):
if m[i] == 0:
continue
elif m[i]%2 == 0:
... | [
"def mobius(n, fn=prime_factor):\n if n < 1: return None\n r = 1\n for (p, e) in fn(n):\n if e > 1: return 0\n r = -r\n return r",
"def lista_numeros_primos(m):\n for n in range(2, m):\n resultado = eh_primo(n)\n if resultado == True:\n print(n, 'é um número primo')\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Algoritmo di integrazione Simpson 1/3, per calcolare l'integrale della funzione f tra gli estremi a e b. L'intervallo è suddiviso in n sottointervalli. Aumentando n aumenta la precisione. | def simpson_13(f,a,b,n=1):
step = (b-a)/n
h = step/2
ret = 0
for i in range(n):
a_1 = a + i*step
b_1 = a_1 + step
ret += h/3*(f(a_1)+4*f(a_1+h)+f(b_1))
return ret | [
"def simpson1(func, g, a, b, n):\n\n if n%2!=0: #Verifica se é divisivel por 2\n print(\"Não é possivel calcular com esse numero de subintervalos! Insira um multiplo de 2!\\n\")\n return\n\n h=(b-a)/n\n x=a\n soma=0\n\n for i in range(0, n+1):\n if i==0 or i=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Algoritmo di kruskal per la ricerca dell'MST di un grafo, fornito in tramite la sua matrice di adiacenza, usa la funzione ring_finder per cercare anelli nel grafo e di min_nonzero_idx per trovare gli inidici dei rami con costo minimo | def kruskal(m):
n = m.shape[0]
m_ret = np.zeros([n,n], dtype=int)
while np.count_nonzero(m_ret) != 2*(n-1):
i_min, j_min = min_nonzero_idx(m)
n_min = m[i_min, j_min]
m[i_min, j_min], m[j_min, i_min] = 0, 0
m_ret[i_min, j_min], m_ret[j_min, i_min] = n_min, n_min
if rin... | [
"def kruskal(self, matr, minimo=True):\n ncomps = len(matr)\n already = []\n ramas = []\n dists = []\n matrix = [ele[:] for ele in matr]\n dic_posis = [-(ele+1) for ele in range(ncomps)]\n comps = [[] for ele in range(ncomps)]\n nrama = 0\n mins = []\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PRIME FACTORS OF FACTORIAL Restituisce una lista in cui all'iesima posizione si trovala potenza a cui l'iesimo numero primo è elevato nella scomposizione in fattori primi del fattoriale di n | def pff(n):
global primes
#primes = primi(n)
ret = []
for p in primes:
a = 0
if p > n:
break
for i in range(1, int(log(n,p)) + 1):
a += int(n/p**i)
ret.append(a)
return ret | [
"def factorization(n):\r\n pf = []\r\n for p in primeslist:\r\n if p * p > n : break\r\n count = 0\r\n while not n % p:\r\n n //= p\r\n count += 1\r\n if count > 0: pf.append((p, count))\r\n if n > 1: pf.append((n, 1))\r\n return pf",
"def factorization(n):\n pf = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PRIME FACTORS OF BINOMIAL Restituisce una lista in cui all'iesima posizione si trovala potenza a cui l'iesimo numero primo è elevato nella scomposizione in fattori primi del coefficiente binomiale di (n1 n2) | def pfb(n1, n2):
global primes
#primes = primi(n)
n3 = n1 - n2
factors_1, factors_2, factors_3 = pff(n1), pff(n2), pff(n3)
for i in range(len(factors_2)):
factors_1[i] -= factors_2[i]
if i < len(factors_3):
factors_1[i] -= factors_3[i]
return factors_1 | [
"def pff(n):\n global primes\n #primes = primi(n)\n ret = []\n for p in primes:\n a = 0\n if p > n:\n break\n for i in range(1, int(log(n,p)) + 1):\n a += int(n/p**i)\n ret.append(a)\n return ret",
"def factorization(n):\r\n pf = []\r\n for p ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Restituisce una lista con le prime n righe del triangolo di Pascal, ogni riga è una a sua volta una lista | def triangolo_pascal(n):
tri = [[1]]
for i in range(1,n):
tri.append([1])
for j in range(1,i):
tri[i].append(tri[i-1][j-1] +tri[i-1][j])
tri[i].append(1)
return tri | [
"def UtworzPustaPlansze (rozmiar):\r\n tablica=[0]*rozmiar # najpierw tworzymy listę z <wierszy> elementów\r\n # elementy listy mogą być dowolne\r\n for i in range (rozmiar):\r\n tablica[i]=[\" \"]*rozmiar\r\n return tablica",
"def pascal_triangle(n):\n myList = []\n i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get current NFL season After March, returns year of upcoming season. | def current_season() -> int:
now = datetime.now()
month, year = now.month, now.year
if month < 4:
year -= 1
return year | [
"def current_season():\n td = datetime.datetime.today()\n if td.month > 8:\n return td.year\n return td.year - 1",
"def get_current_season():\n month_nr = date.today().month\n return (month_nr % 12 + 3) // 3",
"def get_current_season():\n current_time = datetime.now()\n if current_ti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get NFL week (ESPN scoring period) from date The year of the given date determines the relevant NFL season. Assumes week 1 begins the week of Labor Day and ends the following Wednesday. Does not cap value, so may be below 1 or above 17. | def get_week_from_date(date) -> int:
month, year = date.month, date.year
if month < 4:
year -= 1
ld = _labor_day(year)
wk1_wed = ld + timedelta(days=2)
days_since = (date - wk1_wed).days
weeks_since = days_since / 7.
week = math.floor(weeks_since) + 1
return int(week) | [
"def get_week(date):\n\n # TODO: the API seems broken. It returns week, year not year, week as documentef\n # why not use date.isocalendar() from the stdlib?\n\n date = date_trunc('week', date)\n\n first_monday = date_trunc('week', date_trunc('year', date))\n if first_monday.year < date.year:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find list of edl directories in all dependencies for the passed module | def get_edl_dirs(mod, gen_cfg):
log.info("Fetching dependencies for %s", coordinates.as_path(mod.coords))
dependencies = mod.get_dependencies()
edl_dirs = [mod.get_edl_path()]
for dep, dep_coords in dependencies.items():
dep_cfg = gen_cfg.get_mod_cfg(dep)
log.info("Dependency: %s", coor... | [
"def retrieve_module_list():\n\n current_dir = getcwd()\n mod_list = []\n\n for item in listdir(current_dir):\n\n if item.endswith('db'):\n\n mod_list.append(item)\n\n return mod_list",
"def getModules() -> tuple:\n return data.getFoldersOf(data.ETC)",
"def library_dirs(self):",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the symbol XML node | def edit_symbol_node(node, filename):
size = int(re.findall('\d+', filename)[-1])
log.info('New filename %s; size %s', filename, size)
node.set('typeId', SYMBOL_ID)
node.find('name').text = 'DLS symbol'
# Use PV name from rule in control PV for tooltip etc.
# Reference that PV in rule to avoid... | [
"def update_sym(self, new_symbol):\n self.symbol = new_symbol\n self.layer_type_dict = self._get_layer_type_dict()\n self.arg_params = self._clean_params(self.symbol, self.arg_params)\n self.aux_params = self._clean_params(self.symbol, self.aux_params)",
"def symbol(self, new_symbol: i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Grep on the basepath to find all files that contain an EDM symbol widget. control | def build_filelist(basepath):
log.info("Building list of files containing EDM symbols in %s", basepath)
symbol_files = []
for dir_path, _, filenames in os.walk(basepath):
for filename in filenames:
filepath = os.path.join(dir_path, filename)
if filename.endswith(".opi") and u... | [
"def GetSupplementalFiles():\n # Can't use the one in gyp_chromium since the directory location of the root\n # is different.\n t = glob.glob(os.path.join(checkout_root, 'supplement.gypi'))\n print t\n return t",
"def find_dcds(src):\n\n dcd_paths = []\n\n for root, dirs, files in os.walk(src):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process one symbol file and convert to PNG. | def process_symbol(filename, mod, mod_cfg, mirror_root, prod_root):
working_path = os.path.join(mirror_root, prod_root[1:])
log.debug("Finding version from %s", working_path)
mod_version = utils.get_module_version(working_path, mod_cfg.area, mod, mod_cfg.version)
log.info("Found version %s", mod_version... | [
"def __export_jpg(self, filename):\n name = os.path.splitext(os.path.basename(filename))[0]\n count = len(self.__colors)\n chars = [chr(x) for x in range(32, 127) if chr(x) != '\"']\n if count > len(chars):\n chars = []\n for x in range(32, 127):\n if... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
calculate_angles(chunk) calculates elevation and azimuth given a jsonformatted chunk from ODAS | def calculate_angles(self,chunk):
import math
import collections
Angles = collections.namedtuple("Angles", "ev az")
x = float(chunk['x'])
y = float(chunk['y'])
z = float(chunk['z'])
ev = round(90 - math.acos(z/math.sqrt(x*x+y*y+z*z))*180/math.pi)
az = rou... | [
"def _azimuth(section, soma):\n vector = morphmath.vector(section[0], soma.center)\n return np.arctan2(vector[COLS.Z], vector[COLS.X])",
"def extract_angles(self):\n atom_ids = self.contents['ID']\n angle_list = []\n for key, value in self.angles.items():\n a = value[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an "absolute" value for a timedelta, always representing a time distance. | def abs_timedelta(delta):
if delta.days < 0:
now = datetime.datetime.now()
return now - (now + delta)
return delta | [
"def abs_timedelta(delta):\r\n if delta.days < 0:\r\n now = _now()\r\n return now - (now + delta)\r\n return delta",
"def __abs__(self):\n return Duration(self._frame, abs(self._seconds))",
"def delta(self, abs_value=False):\n return self.current - self.last if not abs_value el... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Turn a value into a date and a timedelta which represents how long ago it was. If that's not possible, return (None, value). | def date_and_delta(value):
now = datetime.datetime.now()
if isinstance(value, datetime.datetime):
date = value
delta = now - value
elif isinstance(value, datetime.timedelta):
date = now - value
delta = value
else:
try:
value = int(value)
de... | [
"def date_and_delta(value):\r\n now = _now()\r\n if isinstance(value, datetime):\r\n date = value\r\n delta = now - value\r\n elif isinstance(value, timedelta):\r\n date = now - value\r\n delta = value\r\n else:\r\n try:\r\n value = int(value)\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the Hamming distance between equallength sequences | def __hamming_distance(s1, s2):
if len(s1) != len(s2):
raise ValueError("Undefined for sequences of unequal length")
return sum(el1 != el2 for el1, el2 in zip(s1, s2)) | [
"def hamming_distance(seq1, seq2):\n dist = sum([char1 != char2 for char1, char2 in zip(seq1, seq2)])\n return dist",
"def modified_hamming_distance(s1, s2):\n if len(s1) != len(s2):\n raise ValueError(\"Undefined for sequences of unequal length\")\n score = 0\n for el1, el2 in zip(s1, s2):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return checkpoints for recomputing | def get_checkpoints(self):
# recompute checkpoints
return self._checkpoints | [
"def checkpoint():",
"def get_all_overall_checkpoint(cls):\n return cls.create_all_overall_checkpoint()",
"def checkpoint(self):\r\n return self._checkpoint",
"def finish_checkpoint(self):\n return self.this_evaluation.checkpoint",
"def create_all_overall_checkpoint(cls):\n return DB... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
append name with postfix | def append_name(name, postfix):
if name is None:
ret = None
elif name == '':
ret = postfix
else:
ret = '%s_%s' % (name, postfix)
return ret | [
"def add_name_index(self, index):\n self.name += \".%d\" % index",
"def NewName(self) -> str:",
"def print_name(name):\r\n\r\n\r\n return name + \"-apple\"",
"def add_name(self, node):\n if 'name' in self.options:\n name = nodes.fully_normalize_name(self.options.pop('name'))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lands the rover, and makes it part of the grid Throws an exception if A rover with that name already existed The rover being landed has a bad direction The rovers coordinates are off the grid A rover already exists on the gird at the rover's coordinates | def land_rover(self, rover):
if self.rovers.get(rover.name):
raise RoverException(ExceptionMessages.ROVER_ALREADY_LANDED)
if not Rover.valid_direction(rover.direction):
raise RoverException(ExceptionMessages.BAD_DIRECTION)
if not self._is_coordinate_in_the_grid(rover.c... | [
"def move(self, rover_id, grid_point):",
"def make_move(self, playername, coordinates, direction):\n curr_player = self.get_player_from_name(playername)\n curr_player_marble = curr_player.get_marble_color()\n\n # if Game has already been won - return False\n if self._winner is not None... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tries to navigate and reposition the rover on the gird. Throws an exception if It cannot find that rover on the grid A bad instruction is passed Executing the instruction string will cause a collision with another rover on the gird | def navigate_rover(self, name, instruction_str):
rover = self.rovers.get(name)
if not rover:
raise RoverException(ExceptionMessages.BAD_NAME)
coordinate = copy.deepcopy(rover.coordinate)
direction = rover.direction
for instruction in instruction_str:
i... | [
"def move(self, rover_id, grid_point):",
"def move(self, direction):\r\n #create moving direction vectors if the N S E W or a combination is entered\r\n if direction == \"N\":\r\n new = (0,-1)\r\n elif direction == \"S\":\r\n new = (0,1)\r\n elif direction == \"E\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Basically a state machine Given a instruction('R' or 'L') and a direction('N' or 'S' or 'E' or 'W'), returns the new direction Throws an exception in case of bad instruction | def _direction_after_turning(self, direction, instruction):
next_left_states = {'N':'W', 'W': 'S', 'S': 'E', 'E': 'N'}
next_right_states = {'N': 'E', 'E': 'S', 'S': 'W', 'W': 'N'}
if instruction == 'R':
return next_right_states[direction]
elif instruction == 'L':
... | [
"def go_one_step(old_state, direction):\n assert direction in ['R', 'L', 'U', 'D']\n\n x, y = old_state\n if direction == 'R':\n return (x+1, y)\n if direction == 'L':\n return (x-1, y)\n if direction == 'U':\n return (x, y+1)\n if direction == 'D':\n return (x, y-1)",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a new coordinate after moving the rover, Based on the direction, it applies a movement of one grid and calculates the new coordinates. Its throws an exception if the new coordinate is off grid the new coordinate results in an collision with another rover | def _coordinate_after_moving(self, direction, coordinate):
if direction == 'N':
new_coordinate = Coordinate(coordinate.x, coordinate.y + 1)
elif direction == 'S':
new_coordinate = Coordinate(coordinate.x, coordinate.y - 1)
elif direction == 'W':
new_coordinat... | [
"def move(self, rover_id, grid_point):",
"def _calculate_move_location(self, direction):\n current_row = self._current_loc.get_row()\n current_column = self._current_loc.get_column()\n\n # Calculate the new location for a left move\n if (direction == \"l\"):\n return Locatio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return any binary tree that matches the given preorder and postorder traversals. Values in the traversals pre and post are distinct positive integers. | def constructFromPrePost(self, pre, post):
if not pre and not post:
return None
root = TreeNode(pre[0])
if len(pre) == 1 and len(post) == 1:
return root
if pre[1] == post[-2]:
lpre, lpost = pre[1:], post[:len(post)-1]
ltree = self.construc... | [
"def constructFromPrePost(pre, post):\n \"\"\"\n # 17%\n def helper(l1, r1, l2, r2):\n cur = TreeNode(pre[l1])\n if l1 == r1: return cur\n a1, a2 = pre[l1 + 1], post[r2 - 1]\n nx = d_pre[a2]\n nt = d_post[a1]\n if a1 != a2:\n left = helper(l1 + 1, nx - 1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create and return an instance of the Isort plugin. | def setup_isort_tool_plugin(custom_rsc_path=None):
arg_parser = argparse.ArgumentParser()
if custom_rsc_path is not None:
resources = Resources([custom_rsc_path])
else:
resources = Resources(
[os.path.join(os.path.dirname(statick_tool.__file__), "plugins")]
)
config ... | [
"def sorter(Plugin):\n return Plugin.order",
"def create_plugin(self, **kwargs):\n return self.plugin_class(**kwargs)",
"def addSortMethod(*args, **kwargs):\n return mundane_xbmcplugin.addSortMethod(*args, **kwargs)",
"def __init__(self, plugin):\n self.plugin = plugin",
"def wit... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the plugin manager can find the Isort plugin. | def test_isort_tool_plugin_found():
if sys.version_info.major == 3 and sys.version_info.minor < 6:
pytest.skip("isort is only available for Python 3.6+, unable to test")
manager = PluginManager()
# Get the path to statick_tool/__init__.py, get the directory part, and
# add 'plugins' to that to g... | [
"def test_plugins(self):\n from omtk import plugin_manager\n pm = plugin_manager.plugin_manager\n\n loaded_plugin_names = [plugin.cls.__name__ for plugin in pm.get_loaded_plugins_by_type('modules')]\n\n builtin_plugin_names = (\n 'Arm',\n 'FK',\n 'Additiv... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify that we can parse the normal output of isort. | def test_isort_tool_plugin_parse_valid():
itp = setup_isort_tool_plugin()
total_output = []
output = "/tmp/x.py"
total_output.append(output)
output = "/tmp/y.py"
total_output.append(output)
issues = itp.parse_output(total_output)
assert len(issues) == 2
assert issues[0].filename == "... | [
"def isort(ctx):\n ctx.run(tools.render_isort_check(ctx))",
"def isort(context):\n exec_cmd = \"isort . --check --diff\"\n run_cmd(context, exec_cmd)",
"def test_shell(self):\n integers = shell_sort(self.actual)\n self.assertEqual(self.expected, integers)",
"def isort(c):\n c.run(\"i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test what happens when a CalledProcessError is raised (usually means isort hit an error). | def test_isort_tool_plugin_scan_calledprocesserror(mock_subprocess_check_output):
mock_subprocess_check_output.side_effect = subprocess.CalledProcessError(
0, "", output="mocked error"
)
itp = setup_isort_tool_plugin()
package = Package(
"valid_package", os.path.join(os.path.dirname(__fi... | [
"def check_returncode(self):\n if self.returncode != 0:\n raise CalledProcessError(self.returncode, self.args, self.stdout)",
"def check_returncode(self):\n if self.returncode:\n raise CalledProcessError(self.returncode, self.args, self.stdout,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the release history from pypi Use the json API to get the release history from pypi. The returned json structure includes a 'releases' dictionary which has keys that are release numbers and the value is an array of uploaded files. While we don't have a 'release time' per say (only the upload time on each of the fil... | def get_releases_for_package(name, since):
f = urlreq.urlopen("http://pypi.org/project/%s/json" % name)
jsondata = f.read()
data = json.loads(jsondata)
releases = []
for relname, rellist in data['releases'].iteritems():
for rel in rellist:
if rel['python_version'] == 'source':
... | [
"def list_releases():\n response = requests.get(PYPI_URL.format(package=PYPI_PACKAGE_NAME))\n if response:\n data = response.json()\n\n releases_dict = data.get('releases', {})\n\n if releases_dict:\n for version, release in releases_dict.items():\n release_forma... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates X values for given list of Y values in range defined by a and b parameters. X values are simply calculated by dividing given X range by number of nodes, so they are distributed in even range. | def prepare_initial_nodes(x_start, x_end, nodes_y):
nodes_x = [float(x_start + ((x_end - x_start) / (len(nodes_y) - 1)) * i) for i in range(0, len(nodes_y))]
nodes_y = [float(y) for y in nodes_y]
print(nodes_x)
print(nodes_y)
nodes = list(zip(nodes_x, nodes_y))
return nodes | [
"def arange(a, b, dx, logx=False):\n\tif a > b:\n\t\treturn []\n\telif logx:\n\t\treturn [math.exp(math.log(a) + dx*i) for i in range(int((math.log(b)-math.log(a))/dx))] + [b]\n\telse:\n\t\treturn [a + dx*i for i in range(int((b-a)/dx))] + [b]",
"def linear_input(self, a, b):\r\n y = np.linspace(a, b, b - ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes list of divided differences nodes and calculates new divided differences node from each pair of nodes_to_compute. In other words, it computes next level of so called Newton's second interpolation form tree. | def calculate_divided_differences_row(nodes_to_compute):
divided_differences = []
if len(nodes_to_compute) == 1:
return None
for i in range(0, len(nodes_to_compute) - 1):
child = DividedDifferenceNode.create_child_node(nodes_to_compute[i], nodes_to_compute[i + 1])
child.calculate_v... | [
"def calculate_divided_differences(nodes):\n nodes_to_compute = []\n divided_differences = []\n for node in nodes:\n nodes_to_compute.append(DividedDifferenceNode(x=node[0], divided_difference=node[1]))\n\n divided_differences.append(tuple(nodes_to_compute))\n\n while len(nodes_to_compute) > 1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates divided differences for given interpolation nodes. It is assumed, that at least two interpolation nodes are provided. Each tuple of returned list represents one level of divided differences tree. | def calculate_divided_differences(nodes):
nodes_to_compute = []
divided_differences = []
for node in nodes:
nodes_to_compute.append(DividedDifferenceNode(x=node[0], divided_difference=node[1]))
divided_differences.append(tuple(nodes_to_compute))
while len(nodes_to_compute) > 1:
nex... | [
"def calculate_divided_differences_row(nodes_to_compute):\n divided_differences = []\n\n if len(nodes_to_compute) == 1:\n return None\n\n for i in range(0, len(nodes_to_compute) - 1):\n child = DividedDifferenceNode.create_child_node(nodes_to_compute[i], nodes_to_compute[i + 1])\n chil... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates polynomial from given list of divided differences. Polynomial string is created according to equation provided in project docs. | def calculate_newton_interpolation(divided_differences):
polynomial = []
for i, divided_differences_row in enumerate(divided_differences):
polynomial_part = '({0})'.format(divided_differences_row[0].divided_difference)
for j in range(0, i):
polynomial_part += '*(x-{0})'.format(divid... | [
"def list_to_poly(polynomial_list):\n max_degree = len(polynomial_list) - 1\n strings = []\n opts = ['x', '']\n for index, num in enumerate(polynomial_list):\n if num == 0:\n continue\n if index < max_degree - 1:\n string = '{}x^{}'.format(num, max_degree - index)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draws interpolation plot for given interpolation polynomial and nodes. | def draw_interpolation_plot(start_x, end_x, interpolation_polynomial, nodes, freq=200, additional_polynomial=None,
additional_nodes=None):
# TODO: calculate figure size dynamically
plt.figure(figsize=(8, 6), dpi=80)
x = numpy.linspace(start_x, end_x, freq)
# TODO: eval should... | [
"def create_lookup_plot():\n\n # init data based on function of this module\n temp_points = [30, 55, 80, 105, 130]\n delta_surface = [2.04, 4.04, 7.01, 11.01, 14.64]\n delta_air = [2.89, 6.37, 12.16, 15.41, 18.52]\n delta_electrode = [3.08, 7.24, 13.28, 15.75, 20.80]\n\n # calculate coefficients f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method generates a header file containing the data contained in the numpy array provided. It is used to capture the tensor data (for both inputs and expected outputs) to be bundled into the standalone application. | def _create_header_file(tensor_name, npy_data, output_path, data_linkage):
file_path = pathlib.Path(f"{output_path}/" + tensor_name).resolve()
# create header file
raw_path = file_path.with_suffix(".h").resolve()
with open(raw_path, "w") as header_file:
header_file.write("#include <stddef.h>\n")... | [
"def create_header_file(name, tensor_name, tensor_data, output_path):\n file_path = pathlib.Path(f\"{output_path}/\" + name).resolve()\n # Create header file with npy_data as a C array\n raw_path = file_path.with_suffix(\".h\").resolve()\n with open(raw_path, \"w\") as header_file:\n header_file.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert a tflite model buffer in a Relay module | def convert_to_relay(tflite_model_buf, bind_params_by_name=True):
# TFLite.Model.Model has changed to TFLite.Model from 1.14 to 2.1
try:
import tflite.Model # pylint: disable=import-outside-toplevel
tflite_model = tflite.Model.Model.GetRootAsModel(tflite_model_buf, 0)
except AttributeError... | [
"def create_relay_module_and_inputs_from_tflite_file(tflite_model_file, bind_params_by_name=True):\n with open(tflite_model_file, \"rb\") as f:\n tflite_model_buf = f.read()\n mod, params = convert_to_relay(tflite_model_buf, bind_params_by_name)\n\n inputs = dict()\n for param in mod[\"main\"].pa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate reference data through executing the relay module | def generate_ref_data(mod, input_data, params=None, target="llvm"):
with tvm.transform.PassContext(opt_level=3, config={"tir.disable_vectorize": True}):
lib = relay.build(mod, target=target, params=params)
lib_name = "mod.so"
temp = utils.tempdir()
lib_path = temp.relpath(lib_name)
lib.expo... | [
"def make_reference(self):\n self.make_reference2()",
"def link_data(ctx, output_path='./material/'):\n run_data_linking(output_path)",
"def refant() :\n return ref",
"def use(self):",
"def generate(self):\n self.graph_repl = self.master.graph_repl",
"def do_generate(self):\n pa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A helper function to create a Relay IRModule with inputs and params from a tflite file | def create_relay_module_and_inputs_from_tflite_file(tflite_model_file, bind_params_by_name=True):
with open(tflite_model_file, "rb") as f:
tflite_model_buf = f.read()
mod, params = convert_to_relay(tflite_model_buf, bind_params_by_name)
inputs = dict()
for param in mod["main"].params:
n... | [
"def create_relay_module(\n input_shape: List[int], dtype: str, ops: List[Union[OpPattern, Tuple[str, str]]]\n) -> tvm.IRModule:\n input_data = relay.var(\"input\", shape=input_shape, dtype=dtype)\n\n cur_data = input_data\n for op_info in ops:\n # Progressively build type info\n relay.tra... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
2. SELECTION PHASE. If a tree does not reproduce, it becomes extinct. Thus, this leads to the requirement of a competitive exclusion in order to eliminate those trees with lower metric values. This is done to limit the maximum number of trees in the forest. Initially, fast reproduction of trees take place and all of th... | def select(self):
def truncate(self):
""" Truncates forest to maximum number of trees. """
self.population = self.population[:self.max_number_trees]
def SortOnItem(list_, item_loc):
""" Sorts based on a given item. """
templist = [elmt[item_loc] for el... | [
"def hyperparameter_selection_rf():\n # Number of trees in random forest\n n_estimators = [int(x) for x in np.linspace(start=100, stop=1200, num=12)]\n # Number of features to consider at every split\n max_features = ['auto', 'sqrt']\n # Maximum number of levels in tree\n max_depth = [int(x) for x... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Truncates forest to maximum number of trees. | def truncate(self):
self.population = self.population[:self.max_number_trees] | [
"def delete_max(self):\n if len(self) == 0:\n raise IndexError('underflow')\n self.root = self._delete_max_node(self.root)",
"def prune_overly_long_traces(self):\n for trace in self.trace_pool:\n if len(trace.nodes) > self.max_trace_length:\n trace.nodes =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
3. REPRODUCTION PHASE. The trees will produce seeds based on their relative fitness which will then be spread over the problem space. Each seed, in turn, will grow into a new tree depending on external factors. A linear increase in the number of seeds produced by the trees of the forest is considered from max_seeds for... | def reproduce(self):
def compute_seeds(fitness):
""" Computes the number of seeds given a fitness value. """
seeds = (fitness-min_fitness) / (max_fitness-min_fitness) * \
(self.max_seeds-self.min_seeds) + self.min_seeds
return round(seeds)
# ev... | [
"def grow_forest(forest, X, y, seeds, labels=None):\n # Convert data\n X, = check_arrays(X, dtype=DTYPE, sparse_format=\"dense\")\n # Make a list container for grown trees\n n_trees = forest.n_estimators\n trees = []\n # For each tree in the forest\n for i in range(n_trees):\n # Make a n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the number of seeds given a fitness value. | def compute_seeds(fitness):
seeds = (fitness-min_fitness) / (max_fitness-min_fitness) * \
(self.max_seeds-self.min_seeds) + self.min_seeds
return round(seeds) | [
"def iterations(self, n, fitness_function):",
"def calcFitness (self) :\n fitnessArray = [[8, 4, 2, 1],\n [16, 8, 4, 2],\n [32, 16, 8, 4],\n [64, 32, 16, 8]]\n # fitnessArray = [[160, 80, 5, 4],\n # [320,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draws a random float number from a uniform distribution given by U[lower, upper]. | def uniform(lower, upper):
return lower + random.random() * (upper - lower) | [
"def uniform(lower: float, upper: float):\n return Float(lower, upper).uniform()",
"def _rand_float(self, low, high):\n\n return self.np_random.uniform(low, high)",
"def rand_uni_val() -> float:\n return random.uniform(0, 1)",
"def random_float(low: float, high: float):\n seed = time.time(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |