query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Checks that the solution vector is within optimal problem's boundaries. | def _check(self, vector):
for i, elmt in enumerate(vector):
# checks lower bound
if (elmt < self.lower[i]):
vector[i] = self.lower[i]
# checks upper bound
elif (elmt > self.upper[i]):
vector[i] = self.upper[i]
return ve... | [
"def in_box_bounds(self, test_vec):\n above_min = np.greater(test_vec, self.lower_vertex).all()\n below_max = np.greater(self.upper_vertex, test_vec).all()\n return above_min and below_max",
"def _in_bounds(v, lb, ub):\n\n return np.logical_and(v >= lb, v <= ub).all()",
"def _paramet... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
initmethod = ['random', 'pca'] algos = ['seq','batch'] all_neigh = ['gaussian','manhatan','bubble','cut_gaussian','epanechicov' ] alfa_types = ['linear','inv','power'] | def set_algorithm(self, initmethod = 'pca', algtype = 'batch', neighborhoodmethod = 'gaussian', alfatype = 'inv', alfaini = .5, alfafinal = .005):
self.initmethod = initmethod
self.algtype = algtype
self.alfaini = alfaini
self.alfafinal = alfafinal
self.neigh = neighborhoodmethod | [
"def initFA(Y, terms, I, gene_ids=None, nHidden=3, nHiddenSparse = 0,pruneGenes=True, FPR=0.99, FNR=0.001, \\\n noise='gauss', minGenes=20, do_preTrain=True, nFix=None, priors=None, covariates=None, dropFactors=True, learnPi=False):\n\n \n #check for consistency of input parameters\n [num_cells,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
som and bmu_ind depending on the lattice "hexa" or "rect" we have different grid distance functions. bmu_ind is a number between 0 and number of nodes1. depending on the map size bmu_coord will be calculated and then distance matrix in the map will be returned | def grid_dist(self,bmu_ind):
try:
lattice = getattr(self, 'lattice')
except:
lattice = 'hexa'
print 'lattice not found! Lattice as hexa was set'
if lattice == 'rect':
return rect_dist(self,bmu_ind)
elif lattice == 'hexa':
try:
msize = getattr(self... | [
"def som(X, range_n_dim, top_lbls=10, preprocessing = None, bin_X=False, transform=None, experiment_name=None, **kwargs):\n\n for dim in range_n_dim: \n limit = int(np.sqrt(len(X)/20))\n if dim > limit: #verify that number of nodes are sensible for size of input data\n return print('Inpu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
helper function to get the next ocurring monday as a date object | def _get_next_monday(self):
today = datetime.date.today()
weekday_int = today.weekday()
if weekday_int == 0:
return today
next_mon = today + timedelta(7 - weekday_int)
return next_mon | [
"def get_next_monday(date):\n return date + datetime.timedelta(days=-date.weekday(), weeks=1)",
"def memorial_day():\n this_year = datetime.datetime.now().year\n # first monday in june minus one week\n this_year_memorial_day = (datetime.datetime(this_year, 6, 1) +\n relati... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper function adding some known todo list items for the test user | def _add_todo_items(self):
todo_list = ToDoList(day=self.day, user=self.user.user.rolllistuser)
todo_list.save()
items = [
'feed the cats',
'drive to work',
'read a book',
'eat some food',
]
todo_items = []
for item in ite... | [
"def add_item(todo_list):\r\n text = input(\"Please enter the name of the new item\\n\")\r\n priority = check_priority_overlap(\r\n int(clean_input(\"Please enter the priority of this item\")), todo_list)\r\n # group = int(clean_input(\"Please enter the group number of this item\"))\r\n group = 0... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper function adding some known todo list items for the test user for the previous day | def _backfill_todo_items_for_previous_day(self):
previous_day_date = self.day.date - timedelta(days=1)
day, created = Day.get_or_create(date=previous_day_date)
todo_list = ToDoList(day=day, user=self.user.user.rolllistuser)
todo_list.save()
items = [
'cut the grass'... | [
"def _add_todo_items(self):\n\n todo_list = ToDoList(day=self.day, user=self.user.user.rolllistuser)\n todo_list.save()\n\n items = [\n 'feed the cats',\n 'drive to work',\n 'read a book',\n 'eat some food',\n ]\n todo_items = []\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper function adding some known schedule items for the test user | def _add_schedule_items(self):
schedules = [
{
'start_time': '9:30 AM',
'end_time': '10:00 AM',
'title': 'Daily Scrum',
'location': 'Hogwarts',
'day': self.day,
'user': self.user.user.rolllistuser,
... | [
"def test_add_recurring_schedule(self):\n pass",
"def test_list_schedules(self):\n pass",
"def _create_schedules(self):\n\n ''''''",
"def test_create_schedule(self):\r\n pass",
"def add_schedule(self):\r\n\r\n # Take the schedule entires from TOML file\r\n entries =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a list of victory conditions based on the size of the board | def create_victory_conditions(size): #Written by Cody West. Not used in current program, could be used to make boards of different sizes
victory_conditions = []
for i in range(size):
horizontal_victory = []
for n in range(size):
horizontal_victory.append(size*i+n)
victory_co... | [
"def build_a_board(self, size):\n return [self.EMPTY for i in range(size*size)]",
"def create_board(size) -> list:\n return list(itertools.product([i for i in range(size)], repeat=2))",
"def board(constraints):\n rows = len(constraints[0])\n columns = len(constraints[1])\n board = []\n for... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates rscu values for each codon | def calculate_rscu(handle: str, genetic_code_num: int, min_len_threshold: int = 200, gene_analysis: bool = False,
save_file: bool = False, file_name: str = 'RSCU_report', folder_path: str = 'Report') -> \
dict[str, float | dict[str, float]]:
records = parse(handle, 'fasta')
references... | [
"def compute_score(list_scu_ids):\n\tsum_scu = 0\n\tfor scu_id in list_scu_ids:\n\t\tsum_scu += scu_dict[scu_id]\n\treturn sum_scu",
"def calculate_Ricci_tensor(self, riemann, simplify):\n\n ricci = Ricci(index_dict=riemann.index_dict) \n ricci.convert_to_shorthand()\n\n dim = len(ricci.index... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return a set of nodes who are within max_dist of self | def neighbors(self, max_dist=3):
# TODO: this may have problems because the set doesn't
# compare object id but uses user defined comparison methods
# TODO: outgoing edges are no longer saved
found = set()
found.add(self)
queue = [(self, 0)]
while queue:
... | [
"def farthest_nodes(self):\n\n diameter = self.diameter() # also initializes self._distance_matrix\n ret = set()\n for u, neigh in self._distance_matrix.items():\n for v, dist in neigh.items():\n if dist == diameter:\n ret.add((u, v))\n asser... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
show the neighborhood of this node in a picture | def show_neighborhood(self, max_dist=3, detailed=True):
dotstr = ''
for node in self.neighbors(max_dist):
if node is self:
dotstr += node.dot(color='dodgerblue', detailed=detailed)
else:
dotstr += node.dot(detailed=detailed)
dotstr = 'digra... | [
"def show(self):\n data = []\n for row in self.grid:\n mid, bottom = [], []\n for node in row:\n \tmid += [0, int(node.right)]\n \tbottom += [int(node.down), 1]\n data += mid + [0] + bottom + [0] \n data[self.width*2+1] = 1\n data[-1] = 1\n data += (s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
subpaths is a list of paths on tail nodes. return a new path generated by concatenating this edge. this is used in kbest paths generation. | def make_path(self, subpaths):
assert len(self.tail) == len(subpaths), '%s' % self
path = Path(self, subpaths)
weight = self.hg.one
for p in subpaths:
if p is not None:
weight = self.hg.prod(weight, p.weight)
weight = self.hg.prod(weight, self.hg.w(sel... | [
"def _generate_subpaths(self):\n\n scale = self.SCALE\n\n for point in self._points:\n x_base = point[0] * scale + self.border * scale + self.line_size\n y_base = point[1] * scale + self.border * scale + self.line_size\n\n yield 'M {x0} {y0} L {x0} {y1} L {x1} {y1} L {... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
top down topo sort. nodes that don't reach the target node are thrown away | def topo_sort(self):
# TODO: detect cycles
self.find_reachable_nodes()
# save list of nodes in topo order
self.nodes = []
# assign each node an id field incrementally
cur_id = 0
# count visited outgoing edges for each node
unvisited = {}
for nid, n... | [
"def _prune_top_down(self):\r\n self.logger.info('Pruning tree top-down...')\r\n # starting at the second-to-last level of the tree\r\n for order in range(self.k-1, 0, -1):\r\n # getting nodes from nmap is faster than tree traversal\r\n cur_order = [n for n in self.nmap.va... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read a file and return a toposorted hypergraph. | def deserialize(self, filename):
f = open(filename)
edges_tails = []
nodes = []
# first pass adds incoming edges to nodes
for line in f:
if '->' in line: # edge
edge = self.edge_class()
tail_ids, head_id = edge.deserialize(line)
... | [
"def read_graph(filename):\n return nx.read_edgelist(filename, delimiter='\\t')",
"def read_graph(filename):\n with open(filename) as f:\n g = eval(f.read())\n return g",
"def read_file(file):\n\t# File where the graph data is writen\n\tf = open(file, 'r')\n\n\t# Number of nodes\n\tN = int(f.rea... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Standard backtracking approach to find the optimal opmesh assignment, starting with the optimal number of stages (best_n_stages). The return is a list [((layer_start, next_layer_start), submesh_shape_idx, sharding_config_idx)] where (layer_start, next_layer_start) is [) slice of the ops and submesh_shape_idx is the sub... | def get_optimal_submesh_assignments(
best_n_stages, F_argmin, n_devices, n_ops, submesh_sizes
):
current_s = best_n_stages
current_layer = 0
current_devices = n_devices
optimal_layer_submesh_assignments = []
while current_s > 0 and current_layer < n_ops and current_devices > 0:
next_sta... | [
"def split_to_stages(self) -> Dict[int, \"Graph\"]:\n stages = dict()\n\n tmp = Graph(None, None, None, None, None).load_state(self.state())\n\n groups = defaultdict(list)\n for n in tmp.nodes:\n if n.type != NodeTypes.IN:\n groups[n.stage_id].append(n)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Count the number of times elem appears in the reversed iterator. | def count(self, elem):
return self.iter.count(elem) | [
"def sequence_sorted_count(self, x, reverse=False):\n c = 0\n if reverse: it = reversed(self)\n else: it = iter(self)\n for v in it:\n if x == v:\n c += 1\n break\n for v in it:\n if x == v: c += 1\n else: break\n return c",
"def elem_count(self, elem):\n res = 0\n for value... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find the index of elem in the reversed iterator. | def index(self, elem):
return _coconut.len(self.iter) - self.iter.index(elem) - 1 | [
"def r_index(sequence, element):\n\n for i, e in enumerate(reversed(sequence)):\n if element == e:\n return len(sequence) - 1 - i\n else:\n raise ValueError(\"r_index(sequence, element):\\\n element not in the sequence\")",
"def index(self, elem):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
consume(iterable, keep_last) fully exhausts iterable and return the last keep_last elements. | def consume(iterable, keep_last=0):
return _coconut.collections.deque(iterable, maxlen=keep_last) | [
"def last(iterable: Iterable):\n hey = None\n for hey in iterable: pass\n return hey",
"def last(iterable):\n d = deque(iterable, maxlen=1)\n try:\n return d.pop()\n except IndexError:\n raise ValueError(\"Cannot return last item from empty iterable {!r}\".format(iterable))",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Construct an object of the given data_type containing the given arguments. | def makedata(data_type, *args):
if _coconut.hasattr(data_type, "_make") and _coconut.issubclass(data_type, _coconut.tuple):
return data_type._make(args)
if _coconut.issubclass(data_type, (_coconut.map, _coconut.range, _coconut.abc.Iterator)):
return args
if _coconut.issubclass(data_type, _co... | [
"def data_type_constructor(\n data_type: str,\n nbits: Optional[int] = None,\n compression: str = \"DEFLATE\",\n):\n\n def get_data_type(no_data):\n return DataType(\n data_type=data_type, no_data=no_data, nbits=nbits, compression=compression\n )\n\n return get_data_type",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
fmap(func, obj) creates a copy of obj with func applied to its contents. Override by defining obj.__fmap__(func). | def fmap(func, obj):
if _coconut.hasattr(obj, "__fmap__"):
return obj.__fmap__(func)
if obj.__class__.__module__ == "numpy":
from numpy import vectorize
return vectorize(func)(obj)
return _coconut_makedata(obj.__class__, *(_coconut_starmap(func, obj.items()) if _coconut.isinstance(ob... | [
"def fmap(functor: Any, func: Callable[[Any], Any]) -> Any:\n ...",
"def fmap(f, g):\n pass",
"def fmap(function, descriptor):\n return MappedDescriptor(descriptor, function)",
"async def afmap(function: t.Callable, functor: F = _NO_ARGUMENT):\n # Curry if no functor given.\n if functor is _NO_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Thread loop. This is an infinite loop. The iter method calls self.sql_queue.get() which blocks if there are not values in the queue. As soon as values are placed into the queue the process will continue. If many executes happen at once it will churn through them all before calling commit() to speed things up by reducin... | def run(self):
logging.debug("run: Thread started")
execute_count = 0
for token, query, values in iter(self.sql_queue.get, None):
logging.debug("sql_queue: %s", self.sql_queue.qsize())
if token != self.exit_token:
logging.debug("run: %s", query)
... | [
"def run ( self ):\n\t\tLOGGER.debug(\"run: Thread started\")\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\tx = self._sql_queue.get()\n\t\t\t\tx.execute()\n\t\t\texcept Sqlite3WorkerExit as e:\n\t\t\t\tif not self._sql_queue.empty(): # pragma: no cover ( TODO FIXME: come back to this )\n\t\t\t\t\tLOGGER.debug ( 'requeueing... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the query results for a specific token. | def query_results(self, token):
delay = .001
while True:
if token in self.results:
return_val = self.results[token]
del self.results[token]
return return_val
# Double back on the delay to a max of 8 seconds. This prevents
... | [
"def listSearches(self, authenticationToken):\r\n pass",
"def get_by_session_token(cls, token):\n return cls.query(\n cls.session.token == token).order(-cls.created_date).fetch()",
"def retrieve_results(self, token: str = '', measurement_id: str = ''):\n with open(self.config_file) a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the 2nd largest value from a given list. | def second_largest(values: List[int]) -> int:
try:
return sorted(set(values))[-2]
except IndexError:
raise ValueError("second_largest() needs at least two distinct values") | [
"def two_largest(inlist):\n largest = second_largest = 0\n it1 = it2 = 0\n\n for i,item in enumerate(inlist):\n if item > largest:\n largest = item\n it1 = i\n elif largest > item > second_largest:\n second_largest = item\n it2 = i\n # Return the... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Try to get the path to pdb.py and return it in a list. | def GetPdbArgs(python):
# Usually, python is /usr/bin/pythonxx and pdb is /usr/lib/pythonxx/pdb.py
components = python.split('/')
if len(components) >= 2:
pdb_path = '/'.join(components[0:-2] + ['lib'] +
components[-1:] + ['pdb.py'])
if os.access(pdb_path, os.R_OK):
return [p... | [
"def get_pex_python_paths():\n ppp = Variables.from_rc().get(\"PEX_PYTHON_PATH\")\n if ppp:\n return ppp.split(os.pathsep)\n else:\n return []",
"def retrieve_module_list():\n\n current_dir = getcwd()\n mod_list = []\n\n for item in listdir(current_dir):\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print usage for the stub script. | def PrintOurUsage():
print 'Stub script %s (auto-generated). Options:' % sys.argv[0]
print ('--helpstub '
'Show help for stub script.')
print ('--debug_binary '
'Run python under debugger specified by --debugger.')
print ('--debugger=<debugger> '
"Debugger f... | [
"def print_usage():\n print(helptxt)\n sys.exit(2)",
"def usage():\n print(__doc__)",
"def print_usage():\n print(\"Usage: python app.py [OPTIONS]\\n\"\n \"OPTIONS:\\n\"\n \"\\t--debug-print Enables verbose output for debugging the \"\n \"tool.\\n\"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run a module as a script. Locates the module's file and runs it in the current interpreter, or optionally a debugger. | def RunScriptModule(module):
args = sys.argv[1:]
debug_binary = False
debugger = 'gdb --args'
debug_script = False
show_command_and_exit = False
while args:
if args[0] == '--helpstub':
PrintOurUsage()
sys.exit(0)
if args[0] == '--debug_binary':
debug_binary = True
args = ar... | [
"def run_python_script(package=None, module=None, args=[], p_args=[]):\n assert module is not None\n assert isinstance(args, (tuple, list)) and isinstance(p_args, (tuple, list))\n path = python_script_exists(package, module)\n run_program(sys.executable, p_args + [path] + args)",
"def exec_module(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates a dict of dicts from dot separated keys. Yet without associated values. | def make_tree(dot_separated_keys):
tree = {}
for item in dot_separated_keys:
inside_tree = tree
for part in item.split('.'):
inside_tree = inside_tree.setdefault(part, {})
return tree | [
"def undotted_keys(dict):\n return {k.lstrip(\".\"): v for k, v in dict.items()}",
"def _dotted_dict_to_nested_dicts(dotted_dict, delimiter_nested=\".\"):\n nested_dict = {}\n for key, value in dotted_dict.items():\n tokens = key.split(delimiter_nested)\n if len(tokens) > 1:\n tm... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sum of the factorials of the digits of a number x | def factsum(x):
return sum(list(map(lambda x: factorial(x), getdigits(x)))) | [
"def digit_factorial_sum(n):\n\n factorial_sum = 0\n\n while n:\n digit = n%10\n factorial_sum += cached_factorials[digit]\n n //= 10\n\n return factorial_sum",
"def sum_of_digit_factorials(num):\n return sum(\n FACTORIAL_TABLE[int(char)]\n for char in str(num)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clone a `Sequential` model instance. Model cloning is similar to calling a model on new inputs, except that it creates new layers (and thus new weights) instead of sharing the weights of the existing layers. Arguments | def _clone_sequential_model(model, input_tensors=None):
if not isinstance(model, Sequential):
raise ValueError('Expected `model` argument '
'to be a `Sequential` model instance, '
'but got:', model)
def clone(layer):
return layer.__class__.from_... | [
"def clone_model(model, input_tensors=None):\n if isinstance(model, Sequential):\n return _clone_sequential_model(model, input_tensors=input_tensors)\n else:\n return _clone_functional_model(model, input_tensors=input_tensors)",
"def clone_model(model):\n model = copy.deepcopy(model)\n z... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clone any `Model` instance. Model cloning is similar to calling a model on new inputs, except that it creates new layers (and thus new weights) instead of sharing the weights of the existing layers. Arguments | def clone_model(model, input_tensors=None):
if isinstance(model, Sequential):
return _clone_sequential_model(model, input_tensors=input_tensors)
else:
return _clone_functional_model(model, input_tensors=input_tensors) | [
"def clone_model(model):\n model = copy.deepcopy(model)\n zero_grad(model)\n return model",
"def clone(self):\n return _libsbml.Model_clone(self)",
"def clone_model(self, elite):\n print(\"Cloning elite model\")\n self.model = copy.deepcopy(elite)",
"def copy_model(model: Module)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize the joystick components | def init(self):
pygame.init()
pygame.joystick.init()
self.controller = pygame.joystick.Joystick(0)
self.controller.init()
self.x=0
self.y=0 | [
"def init(self):\n \n pygame.init()\n pygame.joystick.init()\n self.controller = pygame.joystick.Joystick(0)\n self.controller.init()",
"def __init__(self):\n self.isMoving = 0#0 is stop, 1 is moving forward, -1 is moving backward\n self.isRoutating = False\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shift the colormap by dragging the cursor left or right. Stretch the colormap by dragging the cursor up or down. | def ms_contrast(self, viewer, event, data_x, data_y, msg=True):
if not self.cancmap:
return False
event.accept()
msg = self.settings.get('msg_contrast', msg)
x, y = self.get_win_xy(viewer)
if event.state == 'move':
self._tweak_colormap(viewer, x, y, 'pre... | [
"def ms_cmap_rotate(self, viewer, event, data_x, data_y, msg=True):\n if not self.cancmap:\n return True\n msg = self.settings.get('msg_cmap', msg)\n\n x, y = self.get_win_xy(viewer)\n\n if event.state == 'move':\n self._rotate_colormap(viewer, x, y, 'preview')\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
An interactive way to restore the colormap contrast settings after a warp operation. | def ms_contrast_restore(self, viewer, event, data_x, data_y, msg=True):
if not self.cancmap:
return False
event.accept()
if event.state == 'down':
self.restore_contrast(viewer, msg=msg) | [
"def ms_contrast_restore(self, viewer, event, data_x, data_y, msg=True):\n if self.cancmap and (event.state == 'down'):\n self.restore_contrast(viewer, msg=msg)\n return True",
"def ms_contrast(self, viewer, event, data_x, data_y, msg=True):\n if not self.cancmap:\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This decorator is meant to decorate management commands. Any exceptions raised in the command's handle method will be logged and reraised. | def log_exceptions(cls):
class NewClass(cls):
def handle(self, *args, **options):
try:
super().handle(args, options)
except Exception:
logger.exception("Management command '{}' failed. Traceback follows: ".format(sys.argv[1]))
raise
... | [
"def wraps(command):\n\n return CommandWrapper(command)",
"def track_command(func):\n\n def wrapped(*args, **kwargs):\n\n if not _telemetry_enabled():\n # When Telemetry is disabled, call the function immediately and return.\n return func(*args, **kwargs)\n\n telemetry = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a list of random minibatches from (X, Y) | def random_mini_batches(X, Y, mini_batch_size = 64, seed = 0):
np.random.seed(seed) # To make your "random" minibatches the same as ours
m = X.shape[1] # number of training examples
mini_batches = []
# Step 1: Shuffle (X, Y)
permutation = list(np.random.perm... | [
"def minibatches(X, Y, batch_size):\n\tm = X.shape[0]\n\tn_batches = int(np.floor(m / batch_size))\n\trandom_indices = np.random.permutation(np.arange(m))\n\tfor i in range(n_batches):\n\t\tbatch_indices = np.arange(i * batch_size, (i + 1) * batch_size)\n\t\tbatch_indices = random_indices[batch_indices]\n\t\tyield ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that Predictor instances are not serializable. | def test_serialization():
# Class is serializable.
ray.put(DummyPredictor)
# Instance is not serializable.
predictor = DummyPredictor()
with pytest.raises(PredictorNotSerializableException):
ray.put(predictor) | [
"def test_serializable_check(self):\n with patch_config_options({\"runner.enforceSerializableSessionState\": True}):\n script = self.script_from_string(\n \"\"\"\n import streamlit as st\n\n def unserializable_data():\n return lambda ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds player calendar to team_cal and returns filled teams | def match_with_player(self, name, player_cal):
updated_team_cal = self.team_cal.copy()
filled_team_keys = []
for loc in player_cal.stack().index:
current_player_count = self.team_cal.at[loc]
if self.price_cal.at[loc] <= player_cal.at[loc]:
if current_play... | [
"def schedule_set(teams):\n for day in league:\n for num in day:\n num[0] = teams[num[0]]\n num[1] = teams[num[1]]\n show_schedule()\n return league",
"def get_playoff_teams(self, simulation=False, final_day=False):\n if simulation:\n league_standings = DayO... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Email summary of results to user. | def EmailResults(recipient, error_mesg, topdir, dumpfile, logfile, motcor_summary):
#*********************************************************************************
if recipient is None:
return
elif 'noname' in recipient:
return
sender = 'preprocess'
if 'Abnormal' in error_mesg > 0:
... | [
"def send_summary():\n root_dir = os.getcwd()\n log_file = os.path.join(root_dir, 'logs', time.strftime(\"%Y%m%d\") + '.log')\n\n result_text = read_log_to_result_text(log_file)\n send_email(result_text)",
"def email_ssh_report(self, results: list):\n body = self.header\n try:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Synthesize yaml header filename from directory name. | def _yaml_filename(self, path):
fullpath = os.path.abspath(path)
if not os.path.isdir(fullpath):
dirname = os.path.dirname(fullpath)
else:
dirname = path
if dirname.endswith('/'):
dirname = dirname[:-1]
fname = dirname.split('/')[-1] + '.yaml'
... | [
"def get_filename(self, source):\n return '{}/{}.yml'.format(self.config_dir, source)",
"def generate_html_header(name):\n name = name.split(\"/\")[-1]\n return \"<h1>{0}</h1>\".format(name).replace(\".txt\", \"\").replace(\"_\", \" \").upper()",
"def convert_dir_filename(dir_, tldir):\n dir_pat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create list of epis in pfile format (epi_series) and of epis in dicom format (epirt_paths) | def _EpiInfo(self, info, path):
epi_vals = {'tdim':self.hdr['tdim'], 'plane':self.hdr['plane'], \
'SeriesNumber':self.hdr['subhdr']['SeriesNumber']}
for key in self.epi_keys.keys():
if self.epi_keys[key] != str(epi_vals[key]):
# Return None, which will caus... | [
"def AssignEpiNames(self):\n# Sort each run in the series by its acquisition time.\n epi_sort = self.epi_times.keys()\n epi_sort.sort()\n# Rewrite pfiles as an ordered list of p-files to be reconstructed.\n for idx in xrange(len(epi_sort)):\n entry = self.epi_times[epi_so... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pair up each epi with a fieldmap. | def _SetFmapInfo(self):
for epi in self.pfiles + self.epirt_paths:
self.info[epi]['fmapname'] = None
self.info[epi]['fmap_entry'] = None
for entry in self.entry_map['fmap']:
fmap_name = self.info[entry]['imgfile'] + self.info[entry]['suffix']
i... | [
"def _map(event_name, data):\n pk = _pk(data)\n for (column, value) in data.items():\n yield (event_name, pk, column, value)",
"def MakeFieldmaps(self):\n if self.verbose:\n print 'Compute fieldmaps.'\n for entry in self.info:\n if self.info[entry]['typ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find the hires structural image that was acquired nearest to "acqtime" | def _FindNearestAnat(self, acqtime):
tdiff_min = 1e6
for anat in self.entry_map['anat']:
if self.info[anat]['type'] == 'T1High' and \
self.info[anat]['InversionTime'] > 0.:
tdiff = abs(acqtime - self.info[anat]['acqtime'])
if tdiff ... | [
"def closest_in_time(images, target):\n\n tgt_mjd = fits.getheader(target, ext=1)['mjd-obs']\n mjds = np.array([fits.getheader(i, ext=1)['mjd-obs'] for i in images])\n\n return images[abs(mjds - tgt_mjd).argsort()[0]]",
"def find(image):\n keypoint, description = describe(image)\n # load keypoints, des... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create structures defining acquisition time for fieldmaps and anatomicals. First find the fieldmap (or hires structural if no fieldmap was collected) nearest (on average) to the epis. Then define this series as the one that should be in register with the epis. | def _SetAnatTgts(self):
anat_candidates = {}
fmap_candidates = {}
for entry in self.entry_map['anat']:
if self.info[entry]['type'] == 'T1High':
anat_candidates[entry] = self.info[entry]['acqtime']
# Find the valid anatomical acquired nearest to fieldmap.
... | [
"def make_primarybeammap(datetimestring, delays, frequency,\n center=False,\n sunline=True,\n low=1,\n high=2000,\n plothourangle=True,\n extension='png',\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a text string summarizing how the motion correction was done. | def SummarizeMotionTargets(self):
text = '\nSummary of motion-correction: \n'
for epi in self.entry_map['epi']:
info = self.info[epi]
text += self.GetBase(epi, '')
base = self.GetBase(info['base_entry'], '')
text += ' ->3dvolreg-> %s[%s]' % (base, info['ba... | [
"def Explanation(self) -> str:",
"def summary(self) -> str:\n def get_conjugations_summary(json_dict: dict) -> str:\n conjugations = ConjugationsDB()\n conjugations.from_json(json_dict)\n return conjugations.summary\n\n result = textwrap.dedent(f\"\"\"\\\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find the correct ref.dat file for each pfile. | def _GetRefdat(self):
for rfile in self.refdats.keys():
# Get times for ref.dat files with a time-stamp.
words = rfile.replace('.','_').split('_')
if len(words) == 6 and words[-2].count(':') == 20:
# This file was time-stamped by the sequence. Get the
# ... | [
"def _find_references(self, input_files):\n reference_regex = re.compile(r'(?:(?:src=|href=|importScripts\\(|url\\()(?:\"([^\"]+)\"|\\'([^\\']+)\\')|url\\(([^\\)\\'\"]+)\\))')\n references = {}\n for input_file in input_files:\n matches = reference_regex.findall(self._filesystem.read... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assign names to each epi file based on information in the template. | def AssignEpiNames(self):
# Sort each run in the series by its acquisition time.
epi_sort = self.epi_times.keys()
epi_sort.sort()
# Rewrite pfiles as an ordered list of p-files to be reconstructed.
for idx in xrange(len(epi_sort)):
entry = self.epi_times[epi_sort[idx]]
... | [
"def set_templates(self):\n templates = glob(os.path.join(self.tempdir, '*m*tau*.fits'))\n for template in templates:\n temp = os.path.splitext(os.path.basename(template))[0]\n nly = os.path.splitext(os.path.basename(template))[0] + '_nly'\n setattr(self, temp, fits.ge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Dump the info object to a yaml file. | def DumpInfo(self):
if self.logdir is None:
return
self.dumpfile = '%s/preprocess_info.yaml' % (self.logdir)
try:
f = open(self.dumpfile,'w')
f.write(yaml.dump(self.info,default_flow_style=False, indent=4))
f.close()
except IOError:
... | [
"def dump(self):\n print(yaml.dump(self.toYaml(), width=float(\"inf\")))",
"def write(self):\n self.f.write(yaml.safe_dump(self.data, default_flow_style=False, indent=4))",
"def write(self):\n print yaml.dump(self._config, default_flow_style=False),",
"def save(self, filename): \n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert anatomical images from dicom or ifiles to briks or niftis. | def ConvertAnat(self):
if self.verbose:
print 'Convert T1 and T2 images...'
for entry in self.info:
info = self.info[entry]
if self.info[entry]['imgfile'] is None:
continue
if self.info[entry]['type'] in self.anat_types:
ke... | [
"def _get_medical_image_blob(roidb):\n num_images = len(roidb)\n processed_ims = []\n pre_ims = []\n post_ims = []\n abdo_masks = []\n for i in range(num_images):\n im = raw_reader(roidb[i][\"image\"], cfg.MET_TYPE, [roidb[i][\"height\"], roidb[i][\"width\"]])\n if roidb[i]['flipped'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create the fieldmap(s) and the corresponding magnitude images. | def MakeFieldmaps(self):
if self.verbose:
print 'Compute fieldmaps.'
for entry in self.info:
if self.info[entry]['type'] == 'fmap':
if self.info[entry]['imgfile'] == None:
# Fieldmap data not found.
return
# Make... | [
"def calcMagneticFieldMap(self):\n # Normalised b-field (note lower case)\n self.solenoid.calcMagneticFieldMap()\n self.b = lambda z: self.solenoid.B_interp(z) * -e / (2 * m * c)\n self.calc_level = CALC_B_MAP",
"def _get_magnitudes(self):\n\n self.logging.debug('Get magnitudes ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create links to BRIK, HEAD, and .nii files. | def LinkFiles(self, srcdir, target):
if '+orig' in target:
tgt_prefix = target.replace('.BRIK','')
tgt_prefix = tgt_prefix.replace('.HEAD','')
linkfiles = ['%s.HEAD'%tgt_prefix, '%s.BRIK' %tgt_prefix]
else:
linkfiles = [target]
for linkfile in link... | [
"def _create_links(self):\n for line in self.iter_files_to_install():\n arcname, link = line.split()\n if link == 'False':\n continue\n self.files.append(create_link(arcname, link, self.prefix))",
"def _create_links(output_dir: str) -> None:\n os.symlink(o... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract the initial EPIs stored in dicom format. | def ExtractFirstEpi(self):
for entry in self.info:
if self.info[entry]['type'] == 'first_epi':
epiname = self.info[entry]['imgfile']
cmd = 'convert_file %s -f0 %s %s %s' % \
(self.flip_opts, entry,epiname, self.info[entry]['filetype'])
... | [
"def _EpiInfo(self, info, path):\n\n epi_vals = {'tdim':self.hdr['tdim'], 'plane':self.hdr['plane'], \\\n 'SeriesNumber':self.hdr['subhdr']['SeriesNumber']}\n for key in self.epi_keys.keys():\n if self.epi_keys[key] != str(epi_vals[key]):\n# Return None, whi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reconstruct the EPIs from pfiles. | def ReconEpis(self):
run = zeros(100)
if self.verbose:
print 'Reconstruct EPIs'
for pfile in self.pfiles_recon:
if self.info[pfile]['refdat'] is None:
# Find the ref.dat file later.
continue
if self.info[pfile]['compression'] is n... | [
"def AssignEpiNames(self):\n# Sort each run in the series by its acquisition time.\n epi_sort = self.epi_times.keys()\n epi_sort.sort()\n# Rewrite pfiles as an ordered list of p-files to be reconstructed.\n for idx in xrange(len(epi_sort)):\n entry = self.epi_times[epi_so... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Eliminate entries in epi recon table that have already been reconstructed. I don't remember why this is here but I know that at one time it was important. | def PruneEpiEntries(self):
pruned = {}
basefiles = []
baseentries = {}
for entry in self.entry_map['epi']:
if baseentries.has_key(self.info[entry]['basefile']):
baseentries[self.info[entry]['basefile']].append(entry)
else:
baseentri... | [
"def purgeTable(self):\n todelete = set()\n for implicant in self.implicant_list:\n todelete.add(implicant)\n for f in self.functions_to_simplify:\n if (implicant.funmask >> f.number) & 1 == 1:\n s = {i for i in f.to_be_covered if i in implicant.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert epis reconstructed on the scanner. | def ConvertRtEpis(self):
if self.verbose:
print 'Convert EPIs to brik'
for entry in self.entry_map['epi']:
if ('epirt' in self.info[entry]['psdname'] or \
self.info[entry]['psdname'] == 'epi' or \
self.info[entry]['psdname'] == '*epfid2d1_64') and ... | [
"def ReconEpis(self):\n run = zeros(100)\n if self.verbose:\n print 'Reconstruct EPIs'\n for pfile in self.pfiles_recon:\n if self.info[pfile]['refdat'] is None:\n# Find the ref.dat file later.\n continue\n if self.info[pfile]['compr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Correct for motion and call SliceTimeCorrect. | def CorrectMotion(self):
if self.verbose:
print "Correct for motion"
for entry in self.entry_map['epi']:
info = self.info[entry]
if os.path.exists(info['imgfile_m'] + info['suffix']):
return
# Always use brik for 3dDeconvolve.
su... | [
"def _drift_correct(self, loc, target_callback):\n e = \"Drift correct has not been implemented for this tracker.\"\n raise NotImplementedError(e)",
"def update(self, mAcrotime_clickEquivalentIn_second):\n self.start_tick = self.photons['timestamps'][0]\n self.end_tick = self.photons['... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Call the jump_censor program to characterize the degree of motion. | def JumpCensor(self):
if self.verbose:
print 'Computing censor files.'
for entry in self.entry_map['epi']:
if self.censor_interleave:
input_file = '%s+orig' % self.info[entry]['imgfile']
interleave = '--interleave'
else:
... | [
"def censoring_fcn(self, q):\n return 1.0",
"def censor(text, censor_char=\"*\"):\n\n if not isinstance(text, str):\n text = str(text)\n if not isinstance(censor_char, str):\n censor_char = str(censor_char)\n\n if not CENSOR_WORDSET:\n load_censor_words()\n return hide_swea... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the temporal SNR for each epi, save in a nifti file, and store a summmary in a png file. | def ComputeSNR(self):
for epi in self.entry_map['epi']:
epifile = self.info[epi]['imgfile_final'] + self.info[epi]['suffix']
prefix = self.info[epi]['imgfile_final'] + '_snr'
if not os.path.exists('%s_snr.png' % prefix):
if self.verbose:
pr... | [
"def plot_tsnr(self, participant_list = [], input_pth = None, use_atlas_rois = True,\n file_ext = {'pRF': '_cropped_dc_psc.npy', 'FA': '_cropped_confound_psc.npy'}): \n\n ## output path to save plots\n output_pth = op.join(self.outputdir, 'tSNR')\n\n ## input path, if not defined g... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Empties the models within the bag | def empty_bag(self):
if self.peds is not None:
for _, model in self.peds.items():
model.reset()
self.drone.reset()
self.subject.reset() | [
"def clearmodels(self):\n \n dbpath, config = self._start() \n ModelDescriptionTable(dbpath).empty()\n ModelPhenotypeTable(dbpath).empty()\n ModelScoreTable(dbpath).empty() \n self._end()",
"def clear(self):\n for m in self._models:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determines if an input is a float. | def is_float(self, input):
try:
float(input)
return True
except ValueError:
return False | [
"def IsFloat(param):\n if type(param) is types.FloatType:\n return True\n return False",
"def isfloat(value): \n try:\n float(value)\n return True\n\n except ValueError:\n return False",
"def isfloat(value):\n try:\n float(value)\n return True\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
c = 2 ⋅ atan2( √a, √(1−a) ) | def _calculate_c(self, a: float) -> float:
sqrt_a = cmath.sqrt(a)
sqrt_one_minus_a = cmath.sqrt(1 - a)
return 2 * math.atan2(sqrt_a.real, sqrt_one_minus_a.real) | [
"def arctan2(a, b):",
"def _atan2(y, x):\n tan = tf.atan(y / (x + 1e-8)) # this returns in -pi/2 .. pi/2\n\n one_map = tf.ones_like(tan)\n\n # correct quadrant error\n correction = tf.where(tf.less(x + 1e-8, 0.0), 3.141592653589793*one_map, 0.0*one_map)\n tan_c = tan + correcti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
gpu_model_to_scale is a dict from model string to scale. | def avail_gpu_compute(self, gpu_model_to_scale):
self._check_spy_stats_available()
l = []
for u, model in zip(self._util.gpu_compute, self._capacity.gpu_model):
found = False
for k, scale in gpu_model_to_scale.items():
if k in model:
found = True
break
if found... | [
"def scale_model(model, scale):\n params = model.named_parameters()\n dict_params = dict(params)\n with torch.no_grad():\n for name, param in dict_params.items():\n dict_params[name].set_(dict_params[name].data * scale)",
"def scale_model(model,scaleparname='A',scaleval=1):\n model =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
From all the data, it takes the columns TopicID, and count the topic based on the gender | def get_data_frame_count_male_gender_by_topic(data_frame: DataFrame) -> pb.DataFrame:
data_frame_topic = data_frame \
.filter(data_frame["Stratification1"].contains("Male")) \
.distinct() \
.groupBy("TopicID") \
.count() \
.sort("TopicID")
print("The following table repr... | [
"def get_male_female_topicsDF(data_dict, gender):\n dataDF = pd.DataFrame.from_dict(data_dict[gender], orient='index')\n outlet_gender_topicsDF = pd.json_normalize(dataDF['topic_mean'])\n outlet_gender_topicsDF.index = dataDF.index\n outlet_gender_topicsDF = outlet_gender_topicsDF.sort_index()\n outl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
From all the data, it takes the columns TopicID, and count the topic based on the ethnicity | def get_data_frame_count_black_ethnicity_by_topic(data_frame: DataFrame) -> pb.DataFrame:
data_frame_topic = data_frame \
.filter(data_frame["Stratification1"].contains("Black, non-Hispanic")) \
.distinct() \
.groupBy("TopicID") \
.count() \
.sort("TopicID")
print("The f... | [
"def get_data_frame_count_male_gender_by_topic(data_frame: DataFrame) -> pb.DataFrame:\n data_frame_topic = data_frame \\\n .filter(data_frame[\"Stratification1\"].contains(\"Male\")) \\\n .distinct() \\\n .groupBy(\"TopicID\") \\\n .count() \\\n .sort(\"TopicID\")\n\n print... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot a data frame with bar type | def plot_type_of_topic(data_frame: pb.DataFrame) -> None:
plt.interactive(False)
plt.figure()
data_frame.plot(kind='bar', x= data_frame['TopicID'])
plt.show() | [
"def bar(df, ax=None, **kwargs):\n if df.shape[1] != 2:\n raise ValueError('Two columns required: %s.' % (df.columns,))\n else:\n df = _preprocess_dataframe(df)\n if ax is None:\n fig, ax = plt.subplots()\n else:\n fig = ax.get_figure()\n\n xlabels = df.ix[:,0].values\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the account for the given client. If it does not exist a new one is created and returned | def get_account(self, client: int):
try:
return self.accounts[client]
except KeyError:
return self._create_account(client) | [
"def get_client(self, clientname):\n client = self.dbsession.query(Client).filter_by(clientname=clientname).all()\n if not client:\n return self.create_client({'clientname': clientname})\n else:\n return client[0]",
"def get(client_id):\n return Client.query.filte... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate Linke turbidity using Kasten pyrheliometric formula. Note that broadband aerosol optical depth (AOD) can be approximated by AOD measured at 700 nm according to Molineaux [4] . Bird and Hulstrom offer an alternate approximation using AOD measured at 380 nm and 500 nm. Based on original implementation by Armel ... | def kasten96_lt(airmass_absolute, precipitable_water, aod_bb):
# "From numerically integrated spectral simulations done with Modtran
# (Berk, 1989), Molineaux (1998) obtained for the broadband optical depth
# of a clean and dry atmospshere (fictitious atmosphere that comprises only
# the effects of Rayl... | [
"def linke_turbidity(wv_i, aod550_i, p_air_i, p_air_0_i):\n # prel = p0 / p # Papers mixes p/p0 and p0/p????\n prel = p_air_i / p_air_0_i\n\n term1 = 3.91 * np.exp(0.689 * prel) * aod550_i\n term2 = 0.376 * np.log(wv_i)\n\n Tl2 = term1 + term2 + (2 + 0.54 * prel - 0.5 * prel**2 + 0.16 * prel**2)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
input h (meters) and the coefficients for the linear profile for the free troposphere theta (ft_intercept (K) and slope gamma (K/m)) return the free tropospher theta at height h | def theta_ft(h,ft_intercept,gamma):
theta_top = ft_intercept + h*gamma
return theta_top | [
"def phase_screen_r(h, k, theta=0):\n term = np.exp(-2 * h**2 * k**2 * np.cos(theta)**2)\n return term",
"def rungeKutta(t0,uu,h):\n \n g1=slope(t0,uu) #slope1\n g2=slope(t0+h/2,uu+(h/2)*g1) #slope2\n g3=slope(t0+h/2,uu+(h/2)*g2) #slope3\n g4=slope(t0+h,uu+h*g3) ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
the_vars[0]= thetabar the_vars[1] = h the_vars[2] = qv surface flux from drag law with subsidence and diagnosed deltheta | def dmixed_vars(the_vars,tstep,coeffs):
deltheta = theta_ft(the_vars[1],coeffs.ft_intercept,coeffs.ft_gamma) - the_vars[0]
F0 = coeffs.U*coeffs.Cd*(coeffs.sst - the_vars[0]) #surface heat flux
Fqv0 = coeffs.U*coeffs.Cd*(coeffs.qsfc - the_vars[2]) #surface vapor flux
Fint = -coeffs.k*F0 #entrainment ... | [
"def calc_went_NT(the_vars, coeffs, deltheta, F0, Fqv0):\n thetal_m = the_vars[0]\n qt_m = the_vars[2]\n zi = the_vars[1]\n dth = deltheta\n \n thetal_ft = thetal_m + dth\n qt_ft = coeffs.ft_qv\n \n dqt = qt_ft - qt_m\n \n # calculate thetal at z = 3000 m (take qt(z = 3000m) = qt(z ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
NichollsTurton entrainment parameterization the_vars and coeffs are inputs into dmixed_vars deltheta, F0, Fqv0 are calculated in dmixed_vars | def calc_went_NT(the_vars, coeffs, deltheta, F0, Fqv0):
thetal_m = the_vars[0]
qt_m = the_vars[2]
zi = the_vars[1]
dth = deltheta
thetal_ft = thetal_m + dth
qt_ft = coeffs.ft_qv
dqt = qt_ft - qt_m
# calculate thetal at z = 3000 m (take qt(z = 3000m) = qt(z = h), so delta_q... | [
"def dmixed_vars(the_vars,tstep,coeffs):\n\n deltheta = theta_ft(the_vars[1],coeffs.ft_intercept,coeffs.ft_gamma) - the_vars[0]\n F0 = coeffs.U*coeffs.Cd*(coeffs.sst - the_vars[0]) #surface heat flux\n Fqv0 = coeffs.U*coeffs.Cd*(coeffs.qsfc - the_vars[2]) #surface vapor flux\n Fint = -coeffs.k*F0 #en... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
find the lcl (in m) for a row in the dataframe | def calc_lcl(row,psfc):
Tdew = tf.tmr(row['qv'],psfc)
LCL = tf.LCL(Tdew,row['theta'],psfc) #kPa
#
# rough approximation: 10 kPa = 1 km
#
delp=psfc - LCL
lcl_h = delp*100.
return lcl_h | [
"def compute_kl(self, df):\n value_counts = [df[col].value_counts() for col in self.hist_cols]\n next_hists = self.value_counts_to_hists(value_counts)\n\n if self.prev_hists is None:\n self.prev_hists = next_hists\n return None\n\n output = []\n for prev_h, c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adapted from interactive_vaporflux.ipynb sst, sea surface temperature (K) ft_qv, mixedlayer top qv (kg kg^1) use_NT, True or False outputs csv and json files with equilibrium values | def run_main(sst, ft_qv, use_NT):
dtout=10. #minutes
end_time=8*24. #hours
del_time=dtout*60. #seconds
end_time=end_time*3600. #seconds
#sst=297
D=5.e-6 #s-1
U=7 #m/s
psfc=100. #kPa
qsfc=tf.qs_tp(sst,psfc)
ft_intercept = 292 #K
ft_gamma = 6.e-3 #K/m
#ft_qv = 2.e-3
... | [
"def calc_equil(sst, ft_qv, use_NT=False):\n \n run_main(sst, ft_qv, use_NT)\n \n # grab csv file\n with open('dumpmodel.csv','r') as f:\n df_result=pd.read_csv(f)\n\n # last time step into named tupple\n out=df_result.iloc[-1]\n steady_state=make_tuple(out.to_dict())\n steady_stat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adapted from nicholls_turton.ipynb sst, sea surface temperature (K) ft_qv, mixedlayer top qv (kg kg^1) use_NT, True or False | def calc_equil(sst, ft_qv, use_NT=False):
run_main(sst, ft_qv, use_NT)
# grab csv file
with open('dumpmodel.csv','r') as f:
df_result=pd.read_csv(f)
# last time step into named tupple
out=df_result.iloc[-1]
steady_state=make_tuple(out.to_dict())
steady_state
#... | [
"def run_main(sst, ft_qv, use_NT):\n\n dtout=10. #minutes\n end_time=8*24. #hours\n del_time=dtout*60. #seconds\n end_time=end_time*3600. #seconds\n #sst=297\n D=5.e-6 #s-1\n U=7 #m/s\n psfc=100. #kPa\n qsfc=tf.qs_tp(sst,psfc)\n ft_intercept = 292 #K\n ft_gamma = 6.e-3 #K/m\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks a service's replication levels based on how the service's replication should be monitored. (smartstack or mesos) | def check_service_replication(
instance_config,
all_tasks,
smartstack_replication_checker,
):
expected_count = instance_config.get_instances()
log.info("Expecting %d total tasks for %s" % (expected_count, instance_config.job_id))
proxy_port = marathon_tools.get_proxy_port_for_instance(
n... | [
"def ensure_service_level(self):\n try:\n self.session = SQLalchemyUtil.get_session()\n self.logger.info('Start to check service level.')\n current_tenant_mppdb_group_list = self.database_analyzer.get_current_tenant_mppdb_group_list()\n unsatisfied_tenant_mppdb_gro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Traverses backwards through predecessors from end | def _deconstruct_path(predecessors, end):
if end not in predecessors:
return None
current = end
path = []
while current:
path.append(current)
current = predecessors.get(current)
return list(reversed(path)) | [
"def reverse_iterative(self):\n \"\"\"O(n) / O(1) solution.\"\"\"\n pre = None\n current = self.head\n while current is not None:\n next = current.next\n current.next = pre\n pre = current\n current = next\n self.head = pre",
"def forw... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recursively creates Level_Pair nodes from start up to end. Assumes that end's attack and strength are greater than start's. Neighbours for a node are stored in graph[node]. Distances between neighbours are stored in graph[nodeA][nodeB]. | def populate_graph(
graph, start, end, attack_bonus, strength_bonus):
# Check if already created
if start in graph:
return
graph[start] = dict()
# Recursively create neighbouring level pairs
if start.attack < end.attack:
inc_attack = Level_Pair(start.attack + 1, start.... | [
"def generate_adjacents(node):\n # Makes a dictionary where keys are current upper token positions and\n # values are the list of positions attainable from one slide move\n slide_moves = {}\n for key, value in node.boardstate.items():\n if value.isupper() and value != \"B\":\n slide_mo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Runs simulations to determine time (ticks) to level up attack or strength Enemy is set as sand crab (60hp, 1 def, 0 def bonus) Weapon is best available scimitar | def level_time_simulate(start_levels, attack_style, attack_bonus, strength_bonus):
ticks_per_attack = 4 # Scimitar attack speed
enemy_health = 60 # Sand crab health
max_hit, accuracy = get_max_hit_and_accuracy(
start_levels, attack_style, attack_bonus, strength_bonus)
if attack_st... | [
"def doMonsterAttack(self):\n #random monster attacks option\n #amoveNum = random.choices([0, 1, 2], [0.08, 0.46, 0.46])[0]\n weighted_choices = [(0, 8), (1, 46), (2, 46)]\n moveNum = random.choice([val for val, cnt in weighted_choices for i in range(cnt)])\n\n\n ########## Frame ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns tuple of the form, (max_hit, accuracy), for the given levels after factoring in the weapons available and the selected attack style. Assumes enemy has level 1 defence and 0 defence bonus | def get_max_hit_and_accuracy(
levels, attack_style, attack_bonus, strength_bonus):
weapon_attack, weapon_strength = get_weapon_stats(levels.attack)
attack_bonus += weapon_attack
strength_bonus += weapon_strength
if attack_style == Attack_Style.ATTACK:
effective_attack = osrs.effective_l... | [
"def get_weapon_stats(attack_level):\n if attack_level >= 60:\n # Dragon scimitar\n return (67, 66)\n elif attack_level >= 40:\n # Rune scimitar\n return (45, 44)\n elif attack_level >= 30:\n # Adamant scimitar\n return (29, 28)\n elif attack_level >= 20:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns tuple of the form (attack_bonus, strength_bonus) for the best scimitar (weapon) at a given attack level. Scimitars are almost always the most efficient weapon | def get_weapon_stats(attack_level):
if attack_level >= 60:
# Dragon scimitar
return (67, 66)
elif attack_level >= 40:
# Rune scimitar
return (45, 44)
elif attack_level >= 30:
# Adamant scimitar
return (29, 28)
elif attack_level >= 20:
# Mithril sci... | [
"def most_powerful_weapon(self):\n # sets inital damge to 0\n max_damage = 0\n # sets the best weapon to nothing\n best_weapon = None\n # Loop for each item in inventory\n for item in self.weaponinventory:\n # Code adapted from Make Your own Python Text Based Adv... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns list of tuples of the form (level, max_hit) for levels between start_strength_level and end_strength_level that increase max_hit. Assumes start_strength_level < end_strength_level and no multipliers | def get_max_hit_increases(
start_strength_level, end_strength_level,
strength_bonus, stance_adder):
greatest_max_hit = 0
max_hit_increases = []
cur_strength_level = start_strength_level
while cur_strength_level < end_strength_level:
effective_strength = osrs.effective_level(
... | [
"def calculateGagLimits():\r\n \"\"\"\r\n (may be different here with corporate clash, as this is from ttr)\r\n Limit from a maxed gagtrack: 30,25,20,15,7,3,1\r\n when level is 8 (max) is 30,25,20,15,7,3,1\r\n when level is 7 it is 30,25,20,15,7,3\r\n 6 is ?? (probably 25,20,15,10,7,3)\r\n 5 is... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates steric beads required for checking for steric clashes between motifs. Each residues has three beads modeled after the typical three bead models used in coarse grain modeling. The three beads are, Phosphate (P, OP1, OP2) Sugar (O5',C5',C4',O4',C3',O3',C1',C2',O2') and Base (All remaining atoms). | def get_beads(self):
phos_atoms,sugar_atoms,base_atoms = [],[],[]
for i,a in enumerate(self.atoms):
if a is None:
continue
if i < 3:
phos_atoms.append(a)
elif i < 12:
sugar_atoms.append(a)
else:
... | [
"def rec_events_scaffold_protein_binding_shc():\n \n # SHC binds to ErbB dimers\n for i in ['1', '2', '3', '4']:\n bind_complex(erbb(ty='1', bd=1, st='P', b=None, pi3k1=None, pi3k2=None, pi3k3=None, pi3k4=None, pi3k5=None, pi3k6=None) % erbb(ty=i, bd=1, st='P', b=None, pi3k1=None, pi3k2=None, pi3k3=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
messages1 and messages2 represent the encoded headlines from two news sources corr represents the correlation between the two currently returns average correlation | def average_similarity(messages1, messages2):
if np.array_equal(messages2, messages1):
return 1
corr = np.corrcoef(messages1, messages2)
return np.average(corr) | [
"def compute_correlation(distribution1, distribution2):\n\taverage1 = compute_average(distribution1)\n\taverage2 = compute_average(distribution2)\n\tstd1 = compute_std(distribution1)\n\tstd2 = compute_std(distribution2)\n\tnewdistribution = []\n\tfor entry in range(len(distribution1)):\n\t\tnewdistribution.append((... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
represents messages as vectors which are used to calculate similarity | def find_similarity(message1, message2):
total = 0
for i in range(len(message1)):
max = 0
for j in range(len(message2)):
message1_encoded = embed([message1[i]])
message2_encoded = embed([message2[j]])
sim = average_similarity(message1_encoded, message2_encoded... | [
"def get_similarity_vector(self, title, content, seperator, weightpara, language='Chinese'):\r\n print('Title is:', title, '\\n')\r\n if language == 'Chinese':\r\n clean_content = content.replace(' ', '').replace('\\r\\n', '')\r\n else:\r\n clean_content = content.replace(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
An iterator that will in turn yield all drawable curves in the form of (kind, name, ds, style) tuples (where kind is one of 'algorithm', 'oracle', 'unifpf', 'strategy'). | def _pds_plot_iterator(pds, dim, funcId):
i = 0
for (algname, ds) in pds.algds_dimfunc((dim, funcId)):
yield ('algorithm', algname, ds, _style_algorithm(algname, i))
i += 1
yield ('oracle', 'oracle', pds.oracle((dim, funcId)), _style_oracle())
yield ('unifpf', 'eUNIF', pds.unifpf().dictB... | [
"def iter_svgs(self):\n for name in self.parent.layers:\n yield name, self.parent.layers[name]\n for elem in self.parent.elements:\n if isinstance(elem, SVG):\n yield None, elem",
"def efficiency_curves(self):\n for key in self._efficiency_curves:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Show a legend. obj can be an Axes or Figure (in that case, also pass handles and labels arguments). | def legend(obj, ncol=3, **kwargs):
# Font size handling here is a bit weird. We specify fontsize=6
# in legend constructor since that affects spacing. However, we
# need to manually override with 'small' later, because the original
# specification did not take effect on whole-figure legends (and for
... | [
"def legend(**options):\n underride(options, loc=\"best\", frameon=False)\n\n ax = plt.gca()\n handles, labels = ax.get_legend_handles_labels()\n if handles:\n ax.legend(handles, labels, **options)",
"def legend (self, **kwargs):\n axes = self.twin_axes or self.axes\n self.mpl_leg... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot each algorithm/method's rank evolving as budget increases. groupby is the method of aggregating results of multiple instances a callable, stringable object, GroupByMedian by default. Note that funcId may be an array of id numbers; in that case, an average rank over listed functions is taken. | def rank_by_budget(ax, pds, dim=None, funcId=None, groupby=None):
if groupby is None: groupby = GroupByMedian()
pfsize = len(pds.algds.keys())
try: # funcId is array?
# _pds_plot_iterator[] uses funcId only for things we don't care for
fakeFuncId = funcId[0]
manyranking = np.array(... | [
"def ranking(self, dimfun, groupby, ftarget=10**-8):\n nameds = list(itertools.chain(self.algds_dimfunc(dimfun), self.stratds_dimfunc(dimfun)))\n count = len(nameds)\n\n # Produce \"fv\" items, one per dataset, containing single function value\n # for each budget\n fvset = []\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot a rotated convergence plot. It is essentially like fval_by_budget(), but rotated by 90 degrees, showing how big budget is required to reach every target. While this is a little less intuitive at first, it allows better judgement of performance impact of each strategy. With fval_by_budget(), performance change is r... | def evals_by_target(ax, pds, baseline_ds=None, baseline_label="", dim=None, funcId=None, groupby=None):
if groupby is None: groupby = GroupByMedian()
pfsize = len(pds.algds.keys())
runlengths = 10**np.linspace(0, np.log10(pds.maxevals((dim, funcId))), num=500)
target_values = pp.RunlengthBasedTargetVal... | [
"def kde_target_plot(df, feature):\n\n # Need to reset index for loc to workBU\n df = df.reset_index()\n plt.figure(figsize=(10, 6))\n plt.style.use('fivethirtyeight')\n\n # plot repaid loans\n sns.kdeplot(df.loc[df['TARGET'] == 0, feature], label='target == 0')\n # plot loans that were not rep... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot the evolution of relative evaluations for a target based on increasing absolute evaluations. In other words, for each absolute number of evaluations, determine the target reached and show how faster did baseline reach it. groupby is the method of aggregating results of multiple instances a callable, stringable obj... | def evals_by_evals(ax, pds, baseline1_ds=None, baseline1_label="", baseline2_ds=None, baseline2_label="", dim=None, funcId=None, groupby=None):
if groupby is None: groupby = GroupByMedian()
pfsize = len(pds.algds.keys())
runlengths = 10**np.linspace(0, np.log10(pds.maxevals((dim, funcId))), num=500)
ta... | [
"def evals_by_target(ax, pds, baseline_ds=None, baseline_label=\"\", dim=None, funcId=None, groupby=None):\n if groupby is None: groupby = GroupByMedian()\n pfsize = len(pds.algds.keys())\n\n runlengths = 10**np.linspace(0, np.log10(pds.maxevals((dim, funcId))), num=500)\n target_values = pp.RunlengthBa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
pinForward is the forward Pin, so we change its duty cycle according to speed. | def forward(self, speed):
self.pwm_backward.ChangeDutyCycle(0)
self.pwm_forward.ChangeDutyCycle(speed) | [
"def __init__(self, pinForward1, pinBackward1,pinForward2, pinBackward2):\n\n self.pinForward1 = pinForward1\n self.pinBackward1 = pinBackward1\n self.pinForward2 = pinForward2\n self.pinBackward2 = pinBackward2\n\n GPIO.setup(self.pinForward1, GPIO.OUT)\n GPIO.setup(self.p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the duty cycle of both control pins to zero to stop the motor. | def stop(self):
self.pwm_forward.ChangeDutyCycle(0)
self.pwm_backward.ChangeDutyCycle(0)
self.pwm_left.ChangeDutyCycle(0)
self.pwm_right.ChangeDutyCycle(0) | [
"def stop(self):\n\n GPIO.output(self.pin1, False)\n GPIO.output(self.pin2, False)\n self.pwm_control.ChangeDutyCycle(0)",
"def stop(self):\n\n self.pwm_forward.ChangeDutyCycle(0)\n self.pwm_backward.ChangeDutyCycle(0)",
"def stop_motor(self):\n self.output(self.steerin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Interpolate the points and radii between sections that have too few points. | def interpPoints(self, interpRad=False):
# print(np.shape(long_distances))
long_sections, long_distances, meddist = self.findLongSections()
print('Long inter-point distances found: %i' % len(long_sections))
count = 0
for sec in long_sections:
print('Supposed long section %i has %i nodes' \... | [
"def interpolate_old(self):\n\n # FIXME (Ole): Maybe this function\n # should move to the C-interface?\n # However, it isn't called by validate_all.py, so it\n # may not be that important to optimise it?\n\n# N = self.vertex_values.shape[0]\n# for i in range(N):\n# ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads the data set provided in this repository and returns a list of Decks or FuzzyDecks. The deck list is sorted by archetype so the distance matrix is easier to visualize. | def load_data_set(hero_class: str, fuzzy: bool, filename: str = "data/Decks.json", debug: bool = False) \
-> Union[List[Deck], List[FuzzyDeck]]:
if debug:
print("### loading dataset...")
with open(filename) as f:
data = json.load(f)
hero_classes = list(data["series"]["metadata"].key... | [
"def test_read_deck() -> None:\n ex_full = \"\"\"TD-DFT calculation \nFreq RB3LYP 6-31G(d) \nNumber of atoms I 12\nInfo1-9 ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the distance matrix of a list of Deck or FuzzyDeck objects. Returns the vectorform distance vector. | def calculate_distance_matrix(played_decks: Union[List[FuzzyDeck], List[Deck]], measure: str):
deck_data = np.array(played_decks).reshape(len(played_decks), 1)
if measure == "jaccard":
dist = pdist(deck_data, lambda u, v: u[0].jaccard_distance(v[0]))
elif measure == "euclidean":
dist = pdist... | [
"def get_distance_matrix(df_vectorized):\n\n\n gram_matrix = np.dot(df_vectorized.values,df_vectorized.values.T)\n\n norms_matrix = np.sqrt(np.outer(np.diag(gram_matrix),np.diag(gram_matrix)))\n\n cosine_distance_matrix = gram_matrix/norms_matrix\n\n return cosine_distance_matrix",
"def compute_distan... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates vmeasure, homogeneity, and completeness for each clustering algorithm stored in clustering_alg and adds it to each algorithms dictionary. | def eval_v_measure_homogeneity_completeness(clustering_alg: List, sdist_euclidean, sdist_jaccard,
labels_true, debug: bool = False):
for i, alg_dict in enumerate(clustering_alg):
if "alg" in alg_dict:
if alg_dict["distance"] == "euclidean":
... | [
"def get_clustering_algorithm_class(cls):\n return {\n \"spectral\": SpectralClusteringAlgorithm,\n \"dbscan\": DBSCANAlgorithm,\n \"gromos\": GromosAlgorithm,\n \"kmedoids\": KMedoidsAlgorithm,\n \"random\": RandomClusteringAlgorith... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates a clustering's contingency matrix for each clustering algorithm stored in the list clustering_alg and adds it to the dict. | def eval_cluster_contingency(clustering_alg: List, labels_true, sdist):
for (alg_name, alg_dict) in clustering_alg:
if "alg" in alg_dict:
clustering = alg_dict["alg"].fit(sdist)
labels_pred = clustering.labels_
alg_dict["labels"] = labels_pred
else:
la... | [
"def generate_clustering_info(self, algorithm_type, clustering_parameters, clusterings = []):\n clustering_info = {}\n for i, running_parameters in enumerate(clustering_parameters):\n\n clustering_id = \"clustering_%04d\"%(self.current_clustering_id)\n self.current_clustering_id ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modify the column name to make it Pythoncompatible as a field name | def normalize_col_name(col_name, used_column_names, is_relation):
field_params = {}
field_notes = []
new_name = col_name.lower()
if new_name != col_name:
field_notes.append('Field name made lowercase.')
if is_relation:
if new_name.endswith('_id'):
new_name = new_name[:-... | [
"def column_rename(self):\n # TODO develop method\n pass",
"def _update_column_name(self, column, idx, old_name, name):\n dtype = self.dtype\n # Updating the names on the dtype should suffice\n dtype.names = dtype.names[:idx] + (name,) + dtype.names[idx + 1 :]",
"def py_field_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given the database connection, the table name, and the cursor row description, this routine will return the given field type name, as well as any additional keyword parameters and notes for the field. | def get_field_type(connection, table_name, row):
field_params = OrderedDict()
field_notes = []
is_geometry = False
try:
field_type = connection.introspection.get_field_type(row[1], row)
except KeyError:
field_type = 'TextField'
field_notes.append('This field type is a guess.'... | [
"def processClassField(cursor):\n type = None\n fieldChilds = list(cursor.get_children())\n if len(fieldChilds) == 0: # if there are not cursorchildren, the type is some primitive datatype\n type = cursor.type.spelling\n else: # if there are cursorchildren, the type is some non-primitive dataty... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Authenticate user based on code. | def authenticate_user(authentication_code):
for suffix in ('', '=', '=='):
attempt = authentication_code + suffix
decoded = base64.decodestring(attempt)
fields = decoded.split('_')
email, user_id, time_stamp, str_hex = fields
if time_stamp < time.time():
# Auth... | [
"def authenticate(self, code=None):\n params = {\n \"grant_type\": \"authorization_code\",\n \"code\": code\n }\n data = urllib.urlencode(params)\n request = urllib2.Request(SSO_TOKEN_URL, data)\n request.add_header(\"Authorization\", \"Basic \" + b64encode(\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Activates the specified MFA TOTP device for the user. Activation requires manual interaction with the Console. | def activate_mfa_totp_device(self, user_id, mfa_totp_device_id, mfa_totp_token, **kwargs):
resource_path = "/users/{userId}/mfaTotpDevices/{mfaTotpDeviceId}/actions/activate"
method = "POST"
# Don't accept unknown kwargs
expected_kwargs = [
"retry_strategy",
"if_... | [
"async def activate_application_token(self, apptoken, temptoken) -> bool:\n await self.raw_request(\n self.URL_ACTIVATE.format(apptoken=apptoken, temptoken=temptoken)\n )\n return True",
"def enable_mfa_device(self, user_name, serial_number,\r\n auth_code_1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Moves the specified tag namespace to the specified compartment within the same tenancy. To move the tag namespace, you must have the manage tagnamespaces permission on both compartments. For more information about IAM policies, see `Details for IAM`__. Moving a tag namespace moves all the tag key definitions contained ... | def change_tag_namespace_compartment(self, tag_namespace_id, change_tag_namespace_compartment_detail, **kwargs):
resource_path = "/tagNamespaces/{tagNamespaceId}/actions/changeCompartment"
method = "POST"
# Don't accept unknown kwargs
expected_kwargs = [
"retry_strategy",
... | [
"def delete_namespace_tag(self, namespace, tag_name):\n url = 'metadefs/namespaces/%s/tags/%s' % (namespace, tag_name)\n resp, _ = self.delete(url)\n self.expected_success(204, resp.status)\n return rest_client.ResponseBody(resp)",
"def remove_namespace(self, doc, namespace):\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a new dynamic group in your tenancy. You must specify your tenancy's OCID as the compartment ID in the request object (remember that the tenancy is simply the root compartment). Notice that IAM resources (users, groups, compartments, and some policies) reside within the tenancy itself, unlike cloud resources su... | def create_dynamic_group(self, create_dynamic_group_details, **kwargs):
resource_path = "/dynamicGroups"
method = "POST"
# Don't accept unknown kwargs
expected_kwargs = [
"retry_strategy",
"opc_retry_token"
]
extra_kwargs = [_key for _key in six.i... | [
"def create_dynamic_group(data=None):\n return connector.SCIMGroup(\n displayName='display_name{0}'.format(uuid.uuid4()))",
"def product_group_create(obj, name, department):\n client = get_client(obj)\n\n with Action('Creating product_group: {}'.format(name), nl=True):\n pg = client.product... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |