query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Return multinomial selection with different probabilities.
def multinomial(prob, unique=False, rng=np.random): rechoose = np.where(prob.sum(axis=1) > 0.0)[0] choice = np.zeros(prob.shape[0], int) - 1 while len(rechoose) > 0: prob = prob / prob.sum(axis=1, keepdims=True) rnd = rng.rand(len(rechoose))[:, None] choice[rechoose] = (rnd > prob[re...
[ "def _sample_multinomial(data=None, shape=_Null, get_prob=_Null, dtype=_Null, name=None, attr=None, out=None, **kwargs):\n return (0,)", "def multinomial_pmf(observation, probabilities):\n # TODO\n probability = {}\n n = 0\n for word, num in observation.items():\n n = n + num\n # pi = xi/...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return bool array of women having babies.
def assign_babies(age, female, partner, alive, fr_a, rng): n_agent = len(age) if age.max() >= len(fr_a): # Extend fertility array, assuming fertility rate of 0 fr_a = np.hstack((fr_a, np.zeros(age.max() + 1 - len(fr_a)))) have_baby = alive & female & (partner >= 0) & (rng.rand(n_agent) < fr_...
[ "def find_binary(self):\n binary=[]\n for col in self.categorical_variables:\n if len(self.data[col].value_counts())==2:\n binary.append(col)\n return binary", "def boys(self):\n return self._boys", "def find_binary(self):\n binary=[]\n for col...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensures that the val is the default str() type for python2 or 3
def _str(val): if str == bytes: if isinstance(val, str): return val else: return str(val) else: if isinstance(val, str): return val else: return str(val, 'ascii')
[ "def __expectString(val):\n if type(val) != str:\n raise Exception('Expected string, received {}'.format(type(val)))", "def _assert_type_string(self, name, val):\n self._assert_type(name, val, basestring)", "def can_to_str(_type):\n return isinstance(_type, String)", "def convert_str_or_no...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Samples a random row (polygon) in the shapefile
def _sample(self): return self.shp.sample(1)['geometry'].values[0]
[ "def random_polygon(cx, cy, avg_r, variance, frequency, num_verts):\n def clip(_x, vmin, vmax):\n if vmin > vmax:\n return _x\n elif _x < vmin:\n return vmin\n elif _x > vmax:\n return vmax\n else:\n return _x\n\n variance = clip(variance...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test colour using kwargs
def test_kwarg_colour(self): colour = adapter.SFFRGBA( red=self.red, green=self.green, blue=self.blue, alpha=self.alpha ) self.assertEqual(colour.red, self.red) self.assertEqual(colour.green, self.green) self.assertEqual(colour.blue...
[ "def hasColor(*args, **kwargs):\n \n pass", "def test_kwarg_colour(self):\n colour = schema.SFFRGBA(\n red=self.red,\n green=self.green,\n blue=self.blue,\n alpha=self.alpha\n )\n self.assertEqual(colour.red, self.red)\n self.assert...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that using a kwarg random_colour will set random colours
def test_native_random_colour(self): colour = adapter.SFFRGBA(random_colour=True) self.assertTrue(0 <= colour.red <= 1) self.assertTrue(0 <= colour.green <= 1) self.assertTrue(0 <= colour.blue <= 1) self.assertTrue(0 <= colour.alpha <= 1)
[ "def setRandomColor(self):\n self.color=mycolors.random()", "def randomColor():\n return Color((_random.randint(0,255),_random.randint(0,255),_random.randint(0,255)))", "def random_color():\n colors = [\n Color.HEADER,\n Color.OKBLUE,\n Color.WARNING,\n Color.FAIL\n ]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that we can create an SFFExternalReferenceList from a literal list
def test_create_from_list(self): ee = [adapter.SFFExternalReference( resource=self.rr[i], url=self.uu[i], accession=self.aa[i], label=self.ll[i], description=self.dd[i] ) for i in _xrange(self._no_items)] E = adapter.SFFExternalReferenc...
[ "def _build_feature_references(feature_ref_strs: List[str]) -> List[FeatureRefProto]:\n\n feature_refs = [FeatureRef.from_str(ref_str) for ref_str in feature_ref_strs]\n feature_ref_protos = [ref.to_proto() for ref in feature_refs]\n\n return feature_ref_protos", "def parse_list(list_bytes):\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that we can create from a gds_type
def test_create_from_gds_type(self): _b = emdb_sff.biological_annotationType( name=self.name, description=self.description, number_of_instances=self.no, external_references=self._external_references ) b = adapter.SFFBiologicalAnnotation.from_gds_ty...
[ "def test_create_from_gds_type(self):\n _S = emdb_sff.software_type()\n S = adapter.SFFSoftware.from_gds_type(_S)\n self.assertRegex(\n _str(S),\n r\"\"\"SFFSoftware\\(id={}, name={}, version={}, processing_details={}\\)\"\"\".format(\n S.id, None, None, Non...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that we can create from unicode using __init__
def test_create_init_unicode(self): v = adapter.SFFVertices( num_vertices=self.num_vertices, mode=self.mode, endianness=self.endian, data=self.unicode ) self.assertIsInstance(v, adapter.SFFVertices) self.assertEqual(v.mode, self.mode) ...
[ "def _init_unicode():\n global _unicode_properties\n global _unicode_key_pattern\n _unicode_properties = _build_unicode_property_table((0x0000, 0x10FFFF))\n _unicode_key_pattern = _build_unicode_key_pattern()", "def __init__(self, length=None, **kwargs):\n kwargs.setdefault('convert_unicode', T...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that we can create from gds_type
def test_create_from_gds_type(self): _S = emdb_sff.software_type() S = adapter.SFFSoftware.from_gds_type(_S) self.assertRegex( _str(S), r"""SFFSoftware\(id={}, name={}, version={}, processing_details={}\)""".format( S.id, None, None, None ) ...
[ "def test_create_from_gds_type(self):\n _b = emdb_sff.biological_annotationType(\n name=self.name,\n description=self.description,\n number_of_instances=self.no,\n external_references=self._external_references\n )\n b = adapter.SFFBiologicalAnnotation...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that we can create from gds_types
def test_create_from_gds_type(self): # without ids _TT = emdb_sff.transform_listType(self.gds_txs) TT = adapter.SFFTransformList.from_gds_type(_TT) self.assertEqual(self.tx_count, len(TT)) self.assertEqual(len(TT.get_ids()), 0) # with ids _TT = emdb_sff.transform_...
[ "def test_tool_types_create(self):\n pass", "def test_create_from_gds_type(self):\n _S = emdb_sff.software_type()\n S = adapter.SFFSoftware.from_gds_type(_S)\n self.assertRegex(\n _str(S),\n r\"\"\"SFFSoftware\\(id={}, name={}, version={}, processing_details={}\\)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create an SFFSegmentation object with 3D volume segmentation from scratch
def test_create_3D(self): segmentation = adapter.SFFSegmentation() segmentation.name = rw.random_word() segmentation.primary_descriptor = u"three_d_volume" # transforms transforms = adapter.SFFTransformList() transforms.append( adapter.SFFTransformationMatrix(...
[ "def test_create_3D(self):\n segmentation = schema.SFFSegmentation() # 3D volume\n segmentation.primaryDescriptor = \"threeDVolume\"\n # transforms\n transforms = schema.SFFTransformList()\n transforms.add_transform(\n schema.SFFTransformationMatrix(\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that we can create a segmentation of shapes programmatically
def test_create_shapes(self): segmentation = adapter.SFFSegmentation() segmentation.name = rw.random_word() segmentation.software_list = adapter.SFFSoftwareList() segmentation.software_list.append( adapter.SFFSoftware( name=rw.random_word(), ve...
[ "def test_create_shapes(self):\n segmentation = schema.SFFSegmentation()\n segmentation.primaryDescriptor = \"shapePrimitiveList\"\n transforms = schema.SFFTransformList()\n segments = schema.SFFSegmentList()\n segment = schema.SFFSegment()\n # shapes\n shapes = sche...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that we can create a segmentation of meshes programmatically
def test_create_meshes(self): segmentation = adapter.SFFSegmentation() segmentation.name = rw.random_word() segmentation.primary_descriptor = u"mesh_list" segments = adapter.SFFSegmentList() segment = adapter.SFFSegment() # meshes mesh_list = adapter.SFFMeshList()...
[ "def test_create_shapes(self):\n segmentation = adapter.SFFSegmentation()\n segmentation.name = rw.random_word()\n segmentation.software_list = adapter.SFFSoftwareList()\n segmentation.software_list.append(\n adapter.SFFSoftware(\n name=rw.random_word(),\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that we can add annotations programmatically
def test_create_annotations(self): segmentation = adapter.SFFSegmentation() # annotation segmentation.name = u"name" segmentation.software_list = adapter.SFFSoftwareList() segmentation.software_list.append( adapter.SFFSoftware( name=u"Software", ...
[ "def create_annotations(self) -> None:\n pass", "def test_annotations(defined_object, expected):\n assert getattr(defined_object, \"__annotations__\") == expected", "def test_get_annotations(self):\n\n itemuri = \"http://localhost:3000/catalog/cooee/items/1-012\"\n docurl = \"http://loca...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that transform ids work correctly
def test_transform_ids(self): transforms = adapter.SFFTransformList() matrix = adapter.SFFTransformationMatrix(rows=3, cols=3, data=' '.join(map(_str, range(9)))) transforms.append(matrix) transforms2 = adapter.SFFTransformList() matrix2 = adapter.SFFTransformationMatrix(rows=3,...
[ "def test_transform_ids(self):\n transforms = schema.SFFTransformList()\n matrix = schema.SFFTransformationMatrix(rows=3, cols=3, data=' '.join(map(str, range(9))))\n transforms.add_transform(matrix)\n\n transforms2 = schema.SFFTransformList()\n matrix2 = schema.SFFTransformationM...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Export to an XML (.sff) file
def test_export_sff(self): temp_file = tempfile.NamedTemporaryFile() self.segmentation.export(temp_file.name + u'.sff') # assertions with open(temp_file.name + u'.sff') as f: self.assertEqual(f.readline(), u'<?xml version="1.0" encoding="UTF-8"?>\n')
[ "def write_toXMLfile(self):\n sfbxml = self.sdict['sfbxml']\n self._make_sfbxmlfile(sfbxml)", "def test_export_xml_to_file(self):\n pass", "def exportXML(self):\r\n encoding:str = self.encodingVariable.get()\r\n\r\n try:\r\n self.filePath:str = asksaveasfilename(\r\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that we can merge annotation from one to another
def test_merge_annotation(self): seg1_fn = os.path.join(TEST_DATA_PATH, u'sff', u'v0.8', u'annotated_emd_1014.json') seg2_fn = os.path.join(TEST_DATA_PATH, u'sff', u'v0.8', u'emd_1014.json') seg1 = adapter.SFFSegmentation.from_file(seg1_fn) seg2 = adapter.SFFSegmentation.from_file(seg2_f...
[ "def fix_annotations(nanopub: Nanopub) -> Nanopub:\n\n if \"nanopub\" in nanopub:\n for idx, anno in enumerate(nanopub[\"nanopub\"][\"annotations\"]):\n update_bel_annotation(anno)\n\n nanopub[\"nanopub\"][\"annotations\"][idx][\"type\"] = anno[\"type\"]\n nanopub[\"nanopu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create json for zabbix discovery service
def createZabbixJson(data): try: result = {"data":[]} for name, value in data.iteritems(): result['data'].append({"{#NAME}":name, "{#IP_STREAM}": value['ip_stream'], "{#RC_PORT}": value['rc_port'] }) return json.dumps(result) except: return 0
[ "def GetServices(self):\n return json.dumps(SERVICES)", "def servicesJson():\n # get the services from the database\n dbSession = current_app.config['DBSESSION']\n services = dbSession.query(Service).all()\n\n # create the list of services that will be returned as json\n servicesList = []\n f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets enforcing mode of SElinux
def setenforce(mode): mode = mode.strip().title() assert mode in ["Permissive", "Enforcing"] assert Test.Run.command("/usr/sbin/setenforce %s" % mode)
[ "def set_mode(self, nt):\n return _radio_astro_swig.detect_set_mode(self, nt)", "def safe_mode(self):\n\n self.send_code(SAFE_MODE)", "def _change_mode(self, attr, old, new):\n self.exg_mode = new", "def _set_server_mode_faulty(server, mode):\n allowed_mode = ()\n _do_set_server_mod...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a GeoJson plugin to append into a map with Map.add_plugin.
def __init__(self, data): super(GeoJson, self).__init__() self.plugin_name = 'GeoJson' if 'read' in dir(data): self.data = data.read() elif type(data) is dict: self.data = json.dumps(data) else: self.data = data
[ "def _get_geojson(self):\n pass", "def new_map(self, name):\n from . import packers\n map2 = HeteroMap()\n self.add(name, self._get_packer(name), map2, packers.BuiltinHeteroMapPacker)\n return map2", "def __init__(self, data, transition_time=200, loop=True, auto_play=True):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A function that takes the string value of an individual item of data that will become a tagvalue in FluidDB. The default version of this function in flimp will attempt to cast the value into something appropriate see flimp.parser.csv_parser.clean_row_item for the source.
def clean_row_item(item): # We just want to make sure we return None for empty values. By default # flimp will ignore tags with None as a value (this can be overridden) value = item.strip() if value: return value else: return None
[ "def _item_to_value(_, item: str) -> str:\n return item", "def prep_value(self, db_field, value):\n\t\treturn force_unicode(value)", "def _parse_value(self,value):\n value = value.strip()\n if not value:\n return None\n\n # assume that values containing spaces are lists of...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Timeout after given duration.
def set_timeout(duration, callback=None): # SIGALRM is only usable on a unix platform! signal.signal(signal.SIGALRM, raise_signal) signal.alarm(duration) # alarm after X seconds if callback: callback()
[ "def set_timeout(cls, timeout):\n ...", "def set_timeout(self, timeout):\r\n self.timeout = float(timeout)/1000.", "def delay_timeout(self, delay_timeout):\n\n self._delay_timeout = delay_timeout", "def set_timeout(self, timeout):\n self.m_timeout = timeout", "def timeout(self):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the list of tuples sorted by the index passed as argument.
def sort_tuple_list(l, tup_idx=0): return sorted(l, key=lambda tup: tup[tup_idx])
[ "def sort_by_index(elements: Iterable, indexes: Iterable):\n\n return tuple(sorted(elements)[index] for index in indexes)", "def sortedListOfIndexAssyRec(self):\n l = []\n for ar in self:\n l.append((ar.orgpos, ar))\n # sort\n l.sort(key=lambda k: k[0])\n # done\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Apply `fn` taking as arguments consecutive elements of `l`.
def apply_consecutive_elements(l, fn): return [fn(i, j) for i, j in zip(l[:-1], l[1:])]
[ "def lmap(fn, *args):\n return list(map(fn, args))", "def apply(func, iterable):\n for item in iterable:\n func(item)\n yield item", "def apply_to_all_elements(lst, fct):\n return map(fct, lst)", "def map(fn, lst):\n \"*** YOUR CODE HERE ***\"\n for i in range(len(lst)):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
search the source for the original name of a module if it was aliased. if the module is instead simply found, return that.
def _module_from_alias(source, module_name): regular_or_aliased = _aliased_module_regex(module_name) _search = [regular_or_aliased(i) for i in source.split("\n")] matches = [i for i in _search if i is not None] assert len(matches) == 1, ("only mode module name " "should ma...
[ "def _ResolveUsingStarImport(self, module, name):\n wanted_name = self._ModulePrefix() + name\n for alias in module.aliases:\n type_name = alias.type.name\n if not type_name or not type_name.endswith(\".*\"):\n continue\n imported_module = type_name[:-2]\n # 'module' contains 'from ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
if a given identifier is qualified, trace it to the module which was imported
def _qualified_namespace(source, line, col, identifier): lines = source.split("\n") line_of_id = lines[line] try: just_before_id = line_of_id[col - 1] except IndexError: print({ "line_of_id": line_of_id, "line": line, "col": col, "identifie...
[ "def is_import(node):\r\n return node.type in (syms.import_name, syms.import_from)", "def breakpoint_on_module(session_id, module_type, trace_bp=False):\n session = manager.DebugSessions.retrieve_session(session_id)\n if session is None:\n print(f\"\"\"session ${session_id} doesn't exist\"\"\")\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
given the identifier, give list of module names that you should search in for the symbol
def modules_to_search(source, line, col, identifier): # check if identifier is qualified, if it's # like "String.join" instead of just "join" qualified_module = _qualified_namespace(source, line, col, identifier) if qualified_module: return qualified_module # search for explicit import ...
[ "def get_symbols_in_submodule(name):\n symbols = {}\n for k, v in _API_SYMBOLS.items():\n if k.startswith(name):\n symbols[k] = v\n return symbols", "def find_symbol(target, name, module=MACINTALK_MODULE):\n for mod in target.module_iter():\n if module and module != mod.GetFileSpec().GetFilen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get elmpackage.json as a dict
def get_package_json(path): with open(os.path.join(path, "elm-package.json")) as p: return json.loads(p.read())
[ "def get_package_data(self) -> dict:\n return self.pack_data", "def load(self):\n if not self.exists():\n return {}\n with open(self.filepath) as f:\n j = json.load(f)\n try:\n self.pkgname = j['name']\n self.packages = set(j['package...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the path to the elmpackage.json for a given file
def _elm_package_for(file_path): # just troll up the file tree parts = file_path.split(os.path.sep) for i in list(reversed(range(len(parts))))[:-1]: guess_parts = parts[:i] + ["elm-package.json"] current_guess = "/" + os.path.join(*guess_parts) if os.path.exists(current_guess): ...
[ "def get_package_json(path):\n with open(os.path.join(path, \"elm-package.json\")) as p:\n return json.loads(p.read())", "def example_of_how_to_refer_to_a_file_in_the_package(self):\n file_name = pkg_resources.resource_string(\"{{library_name}}\", \"module_data/file_required_by_module.json\")\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return an html chunk with a table that lists all current users (i.e. participants), their names, and their user ids.
def users_table(cls, with_buttons=None): to_render = "Users table:<br /><table><tr><td>User ID</td><td>Last name</td><td>First name</td>" if with_buttons != None: to_render = to_render + "<td>In XP?</td>" to_render = to_render + "</tr>" cur_session = xp_management.ExpS...
[ "def show_all_users():\n users = User.query.all()\n\n return render_template('user_list.html', users=users)", "def list_members():\n\tcheck_admin()\n\tmembers = db.engine.execute('select s.id as id, s.name as name, t.title as title, p.task as task,\\\n \t\tp.progress as progress, s.email as email\\\n \t\tfr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a number/items it checks if the item/number is present in the range or not
def contains(self, item : int) -> bool: return self.start <= item and item < self.end
[ "def _in_range(value, range):\n # TODO: Implement this\n return True", "def hasRange(*args, **kwargs):\n \n pass", "def if_numbers_within_bounds(result):\n for number in result:\n if number < 1 or number > 20:\n return False\n return True", "def hasValidRange(*args, **k...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if the range object is a subrange of the given superrange or not
def is_sub_range(self, range_obj) -> bool: return self.start >= range_obj.start and self.end <= range_obj.end
[ "def hasRange(*args, **kwargs):\n \n pass", "def hasValidRange(*args, **kwargs):\n \n pass", "def _in_range(value, range):\n # TODO: Implement this\n return True", "def is_range(self):\n return True", "def is_in_boundary(x, start, end):\n return x >= start and x <= end", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a new Range object which is a combination of the two ranges if they are not disjoint
def combine(self, range_obj) -> bool: if self.is_disjoint(range_obj): return Range(0) new_start = min(self.start, range_obj.start) new_end = max(self.end, range_obj.end) return Range(new_start, new_end)
[ "def union(self, other: \"Interval\") -> \"Interval\":\n return Interval(min(self.start, other.start), max(self.end, other.end))", "def union(self, rng):\r\n # if RangeSet, return union of that instead\r\n if isinstance(rng, RangeSet):\r\n return rng.union(self)\r\n # conver...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns length of the Range
def length(self) -> int: return self.end - self.start
[ "def _range_len_ ( self ) :\n return self.size()", "def __len__(self):\n return sum(len(r) for r in self.ranges)", "def length(self):\r\n # try normally\r\n try:\r\n return self.end - self.start\r\n except (TypeError, ArithmeticError, ValueError) as _:\r\n pa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shifts Range by n by adding n to the limits
def shift(self, n: int) -> None: self.start += n self.end += n if self.start > self.end: self.reset()
[ "def rshift(self, n: int) -> None:\n self.end += n\n if self.start > self.end:\n self.reset()", "def lshift(self, n: int) -> None:\n self.start += n\n if self.start > self.end:\n self.reset()", "def shift(x, n):\n if n > 0:\n return np.pad(x, (n, 0), m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shifts ending point of Range by n
def rshift(self, n: int) -> None: self.end += n if self.start > self.end: self.reset()
[ "def shift(self, n: int) -> None:\n self.start += n\n self.end += n\n\n if self.start > self.end:\n self.reset()", "def lshift(self, n: int) -> None:\n self.start += n\n if self.start > self.end:\n self.reset()", "def shift(x, n):\n if n > 0:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shifts starting point of Range by n
def lshift(self, n: int) -> None: self.start += n if self.start > self.end: self.reset()
[ "def shift(self, n: int) -> None:\n self.start += n\n self.end += n\n\n if self.start > self.end:\n self.reset()", "def rshift(self, n: int) -> None:\n self.end += n\n if self.start > self.end:\n self.reset()", "def shift(x, n):\n if n > 0:\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mark the given address as warm if it was not previously.
def _mark_address_warm(computation: ComputationAPI, address: Address) -> bool: if computation.state.is_address_warm(address): return False else: computation.state.mark_address_warm(address) return True
[ "def freeze(self, address: str):\n address = Address.from_string(address)\n return self.wallet.set_frozen_state([address], True)", "def setAddress(self, address: ghidra.program.model.address.Address) -> None:\n ...", "def new_address(self, name, address):\n if address not in self.ip_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a list of interested pii from the document. Return a list of pii entity types of the given document with only the entities of interest and above the confidence threshold.
def get_interested_pii(document: Document, classification_config: PiiConfig): pii_entities = [] for name, score in document.pii_classification.items(): if name in classification_config.pii_entity_types or ALL in classification_config.pii_entity_types: if score >= classification_config.confid...
[ "def prob_classify(self, document):\n features = document.get_features()\n probs = self.classifier.prob_classify(features)\n return probs", "def extract_skills_in_document(document_id) -> List[SkillExtract]:\n\n skills_resource_dir = os.path.join(app.root_path, \"resources/ontologies\")\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The function find all dates
def findall_date(f_date): for i in xrange(len(f_date)): find_date = re.findall('\d{2}-\d{2}-\d{4}|\d{2}.\d{2}.\d{4}|' '\d{2}.\d{2}.\d{2}|\d{2} \d{2} \d{2}|' '\d{2} \d{2} \d{4}', str(f_date)) return find_date
[ "def search_date(self):", "def dates(self):\n drs = self._data_record_class.objects.filter(**self._kwargs()).values('date').distinct()\n return [d['date'] for d in drs]", "def available_dates(self):\n output = []\n\n for row in self.rows[:]:\n if row['Date'] not in output:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The function split dates for 3 elements(dmy day, month, year)
def split_date(dmy): for i in xrange(len(dmy)): if '.' in dmy[i]: dmy[i] = dmy[i].split('.') elif '-' in dmy[i]: dmy[i] = dmy[i].split('-') else: dmy[i] = dmy[i].split(' ') return dmy
[ "def breakdate(date):\n day=int(date[6:8])\n month=int(date[4:6])\n year=int(date[0:4])\n return day, month, year", "def split_date(df, date_col):\n list_date = df[date_col].tolist()\n list_year = [int(date[:4]) for date in list_date]\n list_month = [int(date[5:7]) for date in list_date]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the given GW shows up in the routes for both modes.
def test_gateway(self): anIP = "192.168.1.100" for aMode in trans.mode_list: tup = trans.transform_to_routes("sampleStatFile.txt", anIP, aMode) for line in tup[1]: if anIP in line: break else: print(f"The GW of '{anIP}' is no...
[ "def test_is_hallway(self):\n self.assertFalse(self.gamerules.is_hallway(\"Dinning Room\")) #Not hallway\n self.assertTrue(self.gamerules.is_hallway(\"Hall-Lounge\")) #Is a hallway", "def check_test_route(self):\n if self.target_ip:\n (retcode,route) = run('/sbin/ip route show {target_ip}'.f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that we handle 32 bit networks using correct syntax.
def test_32_bit_macOS(self): tup = trans.transform_to_routes("sampleStatFile.txt", "192.168.1.131", "macOS") host_lines = [line for line in tup[1] if re.search("route -n add \d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}/32", line)] self.assertEqual(tup[0], 0) self.assertEqual(len(host_lines), 2)
[ "def test_unsigned_integer_32(self):\n self.assertIsInstance(self.dataset.structure.ui32, BaseType)\n self.assertEqual(self.dataset.structure.ui32.dtype, np.dtype(\">I\"))\n self.assertEqual(self.dataset.structure.ui32.shape, ())", "def test_isnetid():\n print('Testing isnetid()')\n\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve the serializer for a device.
def __getitem__(self, device): if not self.initialized: raise RuntimeError("The registry isn't initialized yet") return self._serializers[device]
[ "def get_serializer(self, format):\n serializer = self._serializers.get(format)\n if not serializer:\n raise ValueError(format)\n return serializer()", "def _get_serializer(self, model, serializer):\n app_lbl = getattr(model, \"_meta\").app_label\n package = apps.get_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize the registry. This method will import all the registered devices and serializers and put them into a mapping.
def initialize(self): if self.initialized: raise RuntimeError("The registry is already initialized") for specifier, serializer in self._prematurely.items(): model = apps.get_model(specifier) self._serializers[model] = self._get_serializer(model, serializer) ...
[ "def populate_registry():\n # We import the register_classes modules as a direct submodule of labscript_devices.\n # But they cannot all have the same name, so we import them as\n # labscript_devices._register_classes_script_<num> with increasing number.\n module_num = 0\n for devices_dir in LABSCRIP...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Register a device (specifier). The device should be registered as '.' and the serializer as '.'.
def register(self, specifier, serializer): if self.initialized: raise RuntimeError("The registry is already initialized") if specifier in self._prematurely.keys(): if serializer == self._prematurely[specifier]: raise RuntimeError("Double register for {0}".format(...
[ "def device_register():\n\n resp = routing.base.generate_error_response(code=501)\n resp[\"message\"] = \"Not yet implemented.\"\n\n return json.dumps(resp) + \"\\n\"", "def register_device(ctx, device, model, nickname, client_type):\n session, api_url, project_id = build_client_from_conte...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a serializer from a app and serializer specifier.
def _get_serializer(self, model, serializer): app_lbl = getattr(model, "_meta").app_label package = apps.get_app_config(app_lbl).module if "." in serializer: # pragma: no cover module, serializer = serializer.split(".", 1) else: module = "serializers" ...
[ "def get_serializer(self, format):\n creator = self.serializer_format_dict.get(format.upper())\n if not creator:\n raise ValueError(format)\n\n return creator()", "def get_serializer(self, format):\n serializer = self._serializers.get(format)\n if not serializer:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate WAV header that precedes actual audio data sent to the speech translation service.
def get_wave_header(frame_rate,stream=True): if frame_rate not in [8000, 16000]: raise ValueError("Sampling frequency, frame_rate, should be 8000 or 16000.") nchannels = channels bytes_per_sample = sampwidth data = b'RIFF' # user 0 length for audio stream if stream : ...
[ "def gen_header(sample_rate=int(config[\"SETTINGS\"][\"RECORD_SAMPLING_RATE\"]), bits_per_sample=16, channels=1):\n data_size = 2000*10**3\n o = bytes(\"RIFF\", 'ascii') # (4byte) Marks file as RIFF\n o += (data_size + 36).to_bytes(4, 'little') # (4byte) File ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a disease subset of functions. A function is considered a disease if its lowercase name is the same as its class and its name is not a function category. Build must be run first
def disease_function_subset(ipa, network_dir, printing=False): disease_names = set() for function in ipa.functions: if function.name.lower() == function.function_class.lower(): disease_names.add(function.name) diseases_to_remove = read_diseases_to_remove(network_dir) disease_names -=...
[ "def get_functions(text, startswith='def '):\n return get_definition(text, startswith)", "def get_disasm_all_functions_from(self, _funcea):\n\t\tfdisasm = {}\n\t\tif (_funcea != BADADDR):\n\t\t\tfroot_disasm = self.get_disasm_function_line(_funcea)\n\t\t\tfroot_name = GetFunctionName(_funcea)\n\t\t\tfdisasm[fr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Calculates conduit lengths in the network assuming pores are cones and throats are cylinders. A conduit is defined as ( 1/2 pore full throat 1/2 pore ).
def cones_and_cylinders( network, pore_diameter="pore.diameter", throat_diameter="throat.diameter" ): L_ctc = _get_L_ctc(network) D1, Dt, D2 = network.get_conduit_data(pore_diameter.split(".", 1)[-1]).T L1 = D1 / 2 L2 = D2 / 2 # Handle throats w/ overlapping pores _L1 = (4 * L_ctc**2 + D1*...
[ "def calcNumberOfCoolers(context):\n diameter = context[\"diameter\"]\n propellant = context.get(\"propellant\", 0)\n if propellant == 0:\n return 0\n coolers = math.log(calcClipToAutoloader(context) / (6 * (5*diameter)**1.5 * (propellant ** 0.5)), 0.92)\n if coolers < 0:\n coolers = 0\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For a tsv file, compute sums, sumsquares and counts for each of the given columns within groups defined by groupCols. >>> z = IDotData( names = ( 'a', 'b' ), Records = ( ( 1, 2 ), ( 1, 3 ), ( 2, 4 ), ( 2, 5 ) ) ) >>> computeSumsWithinGroups( inFN = z, cols = 'b', groupCols = 'a', outFN = sys.stdout )
def computeSumsWithinGroups( inFN, cols, groupCols, groupsAreContiguous = True, outFN = None, getio = None ): cols = tuple( MakeSeq( cols ) ) groupCols = tuple( MakeSeq( groupCols ) ) if outFN is None: outFN = AddFileSubdir( 'stats', AddFileSfx( inFN, 'sums', *( cols + groupCols ) ) ) def combiner( inFNs, out...
[ "def csvsum():\n parser = _default_arguments()\n parser.add_argument('-c', '--cols', nargs='*',\n help='A list of columns. Each column will have a sum generated.')\n parser.add_argument('-a', '--alphabetize',\n action='store_true',\n help='A flag to indicate the output should be displa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute histograms of the specified columns of the input
def computeHistograms( inFN, cols, binSizes = None, outFNs = None, getio = None ): cols = tuple( MakeSeq( cols ) ) binSizesHere = ( .001, ) * len( cols ) if binSizes is None else tuple( MakeSeq( binSizes ) ) outFNsHere = outFNs if outFNsHere is None: outFNsHere = [ AddFileSubdir( 'stats', AddFileSfx( inFN, 'hi...
[ "def vh_histograms(map):\n return np.sum(map, axis=1), np.sum(map, axis=0)", "def histogram(index, data, columns):\n plt.figure(figsize=(10, 5))\n plt.title(\"Histogram for {}\".format(columns[index]))\n ax = sns.distplot(data[:,index], rug=True)", "def show_histo(df, bins=20):\r\n\r\n assert(isi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert DotData to TSV
def DotData2TSV( inFN, outFN, readOpts = {}, getio = None ): if getio: return dict( depends_on = inFN, creates = outFN ) DotData( Path = inFN, **readOpts ).saveToSV( outFN )
[ "def TSV2DotData( inFN, outFN, getio = None ):\n if getio: return dict( depends_on = inFN, creates = outFN )\n DotData( SVPath = inFN ).save( outFN )", "def tsv2npy( inFN, outFN = None, getio = None ):\n if outFN is None: outFN = ReplaceFileExt( inFN, '.npy' )\n if getio: return dict( depends_on = inFN, creat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a TSV file to a DotData dir.
def TSV2DotData( inFN, outFN, getio = None ): if getio: return dict( depends_on = inFN, creates = outFN ) DotData( SVPath = inFN ).save( outFN )
[ "def DotData2TSV( inFN, outFN, readOpts = {}, getio = None ):\n if getio: return dict( depends_on = inFN, creates = outFN )\n DotData( Path = inFN, **readOpts ).saveToSV( outFN )", "def load_from_tsv(tsv_file):\n # Load data from files\n all_examples = list(open(tsv_file, \"r\", encoding='utf-8')....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a TSV file to an .npy file.
def tsv2npy( inFN, outFN = None, getio = None ): if outFN is None: outFN = ReplaceFileExt( inFN, '.npy' ) if getio: return dict( depends_on = inFN, creates = outFN ) z = DotData( SVPath = inFN ) np.save( outFN, z )
[ "def convert_to_npy(filename):\n\n if filename[-4:] == \".txt\":\n filename = filename[:-4] # Removing extension.\n\n print(f\"Converting {filename}.txt to Numpy binary...\")\n t1 = time.time()\n\n data = np.loadtxt(filename + \".txt\", unpack=True)\n np.save(filename + \".npy\", data)\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Normalize data within bins, using previously computed bin means
def normalizeInBins( inData, valCol, binCol, binMin, binMax, binStep, binMeans, commonStd ): binColValues = 1.0 - ( 1.0 - inData[ binCol ].values ) binCount = int( ( binMax - binMin ) / binStep ) bins = np.arange( binMin, binMax, binStep ) means = np.zeros( len( inData ) ) for i in range( binCoun...
[ "def normalize_bins(self):\n self.norm_bin = np.ones(self.nbins)\n for i in range(self.nbins):\n f = lambda z: self.raw_dndz_bin(z, i)\n\n norm = integrate.simps(f(np.linspace(self.z_min,self.z_max,1000)), x=np.linspace(self.z_min,self.z_max,1000))\n\n \n se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Define rules to compute mean and stddev for a given column in the given tsv files
def DefineRulesTo_computeMeanStd( pr, inFNs, colNum, outFN, addRuleArgs = {} ): pr.addRule( commands = ' | '.join(( 'tail -q -n +2 ' + ' '.join( MakeSeq( inFNs ) ), 'cut -f %d' % colNum, 'grep -iv nan', ...
[ "def find_mean_std(subparsers):\n\n subparsers.add_parser(\n \"find_mean_std\",\n help=\"Find mean and std to normalize data\",\n )", "def standardise_stddev(dataframe):\n\n data = dataframe.copy()\n\n for col in data.columns:\n if col == data.columns[-1]:\n preprocess_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Define rules to normalize one column
def DefineRulesTo_normalizeOneColumn( pr, inFN, colName, meanStdFN, outFN, addRuleArgs = {} ): pr.addInvokeRule( invokeFn = normalizeOneColumn, invokeArgs = Dict( 'inFN colName meanStdFN outFN' ), **addRuleArgs )
[ "def normalize_table(self):\n pass", "def _standardize_column_values(dataframe):\n\n # TODO Use None instead of \"-\"; but may affect downstream pipelines that use \"-\" already\n if \"structure.alternate_model\" in dataframe.columns:\n dataframe[\"structure.alternate_model\"].repl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Selects the browser to user according the the argument passed to the behave runner if no one is passed it will run the remote webdriver by default
def select_browser(context): browser = context.config.userdata.get('browser') if not browser: browser = 'remote' if browser.lower() == 'remote': capabilities = { "browserName": "chrome", "browserVersion": "88.0", "selenoid:options": { "enab...
[ "def launch_browser(self):\n self.driver = webdriver.Chrome()", "def driver(request):\n print(\"\\nstart browser for test..\")\n browser_name = request.config.getoption(\"browser_name\")\n if browser_name == \"chrome\":\n options = Options()\n options.add_argument('--no-sandbox')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test to see if the json blob is null, if so, there are no games on specified date, exit.
def test_for_games(): if games_json: pass else: print("There are no NBA games on this day. Life is meaningless.") _exit(1)
[ "def test_get_daily_data_req_empty(self):\n output = self.main.get_daily_data(self.request_empty)\n self.assertIsInstance(\n json.loads(output)[0],\n dict,\n )", "def todays_games(self):\n unplayed_games = []\n live_games = []\n finished_games = []\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the first game of the day's status to see if it has started yet.
def test_first_game_status(game_status, date): if game_status == 1: return False elif game_status == 2: return True else: #status == 3 if date == today: return True else: return False
[ "def test_are_games_in_progress(self):\n pass", "def is_start(self):\n\n com = Competition.query.order_by(Competition.id.desc()).first()\n return com.flag if com else False", "def is_start(self):\n return self._status == EventStatus.START", "def started(self) -> bool:\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes call to AirSim and extract depth and/or RGB images from the UAV's camera. Due to a bug in AirSim an empty array is sometimes returned which is caught in this method.
def get_camera_observation(client, sensor_types=['rgb', 'depth'], max_dist=10, height=64, width=64): requests = [] sensor_idx = {} idx_counter = 0 if 'rgb' in sensor_types: requests.append(airsim.ImageRequest( 'front_center', airsim.ImageType.Scene, pixels_as_float=False, compress=Fa...
[ "def get_camera_image(self):\n upAxisIndex = 2\n camDistance = 500\n pixelWidth = 350\n pixelHeight = 700\n camTargetPos = [0, 80, 0]\n\n far = camDistance\n near = -far\n view_matrix = self.p.computeViewMatrixFromYawPitchRoll(\n camTargetPos, camDi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates 3D positions based on depth map and pixel coordinates. Points with depth larger than max_dist is not included.
def reproject_2d_points(points_2d, depth, max_dist, field_of_view): h, w = depth.shape center_x = w // 2 center_y = h // 2 focal_len = w / (2 * np.tan(field_of_view / 2)) points = [] for u, v in points_2d: x = depth[v, u] if x < max_dist: y = (u - center_x) * x / foca...
[ "def depth_to_local(depth, clip_planes, fov_deg):\n \"\"\" Determine the 'UV' image-space coodinates for each pixel.\n These range from (-1, 1), with the top left pixel at index [0,0] having\n UV coords (-1, 1).\n \"\"\"\n aspect_ratio = (depth.shape[1], depth.shape[0])\n #print (\"aspect ratio\" ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a valid spawn point. If the scene is not basic23 the valid spawn is same as valid target.
def valid_spawn(scene): if scene == 'basic23': r = np.random.rand() if r < 1/5: target_x = 4.2 - np.random.rand() * 1 target_y = 4.7 - np.random.rand() * 9 elif r < 2/5: target_x = 10.2 - np.random.rand() * 1 target_y = 4.7 - np.random.rand() *...
[ "def getSpawnPoint(self):\n return random.choice(self.spawnPoints)", "def rdm_spawn(self):\n\n spawned = False #sprite hasn't spawned\n while not spawned:\n\n self.tile_y = random.randrange(1,14) #randomely sets y postion on grid\n self.tile_x = random.randrange(1,14) #r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a new goal target for the agent to reach. If scene string is None random position relative to current position of the UAV. Else random valid or invalid from predefined areas.
def generate_target(client, max_target_distance, scene=None, invalid_prob=0.0): is_valid = True if scene is not None: r = np.random.rand() if r < invalid_prob: target = invalid_trgt(scene) is_valid = False else: target = valid_trgt(scene) else: ...
[ "def valid_spawn(scene):\n if scene == 'basic23':\n r = np.random.rand()\n if r < 1/5:\n target_x = 4.2 - np.random.rand() * 1\n target_y = 4.7 - np.random.rand() * 9\n elif r < 2/5:\n target_x = 10.2 - np.random.rand() * 1\n target_y = 4.7 - np.ra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate an SPNNeuron class with the given number of gaussians.
def create_spn_neuron(n_gaussians: int): class SPNNeuron(nn.Module): def __init__(self, in_features): """ Initialize the SPNNeuron. Args: in_features: Number of input features. n_mv: Number of different pairwise independence mixtures of t...
[ "def create_network(self, neurons_input=1, neurons_hidden=0):\n\t\t\n\t\tself.rate = 0.01\t#Learning rate\n\t\tself.weights_input = []\n\t\tself.weights_hidden = []\n\t\tself.weights_output = []\n\t\tself.neurons_input = neurons_input\n\t\tself.neurons_hidden = neurons_hidden\n\n\t\tif neurons_input > 1:\n\t\t\tneu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the model for a given tag.
def get_model_by_tag(tag: str, device) -> nn.Module: # Select model if tag.lower() == "spn": model = SPNNet( in_features=28 * 28 * ARGS.n_labels, n_labels=ARGS.n_labels, n_mv=ARGS.n_gaussians, ).to(device) else: raise Exception("Invalid network: %s...
[ "def get_model_by_tag(\n model_name: str,\n tag_name: str,\n tag_value: str,\n aml_workspace: Workspace = None\n) -> AMLModel:\n try:\n # Validate params. cannot be None.\n if model_name is None:\n raise ValueError(\"model_name[:str] is required\")\n if tag_name is Non...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run the MNIST experiment.
def main(): log_file = os.path.join(ARGS.result_dir, ARGS.experiment_name, "log.txt") print("Result dir: %s", ARGS.result_dir) print("Log file: %s", log_file) # Setup logging in base_dir/log.txt setup_logging(level=ARGS.log_level, filename=log_file) logger.info(" -- MNIST Multilabel -- Started ...
[ "def mnist():\n output_header(\"Running the MNIST Classifier Pipeline.\")\n pipeline = MnistPipeline()\n pipeline.execute_pipeline()", "def test_keras_mnist():\n data = fetch('mnist')\n check(data, (60000, 28*28), (10000, 28*28))", "def get_mnist():\n mndata = MNIST('./data/')\n train_x, tr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests whether ``put_value_into`` is working as intended.
def test__put_value_into(): for input_value, defaults, expected_output in ( (None, False, {'value': None}), (None, True, {'value': None}), ('a', False, {'value': 'a'}), (12.6, False, {'value': 12.6}), (6, False, {'value': 6}), ): data = put_value_into(input_value,...
[ "def test__put_type_into(input_value, defaults):\n return put_type_into(input_value, {}, defaults)", "def test_put_value():\n runner = CliRunner()\n testPut = runner.invoke(commands, ['put', 'key1', 'value1'])\n assert testPut.exit_code == 0\n assert testPut.output == '{\"key1\": \"value1\"}\\n\\n'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize the user list.
def __init__(self): self._user_list = [] self._current_user = None
[ "def __init__(\n self, xdata: Optional[XData] = None, name=\"DefaultDict\", appid=\"EZDXF\"\n ):\n self._xlist = XDataUserList(xdata, name, appid)\n self._user_dict: dict[str, Any] = self._parse_xlist()", "def initialize_users_table(self):\n self.execute_queries(queryutils.sql.INIT_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the user that is currently logged in.
def current_user(self, user): self._current_user = user
[ "def set_user(self, user):\n self.user = user", "def set_auth_user(self, user):\n patcher = mock.patch('sndlatr.auth.get_current_user')\n self.get_user_mock = patcher.start()\n self.get_user_mock.return_value = user\n self.addCleanup(patcher.stop)", "def set_new_user(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve the FAM user list.
def user_list(self): return self._user_list
[ "def getUserList(self):\n\n url = self.url.replace('/ClientSettings.do', '/FTPSettings.do', 1)\n self._openPath(url)\n data = self._parseForJsVarPart('tableData0')\n # data['rows'] - list of users\n # There is other information in tableData0, but all we want is the client rows for...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the user list to the value passed in.
def user_list(self, user_list): self._user_list = user_list
[ "def set_AssignedToUser(self, value):\n super(ListIncidentsInputSet, self)._set_input('AssignedToUser', value)", "def modify_users(self, user_list):\n return self.user_manager.modify_objects(user_list)", "def populateList(self):\n self.send(\"USR ,\")", "def update_user_list():\n\n users...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a user to the list.
def _add_user_to_list(self, user): self._user_list.append(user)
[ "def adduser(self, nick):\n # add user\n if not self.users.has_key(nick):\n i = GtkListItem(nick)\n i.show()\n self.list.append_items([i])\n self.users[nick] = i\n if len(self.users) == 1:\n # select the user if it's the first / onl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show the menu for registering a new user to the system.
def _show_registration_menu(self): # register the user self._register_user()
[ "def create_user_form():\n \n\n return render_template(\"/create-user.html\" )", "def show_add_form():\n return render_template(\"add_user.html\")", "def create_new_user(self):\n name = get_param('What is your name?', self.screen)\n address = get_param('What is your street address...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show the actions menu and takes input from the user.
def _show_actions_menu(self): while True: # Check if a user is locked, if so exit out of the actions menu if self.current_user.can_lock_account(): raise UserIsLockedError("Your account is locked. We have logged you out") print(f"\nLogged in as {self.current_u...
[ "def display_menu(self):\n print(\"~~~~~~~~~~~~MENU~~~~~~~~~~~~\")\n self.user_choice = self.utils.ask_choices(self.menu_choices)\n print(\"\")", "def show_main_menu(self):\n\n # Display a welcome message\n print(\"\"\" \n ___ \n /'___\\ ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform an action based on the option selected by a user.
def _perform_action(self, option): if option == 1: self.current_user.view_budgets() elif option == 2: self.current_user.record_transaction() elif option == 3: self.current_user.view_transactions() elif option == 4: self.current_user.view_ba...
[ "def chooseAction(self, choice):\n\n option = 'undefinedMethod'\n\n #If the choice is a valid option, prepare to run the corresponding method\n try:\n option = self._options[choice]\n except Exception:\n pass\n\n #Run the corresponding method. Based on:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Select a user from the user list to log in.
def _login_user(self): # Display list of users and prompt an input print("\n---- Login Menu ----") for user in self.user_list: print(f"{self.user_list.index(user) + 1} - {user}") # Exit if the last option is chosen choice_exit = len(self.user_list) + 1 print(...
[ "def sign_in(self, lb, patients):\n # Check that something is selected\n if lb.curselection() is None or len(lb.curselection()) == 0:\n return\n patient = patients[lb.curselection()[0]]\n self.window.email = patient\n # Swap view to patient\n logging.info(\"Admin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show the main menu with options to register a new user, login, or exit the FAM application.
def show_main_menu(self): # Display a welcome message print(""" ___ /'___\ /\ \__/ __ ___ ___ \ \ ,__\/'__`\ /' __` __`\ \ \ \_/\ \L\.\_/\ \/\ \/\ \ \ \_\\ \__/.\_\ \_\ \_\ \_\\ \/_/ \/__/\/_/\/_...
[ "def _show_registration_menu(self):\n\n # register the user\n self._register_user()", "def main_menu(self) -> None:\n logger.info(\"logged in as GP\")\n while True:\n Parser.print_clean(\"You're currently viewing main menu options for GP {}.\".format(self.username))\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
isAnswer should be true if you are setting the title to a chosen answer
def setTitle(self, newTitle, isAnswer = True): if not self.chosenAnswer: self.title["text"] = newTitle self.backBtn.show() if isAnswer: self.chosenAnswer = True
[ "def test_showanswer_answered(self):\n # Can not see \"Show Answer\" when student answer is wrong\n answer_wrong = CapaFactory.create(\n showanswer=SHOWANSWER.ANSWERED,\n max_attempts=\"1\",\n attempts=\"0\",\n due=self.tomorrow_str,\n correct=Fal...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Translate a named color into rrggbb' format. if 'name' is not a string it is returned unchanged. If 'name' is already in 'rrggbb' format then it is returned unchanged. If 'name' is not in global_color_database then getColor(default, None) is called and that result returned.
def getColor(name: str, default: str = None) -> str: if not isinstance(name, str): return name if name[0] == '#': return name name = name.replace(' ', '').lower().strip() if name in leo_color_database: name2 = leo_color_database[name] return name2 if default: ...
[ "def get_named_color(name: str) -> Optional[LinearColor]:\n blueprint = get_editor_blueprint()\n if blueprint:\n config = blueprint.get_config()\n color_config = config.get(\"colors\", {})\n hex_color = color_config.get(name)\n if hex_color:\n return LinearColor.from_hex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a named color into an (r, g, b) tuple.
def getColorRGB(name: str, default: str = None) -> tuple[int, int, int]: s = getColor(name, default) try: color = int(s[1:3], 16), int(s[3:5], 16), int(s[5:7], 16) except Exception: color = None return color
[ "def colorTuple(c):\n return c.getRgb()", "def name_to_rgb(self, name):\n color = {\n 'R' : (0,0,255),\n 'L' : (0,165,255),\n 'B' : (255,0,0),\n 'F' : (0,255,0),\n 'U' : (255,255,255),\n 'D' : (0,255,255)\n }\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a named color into a cairo color tuple.
def getColorCairo(name: str, default: str = None) -> tuple[float, float, float]: color = getColorRGB(name, default) if color is None: return None try: r, g, b = color return r / 255.0, g / 255.0, b / 255.0 except Exception: return None
[ "def colorTuple(c):\n return c.getRgb()", "def color_to_triple(color: Optional[str] = None) -> Tuple[int, int, int]:\n if color is None:\n r = np.random.randint(0, 0x100)\n g = np.random.randint(0, 0x100)\n b = np.random.randint(0, 0x100)\n return (r, g, b)\n else:\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return lat lon coordinates for an address
def get_lat_lng(address): g = geocoder.google(address) return g.latlng
[ "def address_to_coords(self, address):\n params = urlencode({\"sensor\": \"false\",\n \"address\": address})\n url = \"http://maps.googleapis.com/maps/api/geocode/json?\" + params\n results = json.loads(self.send(url))\n if results['status'] != 'OK':\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add several nodes (eg. a fusion) to the graph.
def add_nodes(self, fusions: List[hmn_fusion.Fusion]) -> None: for fusion in fusions: self.add_node(fusion)
[ "def add_nodes(self, *nodes):\n if isinstance(nodes, tuple):\n for node in nodes:\n self.nodes.add(node)\n else:\n self.nodes.add(nodes)", "def add_edges(self, *nodes):\n for node in nodes:\n self.adjacent.add(node)\n node.adjacent.add(self)", "def add_friend(self,friends):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create consensus nodes from nodes already here in the graph. Return None
def consensus_single(self) -> None: softwares = set( [self.graph.nodes[x]["fusion"].software for x in self.graph.nodes] ) for software in sorted(list(softwares)): g, cons, alone = self._grapp_subgraph(software) nodes = g.nodes nodes_added = [] ...
[ "def create_cluster_branch(self, orphan, line_num): # create cluster\n\n try:\n cluster_id = orphan.flat_value\n except:\n cluster_id = tuple([x.flat_value for x in orphan])\n\n # create a node instance and add it to the graph\n orphan_node = Node(cluster_id, clust...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot graph to a file.
def to_plot(self, path: str) -> None: plt.subplot() nx.draw(self.graph, with_labels=True, font_weight="bold") plt.savefig(path)
[ "def uti_data_file_plot(_fname, _read_labels=1, _e=0, _x=0, _y=0, _graphs_joined=True):\n #if '_backend' not in locals(): uti_plot_init() #?\n _backend.uti_data_file_plot(_fname, _read_labels, _e, _x, _y, _graphs_joined)", "def draw_graph(self, filename: str, scale_x=10, scale_y=10):\n node_dict = se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recursively discover all disciplines on studyportal.
def discover_disciplines(session, url, section_id='DisciplineSpotlight', parent=None): # Parse the HTML for this URL r = session.get(url) r.raise_for_status() soup = BeautifulSoup(r.text, features="lxml") # Extract discipline metadata from the indicated section disciplines = [] section = sou...
[ "def getDisciplines(self):\r\n return self.__dis", "def allDisciplines(self):\n auxList = []\n auxD = []\n for item in self.gradesList:\n if item.getGrValue() != \"none\" and item.getDiscId() not in auxD:\n auxList.append(AllDisciplines(item.getDiscId(), self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Discover degree level counts by discipline.
def discover_level_count(session, discipline_id): r = session.get(SEARCH_FACETS_URL, params={"q": f"di-{discipline_id}", "facets": '["lv"]'}) r.raise_for_status() for degree_level, count in r.json()['lv'].items(): yield degree_level, count
[ "def test_portals_id_designs_count_get(self):\n pass", "def test_portals_id_designs_nk_members_count_get(self):\n pass", "def test_portals_id_designs_nk_design_members_count_get(self):\n pass", "def test_portals_id_designs_nk_comments_count_get(self):\n pass", "def test_portals_i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Hidden method for discovering courses on studyportal.
def _discover_courses(session, di, lvl, total): query_string = '|'.join((f'di-{di}', # Discipline 'en-3002', # Don't know what this is, could be a mechanism for rate limiting f'lv-{lvl}', # Degree level 'tc-EUR', # Curr...
[ "def api_courses_get():\n\tpass", "def get_courses(self):\n return self.q(css='ul.listing-courses .course-item')", "def search_courses(session):\n page = session.get(URL)\n bs = BeautifulSoup(page.text, 'lxml')\n colleges = get_college(bs)\n for college in colleges:\n terms = get_term(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write to disk under the path di/lvl/dilvlcount.json
def flush(courses, di, lvl, count): path = f'{DATA_PATH}/{di}/{lvl}/' if not os.path.exists(path): os.makedirs(path) write_json(courses[(di, lvl)], f'{path}/{di}-{lvl}-{count}.json')
[ "def write_counters_to_file(self):\n with open(os.path.join(self.cwd,'data/others/counters.txt'),'w') as outputfile:\n json.dump(CounterValues().last_counter,outputfile)\n return True \n return False", "def write(self, parsed_data):\n file_path = self.data_dir / 'vic_sta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
An implementation of the local synthetic instances (LSI) method for oversampling a dataset.
def lsi(x, y, params=None): assert isinstance(x, np.ndarray), 'Input x must be a Numpy array' assert isinstance(y, np.ndarray), 'Input y must by a Numpy array' n = x.shape[0] max_num_weighted_samples = params.get('max_num_weighted_samples', np.inf) num_synthetic_instances = params.get('num_syn...
[ "def lsi(\n adata: anndata.AnnData, n_components: int = 20,\n use_highly_variable: Optional[bool] = None, **kwargs\n) -> None:\n if use_highly_variable is None:\n use_highly_variable = \"highly_variable\" in adata.var\n adata_use = adata[:, adata.var[\"highly_variable\"]] if use_highly_va...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write Recaman's sequence to a text file.
def write_sequence(filename, num): with open(filename, mode='wt', encoding='utf-8') as f: f.writelines(f"{r}\n" for r in islice(sequence(), num + 1))
[ "def write_fasta( filename, seq_name, sequence ):\n with FastaWriter( filename ) as writer:\n record = FastaRecord( seq_name, sequence )\n writer.writeRecord( record )", "def write_genome_sequence_toFile(genomeId, genomeSequence = \"\"):\n\ttext_file = open(str(genomeId)+\".txt\", \"w\")\n\tif ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load RabbitMQ config from VOLTTRON_HOME
def load_rmq_config(self, volttron_home=None): """Loads the config file if the path exists.""" with open(self.volttron_rmq_config, 'r') as yaml_file: self.config_opts = yaml.safe_load(yaml_file) if self.config_opts.get('rmq-home'): self.config_opts['rmq-h...
[ "def read_galaxy_amqp_config(galaxy_config, base_dir):\n galaxy_config = add_full_path(galaxy_config, base_dir)\n config = ConfigParser.ConfigParser()\n config.read(galaxy_config)\n amqp_config = {}\n for option in config.options(\"galaxy_amqp\"):\n amqp_config[option] = config.get(\"galaxy_am...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write new config options into $VOLTTRON_HOME/rabbitmq_config.yml
def write_rmq_config(self, volttron_home=None): try: with open(self.volttron_rmq_config, 'w') as \ yaml_file: yaml.dump(self.config_opts, yaml_file, default_flow_style=False) # Explicitly give read access to group and others. RMQ user and #...
[ "def _create_rabbitmq_config(rmq_config, setup_type):\n\n if setup_type == 'single' or setup_type == 'all':\n if os.path.exists(rmq_config.volttron_rmq_config):\n prompt = \"rabbitmq_config.yml exists in {} Do you wish to \" \\\n \"use this file to configure the instance\".f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Download ZIP archive from repository release.
async def download_zip(repository, validate): contents = [] try: for release in repository.releases.objects: repository.logger.info( f"ref: {repository.ref} --- tag: {release.tag_name}" ) if release.tag_name == repository.ref.split("/")[1]: ...
[ "def _download( self ):\n self._system.download_file(\"https://github.com/mastbaum/avalanche/tarball/\" + self._tar_name)", "def repo_downloads(repo, releases, tags):\n downloads = {}\n # for release in repo.iter_releases():\n # name = release.tag_name\n for vers, release in releases.items(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert site to key. `state` is added to end of key.
def site_to_key(site, state=""): if type(state) != str: raise Exception("`state` must be a string.") return ",".join([str(l) for l in site]) + state
[ "def generate_state_key(self, state, role):\n\n pass", "def state_key():\n return jsonify(key=redis.get('state:key').decode('utf8'))", "def create_state_id(self):\n for key, value in config.fips_dict.iteritems():\n if key == self.state.lower():\n state_num = value\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List the possible epistatic coefficients (as label form) for a binary genotype up to a given order.
def genotype_coeffs(genotype, order=None): if order is None: order = len(genotype) length = len(genotype) mutations = [i + 1 for i in range(length) if genotype[i] == "1"] params = [[0]] for o in range(1, order + 1): params += [list(z) for z in it.combinations(mutations, o)] retur...
[ "def CI(orders, numbers_of_states):\n\texcite_strings = []\n\tfor n in orders:\n\t\tif n>len(numbers_of_states): raise Exception(\"CI excitation order exceeds available number of molecules\")\n\t\texcite_strings += _n_tuple_substitutions(n, numbers_of_states)\n\treturn excite_strings", "def get_order_str(self):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Dictionary that maps attr1 to attr2.
def map(self, attr1, attr2): return dict(zip(getattr(self, attr1), getattr(self, attr2)))
[ "def get_attr_map():\n custom_attributes = get_custom_attrs()\n standard_attributes = get_standard_attrs()\n mapping = {}\n for attr in custom_attributes.keys():\n mapping[f'custom:{attr}'] = attr\n mapping.update(standard_attributes)\n return mapping", "def _get_edge_attributes(self, lin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }