query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Bust our cache for a given type, can bust multiple caches
def bust_cache(type, user_pk): bust_keys = BUST_CACHES[type] keys = [CACHE_TYPES[k] % user_pk for k in bust_keys] cache.delete_many(keys)
[ "def applyCache(self, path, type):\n\t\t\n\t\treturn None", "def _clear_type_cache():\n\tpass", "def dynCache():\n pass", "def gen_cache(self, key, value=None, type=Cache):\n if type == MultiHeadAttention.StaticCache: # static_kv\n k, v = self.compute_kv(key, value)\n return s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of all users who favour the given recipe
def favorers(self, recipe): #key = cache_key('following', user.pk) #following = cache.get(key) #if following is None: qs = Favorite.objects.filter(recipe=recipe).all() favorers = [u.favorer for u in qs] #cache.set(key, following) return favorers
[ "def get_queryset(self):\n queryset = super().get_queryset()\n all_favorites = self.request.user.favorites.all().values('recipe')\n return queryset.filter(id__in=all_favorites)", "def get_favorited_recyclers(user_id):\n\n return FavRecycler.query.filter(\n FavRecycler.user_id == use...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create 'favorer' favorites 'recipe' relationship
def add_favorite(self, favorer, recipe): relation, created = Favorite.objects.get_or_create(favorer=favorer, recipe=recipe) if created is False: raise AlreadyExistsError("User '%s' already favors '%s'" % (favorer, recipe)) recipient = User.objects.get(id=recipe.author_id) f...
[ "def create_favorite(user_id, fish_id):\n favorite = Favorite(user_id = user_id, \n fish_id = fish_id)\n\n db.session.add(favorite)\n db.session.commit()\n return favorite", "def post(self, request, format=None):\n recipe_id = request.data['id']\n user = self.request.user,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove 'favorer' favorites 'recipe' relationship
def remove_favorite(self, favorer, recipe): try: rel = Favorite.objects.get(favorer=favorer, recipe=recipe) favorite_removed.send(sender=rel, favorer=rel.favorer) favorer_removed.send(sender=rel, recipee=rel.recipe) favorite_recipe_removed.send(sender=rel, favorer...
[ "def delete_relationship(self, rel_id) -> Relationship:", "def recipe_no_id():\n return remove_id(recipe())", "def remove_pizza_from_menu(self, pizza: Pizza):\n if pizza in self.recipes:\n self.recipes.remove(pizza)\n return", "def remove_relationship(self, relationship):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a like for a spesific user
def add_like(self, liker, recipe): like, created = Like.objects.get_or_create(liker=liker, recipe=recipe) if created is False: raise AlreadyExistsError("User '%s' already likes '%s'" % (liker, recipe)) recipient = User.objects.get(id=recipe.author_id) like_created.send(sende...
[ "def add_like(obj, user):\n obj_type = ContentType.objects.get_for_model(obj)\n with atomic():\n like, is_created = Like.objects.get_or_create(\n content_type=obj_type, object_id=obj.id, user=user\n )\n\n return like", "def test_user_add_like_message(self):\n\n with se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Did user rate the recipe? Smartly uses caches if exists
def rated(self, rater, recipe): try: Rating.objects.get(rater=rater, recipe=recipe) return True except Like.DoesNotExist: return False
[ "def rateThisMethod(request):\n try:\n profileId = ndb.Key(urlsafe=getattr(request, 'profileId'))\n except Exception:\n print \"Invalid profileId\"\n return Response(response=1, description=\"Invalid profileId\")\n try:\n noteBookId = ndb.Key(urlsafe=getattr(request, 'noteBookId...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A view that renders the cart contents page
def view_cart(request): return render(request, 'cart/cart.html')
[ "def cart():\r\n cart_objects = current_user.cart_objects\r\n return render_template(\"cart.html\" , cart_objects = cart_objects)", "def cart(request):\n\n return {'cart': Cart(request)}", "def show_cart():\n session = connect()\n try:\n user_id = current_user.id\n address = get_add...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finalises the compressed version of the spreadsheet. If you aren't using the context manager ('with' statement, you must call this manually, it is not triggered automatically like on a file object.
def close(self): if self.default_sheet is not None: self.default_sheet.finalizeFormat(1) sheet_index = 2 for finalSheet in self.sheets: finalSheet.finalizeFormat(sheet_index) sheet_index += 1 xmlContent = self.dom.toprettyxml(encoding="utf-8") ...
[ "def close(self):\n self.compressed_file.close()", "def _finalize_zip(self):\n del self.zip_file\n if self.buffer:\n self.buffer.flush()", "def __decompress_archive(self):\n self.decompress_path = self.cwd.joinpath(PathVariables.SRC__DECOMPRESSED)\n self.log.debug(\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write a row of cells into the default sheet of the spreadsheet.
def writerow(self, cells): if self.default_sheet is None: self.default_sheet = self.new_sheet(first_row_bold = self.first_row_bold) self.default_sheet.writerow(cells)
[ "def write(self, x, y, data, format=None):\n if format:\n self.sheet.write(y, x, data, self._formats[format])\n else:\n self.sheet.write(y, x, data)", "def write_to_sheet1(data: list):\r\n range = config.get(\"sheet1_range\")\r\n print(\"\\n\\nDo not worry if program appe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an ODSWriter object.
def writer(odsfile, *args, **kwargs): return ODSWriter(odsfile, *args, **kwargs)
[ "def writer_object(cls):\n # Assume this writer is a built-in.\n return writers.get_writer_class(cls.name)()", "def create_simple_writer(outputDef, defaultOutput, outputFormat, fieldNames, compress=True, valueClassMappings=None, datasetMetaProps=None, fieldMetaProps=None):\n\n if not outputDef:\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Client should raise an exception if it is missing arguments.
def test_client_missing_args(self): self.assertRaises(InvalidUsage, Client, instance="test") self.assertRaises(InvalidUsage, Client, instance="test", user="foo") self.assertRaises(InvalidUsage, Client, instance="test", password="foo")
[ "def test_client_incompatible_args(self):\n self.assertRaises(\n InvalidUsage,\n Client,\n instance=\"test\",\n user=\"foo\",\n password=\"bar\",\n session=\"foobar\",\n )", "def test_client_invalid_raise_on_empty(self):\n self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Client should raise an exception if it receives incompatible args.
def test_client_incompatible_args(self): self.assertRaises( InvalidUsage, Client, instance="test", user="foo", password="bar", session="foobar", )
[ "def _handle_args(self, *args):\n pass", "def check_args(self, *args):\n if self._nb_args >= 0 and len(args) != self._nb_args:\n raise ValueError(\n \"Incorrect number of parameters specified. \"\n \"Got {}, expected {}.\".format(len(args), self._nb_args)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Should be able to create a client given a requests session object.
def test_client_with_session(self): session = requests.Session() Client("snow.example.com", session=session)
[ "def __sessionmaker():\n\tsession = requests.ClientSession()\n\treturn session", "def get_client(self, args):\n try:\n # Load existing session, so as to keep current dir etc.\n with open(self.session_path, \"rb\") as fhandle:\n client = pickle.load(fhandle)\n ex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Client should raise an exception if it receives both host and instance
def test_client_with_host_and_instance(self): self.assertRaises( InvalidUsage, Client, instance="test", host="test", user="foo", password="bar", )
[ "def test_thaw_host_with_invalid_host(self):\n self.assertRaises(lib_exc.BadRequest,\n self.admin_volume_services_client.thaw_host,\n host='invalid_host')", "def test_freeze_host_with_invalid_host(self):\n self.assertRaises(lib_exc.BadRequest,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Client host property should match host passed to constructor
def test_client_host(self): host = "123.123.123.123" c = Client(user="foo", password="foo", host=host) self.assertEqual(c.host, host)
[ "def test_clientHost(self, get=\"getHost\"):\n return self._hostpeertest(\"getHost\", False)", "def test_get_remote_host_properties(self):\n pass", "def test_add_remote_host(self):\n pass", "def SetHost(self, host):\n self._host = host", "def test_serverHost(self):\n return se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Client instance property should match instance passed to constructor
def test_client_instance(self): instance = "foo" c = Client(user="foo", password="foo", instance=instance) self.assertEqual(c.instance, instance)
[ "def test_client_with_host_and_instance(self):\n self.assertRaises(\n InvalidUsage,\n Client,\n instance=\"test\",\n host=\"test\",\n user=\"foo\",\n password=\"bar\",\n )", "def example_property(self):", "def __init__(self, client_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Client should raise an exception if `request_params` is of an invalid type
def test_client_invalid_request_params(self): self.assertRaises( InvalidUsage, Client, instance="test", user="foo", password="foo", request_params="a string", ) self.assertRaises( InvalidUsage, Client...
[ "def test_client_valid_request_params(self):\n params = {\"foo\": \"bar\"}\n c = Client(instance=\"test\", user=\"foo\", password=\"foo\", request_params=params)\n self.assertEqual(c.request_params, params)", "def test_params_type_check(test_endpoint):\n\n with pytest.raises(ValueError):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Invalid use_ssl type should raise InvalidUsage
def test_client_invalid_use_ssl(self): self.assertRaises( InvalidUsage, Client, instance="test", user="foo", password="foo", use_ssl="a string", ) self.assertRaises( InvalidUsage, Client, instance="test", user="f...
[ "def test_tlsProtocolsNoMethodWithMaximum(self):\n with self.assertRaises(TypeError) as e:\n sslverify.OpenSSLCertificateOptions(\n privateKey=self.sKey,\n certificate=self.sCert,\n method=SSL.SSLv23_METHOD,\n lowerMaximumSecurityTo=sslve...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Nonbool type to raise_on_empty should raise InvalidUsage
def test_client_invalid_raise_on_empty(self): self.assertRaises( InvalidUsage, Client, instance="test", user="foo", password="foo", raise_on_empty=0, ) self.assertRaises( InvalidUsage, Client, ...
[ "def validate(self, *args):\n pass", "def ensure_valid(self):\n self.op_info.ensure_valid()", "def validate_extended(self):", "def test_value_if_not_asked__raises_exception_without_should_ask():\n with pytest.raises(\n ValueError,\n match=\"You should either remove value_if_not_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Client `request_params` property should match what was passed as an argument
def test_client_valid_request_params(self): params = {"foo": "bar"} c = Client(instance="test", user="foo", password="foo", request_params=params) self.assertEqual(c.request_params, params)
[ "def get_params_from_request(self):\n self._create_moe_log_line(\n type='request',\n content=self.request.json_body,\n )\n\n return self.request_schema.deserialize(self.request.json_body)", "def test_client_invalid_request_params(self):\n self.asse...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads in the text file f which contains one sentence per line.
def readFileToCorpus(f): if os.path.isfile(f): file = open(f, "r") # open the input file in read-only mode i = 0 # this is just a counter to keep track of the sentence numbers corpus = [] # this will become a list of sentences print("Reading file ", f) for line in file: i += 1 sentence = line.split() #...
[ "def load_into_sentence(file_name):\n if not os.path.exists(file_name):\n raise ValueError(\"The file {0} does not exist!\".format(file_name))\n with open(file_name,'r') as fp:\n lines = fp.readlines()\n return ''.join(lines).replace(\"\\n\",' ').decode('utf-8')", "def read(self):\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pull data for monitoring.
def pull_data(self):
[ "def _download_data(self):\n self.raw_data = requests.get(self.api_address).json()\n self.age = datetime.now()", "def poll(self):\n data = self.get_data()\n if data:\n self.add_metrics(data)", "def load_new_data(self):\n r = requests.get(self.STATUS_URL)\n ra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checks the next available space in a column and returns its tuple
def next_avail_space(column): for row in range (1, 7): if board_config[(row, column)] == ' ': return (row, column) else: pass return None #User tries to put chip in a full column
[ "def _next(self, cell):\n row, col = cell\n if col == self.size - 1:\n row, col = row + 1, 0\n else:\n col += 1\n return row, col", "def first_free_position(self):\n\n for row in self._table:\n for col in row:\n if col == -1:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get interest by id
def get_by_id(interest_id: int): interest = Interest.query.get(interest_id) if interest is None: raise NotFound(f"Interest id {interest_id} not found") return interest
[ "def get_by_name(name: str):\n interest = Interest.query.filter(Interest.name == name).first()\n if interest is None:\n raise NotFound(f\"Interest name {name} not found\")\n\n return interest", "def retrieve(self, id):\n _, _, invoice = self.http_client.get(\"/invoices/{id}\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get interest by name
def get_by_name(name: str): interest = Interest.query.filter(Interest.name == name).first() if interest is None: raise NotFound(f"Interest name {name} not found") return interest
[ "def get_by_id(interest_id: int):\n interest = Interest.query.get(interest_id)\n if interest is None:\n raise NotFound(f\"Interest id {interest_id} not found\")\n\n return interest", "def investigation_by_name(self, name):\n endpoint = \"investigationsearch/\"\n r = s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save changes to db
def save(self): db.session.commit()
[ "def save_and_flush(self):\n self.save()\n self.flush()", "def save(self):\n self.session.add(self)\n self.commit_session()", "def commit(self):\n\t\tself.dbConnection.commit()", "def save(self):\n\n # Iterate over each new attribute (check if changed) and validate using Fie...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Models star as an array of uniformly distributed point sources
def generatePoints(starR): if starR == 0: # model as point source return np.array([(0,0)]) n = 5 # number of points to model 1D radius of star pairs = np.array([item for item in product(np.linspace(-starR, starR, 2*n-1), repeat=2) if hypot(item[0], item[1]) <= starR]) return pairs
[ "def starmodel(self,star=None,pars=None):\n\n psf = self.psf.copy()\n if pars is not None:\n psf._params = pars\n \n model = []\n if star is None:\n star = np.arange(self.nstars)\n else:\n star = [star]\n\n for i in star:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates transverse velocity of KBO
def vT(a, vE): # a is distance to KBO, in AU # vE is Earth's orbital speed, in m/s # returns vT, transverse KBO velocity, in m/s return vE * ( 1 - (1./a)**(1/2.))
[ "def velocity(slowness):\n return 0.3048 / ((slowness * (10**(-6))))", "def v(self):\n return self.velocity + self.dv()", "def velocity(self, t):\n pass", "def velocity(obs0, obs1, r0, r1):\n\tsigma = G/(np.linalg.norm(r0)**3)\n\tv0 = (r1 - vel_f(obs1.JD, obs0.JD, sigma, 0)*r0)/vel_g(obs1.JD,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Rounds x to the nearest odd integer
def roundOdd(x): x = ceil(x) if x % 2 == 0: return int(x-1) return int(x)
[ "def iround(x):\n return int(round(x))", "def round_even(number):\n rounded = int(round(number, 0))\n return rounded+1 if number % .5 == 0 and rounded % 2 != 0 else rounded", "def round_to_half(num):\n return round(num * 2) / 2.0", "def intround(n):\r\n return int(round(n))", "def suc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the chromosome where the given path lies.
def get_path_chromosome(pathid, coord_dir='tileid_hg19_split_by_path/'): with open(coord_dir + pathid + '.csv') as f: first_line = f.readline() # Example line: # 000.00.000.000,hg19 chr1 0-24 10534 # Entry 1 is chromosome. chromosome = first_line.split(' ')[1] return chromo...
[ "def getChromosomePath(individual):\n path = [start_cell]\n for Move in [MOVES[gene] for gene in individual]:\n path.append(Move.apply(path[-1])) #append each move to the current Position\n if path[-1] == end_cell : return path #current Position = end cell\n return path", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Also, use GPIO functions to set the row pins as outputs and the column pins as inputs.
def setup(self): for pin in self.row_pins: GPIO.setup(pin, GPIO.OUT) for pin in self.col_pins: GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
[ "def setup_pins():\n\n # Use Board Pin numbers\n gpio.setmode(gpio.BOARD)\n\n # All pins are pulled down as we take to GND on close.\n gpio.setup(LEFT_A, gpio.IN, pull_up_down=gpio.PUD_UP)\n gpio.setup(LEFT_B, gpio.IN, pull_up_down=gpio.PUD_UP)\n gpio.setup(LEFT_PUSH, gpio.IN, pull_up_down=gpio.PU...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
trawl through a list of claims and return a width and height of fabric big enough to fit all of them
def find_fabric_dimensions(claimlist): cur_width = cur_height = 0 for claim in claimlist: cur_width = max(cur_width, claim.x + claim.width) cur_height = max(cur_height, claim.y + claim.height) return cur_width, cur_height
[ "def count_square_claims( input_list ):\n fabric_claims = defaultdict( int )\n\n for line in input_list:\n ( _, x_coord, y_coord, width, height ) = parse_line( line )\n\n for xindex in range( x_coord, x_coord + width ):\n for yindex in range( y_coord, y_coord + height ):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return an empty 2d array width x height filled with blank char, with some extra padding
def build_empty_array(width, height, blank): array = [] for _ in range(width): array.append([blank] * height) return array
[ "def get_empty_cell(self):\n return ' ' * self.width", "def padded_shapes(self):\n return ([None], [None])", "def _get_empty(self):\n empty_cells = []\n row_i = 0\n column_i = 0\n\n for row in self._grid:\n column_i = 0\n for column in row:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
map each claim in claimlist to fabric array, with claim id in claimed space overlap_char and for overlapping claims
def populate_fabric_array(fabric, claimlist, overlap_char): overlap_count = 0 good_claims = set() for claim in claimlist: good_claims.add(claim.id) for claim in claimlist: for offset_x in range(claim.width): for offset_y in range(claim.height): x = claim.x + ...
[ "def count_square_claims( input_list ):\n fabric_claims = defaultdict( int )\n\n for line in input_list:\n ( _, x_coord, y_coord, width, height ) = parse_line( line )\n\n for xindex in range( x_coord, x_coord + width ):\n for yindex in range( y_coord, y_coord + height ):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pushes the given connection on the stack.
def push_connection(redis): funclog() _connection_stack.push(patch_connection(redis))
[ "def push_connection(connection):\n _connection_stack.push(connection)", "def use_connection(connection):\n assert len(_connection_stack) <= 1, \\\n 'You should not mix Connection contexts with use_connection().'\n release_local(_connection_stack)\n push_connection(connection)", "def push(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pops the topmost connection from the stack.
def pop_connection(): funclog() return _connection_stack.pop()
[ "def pop(self):\r\n if self.is_empty():\r\n raise IndexError(\"Tried to remove the top of an empty stack\")\r\n self.top = self.top.next_node\r\n self.size -=1", "def pop(self):\n if self.stack != []:\n self.stack.pop()\n return self", "def remove_from_st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the current Redis connection (i.e. the topmost on the connection stack).
def get_current_connection(): funclog() return _connection_stack.top
[ "def connection(self):\n return self.get_app().extensions['redis'][self.config_prefix]", "def get_redis_connection():\n return redis.StrictRedis(host=C.redis_host, port=C.redis_port, db=C.redis_task_db)", "def getRecurrentConnection(self):\n return self.recurrentConnection", "def _get_redis_con...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes the vdW radii of each atom in a molecule
def compute_vdw_radii( molecule: "Molecule", radii_type: VdWRadiiType = VdWRadiiType.Bondi ) -> unit.Quantity: if radii_type == VdWRadiiType.Bondi: _BONDI_RADII = { "H": 1.20, "C": 1.70, "N": 1.55, "O": 1.52, "F": 1.47, "P": 1.80, ...
[ "def svr(D):\n m = D.shape[0]\n r = ones(m-1)\n for i in xrange(m-1):\n v = svd(D[i:i+2,:],compute_uv=False)\n r[i] = v[0]/v[1]\n \n return r", "def get_radii(self, particles):\n num_atoms = particles.get_num_atoms()\n radii = np.zeros((num_atoms+1,), dtype=np.float64)\n\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns whether each atom and bond in a molecule is aromatic or not according to the MDL aromaticity model.
def apply_mdl_aromaticity_model( molecule: "Molecule", ) -> Tuple[Dict[int, bool], Dict[Tuple[int, int], bool]]: try: return _oe_apply_mdl_aromaticity_model(molecule) except ( ModuleNotFoundError, MissingOptionalDependencyError, ToolkitUnavailableException, ): re...
[ "def test_aromaticity_perception_azulene(self):\n mol = Molecule(smiles='c1cccc2cccc2c1')\n aromatic_atoms, aromatic_bonds = mol.get_aromatic_rings()\n self.assertEqual(len(aromatic_atoms), 0)\n self.assertEqual(len(aromatic_bonds), 0)", "def test_aromatic_naphthalene(self):\n m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Lookup key in collection; if not found return if_none (or None)
def lookup(collection, key, if_none=None): if key in collection: return collection[key] else: return if_none
[ "def find_in_collection_by_name(self, collection_or_key, name):\n if type(collection_or_key) is str:\n collection_or_key = self.graph.get_collection(collection_or_key)\n for v in collection_or_key:\n if v.name == name:\n return v\n name += ':0'\n for ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
assertAlmostEqual checks float values
def test_assert_almost_equal(self): self.assertAlmostEqual(1.0, 1.00000001) #self.assertAlmostEqual(1.0, 1.00000009) self.assertAlmostEqual(1.0, 1.0000001, places=6) self.assertAlmostEqual(1.0, 1.001, delta=.01) #self.assertAlmostEqual(1.0, 1.1, msg="Not close enough.")
[ "def float_equal(a, b):\n try:\n return math.fabs(a - b) < CMP_THR\n except TypeError:\n return False", "def assertFloatsEqual(testCase, lhs, rhs, **kwargs):\n return assertFloatsAlmostEqual(testCase, lhs, rhs, rtol=0, atol=0, **kwargs)", "def _float_equal(fn1, fn2, epsilon=1e-8):\n fn...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
assertNotAlmostEqual is (not assertAlmostEqual)
def test_assert_not_almost_equal(self): self.assertNotAlmostEqual(3.1, 3.3)
[ "def test_assert_almost_equal(self):\n self.assertAlmostEqual(1.0, 1.00000001)\n #self.assertAlmostEqual(1.0, 1.00000009)\n self.assertAlmostEqual(1.0, 1.0000001, places=6)\n self.assertAlmostEqual(1.0, 1.001, delta=.01)\n #self.assertAlmostEqual(1.0, 1.1, msg=\"Not close enough.\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sometimes strategy parameters are learned along side brain parameters. In these caeses the strategy parameters need to be stripped from the population before sending the brain genomes to the evaluation.
def strip_strategy_from_population(population, mutation_learned, strategy_parameter_per_gene=False): if len(population) == 0: return population if mutation_learned: if strategy_parameter_per_gene: half = len(np.array(population)[0]) // 2 return lis...
[ "def reset_parameters(self) -> None:\n if hasattr(self.hopfield, r'reset_parameters'):\n self.hopfield.reset_parameters()\n\n # Explicitly initialise pooling weights.\n nn.init.normal_(self.pooling_weights, mean=0.0, std=0.02)", "def disableStrategies():\n stratDictionary = read...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract limit clause from SQL statement.
def _extract_limit_from_query(statement: TokenList) -> Optional[int]: idx, _ = statement.token_next_by(m=(Keyword, "LIMIT")) if idx is not None: _, token = statement.token_next(idx=idx) if token: if isinstance(token, IdentifierList): # In case of "LIMIT <offset>, <lim...
[ "def add_sql_limit(sql, limit):\n # strip off trialing whitespaces and add limit\n sql = sql.rstrip()\n if sql.endswith(';'):\n sql = sql[:-1]\n sql_with_limit = sql + ' LIMIT %s, %s;' % limit\n return sql_with_limit", "def _make_limit_clause(limit: int) -> psql.Composed:\n if limit !...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract top clause value from SQL statement.
def extract_top_from_query( statement: TokenList, top_keywords: Set[str] ) -> Optional[int]: str_statement = str(statement) str_statement = str_statement.replace("\n", " ").replace("\r", "") token = str_statement.rstrip().split(" ") token = [part for part in token if part] top = None for i,...
[ "def _extract_limit_from_query(statement: TokenList) -> Optional[int]:\n idx, _ = statement.token_next_by(m=(Keyword, \"LIMIT\"))\n if idx is not None:\n _, token = statement.token_next(idx=idx)\n if token:\n if isinstance(token, IdentifierList):\n # In case of \"LIMIT ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse the SQL and return the CTE and rest of the block to the caller
def get_cte_remainder_query(sql: str) -> Tuple[Optional[str], str]: cte: Optional[str] = None remainder = sql stmt = sqlparse.parse(sql)[0] # The first meaningful token for CTE will be with WITH idx, token = stmt.token_next(-1, skip_ws=True, skip_cm=True) if not (token and token.ttype == CTE): ...
[ "def parse_query(self, sql):\n return process_sql.get_sql(self.spider_schema, sql)", "def parse_select(stream):\n # first apply ()\n stream = group(stream, [Parenthesis])\n \n # then split in select from where for first one\n stream = group_select(stream)\n \n return stream", "def pa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Strips comments from a SQL statement, does a simple test first to avoid always instantiating the expensive ParsedQuery constructor This is useful for engines that don't support comments
def strip_comments_from_sql(statement: str) -> str: return ParsedQuery(statement).strip_comments() if "--" in statement else statement
[ "def CleanSQL(self, sql):\n sql = self.cleanComments(sql)\n\n return sql", "def clean_kql_query(query_string: str) -> str:\n remove_comments = re.sub(r\"(//[^\\\"\\'\\n]+)\", \" \", query_string, re.MULTILINE).strip()\n # get rid of newlines and returns\n return re.sub(r\"(\\s*\\n\\s*)\", \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of SQL statements as strings, stripped
def get_statements(self) -> List[str]: statements = [] for statement in self._parsed: if statement: sql = str(statement).strip(" \n;\t") if sql: statements.append(sql) return statements
[ "def format_sql_statements(sql_statements):\n sql_statements = sql_statements.strip()\n # Create a list of SQL statements with delimiter as \";\"\n sql_statements = sqlparse.split(SQL_STMNTS)\n # print \"sqls\",sql_statements\n\n for i, sql_statement in enumerate(sql_statements):\n sql_stateme...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the query with the specified limit. Does not change the underlying query if user did not apply the limit, otherwise replaces the limit with the lower value between existing limit in the query and new_limit.
def set_or_update_query_limit(self, new_limit: int, force: bool = False) -> str: if not self._limit: return f"{self.stripped()}\nLIMIT {new_limit}" limit_pos = None statement = self._parsed[0] # Add all items to before_str until there is a limit for pos, item in enume...
[ "def add_sql_limit(sql, limit):\n # strip off trialing whitespaces and add limit\n sql = sql.rstrip()\n if sql.endswith(';'):\n sql = sql[:-1]\n sql_with_limit = sql + ' LIMIT %s, %s;' % limit\n return sql_with_limit", "def setLimit(self, limit):\n self.limit = limit\n return s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return all the dependencies from a SQL sql_text.
def extract_table_references( sql_text: str, sqla_dialect: str, show_warning: bool = True ) -> Set["Table"]: dialect = "generic" tree = None if sqloxide_parse: for dialect, sqla_dialects in SQLOXITE_DIALECTS.items(): if sqla_dialect in sqla_dialects: break sq...
[ "def _split_sql_script(self, sql):\n lines = list()\n queries = sql.split(';')\n queries = [self._remove_comments(q) for q in queries if len(q.strip()) > 0]\n return queries", "def _get_dependencies(pkgbuild):\n\n print(f\"Getting all dependencies within PKGBUILD file\")\n depend...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests for ResourceSet Currently does not test for ResourceInfo as it is not implemented in the wrapper yet Otherwise this is a direct manual port of the cxx test
def RSTest(): status = 0 result = False n = 0 resourceSet = smtk.common.ResourceSet() system1 = smtk.attribute.System.New() result = resourceSet.addResource(system1, "system1", "", smtk.common.ResourceSet.TEMPLATE); n = resourceSet.numberOfResources() if result == False: print...
[ "def test_vmware_service_resources_management_get(self):\n pass", "def test_get_run_resources(self):\n pass", "def test_load_response_descriptor_tag_sets_tag_set_tag_set_resource_spaces(self):\n pass", "def test_get_resources_success(self):\n resources = self.template.get_resources...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create and compile TeX file to represent CTW tree.
def drawCTWTree(root, filename='ctw_tree', show_probs=False): node = root file = open('{}.tex'.format(filename), 'w') # Write header file.writelines( ["\\documentclass[tikz,border=10pt]{standalone}\n", "\\usepackage[linguistics]{forest}\n", "\\begin{document}\n", "\\begin{forest}\n", "for tree={grow=west}...
[ "def drawCTMTree(root, filename='ctm_tree', show_probs=False):\n\tnode = root\n\tfile = open('{}.tex'.format(filename), 'w')\n\t# Write header\n\tfile.writelines(\n\t\t[\"\\\\documentclass[tikz,border=10pt]{standalone}\\n\",\n\t\t\"\\\\usepackage[linguistics]{forest}\\n\",\n\t\t\"\\\\begin{document}\\n\",\n\t\t\"\\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add each CTW node to TeX file.
def drawCTWNodes(file, node, show_probs=False): if node.label == '': file.write("{{$\\lambda$, {}\\\\ $P_e$={}\\\\ $P_w$={}}}\n".format(node.count,2**node.log2Pe,2**node.log2Pw)) else: file.write("{{`{}\', {}\\\\ $P_e$={}\\\\ $P_w$={}}}\n".format(node.label,node.count,2**node.log2Pe,2**node.log2Pw)) for child in...
[ "def ctw(control):\n if isinstance(control, list) and len(control) == 1:\n control = control[0]\n return control.toxml()", "def generate_tc_output_variables(self, staged_tc_data):\n for staged_data in staged_tc_data:\n self.add_tc_output_variable(staged_data.get('key'), staged_data....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create and compile TeX file to represent CTM tree.
def drawCTMTree(root, filename='ctm_tree', show_probs=False): node = root file = open('{}.tex'.format(filename), 'w') # Write header file.writelines( ["\\documentclass[tikz,border=10pt]{standalone}\n", "\\usepackage[linguistics]{forest}\n", "\\begin{document}\n", "\\begin{forest}\n", "for tree={grow=west}...
[ "def drawCTWTree(root, filename='ctw_tree', show_probs=False):\n\tnode = root\n\tfile = open('{}.tex'.format(filename), 'w')\n\t# Write header\n\tfile.writelines(\n\t\t[\"\\\\documentclass[tikz,border=10pt]{standalone}\\n\",\n\t\t\"\\\\usepackage[linguistics]{forest}\\n\",\n\t\t\"\\\\begin{document}\\n\",\n\t\t\"\\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assume emb1.dim == emb2.dim
def __init__(self, emb1, emb2, normalize=False): self.dim = emb1.dim vocab1 = emb1.wi.viewkeys() vocab2 = emb2.wi.viewkeys() joint_vocab = list(vocab1 & vocab2) only_vocab1 = list(vocab1 - vocab2) only_vocab2 = list(vocab2 - vocab1) self.iw = joint_vocab + only_v...
[ "def __init__(self, emb1, emb2, normalize=False):\r\n self.dim = emb1.dim\r\n\r\n vocab1 = emb1.wi.viewkeys()\r\n vocab2 = emb2.wi.viewkeys()\r\n joint_vocab = list(vocab1 & vocab2)\r\n only_vocab1 = list(vocab1 - vocab2)\r\n only_vocab2 = list(vocab2 - vocab1)\r\n s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
On first time log in check if there is a profile and if there are data entries from a person with name user in the profile.
def check_profile(sender, user: str, request, **kwargs): user_obj = User.objects.get(username=user) if Profile.objects.filter(user__username=user).exists(): # if user has a profile user_profile = Profile.objects.get(user__username=user) if user_profile.checkedAssociation: # Profile should be f...
[ "def verify_profile_availability(self, profile):\n pass", "def check_profile_exists(cls, user_id):\n profile = cls.c.execute(\n select([cls.table]).where(cls.table.c.user_id == user_id)\n ).fetchone()\n\n return profile is not None", "def test_profile_is_created_automatica...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that lookups can be performed on data once stored in the database.
def testLookups(self): for value in self.testing_data: model_test = TestingModel(pickle_field=value) model_test.save() self.assertEquals(value, TestingModel.objects.get(pickle_field__exact=value).pickle_field) model_test.delete()
[ "def test_lookup(self):\n\n # TEST 1: test with abbrevation and use_cache True\n self.assertEqual(states.lookup(val='KA', field='abbr'), states.KA)\n\n # TEST 2: test with full name and use_cache = True\n self.assertEqual(states.lookup(val='manipur', field='name'), states.MN)\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that values can be serialized to a fixture.
def testFixture(self): for value in self.testing_data: model_test = TestingModel(pickle_field=value) model_test.save() dumpdata = Dumpdata() json = dumpdata.handle('mbdb') pass
[ "def test_serializer_field_values(self):\n pass", "def test_serialize_a_pet(self):\n pet = PetFactory()\n data = pet.serialize()\n logging.debug(\"Pet data: %s\", data)\n self.assertNotEqual(data, None)\n self.assertNotIn(\"_id\", data)\n self.assertEqual(data[\"na...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute rotation matrix about the XYZaxes. R = rotxyz(rph) returns a 3x3 rotation matrix R where (r,p,h) is a 3vector of Euler angles (roll, pitch, heading) measured in radians.
def rotxyz(r, p, h): cr = math.cos(r); sr = math.sin(r) cp = math.cos(p); sp = math.sin(p) ch = math.cos(h); sh = math.sin(h) R = np.array([[ch*cp, (-sh*cr + ch*sp*sr), ( sh*sr + ch*sp*cr)], \ [sh*cp, ( ch*cr + sh*sp*sr), (-ch*sr + sh*sp*cr)], \ [-sp, cp*sr, ...
[ "def rotationMatrix(self):\n\n # R = Compute3DRotationMatrix(self.exteriorOrientationParameters[3], self.exteriorOrientationParameters[4],\n # self.exteriorOrientationParameters[5])\n\n return self.__rotationMatrix", "def rotor_to_rotation_matrix(R):\n q = rotor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get rotation matrix (of dim N x N) about zaxis with angle alpha in randians.
def rotZ(alpha, N = 3): R = np.identity(N) R[0,0] = math.cos(alpha) R[0,1] = -math.sin(alpha) R[1,0] = math.sin(alpha) R[1,1] = math.cos(alpha) return R
[ "def create_rot_mat(alpha):\n rot_mat = np.array(\n [[np.cos(alpha), -np.sin(alpha)], [np.sin(alpha), np.cos(alpha)]]\n )\n return rot_mat", "def getRotZ(angle):\n\tc, s = math.cos(angle), math.sin(angle)\n\treturn Matrix3((c, s, 0), (-s, c, 0), (0, 0, 1))", "def rotation_matrix_z(angle, out = N...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calling string returns str(self.Cij).
def __str__(self): return str(self.Cij)
[ "def to_string(self, *_):\n return str(self.constant_coefficient)", "def __str__(self):\n return \"vals: \" + str(self.val) + \" jacobian: \" + str(self.der)", "def toString(self) -> \"SbString\":\n return _coin.SbVec3d_toString(self)", "def __str__(self):\n\n if self.initialized =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transforms the elastic constant matrix based on the supplied axes.
def transform(self, axes, tol=1e-8): axes = np.asarray(axes, dtype='float64') T = axes_check(axes) Q = np.einsum('km,ln->mnkl', T, T) C = np.einsum('ghij,ghmn,mnkl->ijkl', Q, self.Cijkl, Q) C[abs(C / C.max()) < tol] = 0.0 return elastic_constants(Cijkl=C)
[ "def elastic_transform(x: np.ndarray, amplitude: float, axis: AxesLike = None, order: int = 1):\n axis = axis_from_dim(axis, x.ndim)\n grid_shape = extract(x.shape, axis)\n deltas = [gaussian_filter(np.random.uniform(-amplitude, amplitude, grid_shape), 1) for _ in grid_shape]\n grid = np.mgrid[tuple(map...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The Voigt bulk modulus estimate. Uses hydrostatic stress.
def bulk_Voigt(self): c = self.Cij return ((c[0, 0] + c[1, 1] + c[2, 2]) + 2 * (c[0, 1] + c[1, 2] + c[0, 2])) / 9
[ "def model_elastic_modulus(T):\n return 2.25e6", "def Tvir(Mvir):\n return (mu * mp / (2 * kB)) * (G * Mvir * solmass) / Rvir(Mvir)", "def analyte_injected_pmol(self):\n return (self.analyte_injected_ng()/self.molweight)*1000", "def latent_heat_vaporization(T, units=\"mass\"):\n if np.any(T > ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The Hill shear modulus estimate. Equal to average of Voigt and Reuss shear modulus.
def shear(self): return (self.shear_Voigt + self.shear_Reuss) / 2
[ "def wichmann_hill(seed):\n a, x = divmod(seed, 30268)\n a, y = divmod(a, 30306)\n a, z = divmod(a, 30322)\n x = (171 * x) % 30269\n y = (172 * y) % 30307\n z = (170 * z) % 30323\n ret_val = (x / 30269.0 + y / 30307.0 + z / 30323.0) % 1.0\n return ret_val", "def __dowson_hamrock_parameters...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The Voigt shear modulus estimate. Uses nonhydrostatic stresses.
def shear_Voigt(self): c = self.Cij return ((c[0, 0] + c[1, 1] + c[2, 2]) - (c[0, 1] + c[1, 2] + c[0, 2]) + 3 * (c[3, 3] + c[4, 4] + c[5, 5])) / 15
[ "def shear(self):\r\n return (self.shear_Voigt + self.shear_Reuss) / 2", "def shear_Reuss(self):\r\n s = self.Sij\r\n return 15 / (4 * (s[0, 0] + s[1, 1] + s[2, 2]) - 4 * (s[0, 1] + s[1, 2] + s[0, 2]) + 3 * (s[3, 3] + s[4, 4] + s[5, 5]))", "def wichmann_hill(seed):\n a, x = divmod(seed, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The Reuss shear modulus estimate. Uses nonhydrostatic strains.
def shear_Reuss(self): s = self.Sij return 15 / (4 * (s[0, 0] + s[1, 1] + s[2, 2]) - 4 * (s[0, 1] + s[1, 2] + s[0, 2]) + 3 * (s[3, 3] + s[4, 4] + s[5, 5]))
[ "def shear(self):\r\n return (self.shear_Voigt + self.shear_Reuss) / 2", "def wichmann_hill(seed):\n a, x = divmod(seed, 30268)\n a, y = divmod(a, 30306)\n a, z = divmod(a, 30322)\n x = (171 * x) % 30269\n y = (172 * y) % 30307\n z = (170 * z) % 30323\n ret_val = (x / 30269.0 + y / 303...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Testing all public methods in scidblib.scidb_math.
def test_scidb_math_module(): print '*** testing scidblib.scidb_math...' a = scidb_math.comma_separated_number(1234.1234) assert a == '1,234.1234' print 'comma-separate_number(1234.1234) =', a a = scidb_math.fraction_if_less_than_one(0.125) assert a == '1/8' print 'fraction_if_less_than_on...
[ "def test_SMEB():\n testing_function('sme', bilinear=True)", "def test_example_numeric():\n numeric.main(test=True)", "def test_DistMult():\n testing_function('distmult')", "def test_statistics_module():\n print '*** testing scidblib.statistics...'\n data = [3, 3, 4, 8]\n\n a = statistics.ps...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Testing all public methods in scidblib.scidb_afl.
def test_scidb_afl_module(): print '*** testing scidblib.scidb_afl...' class TmpArgs: def __init__(self): self.host = '' self.port = '' args = TmpArgs() iquery_cmd = scidb_afl.get_iquery_cmd(args) scidb_afl.execute_it_return_out_err('ls') scidb_afl.afl(iquery_cmd...
[ "def test_all(db):\r\n # Shelter Registry\r\n from applications.sahana.modules.test_cr import *\r\n test_cr(db)\r\n # Organisation Registry\r\n from applications.sahana.modules.test_or import *\r\n test_or(db)\r\n # Person Registry\r\n from applications.sahana.modules.test_pr import *\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Testing all public methods in scidblib.statistics.
def test_statistics_module(): print '*** testing scidblib.statistics...' data = [3, 3, 4, 8] a = statistics.pstdev(data) assert round(a, 10) == 2.0615528128 print 'pstdev =', a a = statistics.pvariance(data) assert a == 4.25 print 'pvariance =', a a = statistics.stdev(data) as...
[ "def test_show_statistics(self):\n assert show_statistics()", "def test_get_metrics(self):\n pass", "def test_get_summary_usage(self):\n pass", "def calc_statistics(self):\n pass", "def test_get_archive_statistics(self):\n pass", "def test_statistics_shortcut(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Obtain coefficients for PMML elements.
def _get_coefficients(est, table): def coefficient_for_category(predictors, category): predictor = [p for p in predictors if p.get('value') == category] if not predictor: return 0 return float(predictor[0].get('coefficient')) def coefficients_for_field(name, field): predictors = table.finda...
[ "def get_coeffs(weights):\n coeff_num = weights.__len__() - 1\n pub_key = weights.public_key\n\n bn = []\n exp = []\n for i in range(coeff_num):\n bn.append(weights.ciphertextBN(i))\n exp.append(weights.exponent(i))\n ct = ipclCipherText(pub_key.pubkey, bn)\n return IpclPaillierEn...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Opens a .bsx file and loads the values into the propellant parameters. Unused
def open_bsx_file(self, filename): if filename != '': f = open(filename, 'r') file = f.read() attr = file.split('"') for i in range(0, len(attr)): if attr[i].find("Density") != -1: self.values["rhop"] = float(attr[i+1])*2...
[ "def loadParameters(self, filepath) -> retval:\n ...", "def load_param_from_pcs_file(self, pcs_path):\n self.parameter_space = Parameters.load_param_from_pcs_file(pcs_path)", "def browseSettingFile(self):\n #Open file:\n self.settingsFilename = askopenfilename(filetypes=[('settings f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a new grain
def add_grain(self, ri, l): self.engine.add_grain(self.engine.ri, ri, l)
[ "def add_grain_file(self, filename):\r\n f = open(filename, 'r')\r\n fin = f.read()\r\n grains = fin.split(\"grain,\")\r\n for i in grains:\r\n grain = i.split(\",\")\r\n if grain[0] != '':\r\n self.add_grain(float(grain[0]), float(grain[1]))\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets engine grains based off a file. Unused
def add_grain_file(self, filename): f = open(filename, 'r') fin = f.read() grains = fin.split("grain,") for i in grains: grain = i.split(",") if grain[0] != '': self.add_grain(float(grain[0]), float(grain[1])) f.close()
[ "def config_armies(filename: str) -> None:\n game = Game()\n reader = Reader()\n armies = reader.read(filename)\n game.start_step = reader.start_from_step\n for army in armies:\n game.add_army(army)\n game.start()", "def load_grain(grains, k):\n grain = -np.ones(dims)\n ind = grains...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function will fix timestamps for sample events and generate random ids for traces, spans, and the event id. Largely based on sentry.utils.samples.load_data but more simple
def fix_event_data(data): timestamp = datetime.utcnow() - timedelta(minutes=1) timestamp = timestamp - timedelta(microseconds=timestamp.microsecond % 1000) timestamp = timestamp.replace(tzinfo=pytz.utc) data["timestamp"] = to_timestamp(timestamp) start_timestamp = timestamp - timedelta(seconds=3) ...
[ "def create_event(caseId_par,prev_event_dt_par,event_name_par,hrs_par):\n d=prev_event_dt_par+datetime.timedelta(days=random.uniform(0,(hrs_par+random.randint(0,int(hrs_par*2))))/24)\n return [str(d),caseId_par,event_name_par]", "def sample_date_indices():\n observed = xr.open_dataset(settings.SMIPS_AGG,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetch & return a new `Tag` object representing the tag's current state
def fetch(self): api = self.doapi_manager return api._tag(api.request(self.url)["tag"])
[ "async def fetch_tags(self) -> dict:\n self.cur.execute('select type from tags where tag=?', (self.tag,))\n result = self.cur.fetchone()\n if result:\n return {\n 'name': self.tag,\n 'tag_type': result[0]\n }\n\n # since our cache misse...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove the tag from one or more resources
def remove(self, *resources): self.doapi_manager.request(self.url + '/resources', method='DELETE', data={"resources": _to_taggable(resources)})
[ "def remove_resource_tags(req, resource):", "def unlink(self, tag, glob=None, resources=None):\n query = Q(project__in=self.projects) if self.projects else Q()\n if glob is not None:\n resources = list(self.find(glob, include=tag))\n self.tag_manager.filter(query).get(slug=tag)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Returns a generator that yields all of the droplets to which the tag is currently applied
def fetch_all_droplets(self): return self.doapi_manager.fetch_all_droplets(tag_name=self.name)
[ "def get_all_droplets(self):\n self.mock_data = \"droplets/all.json\"\n data = self.get_data(\"droplets/\")\n droplets = list()\n for jsoned in data['droplets']:\n droplet = Droplet(**jsoned)\n droplet.token = self.token\n droplet.mocked = self.mocked\n\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete all of the droplets to which the tag is applied
def delete_all_droplets(self): self.doapi_manager.request('/v2/droplets', method='DELETE', params={"tag_name": self.name})
[ "def delete_tag(session,taglist):\r\n for t in taglist:\r\n session.query(Tag.name==t).delete()\r\n session.commit()", "def cleanup(self):\n\n # Call all trashed posts, active metadata tags, and photos\n trash_posts = self.connection.call(\n GetPosts(\n {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Perform an arbitrary action on all of the droplets to which the tag is applied. ``data`` will be serialized as JSON and POSTed to the proper API endpoint. All currentlydocumented actions require the POST body to be a JSON object containing, at a minimum, a ``"type"`` field.
def act_on_droplets(self, **data): api = self.doapi_manager return map(api._action, api.request('/v2/droplets/actions', method='POST', params={"tag_name": self.name}, data=data)["actions"])
[ "def act(self, **data):\n api = self.doapi_manager\n return api._action(api.request(self.action_url, method='POST',\n data=data)[\"action\"])", "def droplet_actions(ctx, disable_backups, reboot, power_cycle, shutdown, power_off,\n\t\t\t\t\tpower_on, password_res...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Power on all of the droplets to which the tag is applied
def power_on(self): return self.act_on_droplets(type='power_on')
[ "def get_drop_features(self):\n\n self.dropletAnalysis = True\n self.beginDropAnalysisButton.setEnabled(False)\n self.runDippingTestButton.setEnabled(True)", "def act_on_droplets(self, **data):\n api = self.doapi_manager\n return map(api._action, api.request('/v2/droplets/action...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Enable private networking on all of the droplets to which the tag is applied
def enable_private_networking(self): return self.act_on_droplets(type='enable_private_networking')
[ "def enable_ipv6(self):\n return self.act_on_droplets(type='enable_ipv6')", "def setIptables(dev):\n logging.debugv(\"functions/linux.py->setIptables(dev)\", [dev])\n try:\n runWrapper([locations.IPTABLES, \"-A\", \"OUTPUT\", \"-p\", \"TCP\", \"-m\", \"physdev\", \"--physdev-out\", dev, \"--dp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Enable IPv6 networking on all of the droplets to which the tag is applied
def enable_ipv6(self): return self.act_on_droplets(type='enable_ipv6')
[ "def enable_IPV6_grub_level(self):\n for server in self.servers:\n shell = RemoteMachineShellConnection(server)\n shell.execute_command(\"sed -i 's/ipv6.disable=1/ipv6.disable=0/' /etc/default/grub\")\n shell.execute_command(\"grub2-mkconfig -o /boot/grub2/grub.cfg\")\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Enable backups on all of the droplets to which the tag is applied
def enable_backups(self): return self.act_on_droplets(type='enable_backups')
[ "def disable_backups(self):\n return self.act_on_droplets(type='disable_backups')", "def mongo_backup(event, context):\n\n\n ec2 = ec2connect()\n\n #get list of instances with `Backup` tag\n inst = list_instances(ec2)\n backup_volume(ec2,inst)\n remove_old_snapshots(ec2)\n pri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Disable backups on all of the droplets to which the tag is applied
def disable_backups(self): return self.act_on_droplets(type='disable_backups')
[ "def enable_backups(self):\n return self.act_on_droplets(type='enable_backups')", "def delete_all_droplets(self):\n self.doapi_manager.request('/v2/droplets', method='DELETE',\n params={\"tag_name\": self.name})", "def disable_all(self) -> None:\n raise Not...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if client_id and client_secrets set in file client_secrets
def has_client_secrets(client_secrets): with open(client_secrets) as json_data: secrets = json.load(json_data)['installed'] client_id = secrets['client_id'] client_secret = secrets['client_secret'] return not client_id.startswith('<GET') and not client_secret.startswith('<GE...
[ "def Check():\n try:\n credentials = json.loads(os.environ.get(Varname()))\n except json.decoder.JSONDecodeError as jderr:\n logging.warning(f\"CMCREDENTIALS not found in Check. {datetime.now()}.\")\n DefaultCredentials()\n return False\n\n if credentials[\"refreshtoken\"] != \"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a directory of temporary files with file_id for virtualization of drive contents
def create_temp_files(temp_dir, files): for drive_type, drive_files in files.items(): folder_path = os.path.join(temp_dir, drive_type + '/') os.mkdir(folder_path) for file_ in drive_files: # replace reserved characters in title to assure valid filename ...
[ "def _make_temp_dir(self):\n temp_dir = Path(self.file_path.parent, self.file_path.name + '__tmp')\n temp_dir.mkdir(exist_ok=True, parents=True)\n self.temp_dir = temp_dir", "def make_temp_dir():\n return tempfile.mkdtemp()", "def create_temp_folder(self):\n return tempfile.mkdtem...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a list of n numbers in logx scale from x1 to x2.
def logx_grid(x1, x2, n): # the shape if a*x^n. if n=0 => a=x1, if n=N => x1*x^N=x2 if x1 > 0: xx = (x2 / x1)**(1.0 / n) return [x1] + [x1 * xx**(i+1) for i in range(1, n)] else: xx = x2**(1.0/n) return [x1] + [xx**(i+1) - 1 for i in range(1, n)]
[ "def logrange(first=1.0, times=10, multiplier=0.1):\n return [first * multiplier**i for i in range(times)]", "def _log2(n):\n while len(_logtable) <= n:\n _logtable.extend([1 + _logtable[-1]] * len(_logtable))\n return _logtable[n]", "def logrange(start: float, stop: float, num=50, base=10) -> n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the vertex (x,y) of a parabola of the type ax2 + bx + c.
def _vertex_parabola(a, b, c): return -b/(2*a), - (b**2 - 4*a*c) / (4*a)
[ "def _parabola_3points(x1, y1, x2, y2, x3, y3):\n delta = (x1 - x2)*(x1 - x3)*(x2 - x3)\n a = (x3 * (y2 - y1) + x2 * (y1 - y3) + x1 * (y3 - y2)) / delta\n b = (x3**2 * (y1 - y2) + x2**2 * (y3 - y1) + x1**2 * (y2 - y3)) / delta\n c = (x2 * x3 * (x2 - x3) * y1 + x3 * x1 * (x3 - x1) * y2 + ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parabola through 3 points.
def _parabola_3points(x1, y1, x2, y2, x3, y3): delta = (x1 - x2)*(x1 - x3)*(x2 - x3) a = (x3 * (y2 - y1) + x2 * (y1 - y3) + x1 * (y3 - y2)) / delta b = (x3**2 * (y1 - y2) + x2**2 * (y3 - y1) + x1**2 * (y2 - y3)) / delta c = (x2 * x3 * (x2 - x3) * y1 + x3 * x1 * (x3 - x1) * y2 + x1 * x2 *...
[ "def _vertex_parabola(a, b, c):\n return -b/(2*a), - (b**2 - 4*a*c) / (4*a)", "def _parabola(data):\n y = np.asarray(data)\n x = np.linspace(-1, 1, len(y))\n # use only the endpoints; when trying to use the mean of the last few values, the\n # fit is usually not as good since beads expects the ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find first root of f=f(x) for data sets. Given two lists x and f, it returns the value of xstar for which f(xstar) = fstar. Raises an ValueError if no root is found.
def feqc(x, f, fstar): s = f[0] - fstar for i in range(min(len(x), len(f))): if (f[i] - fstar) * s < 0.0: # Linear interpolation dxf = (f[i] - f[i-1]) / (x[i] - x[i-1]) xstar = x[i-1] + (fstar - f[i-1]) / dxf istar = i return xstar, istar ...
[ "def rootof(f, x, index=None, radicals=True, expand=True):\n return CRootOf(f, x, index=index, radicals=radicals, expand=expand)", "def calculate_root(f: Polynomial, a, b, eps):\n assert f(a)*f(b) < 0\n\n df = f.deriv()\n\n def newtons_lambda(x):\n return -1 / df(x)\n\n return sim.calculate_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Callback to filter particles by species. The input species can be an integer (particle id), a string (particle name), or None. In this latter case, all particles are returned.
def filter_species(system, species): s = copy.copy(system) if species is not None: s.particle = [p for p in system.particle if p.species == species] return s
[ "def particles(self, selection_func=None):\n if selection_func is None:\n return self.particles_\n else:\n return filter(selection_func, self.particles_)", "def GetParticles(self, time, species,location=None):\n\n # checking parameters\n\n # check the species\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copy particle property `field` from `trajectory` at the current frame in system. It requires atooms >= 1.10.0
def copy_field(system, field, trajectory): # Only available in atooms > 1.10.0 so = trajectory[system.frame] for p, po in zip(system.particle, so.particle): x = getattr(po, field) setattr(p, field, x) return system
[ "def TrackVelocity3D(particle, fieldset, time):\n print(\"TIME : %g\" % time)\n (u1, v1) = fieldset.UV[time, particle.depth, particle.lat, particle.lon] #\n particle.u = u1 * 1852. * 60. * math.cos(particle.lat * math.pi/180.) \n particle.v = v1 * 1852. * 60.", "def copyFrom(self, field: 'SoField') ->...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Filter a list of entries so as to best match an input template. Lazy, slow version O(NM).
def _templated(entry, template, keep_multiple=False): match = [] for t in template: def compare(x): return abs(x - t) match.append(min(entry, key=compare)) if not keep_multiple: match = list(set(match)) return sorted(match)
[ "def filter_template_list(template_list, output_filter):\n output_filter = [re.compile(flt) for flt in output_filter]\n template_list = [\n templ\n for templ in template_list\n for rex in output_filter if rex.match(templ)\n ]\n LOG.debug('Filtered template files list: %s', template_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a table with traffic data, return a formatted dictionary.
def get_traffic_stats(traffic_table): log = logging.getLogger('get_traffic_stats') traffic_rows = traffic_table.find_all('tr') #log.debug(traffic_rows) traffic = {} i = 0 for j in traffic_rows: # Only lines interested in are 1 and 2 if i in [1, 2]: cols = j.find_all('...
[ "def data_pretty_print(self, data):\n data_str = tabulate(data, headers=\"keys\", tablefmt=\"psql\")\n return data_str", "def pretty_print_table(hashtable):\n for key,val in hashtable.items():\n values = [\",\".join(map(str, v)) for v in val]\n print(key + \"\\t\" + \"\\t\".join(val...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Push a new worker into the queue, but randomly (it has to depend on the type and urgency of the worker)
def pushRandom(t): Worker.push(t) shuffle(Worker.workers)
[ "def push_to_queue(self):\n redis = self.redis_pool.get_connection()\n redis.publish(self.collection_name, self.worker_id)", "def queue_fixture():\n new_queue = our_queue()\n return new_queue", "async def add_worker_to_pool(self, worker_id):\n if not worker_id in self.worker_instances...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
launch the worker, increase the time
def launch(self): Worker.time += 1
[ "def run_job():", "def worker_function(time_left):\r\n timer = TimerApp(time_left)", "def worker():\r\n\r\n while True:\r\n t = threading.Timer(10.0, hello)\r\n t.start()\r\n t.join()", "def do_main(self):\n self.pool.spawn_n(self._periodic_runner)\n super(Manager, sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The Activate workers generates new Compute workers for every linked node
def launch(self): self.target_node.activation += self.activation_to_add for n in self.target_node.linksOut.keys(): Worker.pushRandom(Compute(n)) super().launch()
[ "def activate(self):\n to_state = self.node_states[:] # a copy\n \n # activate the internal nodes\n for i in range(self.size):\n if self.node_connections.has_key(i):\n total = 0.0\n for key, weight in self.node_connections[i]:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load all of the tensors required to begin federated learning.
def _load_initial_tensors(self): tensor_dict, round_number = utils.deconstruct_model_proto( self.model, compression_pipeline=self.compression_pipeline) if round_number > self.round_number: self.logger.info( f'Starting training from round {round_number} of previou...
[ "def _load_initial_tensors_from_dict(self, tensor_dict):\n tensor_key_dict = {\n TensorKey(k, self.uuid, self.round_number, False, ('model',)):\n v for k, v in tensor_dict.items()\n }\n # all initial model tensors are loaded here\n self.tensor_db.cache_tensor(te...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load all of the tensors required to begin federated learning.
def _load_initial_tensors_from_dict(self, tensor_dict): tensor_key_dict = { TensorKey(k, self.uuid, self.round_number, False, ('model',)): v for k, v in tensor_dict.items() } # all initial model tensors are loaded here self.tensor_db.cache_tensor(tensor_key_di...
[ "def _load_initial_tensors(self):\n tensor_dict, round_number = utils.deconstruct_model_proto(\n self.model, compression_pipeline=self.compression_pipeline)\n\n if round_number > self.round_number:\n self.logger.info(\n f'Starting training from round {round_number}...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine if the collaborator certificate and ID are valid for this federation.
def valid_collaborator_cn_and_id(self, cert_common_name, collaborator_common_name): # if self.test_mode_whitelist is None, then the common_name must # match collaborator_common_name and be in authorized_cols # FIXME: '' instead of None is just for protobuf co...
[ "def check_id(self):\n\n is_file = os.path.isfile(self.id_path)\n is_valid = self.validate_id_file()\n return bool(is_file and is_valid)", "def check_cid(self) -> bool:\n return True", "def is_valid(self):\n return self.identifier is not None and self.identifier != \"\"", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }