query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Reset the value of a theano shared variable to all zeros t_S shared theano variable
def reset_shared_var(t_S): t_S.set_value(np.zeros_like(t_S.get_value()).astype('float32'))
[ "def reset_adadelta_variables(t_A=self.t_A):\n A0 = np.zeros_like(t_A.get_value()).astype(theano.config.floatX)\n t_ada_Eg2.set_value(A0)\n t_ada_dA2.set_value(A0)\n t_A.set_value(A0)", "def shared_zeros(shape):\n return theano.shared(value=np.zeros(*shape).astype(th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Take dot product of image with an array of gaussians t_S image variable shape (i2, i1) t_Var variances of receptive fields t_XS X coordinate for image pixels for dimension i1 t_YS Y coordinate for image pixels for dimension i2 t_XE X coordinate for receptive fields j t_YE Y coordinate for receptive fields j t_XR X coor...
def inner_products(t_S, t_Var, t_XS, t_YS, t_XE, t_YE, t_XR, t_YR): # Note in this computation, we do the indices in this form: # b, i, j, t # batch, pixel, neuron, time step # indices: b, i1, j, t t_dX = (t_XS.dimshuffle('x', 0, 'x', 'x') - t_XE.dimshuffle('x', 'x', 0, 'x') - ...
[ "def dot_image(image, B):\n \n imshape = image.shape\n if not image.flags['C_CONTIGUOUS']:\n raise TypeError, 'Error: cannot deal with non-C-contiguous image'\n output = gemm(1.0, image.reshape((np.prod(imshape[:-1]), imshape[-1])), B)\n return output.reshape(imshape[:-1] + (B.shape[1],))", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
t_dIpsdA d Ips / dA indexed as b, k, j, t t_G gain constant t_IE RGC identity, j t_L0, t_L1 min, max firing rates Returns the d log FP / dA indexed b, k, j, t
def dlogfp_dA(t_dIpsdA, t_G, t_IE, t_L0, t_L1, t_SMIN, t_SMAX): t_IEr = t_IE.dimshuffle('x', 'x', 0, 'x') t_dGen_dA = (1 - 2 * t_IEr) * t_G * t_dIpsdA / (t_SMAX - t_SMIN) t_dlogFPdA = T.log(t_L1 / t_L0) * t_dGen_dA return t_dlogFPdA
[ "def hinderedRotor_d_heatCapacity_d_freq(T, freq, barr):\n x = constants.h * constants.c * 100. * freq / constants.kB / T\n exp_x = math.exp(x)\n one_minus_exp_x = 1.0 - exp_x\n return x * exp_x / one_minus_exp_x / one_minus_exp_x * (2 + x + 2 * x * exp_x / one_minus_exp_x) * x / freq", "def rate(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resets ADA Delta auxillary variables
def reset_adadelta_variables(t_A=self.t_A): A0 = np.zeros_like(t_A.get_value()).astype(theano.config.floatX) t_ada_Eg2.set_value(A0) t_ada_dA2.set_value(A0) t_A.set_value(A0)
[ "def reset_delta(self):\n # type: () -> None\n self.last_data = self.instrument.get_data()", "def reset(self):\n print(f\"Undoing all evolutions.\\nSetting current matrix to initial matrix.\")\n self.A_matrix = self.initial_matrix\n self.update_matrix = np.array([])\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reset the values of the hessian term and the bias term to zero to reset the
def reset_hessian_and_bias(self): # reset_shared_var(self.t_H) t = self.QUAD_REG if len(t.shape) == 1: self.t_H.set_value(np.diag(self.QUAD_REG)) elif len(t.shape) == 2: self.t_H.set_value(self.QUAD_REG) else: raise ValueError('Invalid quad_re...
[ "def reset_parameters(self):\n if self.weight is not None:\n init.xavier_uniform_(self.weight)\n if self.bias is not None:\n init.zeros_(self.bias)", "def init_forget_bias(self):\n with torch.no_grad():#so the optimizer doesn't know about this ;)\n self.rnn.bi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verifies CAS 1.0 authentication ticket. Returns username on success and None on failure.
def _verify_cas1(ticket, service): params = {'ticket': ticket, 'service': service} url = (urljoin(settings.CAS_SERVER_URL, 'validate') + '?' + urlencode(params)) page = urlopen(url) try: verified = page.readline().strip() if verified == 'yes': return page.readline(...
[ "def _CAS_login(self):\n import urllib\n self.ticket = current.request.vars.ticket\n if not current.request.vars.ticket:\n redirect(\"%s?service=%s\" % (self.cas_login_url,\n self.cas_my_url))\n else:\n url = \"%s?service=%s&ti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verifies CAS 2.0+ XMLbased authentication ticket. Returns user's attribute on success and None on failure.
def _verify_cas2(ticket, service): try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree params = {'ticket': ticket, 'service': service} url = (urljoin(settings.CAS_SERVER_URL, 'serviceValidate') + '?' + urlencode(params)) page = u...
[ "def verify_ticket(self, ticket, **kwargs):\n\n try:\n from xml.etree import ElementTree\n except ImportError:\n from elementtree import ElementTree\n\n page = self.fetch_saml_validation(ticket)\n\n try:\n user = None\n attributes = {}\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verifies CAS ticket and gets or creates User object
def authenticate(self, ticket, service, request): user = _verify(ticket, service) logger.debug("Verified User %s" % user) if user is None: return None return models.SSOUser(**user)
[ "def authenticate(self, request, ticket, service):\n client = get_cas_client(service_url=service)\n username, attributes, pgtiou = client.verify_ticket(ticket)\n if attributes and request:\n request.session['attributes'] = attributes\n # Attributes\n # {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a HMM from probability tables.
def fromtables(pi, t, e): #sanity checks nStates=len(pi) assert(nStates==len(t) and nStates==len(e) and nStates>0) nObs=len(e[0]) for i in range(nStates): assert(len(t[i])==nStates and len(e[i])==nObs) m=hmm(nStates, nObs) m.pi=deepcopy(pi) m.t=deepcopy(t) m.e=deepcopy(e) ...
[ "def create_hmm(self, state_symbols, emission_symbols, priors=None, init_prob_matrix=True):\n assert len(state_symbols) == self.__num_states, \"number of states does not match with num_states\"\n assert len(emission_symbols) == self.__num_emissions, \"number of emissions does not match \" \\\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Learns from a list of observation sequences and their associated ground truth.
def learn(self, observations, ground_truths): assert(len(observations)==len(ground_truths)) self.__init__(self.nStates, self.nObs) N=len(observations) for i in range(N): o=observations[i] t=ground_truths[i] assert(len(o)==len(t)) self.pi[...
[ "def prepare_sequences(notes, n_vocab):\n sequence_length = 1\n\n # get all pitch names\n pitchnames = sorted(set(item for item in notes))\n\n # create a dictionary to map pitches to integers\n note_to_int = dict((note, number) for number, note in enumerate(pitchnames))\n\n network_input = []\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Viterbi inference of the highest likelihood hidden states sequence given the observations. Time complexity is O(|observation|nStates^2).
def viterbi(self, observation): N=len(observation) tab=[[0]*self.nStates for i in range(N)] backtrack=[[-1]*self.nStates for i in range(N)] if not self.logdomain: self.__convert_to_log() for i in range(self.nStates): tab[0][i]=self.e[i][observation[0]]+se...
[ "def viterbi(self, sequence):\n\n viterbi_probs = {}\n pred_state_seq = {}\n viterbi_probs[0, -1] = 0.0 # initial state is 0\n\n # --- recursion\n # loop over the training sequence (i = 1 .. L)\n for i in range(len(sequence)):\n #print \"POS: \", i, sequence[i]\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the restaurant json or None Use the default ones if mocks are requested
def get_restaurant(id): with current_app.app_context(): if current_app.config["USE_MOCKS"]: id -= 1 # restaurant IDs starting by 1 if 0 <= id < len(restaurants): return restaurants[id] else: return None else: re...
[ "def get_random_restaurant(self, request, **kwargs):\n restaurant = Restaurant.objects.order_by(\n '?'\n ).select_related(\n 'address'\n ).prefetch_related(\n 'employees'\n ).first()\n serializer = RestaurantFullInfoSerializer(restaurant)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the list fo the restaurant's tables or None Use the default ones if mocks are requested
def get_tables(id): with current_app.app_context(): if current_app.config["USE_MOCKS"]: id -= 1 # restaurant IDs starting by 1 if 0 <= id < len(restaurants): return tables[id] else: return None else: return get_...
[ "def get_tables(self):\n if self.page_id == 'wahlrecht_country':\n tables = self.get_tables_wahlrecht_country()\n if self.page_id == 'wahlrecht_states':\n tables = self.get_tables_wahlrecht_states()\n\n return tables", "def test_get_tables(self):\n pass", "def g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a new reservation Return the booking id, otherwise Return None if a db error occured
def add_booking(user_id, rest_id, number_of_people, booking_datetime, table_id, entrance_datetime=None): try: booking = Booking() booking.restaurant_id = rest_id booking.user_id = user_id booking.booking_datetime = booking_datetime booking.entrance_datetime = entrance_d...
[ "def insert_reservation(house, id, check_in_date, check_in_time, check_out_date, guest_name,\n guest_cell, guest_telegram, num_guest, comment, confirm):\n sql = \"\"\"INSERT INTO %s VALUES(%s, '%s', '%s', '%s', '%s', '%s', '%s', %s, '%s', %s) RETURNING reservation_id;\"\"\"\n conn = None...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a free table if it is available, otherwise Return 1 if there are no free tables Return 2 if the restaurant is closed Return None if it is impossible to connect with the restaurant microservice.
def get_a_table(restaurant_id, number_of_people, booking_datetime, excluded=-1): is_open, rest = restaurant_is_open(restaurant_id, booking_datetime) # check is the restaurant is open on that date if is_open is None: # connection error with the restaurant microservice return None if not is_open...
[ "def get(self):\n free_tables = []\n tables = TableDetails.query.all()\n for table in tables:\n if table.table_status == \"Empty\":\n free_tables.append(table)\n return free_tables, 200", "def get_table(runnumber, tablename, db_address, db_host, db_username, d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if a restaurant is open in a given datetime Return true if the restaurant is open (with the json of the restaurant) Return false if the restaurant is closed (with the json of the restaurant) eturn None if it is impossible to connect with the restaurant microservice.
def restaurant_is_open(restaurant_id, booking_datetime): rest = get_restaurant(restaurant_id) if rest is None: # error with the microservice return (None,None) else: if (booking_datetime.weekday()+1) in rest["closed_days"]: return (False,rest) now = datet...
[ "def checker( rest_obj, date_time):\n\n\t# get the day of our intended lunch\n\tlunch_day = date_time.strftime(\"%a\")\n\t# calculate the start time of the lunch + an estimated 59 minutes in order to have time to eat when you want to start your lunch at 12:55 and the restaurant closes at 13:00\n\tlunch_time = date_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a user id, get all application cases that belong to the Company where the user is in
def get_application_cases_by_uid(uid, conditions=[]): cid = employee.get_employee_by_user(userid=uid).company.id return ApplicationCase.objects.filter(job__company_id=cid, *conditions)
[ "def get_companies(self, obj):\n userCompanies = get_objects_for_user(\n obj, \"view_company\", klass=models.Company)\n return [x.id for x in userCompanies]", "def get_habits_by_user(user_id):\n\n return User_habit.query.filter_by(user_id=user_id).all()", "def find_appt_by_user(user_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate satellite body geometry
def create_sat_body(self): # Dimensions of body SAT_SIZE = self.ANI_SCALE*self.SAT_SCALE*np.asarray(self.SAT_PROPS["Size"])/2 bx = SAT_SIZE[0] by = SAT_SIZE[1] bz = SAT_SIZE[2] # Create vertices in body frame ind = 0 V = [] for x in [-1, 1]: ...
[ "def extract_stationary_body( data, body = 'Ground', verbose = False ):\n t_body, x_body, q_body, ypr_body = data.trajectory( body )\n x_body_avg = 1000.0 * np.mean( x_body, axis=0 )\n q_body_avg = dfab.geometry.xyzw_to_wxyz( quat.normalize(np.mean( q_body, axis=0 )))\n transform = dfab.geometry.pos_qua...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create satellite solar panel geometry
def create_sat_panels(self): # Dimensions of body SAT_SIZE = self.ANI_SCALE*self.SAT_SCALE*np.asarray(self.SAT_PROPS["Size"])/2 bx = SAT_SIZE[0] by = SAT_SIZE[1] bz = SAT_SIZE[2] # Panel length L = bx # Panels theta = self.PANEL_ANGLE*pi/180 ...
[ "def make_mesh(self):\n \n self.get_station_locations()\n \n #find the edges of the grid\n west = self.station_locations['rel_east'].min()-self.cell_size_east/2\n east = self.station_locations['rel_east'].max()+self.cell_size_east/2\n south = self.station_locations['...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create FOV actor for camera
def create_cam_fov(self, name): # Vertices of FOV V = [ (0, 0, -self.SAT_PROPS["Alt"]), tuple(self.CAM_PROPS[name]["Intercepts"][:, 0]), tuple(self.CAM_PROPS[name]["Intercepts"][:, 1]), tuple(self.CAM_PROPS[name]["Intercepts"][:, 2]), tuple(se...
[ "def set_camera_fov(args_, client_, new_fov):\n\n args_.camera_bp.set_attribute(\"fov\", \"%s\" % new_fov)\n args_.camera_depth_bp.set_attribute(\"fov\", \"%s\" % new_fov)\n\n # destroy the original actor and make a new camera object\n args_.rgb_camera.camera_actor.stop()\n args_.depth_camera.camera_actor.stop...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create text actor for view labels
def create_text(self, settings, viewport): viewport = np.array(viewport) viewport[[0, 2]] = self.WIN_H_SCALE*viewport[[0, 2]] viewport[[1, 3]] = self.WIN_V_SCALE*viewport[[1, 3]] viewport = list(viewport) # Set defaults if not specified defaults = { "Size": ...
[ "def _createElectrodeTextActors( self ):\n self._electrodeTextActors = [vtkFollower() for _ in range( 8 )]\n\n for i, actor in enumerate( self._electrodeTextActors ):\n textSource = vtkVectorText()\n textSource.SetText( f\"{i + 1}\" )\n\n textMapper = vtkPolyDataMapper...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes a vtkIdList from a Python iterable
def mkVtkIdList(self, it): vil = vtk.vtkIdList() for i in it: vil.InsertNextId(int(i)) return vil
[ "def asVtkIdList(data):\n\n r = vtk.vtkIdList()\n r.SetNumberOfIds(len(data))\n for (i, d) in enumerate(data):\n r.SetId(i, d)\n return r", "def array2vtkIdList(num_array, vtk_idlist=None):\n if vtk_idlist:\n ids = vtk_idlist\n else:\n ids = vtk.vtkIdList()\n\n arr = nump...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Attaches another entity at a position offset from the attachment site.
def attach_offset(self, entity, offset, attach_site=None): frame = self.attach(entity, attach_site=attach_site) frame.pos = offset return frame
[ "def add_entity(self, ent):\n self.tiles[ent.position[x]][ent.position[y]].add_entity(ent)", "def _place_entity(self, entity, x, y, z):\n self._entities[y][x][z] = entity", "def move_to(self, entity, location):\n y, x = location\n if not y in range(self.size) or not x in range(self.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns content of URI or splited by \\n config.
def adv_get_content(URI=None, config=None): if URI != None: content = get_file(URI) elif config != None: if isinstance(config, basestring): content = config.split('\n') elif hasattr(config, '__iter__'): # iterable content = config else: raise e...
[ "def newline_list(value):\n return value.strip().splitlines()", "def test_parse_post_content_line_breaks(self):\n test_str1 = \"Hey \\r\\n This \\r\\n should \\r\\n\\r\\n be \\n\\r\\ be\"\n str1 = parse_post_content(test_str1, 'display')\n self.assertEqual(str1, \"Hey <br/> This <br/> shou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save several arrays into a single file in uncompressed ``.npz`` format. If arguments are passed in with no keywords, the corresponding variable names, in the ``.npz`` file, are 'arr_0', 'arr_1', etc. If keyword arguments are given, the corresponding variable names, in the ``.npz`` file will match the keyword names.
def savez(file, *args, **kwds): ary_list = [] for a in args: ary_list.append(array_create.array(a, bohrium=False)) return numpy.savez(file, *ary_list, **kwds)
[ "def savez_compressed(file, *args, **kwds):\n\n ary_list = []\n for a in args:\n ary_list.append(array_create.array(a, bohrium=False))\n return numpy.savez_compressed(file, *ary_list, **kwds)", "def dump_npy(filename: str, obj, **kwargs):\n return np.save(filename, obj)", "def dump_npz(filena...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save several arrays into a single file in compressed ``.npz`` format. If keyword arguments are given, then filenames are taken from the keywords. If arguments are passed in with no keywords, then stored file names are arr_0, arr_1, etc.
def savez_compressed(file, *args, **kwds): ary_list = [] for a in args: ary_list.append(array_create.array(a, bohrium=False)) return numpy.savez_compressed(file, *ary_list, **kwds)
[ "def savez(file, *args, **kwds):\n\n ary_list = []\n for a in args:\n ary_list.append(array_create.array(a, bohrium=False))\n return numpy.savez(file, *ary_list, **kwds)", "def savenpz(filename, *args, **kwargs): #{{{\n cwd, call, host = calling_metadata()\n np.savez(filename, meta_call=call...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Construct an array from a text file, using regular expression parsing. The returned array is always a structured array, and is constructed from all matches of the regular expression in the file. Groups in the regular expression are converted to fields of the structured array.
def fromregex(file, regexp, dtype, bohrium=True): return array_create.array(numpy.fromregex(file, regexp, dtype), bohrium=bohrium)
[ "def numpy_array_from_file(filename,delimiters):\n data = ''.join(open(filename))\n if data:\n return numpy_array_from_string(data,delimiters)", "def _parse_array_from_file(filename, type, byteorder):\n file = open(filename, 'rb')\n arr = _parse_array_from_str(file.read(), type, byteorder)\n file.close()\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
a.tofile(arr, fid, sep="", format="%s") Write array 'arr' to a file as text or binary (default). Data is always written in 'C' order, independent of the order of `a`. The data produced by this method can be recovered using the function fromfile().
def print_to_file(arr, fid, sep="", format="%s"): f = array_create.array(arr, bohrium=False) return f.tofile(fid, sep=sep, format=format)
[ "def save(arr, fh, compression=0):\n\tflags = []\n\t# I'm not totally clear how, but according to docs, can be both C and F layout for 2D\n\tif arr.flags.c_contiguous and not arr.flags.f_contiguous:\n\t\tflags.append('row-major')\n\telif arr.flags.f_contiguous and not arr.flags.c_contiguous:\n\t\tflags.append('colu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the hash method.
def hash_method(self): return self._hash_class
[ "def signatureHashAlgorithm(self) -> str:\n hash_algo = self['signature_algorithm'].hash_algo\n return hash_algo", "def get_pseudo_hash ( self ):\n return hash (( self.__class__, self.name ))", "def hashlib_type():\n pass", "def HashAlgorithm(self) -> _n_7_t_0:", "def hash_name(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the hash cipher
def hash_cipher(self): return self._digest_cipher
[ "def get_cipher(self):\r\n return self.cipher", "def getCipherFromPassword(password):\n \n return getCipherFromKey(hashlib.sha256(password).digest())", "def HashAlgorithm(self) -> _n_7_t_0:", "def _compute_handshake(self):\r\n return hashlib.sha1(to_utf8(self.stream_id)+to_utf8(self.se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create cookie if not there already. Also deactivates language.
def process_response(self, request, response): if not request.COOKIES.get('site_language'): response.set_cookie('site_language', '') translation.deactivate() return response
[ "def setlang(request):\n next = request.GET.get('next', None)\n if not is_safe_url(url=next, host=request.get_host()):\n next = request.META.get('HTTP_REFERER')\n if not is_safe_url(url=next, host=request.get_host()):\n next = '/'\n response = redirect(next)\n\n lang_code = requ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verifies prediction and label shapes are equal.
def check_shape_equal(pred, labels): if pred.shape != labels.shape: raise ValueError('Prediction and labels shapes must be equal:' f'{pred.shape} vs {labels.shape}.')
[ "def _check_prediction_dimensions(y_test, y_pred, y_score):\n\n assert y_pred.shape[0] == y_test.shape[0], (\n \"Ensure class prediction vector is same length as test set\")\n assert y_score.shape[0] == y_test.shape[0], (\n \"Ensure score prediction vector is same length as test set\")", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verifies the nested dictionary dtypes are equal to target dtype.
def check_dtype_equal(input_dict, target_dtype = jnp.float32, exclude_list = ()): flat_input = traverse_util.flatten_dict(input_dict) for key, value in flat_input.items(): if key[0] in exclude_list: continue key_name = '_'.join([str(sub_key) for sub_key in ...
[ "def test_dtype_equality(self):\r\n dtypes = get_numeric_types(with_complex=True)\r\n # Perform all pairwise comparisons of dtypes, making sure comparing\r\n # their string representation yields the same result.\r\n for dtype1_idx, dtype1 in enumerate(dtypes):\r\n for dtype2 i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Weights and reduces the loss. We convert to float32 before reducing following TF1 implementation. After weighting and reducing the losses, we convert the output back to the dtype of the input.
def compute_weighted_loss( loss, weights, dtype, loss_reduction, ): if loss_reduction == LossReductionType.RETURN_AS_IS: # Handle no loss reduction, by returning tensor as-is. return loss loss = loss.astype(jnp.float32) loss_weight = jnp.broadcast_to(weights, loss.shape).astype(jnp.float32...
[ "def weight_reduce_loss(loss, weight=None, reduction='mean'):\n if weight is not None:\n assert weight.dim() == loss.dim()\n assert weight.size(1) == 1 or weight.size(1) == loss.size(1)\n loss = loss * weight\n if weight is None or reduction == 'sum':\n loss = reduce_loss(loss, red...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes a safe log. This function returns 0.0 wherever x contains any value <= 0.0.
def safe_log(x): safe_x = jnp.where(x > 0.0, x, jnp.ones_like(x)) return jnp.where(x > 0.0, jnp.log(safe_x), jnp.zeros_like(x))
[ "def safelog(x):\n #return np.log(x)\n return np.log(np.clip(x,floor,np.inf))", "def safe_log(signal):\n return np.log(replace_zeros_with_almost_zero(signal))", "def LogZeroish(self, x):\n return x < 0 and math.isinf(x)", "def smart_log(self, value: float) -> float:\n if value > 0:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cosine loss. This loss computes the dot product between predictions and labels as loss. The value ranges from [0, 2.0] depending on the alignment of prediction and label vectors. This loss can be used when we want to optimize the alignment of the vectors directly.
def cosine_loss(predictions, labels, weights = 1.0, loss_reduction = LossReductionType.SUM_BY_NONZERO_WEIGHTS, **kwargs): del kwargs # Unused check_shape_equal(predictions, labels) cosine = 1.0 - jnp.sum(predictions * labels, axis=-1) return compu...
[ "def cosine_similarity(y_true, y_pred, axis=-1):\n y_true = nn.l2_normalize(y_true, axis=axis)\n y_pred = nn.l2_normalize(y_pred, axis=axis)\n return -math_ops.reduce_sum(y_true * y_pred, axis=axis)", "def compute_cosine_similarity(self):\n cos_matrix = []\n for i in range(len(self.train_vec)):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A wrapper to add weight decay to underlying loss function. Use this wrapper if the weight decay in the optimizer is not suitable. For example, if you need to exclude some parameters from decay loss.
def weight_decay_loss_wrapper( loss_fn = gin.REQUIRED, factor = gin.REQUIRED, exclude = (), ): traversal = traverse_util.ModelParamTraversal( lambda path, _: all([e not in path for e in exclude])) def wrapped_loss(outputs, *args, params, **kwargs): losses = loss_fn(outputs, *args, **kwargs) ...
[ "def extend_with_decoupled_weight_decay(base_optimizer):\n\n class OptimizerWithDecoupledWeightDecay(DecoupledWeightDecayExtension,\n base_optimizer):\n \"\"\"Base_optimizer with decoupled weight decay.\n\n This class computes the update step of `base_optimizer` and\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send a LA/SP/SnapMultiplier request command to message receivers.
async def request(self, multiplier: Optional[int]=None): # TODO: validate the multiplier message = Message(self.name_path, multiplier) await self.issue_command(Command(message))
[ "def send_rates_request(self, wtp, lvap):\n\n rates_req = Container(version=PT_VERSION,\n type=PT_RATES_REQUEST,\n length=18,\n seq=wtp.seq,\n rates_id=self.module_id,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Notify all receivers of received LA/SmoothedPosition response.
async def notify_response_receivers(self, position: int) -> None: await asyncio.gather(*[ receiver.on_linear_actuator_smoothed_position(position) for receiver in self.response_receivers ])
[ "def _notify_handlers(self):\n\n # Notify all handlers \n for handler_callback in self._registered_handlers:\n try:\n handler_callback(self._balloon_position)\n except Exception as e:\n # A receiver failed, catch and move on\n pass", "def inform_listeners(self):\n d = s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return Genomic Deletion Range Classifier instance.
def classifier_instance(self): return GenomicDeletionRangeClassifier()
[ "def classifier_instance(self):\n return GenomicDeletionClassifier()", "def classifier_instance(self):\n return CodingDNADeletionClassifier()", "def validator_instance(self):\n return GenomicDeletion(*self.params)", "def classifier_instance(self):\n return ProteinDeletionClassifier...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return Genomic Deletion Range fixture name.
def fixture_name(self): return "genomic_deletion_range"
[ "def fixture_name(self):\n return \"genomic_deletion\"", "def fixture_name(self):\n return \"genomic_delins\"", "def fixture_name(self):\n return \"coding_dna_deletion\"", "def fixture_name(self):\n return \"protein_deletion\"", "def fixture_name(self):\n return 'genomic_s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Attempt to find host with an incomplete tag (no key). Expects 400 response.
def test_get_host_with_invalid_tag_no_key(mq_create_three_specific_hosts, api_get): url = build_hosts_url(query="?tags=namespace/=Value") response_status, response_data = api_get(url) assert response_status == 400
[ "def test_get_host_with_invalid_tag_no_key(self):\n test_url = f\"{HOST_URL}?tags=namespace/=Value\"\n self.get(test_url, 400)", "def test_get_host_with_tag_no_value_in_query(self):\n host_list = self.added_hosts.copy()\n\n expected_response_list = [host_list[0]] # host with tag \"no/...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
send a request to find hosts with a string tag where the length of the namespace excedes the 255 character limit
def test_get_host_tag_part_too_long(tag_query, part_name, mq_create_three_specific_hosts, api_get): url = build_hosts_url(query=f"?tags={tag_query}") response_status, response_data = api_get(url) assert_error_response( response_data, expected_status=400, expected_detail=f"{part_name} is longer tha...
[ "def test_get_host_tag_part_too_long(self):\n too_long = \"a\" * 256\n\n for tags_query, part_name in (\n (f\"{too_long}/key=val\", \"namespace\"),\n (f\"namespace/{too_long}=val\", \"key\"),\n (f\"namespace/key={too_long}\", \"value\"),\n ):\n with s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The number of full days since last checkin. We consider the current day to start from 5AM local time. Note that this can be more than 24 hours ago!
def days_since_last_checkin(self): # TODO use local timezone checkin_date = (self.last_checkin - datetime.timedelta(hours=5)).date() today = datetime.date.today() return (today - checkin_date).days
[ "def get_number_days(self):\r\n return 1", "def total_days(self):\n return self.total_microseconds() / 86400000000", "def dayAhead():\n return int( time.strftime( \"%Y%m%d\",time.gmtime(time.time()+60*60*24) ) )", "def get_fine_due(self):\n fine = 0\n ndays = (dt.datetime.now() ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the owner of this link.
def set_owner(self, owner: Optional["STACObject_Type"]) -> "Link": self.owner = owner return self
[ "def set_owner(self, owner):\n self.settings[\"owner\"] = owner", "def owner(self, owner):\n \n self._owner = owner", "def owner(self, owner):\n self._owner = owner", "def set_owner(self, owner: Owner):\n ...", "def setOwner(self, newOwner):\r\n self.owner = newOwne...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Optional title for this link. If not provided during instantiation, this will attempt to get the title from the STAC object that the link references.
def title(self) -> Optional[str]: if self._title is not None: return self._title if self._target_object is not None and isinstance( self._target_object, pystac.Catalog ): return self._target_object.title return None
[ "def get_title(self):\n return self.display_title and self.title or \"\"", "def link_title(self):\n\n if self.publication_type == u'link' and 'v12' in self.data:\n return self.data['v12'][0]['_']", "def short_title(self):\n if hasattr(self, \"title\"):\n return self.ti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the HREF for this link. If the href is None, this will throw an exception. Use get_href if there may not be an href.
def href(self) -> str: result = self.get_href() if result is None: raise ValueError(f"{self} does not have an HREF set.") return result
[ "def link(self, href):\r\n\r\n return self.find_tag(\"a\", \"href\", href)[\"href\"]", "def href(self):\n return self._href", "def absolute_href(self) -> str:\n result = self.get_absolute_href()\n if result is None:\n raise ValueError(f\"{self} does not have an HREF set.\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the absolute HREF for this link. If the href is None, this will throw an exception. Use get_absolute_href if there may not be an href set.
def absolute_href(self) -> str: result = self.get_absolute_href() if result is None: raise ValueError(f"{self} does not have an HREF set.") return result
[ "def get_absolute_href(self) -> Optional[str]:\n if self._target_object:\n href = self._target_object.get_self_href()\n else:\n href = self._target_href\n\n if href is not None and self.owner is not None:\n href = make_absolute_href(href, self.owner.get_self_hre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the absolute href for this link, if possible.
def get_absolute_href(self) -> Optional[str]: if self._target_object: href = self._target_object.get_self_href() else: href = self._target_href if href is not None and self.owner is not None: href = make_absolute_href(href, self.owner.get_self_href()) ...
[ "def absolute_href(self) -> str:\n result = self.get_absolute_href()\n if result is None:\n raise ValueError(f\"{self} does not have an HREF set.\")\n return result", "def href(self) -> str:\n result = self.get_href()\n if result is None:\n raise ValueError...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The target of the link. If the link is unresolved, or the link is to something that is not a STACObject, the target is an HREF. If resolved, the target is a STACObject.
def target(self) -> Union[str, "STACObject_Type"]: if self._target_object: return self._target_object elif self._target_href: return self._target_href else: raise ValueError("No target defined for link.")
[ "def get_target_str(self) -> Optional[str]:\n if self._target_href:\n return self._target_href\n elif self._target_object:\n return self._target_object.get_self_href()\n else:\n return None", "def get_target_link(self, target):\n for link in self.target...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets this link's target to a string or a STAC object.
def target(self, target: Union[str, "STACObject_Type"]) -> None: if isinstance(target, str): self._target_href = target self._target_object = None else: self._target_href = None self._target_object = target
[ "def setTarget(self, target):\n self.target = target", "def target(self) -> Union[str, \"STACObject_Type\"]:\n if self._target_object:\n return self._target_object\n elif self._target_href:\n return self._target_href\n else:\n raise ValueError(\"No targ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns this link's target as a string. If a string href was provided, returns that. If not, tries to resolve the self link of the target object.
def get_target_str(self) -> Optional[str]: if self._target_href: return self._target_href elif self._target_object: return self._target_object.get_self_href() else: return None
[ "def target(self) -> Union[str, \"STACObject_Type\"]:\n if self._target_object:\n return self._target_object\n elif self._target_href:\n return self._target_href\n else:\n raise ValueError(\"No target defined for link.\")", "def target_url(self):\n if u...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if this link has a string href in its target information.
def has_target_href(self) -> bool: return self._target_href is not None
[ "def linkHasRel(link_attrs, target_rel):\r\n # XXX: TESTME\r\n rel_attr = link_attrs.get('rel')\r\n return rel_attr and relMatches(rel_attr, target_rel)", "def is_link(self):\n return self.__is_link", "def is_href_valid(self, link):\n url = str(link['href'])\n # if it doesn't lead ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resolves a STAC object from the HREF of this link, if the link is not already resolved.
def resolve_stac_object(self, root: Optional["Catalog_Type"] = None) -> "Link": if self._target_object: pass elif self._target_href: target_href = self._target_href # If it's a relative link, base it off the parent. if not is_absolute_href(target_href): ...
[ "def maybe_resolve(object, resolve):\n if isinstance(object, dict) and object.get('$ref'):\n return resolve(object['$ref'])\n return object", "def get_resource_from_uri(self, href):\n if not href.is_absolute():\n # resolve relative to the service root\n href = href.resolv...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines if the link's target is a resolved STACObject.
def is_resolved(self) -> bool: return self._target_object is not None
[ "def target(self) -> Union[str, \"STACObject_Type\"]:\n if self._target_object:\n return self._target_object\n elif self._target_href:\n return self._target_href\n else:\n raise ValueError(\"No target defined for link.\")", "def has_target_href(self) -> bool:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clones this link. This makes a copy of all link information, but does not clone a STACObject if one is the target of this link.
def clone(self) -> "Link": cls = self.__class__ return cls( rel=self.rel, target=self.target, media_type=self.media_type, title=self.title, )
[ "def __copy__(self):\r\n other = self.__class__(\r\n linkers=[copy(l) for l in self.linkers],\r\n wrapper=self.wrapper)\r\n return other", "def copy(self):\r\n\t\tobj = DecaLink()\r\n\t\tfor k in self.__dict__.keys():\r\n\t\t\tobj.__setattr__(k, self.__getattribute__(k))\r\n\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deserializes a Link from a dict.
def from_dict(cls, d: Dict[str, Any]) -> "Link": d = copy(d) rel = d.pop("rel") href = d.pop("href") media_type = d.pop("type", None) title = d.pop("title", None) extra_fields = None if any(d): extra_fields = d return cls( rel=rel...
[ "def link_from_dict(self, link_dict):\n id_a = link_dict.get('endpoint_a')\n id_b = link_dict.get('endpoint_b')\n\n endpoint_a = self.controller.get_interface_by_id(id_b)\n endpoint_b = self.controller.get_interface_by_id(id_a)\n\n link = Link(endpoint_a, endpoint_b)\n link...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a link to a root Catalog or Collection.
def root(cls, c: "Catalog_Type") -> "Link": return cls(pystac.RelType.ROOT, c, media_type=pystac.MediaType.JSON)
[ "def root_catalog(self, cat_paths, root_dir, name=\"THREDDS catalog\"):\n catalogs = []\n\n for path in cat_paths:\n cat_name = get_catalog_name(path)\n\n # href must be relative to the root catalog itself\n href = os.path.relpath(path, start=root_dir)\n cat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a link to a parent Catalog or Collection.
def parent(cls, c: "Catalog_Type") -> "Link": return cls(pystac.RelType.PARENT, c, media_type=pystac.MediaType.JSON)
[ "def _create_question_link(self, parent, child):\n child.link_parent(parent)", "def parent(self, parent: ClienteLinksParent):\n\n self._parent = parent", "def create_urlpath(self, parent, slug):\r\n return URLPath.create_article(parent, slug, title=slug)", "def link_to_parent(self, pcf, p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a link to an item's Collection.
def collection(cls, c: "Collection_Type") -> "Link": return cls(pystac.RelType.COLLECTION, c, media_type=pystac.MediaType.JSON)
[ "def create_link_collection(self):\n return LinkCollection(endpoint=self)", "def get_collection_link(db_id, collection_id):\n\n # Return a link to the relevant CosmosDB Container/Document Collection\n return \"dbs/\" + db_id + \"/colls/\" + collection_id", "def canonical(\n cls,\n ite...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a link to a child Catalog or Collection.
def child(cls, c: "Catalog_Type", title: Optional[str] = None) -> "Link": return cls( pystac.RelType.CHILD, c, title=title, media_type=pystac.MediaType.JSON )
[ "def _create_question_link(self, parent, child):\n child.link_parent(parent)", "def parent(cls, c: \"Catalog_Type\") -> \"Link\":\n return cls(pystac.RelType.PARENT, c, media_type=pystac.MediaType.JSON)", "def create_link_collection(self):\n return LinkCollection(endpoint=self)", "def add...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a link to an Item.
def item(cls, item: "Item_Type", title: Optional[str] = None) -> "Link": return cls( pystac.RelType.ITEM, item, title=title, media_type=pystac.MediaType.JSON )
[ "def createItem(self, item):\r\n try:\r\n self.feed_handler.createItem(item.link, item.title, item.descr,\r\n item.source, item.channelURL)\r\n self.feed_passed = self.feed_passed + 1\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a canonical link to an Item or Collection.
def canonical( cls, item_or_collection: Union["Item_Type", "Collection_Type"], title: Optional[str] = None, ) -> "Link": return cls( pystac.RelType.CANONICAL, item_or_collection, title=title, media_type=pystac.MediaType.JSON, )
[ "def item_link(self, item):\n return item.get_absolute_url()", "def __transform_item_link(self, item: Dict[str, Any]) -> str:\n if item['external_link']:\n return item['external_link']\n else:\n return self.construct_alternate_link() + '/' + item['url']['url']", "def i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fetch the crime data
def test_fetch_crime(self): assert isinstance(_tabular.fetch_crime_data(), pd.DataFrame)
[ "async def get_crime(city: City):\n\n city = validate_city(city)\n value = await select(\"Crime Rating\", city)\n return {\"crime\": value[0]}", "def Crime():\n results = ses.query(CrimeRecord.PrimaryType).all()\n\n # Use numpy ravel to extract list of tuples into a list of Crime Type\n Crime_Li...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unsubscribes a PubgemUser from an RSSFeed.
def unsubscribe(self, *rss_feeds): [self.subscriptions.remove(feed) for feed in rss_feeds if feed in self.subscriptions] self.save()
[ "def unsubscribe(feed):\n from django_salmon.models import Subscription\n Subscription.objects.unsubscribe(feed)", "def unsubscribe(self, feed, **args):\n args.update(feed=feed)\n return self.fetch(\"/unsubscribe\", post_args=args)", "def unsubscribe(id, userId):\n db = core.connect()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save environment identifier to local file for defaulting.
def save_default_environment( environment=None, cwd=None ): env_file = get_local_default_file(cwd=cwd) with open(env_file, 'w') as f_out: f_out.write(f'{str(environment)}\n') return True
[ "def save_environment(path: Optional[str] = None):\n environment = EnvironmentProvider().environment\n serialize_environment_to_file(environment=environment,\n path=path)", "def save_to_env_file(self, envs, env_file_location):\n\n if not self.pre_initiated and envs:\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove saved default environment file.
def clear_saved_default_environment(cwd=None): env_file = get_local_default_file(cwd=cwd) if os.path.exists(env_file): os.remove(env_file) return True else: return False
[ "def reset_default_paths():\n filename = os.path.join(os.path.expanduser('~'), '.gfail_defaults')\n if os.path.exists(filename):\n os.remove(filename)\n print('Default paths cleared\\n')\n else:\n print('No default paths currently set\\n')", "def reset(self):\r\n if os.path.is...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate secrets base directory by presence of a marker file. Returns False if the directory either does not exist or does not contain the expected marker file, or True otherwise.
def is_secrets_basedir(basedir=None, raise_exception=True): result = False if basedir is None: if raise_exception: raise RuntimeError("[-] no basedir was specified") basedir_path = Path(basedir) marker_path = Path(basedir) / MARKER if not basedir_path.exists(): if raise_e...
[ "def validate_secrets_file(self):\n if self._is_pack_file_exists(self.secrets_file) and all([self._is_secrets_file_structure_valid()]):\n return True\n\n return False", "def secrets_file_path_exists(self):\n return self.get_secrets_file_path().exists()", "def secrets_basedir_exis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the default secrets base directory path.
def get_default_secrets_basedir(): default_basedir = Path.home() / BASEDIR_BASENAME return Path( os.getenv('D2_SECRETS_BASEDIR', default_basedir) )
[ "def get_secrets_descriptions_dir(self):\n _env = self._environment\n if not _env:\n return self.get_secrets_basedir()\n else:\n return self.get_secrets_basedir() / self.get_secrets_basename().replace('.json', '.d') # noqa", "def get_secrets_file_path(self, env=None):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create secrets root directory
def secrets_basedir_create( basedir=None, mode=DEFAULT_MODE, ): if basedir is None: raise RuntimeError("[-] a base directory is required") secrets_basedir = Path(basedir) secrets_basedir.mkdir( parents=True, mode=mode, exist_ok=True ) marker = secrets_basedir ...
[ "def ensure_secrets_basedir(\n secrets_basedir=None,\n allow_create=False,\n allow_prompt=False,\n verbose_level=1,\n):\n if secrets_basedir is None:\n secrets_basedir = get_default_secrets_basedir()\n homedir = str(Path.home())\n if allow_create is None:\n allow_create = str(secr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure that the secrets basedir exists. If the path is within the user's home directory, it is OK to create the directory automatically if it does not exist. This was the original behavior. If the path does exist and contains file, but does not have the special marker, that will be considered an error the user needs to...
def ensure_secrets_basedir( secrets_basedir=None, allow_create=False, allow_prompt=False, verbose_level=1, ): if secrets_basedir is None: secrets_basedir = get_default_secrets_basedir() homedir = str(Path.home()) if allow_create is None: allow_create = str(secrets_basedir).st...
[ "def is_secrets_basedir(basedir=None, raise_exception=True):\n result = False\n if basedir is None:\n if raise_exception:\n raise RuntimeError(\"[-] no basedir was specified\")\n basedir_path = Path(basedir)\n marker_path = Path(basedir) / MARKER\n if not basedir_path.exists():\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the default environment identifier. There are multiple ways for a user to specify the environment to use for python_secrets commands. Some of these involve explicit settings (e.g., via command line option, a saved value in the current working directory, or an environment variable) or implicitly from the name of ...
def get_default_environment(cwd=None): # NOTE(dittrich): I know this code has multiple return points # but it is simpler and easier to understand this way. # # Highest priority is inhereted environment variable. environment = os.getenv('D2_ENVIRONMENT', None) if environment is not None: ...
[ "def get_conda_env_name():\n env_name = os.popen('echo $CONDA_DEFAULT_ENV').read().strip()\n if env_name == '' or env_name == '$CONDA_DEFAULT_ENV':\n env_name = 'base'\n logging.info('Anaconda environment: ' + env_name)\n return env_name", "def default_credentials_id(self) -> str:\n if s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Just copy the descriptions portion of an environment directory from src to dst.
def copydescriptions(src: Path, dst: Path): if not dst.suffix == '.d': raise InvalidDescriptionsError( msg=f"[-] destination '{dst}' is not a descriptions ('.d') directory" # noqa ) # Ensure destination directory exists. dst.mkdir(exist_ok=True) if src.suffix == '.d' and no...
[ "def clone_from(self, src: Union[Path, str]):\n if isinstance(src, Path):\n if src.is_dir() and src.suffix != '.d':\n raise RuntimeError(\n \"[-] refusing to process a directory without \"\n f\"a '.d' extension ('{str(src)}')\")\n eli...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Output an ASCII BEL character to ``stderr``.
def bell(): if sys.stderr.isatty(): sys.stderr.write('\a') sys.stderr.flush()
[ "def print_err(str):\n sys.stderr.write(str)\n sys.stderr.write(\"\\n\")", "def err(*s):\n sys.stderr.write(TERM.bold_red)\n sys.stderr.write('Error: ')\n for part in s:\n sys.stderr.write(part)\n sys.stderr.write(TERM.normal)\n sys.stderr.write('\\n')", "def __print_stderr(msg):\n sy...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Identifies the filesystem mount point for the partition containing ``mypath``.
def getmount(mypath): # noqa path_ = os.path.realpath(os.path.abspath(mypath)) while path_ != os.path.sep: if os.path.ismount(path_): return path_ path_ = os.path.abspath(os.path.join(path_, os.pardir)) return path_
[ "def find_mount_point(path):\n path = os.path.abspath(path)\n while not os.path.ismount(path):\n path = os.path.dirname(path)\n return path", "def get_fs_type(mypath):\n\n root_type = ''\n for part in psutil.disk_partitions():\n if part.mountpoint == os.path.sep:\n root_typ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Identifies the file system type for a specific mount path.
def getmount_fstype(mypath): mountpoint = getmount(mypath) return get_fs_type(mountpoint)
[ "def get_fs_type(mypath):\n\n root_type = ''\n for part in psutil.disk_partitions():\n if part.mountpoint == os.path.sep:\n root_type = part.fstype\n continue\n if str(mypath).startswith(part.mountpoint):\n return part.fstype\n return root_type", "def get_ty...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Identifies the file system type for a specific mount path.
def get_fs_type(mypath): root_type = '' for part in psutil.disk_partitions(): if part.mountpoint == os.path.sep: root_type = part.fstype continue if str(mypath).startswith(part.mountpoint): return part.fstype return root_type
[ "def getmount_fstype(mypath):\n\n mountpoint = getmount(mypath)\n return get_fs_type(mountpoint)", "def get_type(self):\n return self.get_udev_property('ID_FS_TYPE')", "def get_fs_type(self):\n\t\treturn call_sdk_function('PrlFsInfo_GetFsType', self.handle)", "def getFsType(partitionDevice):\n i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets a list of absolute paths to one or more files associated with a path. If ``path`` is a directory, the files contained in it are returned, otherwise the path to the file is the only item in the list.
def get_files_from_path(path=None): abspath = os.path.abspath(path) if os.path.isfile(abspath): files = [abspath] elif os.path.isdir(abspath): files = [ os.path.join(abspath, fname) for fname in os.listdir(abspath) ] else: raise RuntimeError(f"[-]...
[ "def get_files_by_path(path):\n path = Path(path)\n if path.is_file():\n return [path]\n if path.is_dir():\n return get_morph_files(path)\n\n raise IOError('Invalid data path %s' % path)", "def get_all_file_paths(path):\n\n # initializing empty file paths list\n file_paths = []\n\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return sorted list of valid environment paths found in `basedir`.
def get_environment_paths(basedir=None): basedir = ( get_default_secrets_basedir() if basedir is None else Path(basedir) ) results = list() for item in sorted(basedir.iterdir()): if is_valid_environment(item): results.append(item) return results
[ "async def _environment_paths() -> list[str]:\n env = await Get(EnvironmentVars, EnvironmentVarsRequest((\"PATH\",)))\n path = env.get(\"PATH\")\n if path:\n return path.split(os.pathsep)\n return []", "def get_environment_paths(env: Environment):\n pathstr = env.get(\"PATH\")\n i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Derives the CIDR netblocks for an IP via WHOIS lookup.
def get_netblock(ip=None): ip = str(ip).split('/')[0] if '/' in str(ip) else ip obj = IPWhois(ip) results = obj.lookup_whois() return results['asn_cidr']
[ "def get_subnet_cidr_block():\n current = 0\n high = 255\n while current <= high:\n yield '10.0.%s.0/24' % current\n current += 1", "def ip_get_blocks():\n # start Requests session\n sc = requests.Session()\n\n # import cookies from Firefox\n sc.cookies.update(get_cookies('imhsc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make all files in path ``dst`` have ``orwx`` permissions.
def remove_other_perms(dst): # File permissions on Cygwin/Windows filesystems don't work the # same way as Linux. Don't try to change them. # TODO(dittrich): Is there a Better way to handle perms on Windows? fs_type = get_fs_type(dst) if fs_type in ['NTFS', 'FAT', 'FAT32']: msg = ( ...
[ "def copystat(src, dst):\n if sys.platform == 'win32' and S_ISDIR(os.stat(dst)[ST_MODE]):\n if os.name == 'nt':\n st = os.stat(src)\n mode = S_IMODE(st[ST_MODE])\n if hasattr(os, 'chmod'):\n os.chmod(dst, mode) # KEEP THIS ONE!\n #else: pass # we are ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Produces the tree structure for groups and secrets in an environment. If output is specified (e.g., as sys.stdout) it will be used, otherwise a list of strings is returned.
def secrets_tree( env=None, outfile=None ): nodes = dict() env_name = str(env) nodes[env_name] = Node(env_name) root_node = nodes[env_name] for group in sorted(env.get_groups()): group_name = os.path.join(env_name, group) nodes[group_name] = Node(group, parent=root_node) ...
[ "def write_tree(self):\n return self._getoutput(\"write-tree\")", "def output_groups(self) -> List[str]:\n return self._output_groups", "def _output_tree(self):\n\n # Base output directory\n primary = os.path.join(self.bids_root, \n 'derivativ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prettyprint environment variable (if set).
def show_current_value(variable=None): value = os.getenv(variable, None) return f" ('{value}')" if value is not None else ''
[ "def print_env_info(key, out=sys.stderr):\n value = os.getenv(key)\n if value is not None:\n print(key, \"=\", repr(value), file=out)", "def print_env():\n denv = fabutils.dot_env()\n import pprint\n\n pprint.pprint(denv)", "def html_for_env_var(key):\n\n value = os.getenv(key)\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Records a lap time. If no lap label is specified, a single 'last lap' counter will be (re)used. To keep track of more laps, provide labels yourself.
def lap(self, lap="__lap__"): t = time.time() self.laps[lap] = t return t
[ "def lap(self, label=None):\n if not label:\n label = f'Lap{len(self.times)}'\n self.times.append((label, datetime.now()))", "def lap(self):\n lap_time = datetime.now()\n lap_index = len(self.laps)\n last_lap = [\n e.time\n for e in self.events\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the timer for label specified by 'lap'
def get_lap(self, lap="__exit__"): return self.lap[lap]
[ "def lap(self, lap=\"__lap__\"):\n t = time.time()\n self.laps[lap] = t\n return t", "def parse_lap_time(s: str) -> int:\n LAP_TIME_PATTERN = r\"(\\d+):(\\d{2})\\.(\\d{3})\"\n\n matches = re.fullmatch(LAP_TIME_PATTERN, s).groups()\n minutes, seconds, millis = tuple(map(int, matches))...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use an HTTP service that only returns IP address.
def myip_http(arg=None): # Return type if no argument for use in Lister. if arg is None: return 'https' page = requests.get(arg, stream=True, timeout=3.05) soup = BeautifulSoup(page.text, 'html.parser') if page.status_code != 200: raise RuntimeError( f"[-] error: {page.re...
[ "def api_myip():\n return request.remote_addr, 200, {'Content-Type': 'text/plain'}", "def GetExternalIp():\n h = httplib2.Http(tempfile.gettempdir(), timeout=10)\n url = 'http://whatismyip.akamai.com'\n resp, content = h.request(url, 'GET')\n if resp.status == 200:\n return content\n for provider in (U...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return list of available method ids for getting IP address.
def get_myip_methods(include_random=False): methods = list(myip_methods.keys()) # For argparse choices, set True if include_random: methods.append('random') return methods
[ "def _get_ids_from_ip(self, ip):\r\n try:\r\n # Does it look like an ip address?\r\n socket.inet_aton(ip)\r\n except socket.error:\r\n return []\r\n\r\n # Find the server via ip address. First try public ip, then private\r\n results = self.list_hardware(p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Main script to initialize DataSource object in interactive python. Currently using ipsana.sh bash script to start this, but should look to using example Dan D. provided for IPython startup. /reg/neh/home/ddamiani/Workarea/psanadev/psmondev/psmon/src/console.py Left some code from psutils module for automatically guessi...
def main(): time0 = time.time() args = initArgs() if not args.exp: from PyDataSource import psutils args.exp = psutils.active_experiment() print('No exp provided -- {:} is the active experiment'.format(args.exp)) ds = PyDataSource.DataSource(**vars(args)) setattr(sys.module...
[ "def setDataSource(self):\n \n self.newExperiment = False\n self.newDataSource = False\n\n if not self.dataSource:\n \n #\n # Select experiment\n #\n \n self.experiment = None\n \n (experimentList,interactionText) = self.getSpecificExperimentList()\n\n if exp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets all unique column names for all csv files in file path.
def get_unique_col_names(source_path: str, sink_path: str) -> None: # Get all files in data directory files = glob.glob(get_project_root() + '/' + source_path + '*.csv') # Get all timestamps from filenames [filename_to_timestamp(f, sink_path) for f in files]
[ "def get_frames_csv_file_names():\n\n\tframes_csv_file_names = list()\n\tfor file in os.listdir(directories.frames_csv_files):\n\t\tif os.path.splitext(file)[1] in directories.csv_files_extensions:\n\t\t\tframes_csv_file_names.append(file)\n\n\t# sort so that we always read in a predefined order\n\t# key: smallest ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retorna o valor do produto com desconto
def desconto(self, porcentagem): return(self.__valor * (100 - porcentagem)/100)
[ "def descricao_produto(self):\n return self._descricao_produto", "def get_descuentos(self):\n return float(\n self.input.get_text(liquidaciones_historicas_catalog.DESCUENTOS).replace(\".\", \"\").replace(\",\", \".\"))", "def obter_valor(c):\n return c[0]", "def get_total_descuento...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets a string designating the mutation type.
def set_mutation_type(self, mut_type=''): if mut_type: # specified mutation type self.mutation_type = mut_type else: # interpret mutation type from attributes if not self.is_valid: # does not correctly fall into a category s...
[ "def type(self, type: str):\n\n self._type = type", "def type(self, string):\n\n\t\tself._interface.type(string)", "def type_name(self, type_name):\n\n self._type_name = type_name", "def data_type_string(self, data_type_string):\n\n self._data_type_string = data_type_string", "def setTy...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the is_splicing_mutation flag
def __set_splice_mutation(self): #len5ss = 6 # positive number since 5SS #len3ss = -20 # use negative syntax like HGVS if type(self.intron_pos) == int: # SNV case, only one position if self.len3ss <= self.intron_pos <= self.len5ss: self.is_splicing_mutat...
[ "def set_seen_op(self, boolean):\n\n self.seen_op = boolean", "def toggle_scattering(self, setting=1):\n if setting not in [0, 1, \"on\", \"off\"]:\n raise ValueError(\n \"The input for the toggle the us of scattering \"\n 'in the model must \"on\" (1) or \"o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets a flag for unkown effect (c.? or ?).
def __set_unknown_effect(self, hgvs_str): unknown_effect_list = ['c.?', '?'] if hgvs_str.lower() in unknown_effect_list: self.unknown_effect = True elif hgvs_str.startswith("("): self.unknown_effect = True else: self.unknown_effect = False
[ "def set_fluorescence(self, flag):\n flag_ = c.c_int(flag)\n logger.debug('StSetFluorFlg(%i)', flag)\n self._lib.StSetFluorFlg(flag_)", "def set_flag(FLAG):\r\n global F\r\n F = F | FLAG", "def set_flag(self, flag, value):\n self.engine.set_flag(flag, value)", "def setFlag(self, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets a flag for missing data (? in HGVS syntax).
def __set_missing_info(self, hgvs_str): if '?' in hgvs_str: self.is_missing_info = True else: self.is_missing_info = False
[ "def missing(self, value):\n self.MISSING = value", "def no_data_value(self, no_data_value):\n\n self._no_data_value = no_data_value", "def _flag_missing_values(ctx, index, replacement):\n col = ctx.matrix.columns[index]\n new_values = [replacement if i is None else i for i in col.values]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse the HGVS DNA mutation string to set attributes. Look at tests/test_nucleotide.py for examples on how specific HGVS strings should be parsed.
def __parse_hgvs_syntax(self, hgvs_str): self.is_valid = True # assume initially the syntax is valid if self.is_substitution: sub_pattern = '(?:(\d+)([+-]\d+)?_)?(\d+)([+-]\d+)?([A-Z]+)>([A-Z]+)$' matches = re.findall(sub_pattern, hgvs_str) if matches: ...
[ "def _parse_nucleotide_level_snp(self, variant_string, hgvs) -> MutationInfo:\n variant_id = self._generate_variant_id(hgvs.protein, hgvs.position, hgvs.reference, hgvs.alternate)\n mutation_info = MutationInfo(\n site=variant_string,\n variant_id=variant_id,\n variant...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Variables for clients scalar aggregation.
def clients_scalar_aggregates(**kwargs): attributes_list = [ "client_id", "ping_type", "os", "app_version", "app_build_id", "channel", ] attributes_type_list = ["STRING", "STRING", "STRING", "INT64", "STRING", "STRING"] user_data_attributes_list = ["metric...
[ "def calculate_vars(self):\n pass", "def _aggregate(self, *params):\n clients_params = np.array(params)\n mean = super()._aggregate(*params)\n noise = np.random.normal(loc=0.0, scale=self._noise_mult*self._clip/len(clients_params), size=mean.shape) \n return mean + noise", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Variables for scalar bucket_counts.
def scalar_bucket_counts(**kwargs): attributes_list = ["ping_type", "os", "app_version", "app_build_id", "channel"] fixed_attributes = ["app_version", "channel"] cubed_attributes = [x for x in attributes_list if x not in fixed_attributes] return dict( attributes=",".join(attributes_list), ...
[ "def bucket_counts(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]:\n pass", "def _num_buckets(self):\n pass", "def _num_buckets(self):\n return self.hash_bucket_size", "def _bucket_frequencies(X, min_bucket_size=32):\n freq = dict()\n total =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Variables for clients histogram bucket counts.
def histogram_bucket_counts(**kwargs): attributes_list = ["ping_type", "os", "app_version", "app_build_id", "channel"] metric_attributes_list = ["metric", "metric_type", "key", "agg_type"] fixed_attributes = ["app_version", "channel"] cubed_attributes = [x for x in attributes_list if x not in fixed_attr...
[ "def _num_buckets(self):\n pass", "def bucket_counts(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]:\n pass", "def _num_buckets(self):\n return self.hash_bucket_size", "def total_clientes(self):\r\n return len(self.clientes_historico)", "def split...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Variables for scalar percentiles.
def scalar_percentiles(**kwargs): attributes = ["ping_type", "os", "app_version", "app_build_id", "channel"] fixed_attributes = ["app_version", "channel"] cubed_attributes = [x for x in attributes if x not in fixed_attributes] return dict( # TODO: be consistent with naming of attributes (e.g. a...
[ "def percentiles(data):\r\n mean = np.array(data).mean()\r\n std = np.array(data).std()\r\n np.array(data).sort() \r\n i_5 = int(0.05 * len(data))\r\n i_50 = int(0.50 * len(data))\r\n i_95 = int(0.95 * len(data))\r\n p_5 = data[i_5]\r\n p_50 = data[i_50]\r\n p_95 = data[i_95]\r\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sort list by Name attribute
def sort_by_name(list_to_sort): return sorted( list_to_sort, key=lambda k: k['Name'].lower() )
[ "def sortedNames(self):\n \n names = [(item.nicename, item.name) for item in self.values()]\n names.sort()\n return [name[1] for name in names]", "def sort_names(li, by_which):\n \n if by_which == 'first':\n li.sort(key = Name.first)\n elif by_which == 'last':\n li.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }