query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Check if user exists in Federal Tax Service Phone and SMS key send as Basic Auth header
def get(self): # Check if authorization is Basic Auth if request.authorization is None: abort(400, message="The resource requires the Basic authentication") # Get phone and SMS key from Basic Auth header phone = request.authorization.username fts_key = request.authori...
[ "def checkUserBasicHttpAuth(self):\n username = self.getBasicHttpUsername()\n if username is None:\n return False\n password = self.getBasicHttpPassword()\n user = authenticate(username=username,password=password)\n if user is None:\n return False\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create new user in Federal Tax Service and send password SMS
def post(self): # Parsing request JSON fields args = fts_user_request.parse_args() # Send signup request fts = FtsRequest() request = fts.signUp(args['name'], args['email'], args['phone']) # Restore password if user exists if request['ftsRequestSuccess'] is False ...
[ "def create_new_user(self):\n name = get_param('What is your name?', self.screen)\n address = get_param('What is your street address?', self.screen)\n city = get_param('What city do you live in?', self.screen)\n state = get_param('What state do you live in?', self.screen)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Private method which builds and returns the model specified by 'self.major_model' and 'self.specific_model', using the parameters given by 'self._model_params' and 'self._training_params'
def _build_model(self): # Confirm that the requested model is real assert self._major_model in _class_method_dict, f"Unknown major model: {self._major_model}" assert self._specific_model in _class_method_dict[self._major_model],\ f"Unknown model: {self._major_model}-{self._specific_m...
[ "def build_model(self):\r\n self.source_images, self.source_labels = self.dataloader.get_model_inputs()\r\n self.target_images, self.target_labels = self.dataloader.get_model_inputs()\r\n\r\n source_model = SimpleModel(self.source_images, self.source_labels, F.output_dim, scope='source_regresso...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Using the base model architecture given by 'self.major_model' and 'self.specific_model' trains MldeModel on x and y.
def train(self, x, y): # Make sure that x and y are the same length # assert len(x) == len(y), "Different number of labels and training points" # Initialize an instance variable for storing models # Build a model # consider ensemble if the model is DNN. For robustness i...
[ "def fit_single_model(self, X,y):\n raise NotImplementedError()", "def __init__(self, model, A, B, **kwargs):\n super(LinearSystem, self).__init__(model)\n self._opts = {}\n self._mats = {'A': np.asarray(A), 'B': np.asarray(B)}\n if 'C' in kwargs:\n self._mats['C'] = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the average predicted values for x over all models trained during train_cv.
def predict(self, x): # Create an array to store predictions in. Add an extra dimension if this predictions = [] # Loop over the cross-validation models for i, model in enumerate(self._models): # Make and store predictions predictions.append(model.predict(x).flat...
[ "def getpreds(models, x_test,y_test,w=None):\n probabs=[]\n i=1\n for clf in models:\n pred=clf.predict(x_test)\n p=np.argmax(pred,axis=1)\n i+=1\n probabs.append(pred) \n probabs=np.array(probabs)\n labels = np.average(probabs, axis=0, weights=w)\n labels=np.argm...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Force deletion of all trained models, and reset the Keras session. Keras sessions are not deleted unless this function is called. Trained models are deleted each time self.train_cv() is called.
def clear_submodels(self): # If a keras model, clear it if self._major_model == "Keras": # If we have the attribute "_models", delete all for model in self._models: model.clear_model() # Dele...
[ "def reset():\n tf.reset_default_graph()\n tf.keras.backend.clear_session()", "def reset_models(self):\n self._models = dict()", "def delete_lens_model_cach(self):\n for model in self._point_source_list:\n model.delete_lens_model_cache()", "def reset_style_models(self) -> None:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copies 'model_params' and 'training_params' and stores them as intance variables.
def __init__(self, model_params, training_params): # Set model and training parameters as instance variables self._model_params = deepcopy(model_params) self._training_params = deepcopy(training_params)
[ "def _update_trainable_params(self):\n self._trainable_params = list(self._par_info)", "def _update_trainable_params(self):\n self._trainable_params = set(self._par_info)", "def get_var_update_params():\n params = benchmark_cnn.make_params(\n batch_size=2,\n model='test_model',\n n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assigns 'mod' as an instance variable.
def __init__(self, mod, placeholder = None): # Set the model as an instance variable as well as the model parameters self._mod = mod
[ "def set_module(self, mod):\n self.module = mod", "def __init__(self, module):\n self.module = module", "def set_modifier(self, mod):\r\n arg_str = p2e._base._util._convert_args_to_string(\"set.node.modifier\", \r\n self._node._eco_id, mod)\r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a SklearnRegressor instance using the GradientBoostingRegressor sklearn model.
def GradientBoostingRegressor(cls, model_params, training_params = None): # Build the sklearn instance mod = GradientBoostingRegressor(**model_params) # Return an instance return cls(mod)
[ "def SGDRegressor(cls, model_params, training_params = None):\n # Build the sklearn instance\n mod = SGDRegressor(**model_params)\n\n # Return an instance\n return cls(mod)", "def RandomForestRegressor(cls, model_params, training_params = None):\n # Build the sklearn instance\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a SklearnRegressor instance using the RandomForestRegressor sklearn model.
def RandomForestRegressor(cls, model_params, training_params = None): # Build the sklearn instance mod = RandomForestRegressor(**model_params) # Create an instance return cls(mod)
[ "def make_rf():\n return sklearn.ensemble.RandomForestRegressor(25, min_samples_leaf=35, max_depth=34, max_features=20)", "def __init__(self, **kwargs):\n\n super().__init__()\n self._forest = RandomForestRegressor_(**kwargs)", "def SGDRegressor(cls, model_params, training_params = None):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a SklearnRegressor instance using the LinearSVR sklearn model.
def LinearSVR(cls, model_params, training_params = None): # Build the sklearn instance mod = LinearSVR(**model_params) # Return an instance return cls(mod)
[ "def svm_regressor(**kwargs):\n return base_models.LinearSVMRegressor(**kwargs)", "def create_linear_regression_model(self):\n\n model = LinearRegression()\n model.fit(self.X_train, self.y_train)\n score = model.score(self.X_test, self.y_test)\n print('Linear regression model:') \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a SklearnRegressor instance using the ARDRegression sklearn model.
def ARDRegression(cls, model_params, training_params = None): # Build the sklearn instance mod = ARDRegression(**model_params) # Return an instance return cls(mod)
[ "def SGDRegressor(cls, model_params, training_params = None):\n # Build the sklearn instance\n mod = SGDRegressor(**model_params)\n\n # Return an instance\n return cls(mod)", "def RandomForestRegressor(cls, model_params, training_params = None):\n # Build the sklearn instance\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a SklearnRegressor instance using the Ridge sklearn model.
def RidgeRegression(cls, model_params, training_params=None): # Build the sklearn instance mod = Ridge(**model_params) # Return an instance return cls(mod)
[ "def ridge_regressor(**kwargs):\n return base_models.RidgeRegressor(**kwargs)", "def create_ridge_model(self):\n \n param_grid = {'alpha': np.arange(0, 2, 0.1)}\n \n model = GridSearchCV(Ridge(), param_grid)\n model.fit(self.X_train, self.y_train)\n score = model.score...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a SklearnRegressor instance using the BayesianRidge sklearn model.
def BayesianRidge(cls, model_params, training_params = None): # Build the sklearn instance mod = BayesianRidge(**model_params) # Return an instance return cls(mod)
[ "def make_blr(**kwargs):\n model = helpers.sk.MultivariateBaggingRegressor(LinearRegression(), max_samples=0.98, max_features=.8, n_estimators=30, **kwargs)\n return model", "def RidgeRegression(cls, model_params, training_params=None):\n # Build the sklearn instance\n mod = Ridge(**model_para...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a SklearnRegressor instance using the BaggingRegressor sklearn model.
def BaggingRegressor(cls, model_params, training_params = None): # Build the sklearn instance mod = BaggingRegressor(**model_params) # Return an instance return cls(mod)
[ "def make_blr(**kwargs):\n model = helpers.sk.MultivariateBaggingRegressor(LinearRegression(), max_samples=0.98, max_features=.8, n_estimators=30, **kwargs)\n return model", "def runBaggingRegressor(trainingData, trainingActions, testData, testActions):\n regressorBR = BaggingRegressor(bootstrap=True, n_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a SklearnRegressor instance using the LassoLarsCV sklearn model.
def LassoLarsCV(cls, model_params, training_params = None): # Build the sklearn instance mod = LassoLarsCV(**model_params) # Return an instance return cls(mod)
[ "def lasso_regressor(**kwargs):\n return base_models.LassoRegressor(**kwargs)", "def build_lasso(alp,X_train,y_train):\n # Training model\n lasso_reg = Lasso(alpha=alp)\n lasso_reg.fit(X_train, y_train)\n\n calculate_rmse(X_train,y_train,lasso_reg)\n \n # Return the model\n return lasso_re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a SklearnRegressor instance using the DecisionTreeRegressor sklearn model.
def DecisionTreeRegressor(cls, model_params, training_params = None): # Build the sklearn instance mod = DecisionTreeRegressor(**model_params) # Return an instance return cls(mod)
[ "def decision_tree_regressor(**kwargs):\n return base_models.DecisionTreeRegressor(**kwargs)", "def RandomForestRegressor(cls, model_params, training_params = None):\n # Build the sklearn instance\n mod = RandomForestRegressor(**model_params)\n\n # Create an instance\n return cls(mo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a SklearnRegressor instance using the SGDRegressor sklearn model.
def SGDRegressor(cls, model_params, training_params = None): # Build the sklearn instance mod = SGDRegressor(**model_params) # Return an instance return cls(mod)
[ "def RandomForestRegressor(cls, model_params, training_params = None):\n # Build the sklearn instance\n mod = RandomForestRegressor(**model_params)\n\n # Create an instance\n return cls(mod)", "def ARDRegression(cls, model_params, training_params = None):\n # Build the sklearn i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a SklearnRegressor instance using the KNeighborsRegressor sklearn model.
def KNeighborsRegressor(cls, model_params, training_params = None): # Build the sklearn instance mod = KNeighborsRegressor(**model_params) # Return an instance return cls(mod)
[ "def create_and_train(self):\n # self.knn = cv2.ml.KNearest_create()\n # self.knn.train(self.flattened_images, cv2.ml.ROW_SAMPLE, self.classifications)\n\n self.knn = neighbors.KNeighborsClassifier(n_neighbors=self.n_neighbors, weights=self.weights,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets an Artist object from the database or creates one.
def get_artist(cls, artist_name: str, session: Session, spotify_svc: Spotify) -> Artist: search = Artist.get_by_name(artist_name, session) if search: return search return cls._create_artist(artist_name, spotify_svc)
[ "def _create_artist(cls, artist_name: str, spotify_svc: Spotify) -> Artist:\n spotify_artist = spotify_svc.get_artist(artist_name)\n genres = [ArtistGenre(genre=x) for x in spotify_artist.genres]\n a = Artist(\n name=spotify_artist.name,\n popularity=spotify_artist.popular...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a nonexistent artist
def _create_artist(cls, artist_name: str, spotify_svc: Spotify) -> Artist: spotify_artist = spotify_svc.get_artist(artist_name) genres = [ArtistGenre(genre=x) for x in spotify_artist.genres] a = Artist( name=spotify_artist.name, popularity=spotify_artist.popularity, ...
[ "def get_or_create_artist(name):\n artist = find_artist(name)\n\n if artist:\n artist.add_name(normalize_name(name))\n return False, artist\n\n return True, create_artist(name)", "def task_4_artists_create_song():\n Song.objects.create(artist_id=3, title='worship the father', album_name=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes ghost atoms from the atom graph (not needed after chirality checks).
def remove_ghost_atoms(atoms): ghost_atoms = [atom for atom in atoms.nodes() if isinstance(atom, GhostAtom)] atoms.remove_nodes_from(ghost_atoms)
[ "def prune_orphaned_nodes(nx_graph): \n\n # Search through graph for every node w/ degree\n unconnected_nodes = [node for node,deg in nx_graph.degree_iter() if deg<1 ]\n \n nx_graph.remove_nodes_from(unconnected_nodes)\n \n return nx_graph", "def remove_unreachable_nodes(graph):\n\n for node ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if the chiral atom candidates have rankable substituents on each site (i.e. discounting those whose neighbour list contains the same univalent atoms).
def rankable_neighbours(chiral_cands): maybe_chiral, not_chiral = [], [] for chiral_cand in chiral_cands: atoms = chiral_cand.molecule.atoms neighbours = atoms.neighbors(chiral_cand) # Univalent atoms only have the original chiral_cand atom in their neighbour list. Possibly twice, becau...
[ "def precheck(atoms, i, j, Hs, As, Ds, fsc0):\n ei, ej = atoms[i].element, atoms[j].element\n altloc_i = atoms[i].parent().altloc\n altloc_j = atoms[j].parent().altloc\n resseq_i = atoms[i].parent().parent().resseq\n resseq_j = atoms[j].parent().parent().resseq\n one_is_Hs = ei in Hs or ej in Hs\n other_is_a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test data for LookupTest test case.
def insert_lookup_test_data(self): self.add_collection('col1', 'Description for collection1') self.add_collection('col2', 'Description for collection2') self.add_coordinate_frame('cf1', 'Description for cf1', 0, 1000, 0, 1000, 0, 1000, 4, 4, 4) self.add_experiment('col1', 'exp...
[ "def getTestingData(self):", "def test_can_build_lookup_table_and_use_it_for_known_values():\n\n # John prepares data to be looked up\n ts = array([0.1, 1.1, 2.1])\n x1 = array([10.2, -1.4, 4.1])\n x2 = array([0.1, 0.01, 0.4])\n\n # John calculates \"trajectory\" for his data\n table = LookupTab...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a new collection and lookupkey to the database
def add_collection(self, collection_name, description): col = Collection.objects.create(name=collection_name, description=description, creator=self.user) # Add a lookup key lkup_key = str(col.pk) bs_key = col.name BossLookup.objects.create(lookup_key=lkup_key, boss_key=bs_key, c...
[ "def add_collection(self, col):\n h = col.get_parent_handle()\n self.collections[h].append(col)\n # Update our cache with the given object's\n self.cache.update(col.get_cache())", "def add_collection(session, collection):\n validate(collection, COLLECTION_SCHEMA)\n collection_obj...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a new coordinate frame
def add_coordinate_frame(self, coordinate_frame, description, x_start, x_stop, y_start, y_stop, z_start, z_stop, x_voxel_size, y_voxel_size, z_voxel_size): cf = CoordinateFrame.objects.create(name=coordinate_frame, description=description, ...
[ "def add(self, event):\r\n self.polygons[0].add (event.x, self.toCartesian(event.y))\r\n self.visit()", "def add_frame(self, frame):\n self.connected_frames.append(frame)\n self.index.append(frame.index)", "def add_frame(self):\n self._frames.append([])", "def add(self, fram...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set availability for teacher.
def set_availability(member_id, start_time, end_time): availability_start_time = start_time.toZone(TimeZone.UTC).asdatetime().strftime("%Y-%m-%dT%H:%M:%SZ") availability_end_time = (end_time + 1).toZone(TimeZone.UTC).asdatetime().strftime("%Y-%m-%dT%H:%M:%SZ") set_availability_json = {"param": ...
[ "def set_as_treasurer(self):\n with transaction.atomic():\n self.is_member = False\n self.is_secretary = False\n self.is_treasurer = True\n self.is_president = False\n self.is_inactive = False", "def addTeacherToCourse(self, teacher):\r\n self.e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a class and set availability for teacher
def create_class_for_teacher(member_id, start_time, service_type=ClassServiceType.GL, service_sub_type=ClassServiceSubType.Global, class_level=ClassLevel.BEG, language_code=LanguageCode.English, market_co...
[ "def create_teacher(teacher_name):\r\n return Teacher(teacher_name)", "def setup_school(self):\n\n self.school = School()\n # setting up the initial faculty\n random.seed()\n num_teachers = random.randint(0, 12)\n print('num_teachers:', num_teachers) #comment\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Teacher book allocated pl for student
def teacher_book_allocated_pl(class_id, student_member_id, topic, topic_id, service_sub_type=ClassServiceSubType.Global, is_video_class=False): class_info = get_class_info(class_id) booking_start_time = class_info.start_time.toZone(TimeZone.UTC).asdatetime().strftime("%Y-%m-%d %H:%...
[ "def teacher_book_additional_pl(teacher_member_id, start_time, student_member_id, topic, topic_id,\n service_sub_type=ClassServiceSubType.Global, is_video_class=False):\n booking_start_time = start_time.toZone(TimeZone.UTC).asdatetime().strftime(\"%Y-%m-%d %H:%M:%S\")\n # cp20 is...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Teacher book additional pl for student
def teacher_book_additional_pl(teacher_member_id, start_time, student_member_id, topic, topic_id, service_sub_type=ClassServiceSubType.Global, is_video_class=False): booking_start_time = start_time.toZone(TimeZone.UTC).asdatetime().strftime("%Y-%m-%d %H:%M:%S") # cp20 is 30 minute...
[ "def addTeacherToCourse(self, teacher):\r\n self.extra_teachers.append(teacher)", "def teacher_book_allocated_pl(class_id, student_member_id, topic, topic_id,\n service_sub_type=ClassServiceSubType.Global, is_video_class=False):\n class_info = get_class_info(class_id)\n b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get information of one class by class_id.
def get_class_info(class_id): class_info_tuple = usvs1_ms_sql.exec_query_and_fetch_first(class_info_query, class_id=class_id) class_info = ClassInfo() class_info.class_id = class_id class_info.service_type = class_info_tuple[0] class_info.service_sub_type = class_info_tuple[1] class_info.start_t...
[ "def getClassbyID(curs, cid):\n curs.execute('select * from classes where cid=%s', (cid,))\n return curs.fetchone()", "def test_get_class_by_id(self):\n response = self.client.open(\n '/pablokvitca/classdeck-api/1.0.0/class/{class_department}/{class_number}'.format(class_department='class_depa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sanitise the redirection URL.
def sanitise_redirect_url(redirect_to): # Light security check -- make sure redirect_to isn't garbage. is_valid = True if not redirect_to or ' ' in redirect_to: is_valid = False elif '//' in redirect_to: # Allow the redirect URL to be external if it's a permitted domain allowed_d...
[ "def _sanitizeURL(self, couchURL):\n return couchURL", "def clean_review_url(self, url):\n url = URL(url)\n if not url.host:\n url = self.base_url.join(url)\n return url", "def clean_url(url) -> str:\n if 'http' not in url:\n return f'http://{url}'\n return ur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Render xrds file This file should contain assertion and return_to urls.
def xrds(request, template_name='openid/xrds.xml'): return_to_url = request.build_absolute_uri(reverse(login_complete)) assertion_url = request.build_absolute_uri(reverse(assertion)) return render_to_response( template_name, { 'return_to_url': return_to_url, 'assertio...
[ "def render_xml(xml):\n response = make_response(xml, 200)\n response.headers['Content-Type'] = 'application/xml'\n return response", "def pytest_runtest_makereport(item):\n pytest_html = item.config.pluginmanager.getplugin('html')\n outcome = yield\n report = outcome.get_result()\n extra = g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Disassociate current user with OpenID
def disassociate(request): # Get the User user = OpenIDBackend.get_user_from_request(request) if not user: raise Http404 # Get OpenID association association = OpenIDBackend.get_user_association(user) if not association: raise Http404 # Remove the association associati...
[ "def __clear_affiliate(request):\n request.session['affiliate'] = None\n if 'old_user_id' in request.session:\n old_user = User.objects.get(id=request.session['old_user_id'])\n old_user.backend = 'django.contrib.auth.backends.ModelBackend'\n logout(request)\n login(request, old_use...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copies common S3 fields from one metadata dict to another.
def copy_object_metadata(source_metadata_dict, destination_metadata_dict): if not destination_metadata_dict: destination_metadata_dict = {} if not source_metadata_dict: return destination_metadata_dict for field in _COMMON_S3_METADATA_FIELDS: if field in source_metadata_dict: destination_metadat...
[ "def copy_metadata(self, other):\n # LOG.debug(f'Copying metadata from {other}') # BUG: Causes infinite recursion!\n if isinstance(other, Dataset):\n for name in self._metadata:\n object.__setattr__(self, name, getattr(other, name, None))\n if isinstance(other, (Datas...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Translates Apitools predefined ACL enum key (as string) to S3 equivalent.
def translate_predefined_acl_string_to_s3(predefined_acl_string): if predefined_acl_string not in _GCS_TO_S3_PREDEFINED_ACL_TRANSLATION_DICT: raise ValueError('Could not translate predefined_acl_string {} to' ' AWS-accepted ACL.'.format(predefined_acl_string)) return _GCS_TO_S3_PREDEFINED_A...
[ "def enum_name(name):\n assert name.startswith('GL_')\n return name[3:]", "def _k(cls, key: Any) -> Any:\n return key.lower() if isinstance(key, str) else key", "def to_api_case(dict_key):\n return snakecase(dict_key)", "def get_aws_reversed_acl_bucket_name(target_bucket):\n if \"target...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates storage_url.CloudUrl from S3 API response.
def _get_object_url_from_s3_response(object_dict, bucket_name, object_name=None): return storage_url.CloudUrl( scheme=storage_url.ProviderPrefix.S3, bucket_name=bucket_name, object_name=object_name, generation=object_dic...
[ "def parse_s3_url(self, s3_url):\n\n self.logger.debug('Parsing S3 URL: {}'.format(s3_url))\n\n parse_result = urlparse(s3_url)\n\n scheme = parse_result.scheme\n if parse_result.scheme == 's3':\n bucket = parse_result.netloc\n key = parse_result.path.lstrip('/')\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns base64 encoded MD5 hash, if etag is valid MD5.
def _get_md5_hash_from_etag(etag, object_url): if etag and MD5_REGEX.match(etag): encoded_bytes = base64.b64encode(binascii.unhexlify(etag)) return encoded_bytes.decode(encoding='utf-8') else: log.debug( 'Non-MD5 etag ("%s") present for object: %s.' ' Data integrity checks are not possib...
[ "def get_hash_md5(self):\n\n if md5 is not None:\n return md5( self.get_data() ).hexdigest()", "def get_md5_bytes(data):\n import hashlib\n\n return hashlib.md5(data).hexdigest()", "def md5_checksum(self) -> str:\n file_hash = FileHash(hashlib.md5())\n file_hash.add_file(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates resource_reference.S3BucketResource from S3 API response.
def get_bucket_resource_from_s3_response(bucket_dict, bucket_name): requester_pays = _get_error_or_value(bucket_dict.get('Payer')) if requester_pays == 'Requester': requester_pays = True elif requester_pays == 'BucketOwner': requester_pays = False versioning_enabled = _get_error_or_value(bucket_dict.ge...
[ "def get_object_resource_from_s3_response(object_dict,\n bucket_name,\n object_name=None,\n acl_dict=None):\n object_url = _get_object_url_from_s3_response(\n object_dict, bucket_name, objec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates resource_reference.S3ObjectResource from S3 API response.
def get_object_resource_from_s3_response(object_dict, bucket_name, object_name=None, acl_dict=None): object_url = _get_object_url_from_s3_response( object_dict, bucket_name, object_name or ...
[ "def get_bucket_resource_from_s3_response(bucket_dict, bucket_name):\n requester_pays = _get_error_or_value(bucket_dict.get('Payer'))\n if requester_pays == 'Requester':\n requester_pays = True\n elif requester_pays == 'BucketOwner':\n requester_pays = False\n\n versioning_enabled = _get_error_or_value(bu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates resource_reference.PrefixResource from S3 API response.
def get_prefix_resource_from_s3_response(prefix_dict, bucket_name): prefix = prefix_dict['Prefix'] return resource_reference.PrefixResource( storage_url.CloudUrl( scheme=storage_url.ProviderPrefix.S3, bucket_name=bucket_name, object_name=prefix), prefix=prefix)
[ "def prefix_gen(bucket, prefix, fn=None):\n client = boto3.client(\"s3\")\n paginator = client.get_paginator(\"list_objects_v2\")\n\n response_iterator = paginator.paginate(Bucket=bucket, Prefix=prefix)\n\n for result in response_iterator:\n if \"Contents\" in result:\n yield from (fn(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns S3 bucket metadata dict fields based on RequestConfig.
def get_bucket_metadata_dict_from_request_config(request_config): metadata = {} resource_args = request_config.resource_args if resource_args: if resource_args.cors_file_path is not None: metadata.update( s3_metadata_field_converters.process_cors( resource_args.cors_file_path)) ...
[ "def _backend_metadata(self) -> dict:\n return {\"storage_type\": \"public_s3_bucket\",\n \"name\": \"Public S3 Bucket\",\n \"description\": \"A type to use data stored in a public S3 bucket\",\n \"tags\": [\"unmanaged\", \"s3\", \"aws\"],\n \"icon\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse a PID from its string representation.
def from_string(cls, pid): try: id_, ip_port = pid.split('@') ip, port = ip_port.split(':') port = int(port) except ValueError: raise ValueError('Invalid PID: %s' % pid) return cls(ip, port, id_)
[ "def parse_pid(s):\n\n try:\n pid = int(s)\n except ValueError:\n pid = int(s[:-1])\n return pid", "def parser(self, id):\n if not isinstance(id, str) or not re.match('^[0-9a-fA-F]{24}$', id):\n raise ValueError('objectid is 12 bytes hex str.')\n self.timestamp = i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A customization of np.matrix.__mul__ so that if two Matrix instances are passed in, their attributes of rowvarids and colvarids are kept.
def __mul__(self, other): if hasattr(other, 'colvarids'): if self.colvarids != other.rowvarids: raise ValueError("...") return Matrix(np.matrix(self)*np.matrix(other), rowvarids=self.rowvarids, colvarids=other.colvarids) else: ...
[ "def mul(self, matrix):", "def __mul__(self, matrix):", "def __mul__(self, *args) -> \"SbVec3d\":\n return _coin.SbDPMatrix___mul__(self, *args)", "def element_mul(self, matrix):", "def matMul(self, mat):\n\t\tcols = mat.getColumns()\n\t\treturn self.__class__(*tuple(\n\t\t\t\ttuple(_dotprod3(row, co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the reduced row echelon form (rref) of the matrix using sympy.
def rref(self): # symmat's dtype is sympy.core.numbers.Integer/Zero/One, and # when converted to np.matrix the dtype becomes 'object' which # slows down the matrix computation a lot symmat = sympy.Matrix.rref(sympy.Matrix(self))[0] return Matrix(np.asarray(symmat.tolist(), dtype...
[ "def row_echelon(A):\n\n # if matrix A has no columns or rows,\n # it is already in REF, so we return itself\n r, c = A.shape\n if r == 0 or c == 0:\n return A\n\n # we search for non-zero element in the first column\n for i in range(len(A)):\n if A[i, 0] != 0:\n break\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
M = dy / dx M_normed = diag(1/y) M diag(x)
def normalize(self, y, x): return Matrix.diag(1/y) * self * Matrix.diag(x) # mat = np.matrix(np.diag(1/y)) * np.matrix(self) * np.matrix(np.diag(x)) # return Matrix(mat, self.rowvarids, self.colvarids)
[ "def zero_diag(mat: torch.Tensor) -> torch.Tensor:\n return mat - torch.diag(mat.diag())", "def generate_normed_diff(m1, m2):\n\n #Calculate the difference between the 2 matrices\n diff = m2 - m1\n\n #We make negative elements in the difference matrix to be positive.\n #This is to make normalization possib...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the diagonal Matrix of vector x. D(x) = diag(x)
def diag(x): return Matrix(np.diag(x), x.index, x.index)
[ "def create_diag(x):\n N = x.shape[0]\n D = np.zeros([N, N])\n\n for i in range(N):\n D[i, i] = x[i]\n\n return D", "def diagonal(self) -> \"vnl_vectorD const &\":\n return _vnl_diag_matrixPython.vnl_diag_matrixD_diagonal(self)", "def get_diagonal(self) -> \"vnl_vectorD\":\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Turn plan into BuildOrder.
async def create_plan(self) -> BuildOrder: attack_tactics = [ PlanZoneGather(), PlanZoneDefense(), self.attack, PlanFinishEnemy(), PlanWorkerOnlyDefense(), ] return BuildOrder( [ CounterTerranTie([PaulBuild(...
[ "def unbufferize(worker: AbstractWorker, protobuf_plan: PlanPB) -> \"Plan\":\n\n worker._tmp_placeholders = {}\n id = sy.serde.protobuf.proto.get_protobuf_id(protobuf_plan.id)\n\n operations = []\n for operation in protobuf_plan.operations:\n op_msg = OperationMessagePB()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate and sort Overlord hidden spots. Automatically called at the start of the game once game info is available.
async def on_start(self): await self.real_init() self.calculate_overlord_spots() # This is Infy's fault # noinspection PyProtectedMember self.hidden_ol_spots.sort( key=lambda x: self.knowledge.ai._distance_pos_to_pos(x, self.knowledge.enemy_main_zone.center_location),...
[ "def calculate_overlord_spots(self):\n # first get all highground tiles\n max_height: int = np.max(self.game_info.terrain_height.data_numpy)\n highground_spaces: np.array = np.where(self.game_info.terrain_height.data_numpy == max_height)\n\n # stack the y and x coordinates together, tran...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate hidden overlord spots for scouting.
def calculate_overlord_spots(self): # first get all highground tiles max_height: int = np.max(self.game_info.terrain_height.data_numpy) highground_spaces: np.array = np.where(self.game_info.terrain_height.data_numpy == max_height) # stack the y and x coordinates together, transpose the ...
[ "def n_spot(n_sim=100000, horizon=7, truck_cap=truck_cap):\n\tspot_used = [0]*4\n\tfor i in range(n_sim):\n\t\tday_number = 1\n\t\twhile day_number <= horizon:\n\t\t\tif day_number % 6 == 0 or day_number % 7 == 0:\n\t\t\t\td = np.random.normal(.8*10000, .8*2000)\n\t\t\telse:\n\t\t\t\td = np.random.normal(1.2*10000,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the centroids of the highground clusters for KMeans.
def find_highground_centroids(self, highground_tiles) -> np.array: # using db index, find the optimal number of clusters for kmeans range_of_k = range(4, 22) # store all the davies-bouldin index values dbindexes = [] for k in range_of_k: # try kmeans for each k value...
[ "def get_cluster_centers(self):\n pass", "def get_cluster_centers(self):\n return None", "def compute_centers(self):\n for cluster_ in range(self.number_clusters): # type: ignore\n center = np.mean(self.data[self.model.labels_ == cluster_], axis=0) # type: ignore\n i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads plugindrivers specified in configuration.
def _load_drivers(self): self.drivers, self.default_provider = service_base.load_drivers( constants.LOADBALANCER, self)
[ "def load_plugins(self):\n for pname in self.config['General']['plugins']:\n self.log(\"\\t\" + pname)\n try:\n self.plugs.append(import_(self.config['General']['plugdir']+os.sep+pname))\n except ImportError:\n #try:\n if pname in ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Applies filter and windowing scheme.
def filter(self, v): log.info("Applying windowing scheme") return self._window(v, self.filter_obj.filter(v))
[ "def updateFilterControls(self):\n window = globalref.mainControl.activeControl.activeWindow\n if window.isFiltering():\n filterView = window.treeFilterView\n conditional = filterView.conditionalFilter\n self.setCondition(conditional, conditional.origNodeFormatName)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle a single HTTP request. Overriden to not send 501 errors
def handle_one_request(self): self.close_connection = True try: self.raw_requestline = self.rfile.readline(65537) if len(self.raw_requestline) > 65536: self.requestline = '' self.request_version = '' self.command = '' ...
[ "def handle_one_request(self):\n\n request = self.rfile.readline()\n response = \"\"\n try:\n # Access to protected member; pylint: disable=W0212\n response = self.server._marshaled_dispatch(request)\n # No exc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the ability to add a customer
def test_add_customer(self): database_setup() for customer in TEST_CUSTOMERS: add_customer(customer['id'], customer['first_name'], customer['last_name'], customer['address'], customer['phone_number'], customer['email'], customer['status'], c...
[ "def test_add_customer(self):\n bo.add_customer(**CUST1)\n querydata = bo.Customer.get(\n bo.Customer.customer_id == CUST1['customer_id'])\n self.assertEqual(querydata.customer_id, CUST1['customer_id'])\n self.assertEqual(querydata.full_name, CUST1['full_name'])\n self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the ability to search for a customer
def test_search_customer(self): database_setup() # add in all the customers for customer in TEST_CUSTOMERS: add_customer(customer['id'], customer['first_name'], customer['last_name'], customer['address'], customer['phone_number'], customer['email'], ...
[ "def test_search_customer(self):\n # expected output\n expected = {\n 'full_name': CUST1['full_name'],\n 'last_name': CUST1['last_name'],\n 'email_address': CUST1['email_address'],\n 'phone_number': CUST1['phone_number']\n }\n\n # add customer ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the ability to ability to update a customer
def test_update_customer(self): database_setup() # add in all the customers for customer in TEST_CUSTOMERS: add_customer(customer['id'], customer['first_name'], customer['last_name'], customer['address'], customer['phone_number'], customer['email'], ...
[ "def test_update_customer_credit(self):\n logger.info('-- Testing update existing customer credit limit.--')\n\n # test existing customer\n bo.update_customer_credit(3, 300)\n self.assertEqual(Customer.get(Customer.customer_id == 3).credit_limit,\n 300)\n #...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes a subset of edges of a given type from an edge dataframe. Generally used in the context of machine learning for holdout edges from a gold standard.
def remove_edges(to_remove, edges, target_type): # Separate the edge type to filter keep_edges = edges.query('type != @target_type') to_filter_edges = edges.query('type == @target_type') # Create a set of edges for set operations remove_pairs = set([(tup.start_id, tup.end_id) for tup in to_remove....
[ "def remove_edges(self, eids, etype=None):\n # TODO(xiangsx): block do not support remove_edges\n if etype is None:\n if self._graph.number_of_etypes() != 1:\n raise DGLError('Edge type name must be specified if there are more than one ' \\\n 'ed...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inplace change of an edge type in a hetnet file.
def change_edge_type(edges, idx, new_type, swap=False): edges.loc[idx, 'type'] = new_type if swap: tmp = edges.loc[idx, 'start_id'] edges.loc[idx, 'start_id'] = edges.loc[idx, 'end_id'] edges.loc[idx, 'end_id'] = tmp
[ "def set_edge_type(self, e, t):\n raise NotImplementedError(\"Not implemented on backend \" + type(self).backend)", "def edge_type(self, value):\n # if hasattr(self, 'grEdge') and self.grEdge is not None:\n # self.scene.grScene.removeItem(self.grEdge)\n self._edge_type = value\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inplace updater of Edge Types from a mapping dataframe
def map_edge_types_from_file(edges, map_df, orig_type='type', new_type='new_type', swap_label='reverse_node_labels', nodes=None, start_label='start_label', end_label='end_label', prog=True): # Option to strictly enforce node ...
[ "def new_dict_features_by_type(dict_features_by_type: Dict, mapping_dict: Dict):\r\n df_mapping = pd.DataFrame({\"layer_old\": [x[0] for x in mapping_dict.keys()], \r\n \"layer_new\": [x[0] for x in mapping_dict.values()],\r\n \"feat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Format dataset files with a tabular output.
def tabular(records, *, columns=None): from renku.command.format.tabulate import tabulate if not columns: columns = "added,creators,dataset,full_path" for record in records: record.creators = record.dataset.creators return tabulate( collection=records, columns=columns,...
[ "def _dump_data(self, fileobj):\n if not fileobj and self._file:\n root = os.path.splitext(self._file.name)[0]\n fileobj = root + \".txt\"\n\n close_file = False\n\n if isinstance(fileobj, str):\n fileobj = open(fileobj, \"w\")\n close_file = True\n\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Try to get file size from Git LFS and check if files are tracked in git lfs.
def get_lfs_tracking_and_file_sizes(records, has_tag: bool): from humanize import naturalsize # Slow import repository = project_context.repository def get_lfs_tracking(): if has_tag: return paths = (r.path for r in records) attrs = repository.get_attributes(*paths) ...
[ "def _check_lfs(everything: bool = False):\n files = check_lfs_migrate_info(everything)\n\n if files:\n communication.warn(\"Git history contains large files\\n\\t\" + \"\\n\\t\".join(files))\n\n return files", "def _get_local_repo_size(self):\n return sum(item.stat().st_size for item in os...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Format dataset files as JSONLD.
def jsonld(records, **_): from renku.command.format.json import dumps from renku.command.schema.dataset import DatasetFileSchema data = [DatasetFileSchema(flattened=True).dump(record) for record in records] return dumps(data, indent=2)
[ "def json(records, **_):\n from renku.command.format.json import dumps\n from renku.domain_model.dataset import DatasetFileDetailsJson\n\n for record in records:\n record.creators = record.dataset.creators\n\n data = [DatasetFileDetailsJson().dump(record) for record in records]\n return dumps(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Format dataset files as JSON.
def json(records, **_): from renku.command.format.json import dumps from renku.domain_model.dataset import DatasetFileDetailsJson for record in records: record.creators = record.dataset.creators data = [DatasetFileDetailsJson().dump(record) for record in records] return dumps(data, indent=...
[ "def to_json(dataset: List[\"InputSample\"], output_file: Union[str, Path]):\n\n examples_json = [example.to_dict() for example in dataset]\n\n with open(\"{}\".format(output_file), \"w+\", encoding=\"utf-8\") as f:\n json.dump(examples_json, f, ensure_ascii=False, indent=4)", "def jsonld...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the aliases of this BaseEntity.
def aliases(self, aliases): self._aliases = aliases
[ "def aliases(self, aliases):\n \n self._aliases = aliases", "def set_aliases (self, alias):\r\n self._check_alias_dict(alias, \"alias\")\r\n self.alias = alias", "def addAliases(self, aliases):\n assert isinstance(aliases, dict);\n\n for alias, identifier in aliases.ite...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the api_detail_url of this BaseEntity.
def api_detail_url(self, api_detail_url): self._api_detail_url = api_detail_url
[ "def create_api_url(self):\n self.constants[\"API_URL\"] = (\n \"https://%s.execute-api.%s.amazonaws.com/prod\" % (\n self.constants[\"REST_API_ID\"], self.region))", "def api_url(self):\n return f\"{self.instance_url}/api/0/\"", "def set_api_endpoint(self):\n if c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the deck of this BaseEntity.
def deck(self, deck): self._deck = deck
[ "def __init__(self, deck):\n # self._name = name\n self._deck = deck", "def update_deck(self, deck):\n updated_deck = self.data_source.update_deck(deck)\n\n return updated_deck", "def put_card(self, card):\r\n self.deck.append(card)", "def draw_from_deck(self, deck):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the site_detail_url of this BaseEntity.
def site_detail_url(self, site_detail_url): self._site_detail_url = site_detail_url
[ "def site(self, value: Optional['BaseSite']) -> None:\n if self._site:\n # Warn in any case where the site is (probably) changed after\n # setting it the first time. The appropriate variant is not to use\n # self.site at all or define it once and never change it again\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the date_added of this BaseEntity.
def date_added(self, date_added): self._date_added = date_added
[ "def added_date(self):\n return datetime.utcfromtimestamp(\n self._asset_record[\"fields\"][\"addedDate\"][\"value\"] / 1000.0\n ).replace(tzinfo=timezone.utc)", "def add_date(self, name, value):\r\n self.__add_field('date', name, value)\r\n return self", "def edit_date(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the date_last_updated of this BaseEntity.
def date_last_updated(self, date_last_updated): self._date_last_updated = date_last_updated
[ "def last_modified_at(self, last_modified_at: \"datetime\"):\n self._attrs[\"last_modified_at\"] = last_modified_at", "def set_last_update_time(self, time):\n self.last_updated = time", "def updated_at(self, updated_at): # noqa: E501\n self._updated_at = updated_at", "def set_updated_at(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Only numeric members with has flag set to on will be subtracted
def subtractAllNumericHas (self, other): pass
[ "def __neg__(self) -> NumericValue:\n return self.negate()", "def get_subtract_flag(self):\n return 0x40 & self.get_f()", "def __neg__(self):\n return _almathswig.Position6D___neg__(self)", "def test_subtract_scalar(self):\n self.assertEqual(self.OneType(1, 2, 3) - 2, self.OneType(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a `storage` object from dictionary `mapping`, raising `KeyError` if d doesn't have all of the keys in `requireds` and using the default values for keys found in `defaults`.
def storify(mapping, *requireds, **defaults): _unicode = defaults.pop('_unicode', False) # if _unicode is callable object, use it convert a string to unicode. to_unicode = safeunicode if _unicode is not False and hasattr(_unicode, "__call__"): to_unicode = _unicode def unicodify(s): ...
[ "def storify(mapping, *requireds, **defaults):\n _unicode = defaults.pop('_unicode', False)\n\n # if _unicode is callable object, use it convert a string to unicode.\n to_unicode = safeunicode\n if _unicode is not False and hasattr(_unicode, \"__call__\"):\n to_unicode = _unicode\n\n def unico...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns what percentage a certain key is of all entries. >>> c = counter() >>> c.add('x') >>> c.add('x') >>> c.add('x') >>> c.add('y') >>> c.percent('x') 0.75 >>> c.percent('y') 0.25
def percent(self, key): return float(self[key])/sum(self.values())
[ "def percent(self, key):\n return float(self[key]) / sum(self.values())", "def percent(ctx, number):\n return '%d%%' % int(round(conversions.to_decimal(number, ctx) * 100))", "def percent(json_dic, tag=fj.TAGS['p']):\n total = len(total_classes(json_dic))\n classes = len(classes_with_tag(json_di...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns keys sorted by value. >>> c = counter() >>> c.add('x') >>> c.add('x') >>> c.add('y') >>> c.sorted_keys() ['x', 'y']
def sorted_keys(self): return sorted(self.keys(), key=lambda k: self[k], reverse=True)
[ "def keys(self):\r\n thelist = self._thedict.keys()\r\n if self._order == True:\r\n thelist.sort()\r\n elif self._order == False:\r\n thelist.sort()\r\n thelist.reverse()\r\n return thelist", "def sorted_keys(self):\n keys = self._key_sort(frozen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
removes the string `remove` from the right of `text` >>> rstrips("foobar", "bar") 'foo'
def rstrips(text, remove): return _strips('r', text, remove)
[ "def regex_strip(text, remove=None):\n if not remove:\n return re.compile(r'^\\s*|\\s*$').sub('', text)\n else:\n return re.compile(f'^({remove})*|({remove})*$').sub('', text)", "def strip(text):\n\n return text.strip()", "def explicit_strip(text: str, target: str):\n assert type(text)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
removes the string `remove` from the left of `text` >>> lstrips("foobar", "foo") 'bar'
def lstrips(text, remove): return _strips('l', text, remove)
[ "def regex_strip(text, remove=None):\n if not remove:\n return re.compile(r'^\\s*|\\s*$').sub('', text)\n else:\n return re.compile(f'^({remove})*|({remove})*$').sub('', text)", "def strip(text):\n\n return text.strip()", "def explicit_strip(text: str, target: str):\n assert type(text)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
removes the string `remove` from the both sides of `text` >>> strips("foobarfoo", "foo") 'bar'
def strips(text, remove): return rstrips(lstrips(text, remove), remove)
[ "def regex_strip(text, remove=None):\n if not remove:\n return re.compile(r'^\\s*|\\s*$').sub('', text)\n else:\n return re.compile(f'^({remove})*|({remove})*$').sub('', text)", "def strip(text):\n\n return text.strip()", "def strip_tweet(text, remove_url=True):\n if remove_url:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Converts any given object to utf8 encoded string. >>> safestr('hello') 'hello' >>> safestr(u'\u1234') '\xe1\x88\xb4' >>> safestr(2) '2'
def safestr(obj, encoding='utf-8'): if isinstance(obj, unicode): return obj.encode(encoding) elif isinstance(obj, str): return obj elif hasattr(obj, 'next'): # iterator return itertools.imap(safestr, obj) else: return str(obj)
[ "def safe_unicode(self, obj, *args):\n try:\n return unicode(obj, *args)\n except UnicodeDecodeError:\n # obj is byte string\n ascii_text = str(obj).encode('string_escape')\n return unicode(ascii_text)", "def _ensure_str(obj):\r\n if isinstance(obj, bas...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A decorator to limit a function to `timeout` seconds, raising `TimeoutError` if it takes longer. >>> import time
def timelimit(timeout): def _1(function): def _2(*args, **kw): class Dispatch(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.result = None self.error = None self.setDaemo...
[ "def timelimit(timeout):\n\n def _1(function):\n def _2(*args, **kw):\n class Dispatch(threading.Thread):\n def __init__(self):\n threading.Thread.__init__(self)\n self.result = None\n self.error = None\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Like re.sub, but returns the replacement _and_ the match object. >>> t, m = re_subm('g(oo+)fball', r'f\\1lish', 'goooooofball') >>> t 'foooooolish' >>> m.groups() ('oooooo',)
def re_subm(pat, repl, string): compiled_pat = re_compile(pat) proxy = _re_subm_proxy() compiled_pat.sub(proxy.__call__, string) return compiled_pat.sub(repl, string), proxy.match
[ "def make_regex_subs(self, change_text: str, groups: MatchGroups) -> str:\n\n # g.printObj(list(groups), tag=f\"groups in {change_text!r}\")\n\n def repl(match_object: re.Match) -> str:\n \"\"\"re.sub calls this function once per group.\"\"\"\n # # 1494...\n n = int(ma...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the first element of the iterator or None when there are no elements. If the optional argument default is specified, that is returned instead of None when there are no elements.
def first(self, default=None): try: return iter(self).next() except StopIteration: return default
[ "def first(self, default=None):\r\n try:\r\n return next(iter(self))\r\n except StopIteration:\r\n return default", "def maybe_first(\n iterable: Iterable[T], default: Optional[T] = None\n) -> Optional[T]:\n try:\n return next(iter(iterable))\n except StopIterat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes an iterator safe by ignoring the exceptions occured during the iteration.
def safeiter(it, cleanup=None, ignore_errors=True): def next(): while True: try: return it.next() except StopIteration: raise except: traceback.print_exc() it = iter(it) while True: yield next()
[ "def safeiter(it, cleanup=None, ignore_errors=True):\n\n def next():\n while True:\n try:\n return it.next()\n except StopIteration:\n raise\n except:\n traceback.print_exc()\n\n it = iter(it)\n while True:\n yield ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Writes the content to a temp file and then moves the temp file to given filename to avoid overwriting the existing file in case of errors.
def safewrite(filename, content): f = file(filename + '.tmp', 'w') f.write(content) f.close() os.rename(f.name, filename)
[ "def write_file(self, path, content):\n tmp_fp, tmp_filename = tempfile.mkstemp()\n os.write(tmp_fp, content)\n os.close(tmp_fp)\n self.move(tmp_filename, path)", "def _create_temp_file_with_content(self, content):\n try:\n tmp = tempfile.NamedTemporaryFile(delete=Tru...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the element at index after moving it to the beginning of the queue. >>> x = [1, 2, 3, 4] >>> requeue(x) 4 >>> x [4, 1, 2, 3]
def requeue(queue, index=-1): x = queue.pop(index) queue.insert(0, x) return x
[ "def dequeue(self):\r\n if not self.is_empty():\r\n\r\n tmp_size = self.size - 1\r\n self.size = tmp_size\r\n old_first_val = self.data[self.head]\r\n self.data[self.head] = None\r\n self.head += 1\r\n self.shrink()\r\n return old_f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns `integer` as an int or `default` if it can't. >>> intget('3') 3 >>> intget('3a') >>> intget('3a', 0) 0
def intget(integer, default=None): try: return int(integer) except (TypeError, ValueError): return default
[ "def getint(str, default=None):\r\n if str == '':\r\n if default==None:\r\n raise ValueError(\"None type object is unexpected\")\r\n else:\r\n return default\r\n else:\r\n try:\r\n val = int(str)\r\n return val\r\n except (ValueError, Typ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes all nondigit characters from `string`. >>> numify('8005551212') '8005551212' >>> numify('800.555.1212') '8005551212'
def numify(string): return ''.join([c for c in str(string) if c.isdigit()])
[ "def nummify_string(s, nummifier):\n return filter(None, [nummifier(each) for each in s])", "def string_to_digits(self, string):\n return ''.join([self.character_to_digit(character) for character in string])", "def num(s):\n\ttry:\n\t\treturn int(s)\n\texcept:\n\t\treturn float(s)", "def str2num(s) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Formats `string` according to `pattern`, where the letter X gets replaced by characters from `string`. >>> denumify("8005551212", "(XXX) XXXXXXX") '(800) 5551212'
def denumify(string, pattern): out = [] for c in pattern: if c == "X": out.append(string[0]) string = string[1:] else: out.append(c) return ''.join(out)
[ "def deobfuscate_number(msg, pattern):\n minimally_validate_content_source(msg)\n pattern = get_pattern_from_content_source(msg)\n deobfuscated = phone_numbers.deobfuscate(pattern)\n normalized_deobfuscated = phone_numbers.normalize(deobfuscated)\n return \"Deobfuscated: `\" + deobfuscated + \"`; deo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add commas to an integer `n`. >>> commify(1) '1' >>> commify(123) '123' >>> commify(1234) '1,234' >>> commify(1234567890) '1,234,567,890' >>> commify(123.0) '123.0' >>> commify(1234.5) '1,234.5' >>> commify(1234.56789) '1,234.56789' >>> commify('%.2f' % 1234.5) '1,234.50' >>> commify(None) >>>
def commify(n): if n is None: return None n = str(n) if '.' in n: dollars, cents = n.split('.') else: dollars, cents = n, None r = [] for i, c in enumerate(str(dollars)[::-1]): if i and (not (i % 3)): r.insert(0, ',') r.insert(0, c) out = ''.join(...
[ "def add_commas_gen(num):\n\t# Could also just use '{:,}'.format(12345) #however this does not seem to work\n\treturn locale.format(\"%d\", int(num), grouping=True)", "def add_commas(num):\n\tnums=str(num)\n\tm=1\n\t#return '{:,}'.format(num) # works in new Python3.2\n\twhile m:\n\t\t(nums, m) = re.subn(r\"(\\d)(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tries a series of functions and prints their results. `context` is a dictionary mapping names to values; the value will only be tried if it's callable.
def tryall(context, prefix=None): context = context.copy() # vars() would update results = {} for (key, value) in context.iteritems(): if not hasattr(value, '__call__'): continue if prefix and not key.startswith(prefix): continue print key + ':', try...
[ "def tryall(context, prefix=None):\n context = context.copy() # vars() would update\n results = {}\n for (key, value) in context.iteritems():\n if not hasattr(value, '__call__'):\n continue\n if prefix and not key.startswith(prefix):\n continue\n print key + ':',...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clears all ThreadedDict instances.
def clear_all(): # for t in list(ThreadedDict._instances): # t.clear() _id = get_ident() if _id in localStorage(): del localStorage()[_id] #print localStorage()
[ "def clear_all(self):\n data = self.Entries\n del data[:]", "def clear(self):\r\n with self._hlock: \r\n self.handlers.clear()\r\n with self._mlock: \r\n self.memoize.clear()", "def clear(self):\n\n self._check_init() # Check for delaye...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Automatically assigns local variables to `self`. >>> self = storage() >>> autoassign(self, dict(a=1, b=2)) >>> self
def autoassign(self, locals): for (key, value) in locals.iteritems(): if key == 'self': continue setattr(self, key, value)
[ "def autoassign(self, locals):\n for (key, value) in locals.iteritems():\n if key == 'self':\n continue\n setattr(self, key, value)", "def __init__(self, mapping=None):\n self.storage = {}\n\n if mapping is not None:\n for k, v in mapping.items():\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts an integer to base 36 (a useful scheme for humansayable IDs). >>> to36(35) 'z' >>> to36(119292) '2k1o' >>> int(to36(939387374), 36) 939387374 >>> to36(0) '0' >>> to36(393)
def to36(q): if q < 0: raise ValueError, "must supply a positive integer" letters = "0123456789abcdefghijklmnopqrstuvwxyz" converted = [] while q != 0: q, r = divmod(q, 36) converted.insert(0, letters[r]) return "".join(converted) or '0'
[ "def b36decode(number: str) -> int:\n return int(number, 36)", "def b36encode(number: int) -> str:\n alphabet, base36 = [\"0123456789abcdefghijklmnopqrstuvwxyz\", \"\"]\n\n while number:\n number, i = divmod(number, 36)\n base36 = alphabet[i] + base36\n\n return base36 or alphabet[0]", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends the email message `message` with mail and envelope headers for from `from_address_` to `to_address` with `subject`. Additional email headers can be specified with the dictionary `headers. Optionally cc, bcc and attachments can be specified as keyword arguments. Attachments must be an iterable and each attachment ...
def sendmail(from_address, to_address, subject, message, headers=None, **kw): attachments = kw.pop("attachments", []) mail = _EmailMessage(from_address, to_address, subject, message, headers, **kw) for a in attachments: if isinstance(a, dict): mail.attach(a['filename'], a['content'], a....
[ "def sendmail(from_address, to_address, subject, message, headers=None, **kw):\r\n attachments = kw.pop(\"attachments\", [])\r\n mail = _EmailMessage(from_address, to_address, subject, message, headers, **kw)\r\n\r\n for a in attachments:\r\n if isinstance(a, dict):\r\n mail.attach(a['fil...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Skip file if it was checked previously. Store file if it is the first occurrence of this file. Unlink and create a new hard link if a file with same md5 already exists.
def handle_file(file_path: Path, stored_files: dict): if file_path.stat().st_mtime <= stored_files['last_check']: return md5 = get_md5(file_path) if md5 not in stored_files.keys(): # File first occurrence. Store. stored_files[md5] = [{'path': file_path.as_posix(), 'st_mtime': file_pa...
[ "def check_duplicates(self, file_path):\n\t\tif not file_path:\n\t\t\treturn file_path # !cover\n\t\twith HandlerThread.ele_lock:\n\t\t\t# The IO here could cause issues if multiple Threads tried to delete the same files, so safety lock.\n\t\t\t# Files currently downloading won't exist in the hashjar yet, so there...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Notifies all observers by calling the given function on all observers. If an observer misbehaves they will be booted.
def notify_all(self, fun_name, *args, **kwargs): bad_observers = [] for index, obs in enumerate(self._observers): try: with timeout(seconds = self._timeout): getattr(obs, fun_name)(*args, **kwargs) except Exception: bad_observer...
[ "def notify_all(self, event):\n for observer in self.observers:\n observer.notify(event)", "def _notify_observers(self, *args, **kwargs):\r\n for observer in self.__observers:\r\n observer.notify(*args, **kwargs)", "def _notify(self):\n for listener in self._listeners:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the walls, adds them to the all_sprites_group and returns their group
def create_wall_group(all_sprites_group): wall_group = pygame.sprite.RenderPlain() # parameters of all walls walls = [ (7, 7, 6, 386), (587, 7, 6, 386), (7, 7, 586, 6), (7, 387, 586, 6), (47, 47, 6, 126), (47, 227, 6, 126), (547, 47, 6, 126), ...
[ "def create_wall(ai_settings, screen, platform, bricks):\n # Create an brick, and find number of bricks in a row.\n brick = Bricks(ai_settings, screen)\n number_bricks_x = get_number_bricks_x(ai_settings, brick.rect.width)\n number_rows = get_number_rows(ai_settings, platform.rect.height, brick.rect.hei...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns, what is supposed to be returned to the main module from do_button_mouse_ingame
def _get_button_return(x_coord, y_coord, inputtype, resource_path, clicked_field="string"): if inputtype == "keyboard": return x_coord, y_coord if x_coord == clicked_field[0] and y_coord == clicked_field[1]: # returns the new clicked field, whether a field was hit, and the hit field ...
[ "def check_mouse():\n events = pygame.event.get()\n for event in events:\n # if x clicked\n if event.type == pygame.QUIT:\n sys.exit()\n # if mousebutton pressed, return mouse position\n if event.type == pygame.MOUSEBUTTONDOWN:\n return pygame.mouse.get_pos()"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
plays a clicking sound everytime mouse input is recognized
def _play_click_sound(resource_path): channel = pygame.mixer.Channel(1) # chooses channel for mouse sound try: sound = pygame.mixer.Sound(resource_path("assets/sounds/click.wav")) # takes the mouse sound except FileNotFoundError: chat.add_missing_message("click.wav", resource_path("as...
[ "def on_mouse_click(self):\n base.graphicsEngine.render_frame()\n p=PNMImage(1, 1,4)\n base.graphicsEngine.extract_texture_data(self.mouse_tex, base.win.getGsg())\n self.mouse_tex.store(p)\n c=p.getXelA(0,0)\n id=self.color_to_id(c)\n if id != 0 and id == self.last_m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create customer & supplier for A/C head
def after_insert(self): try: self.create_supplier() self.create_customer() except Exception as e: frappe.db.rollback() # frappe.msgprint(e)
[ "def test_customer_id_added_to_entity(self):\n self._load_template_database()\n nrth_bnd_api = api.build()\n tmp_mxn = nrth_bnd_api.registry.get_category(\"/silver/\", None)\n self.entity.mixins = [tmp_mxn]\n extras = {\"security\": {\"DSS\": \"dss_pass\"}, \"customer\": \"custome...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function takes a Pubmed ID, Pubmed Central ID, or DOI and use the Pubmed ID mapping service and looks up all other IDs from one of these. The IDs are returned in a dictionary.
def id_lookup(paper_id, idtype=None): if idtype is not None and idtype not in ('pmid', 'pmcid', 'doi'): raise ValueError("Invalid idtype %s; must be 'pmid', 'pmcid', " "or 'doi'." % idtype) if paper_id.upper().startswith('PMC'): idtype = 'pmcid' # Strip off any prefi...
[ "def get_pmids_for_dois(doi_records,verbose=False):\n print('Grabbing information from pubmed')\n print('This will take a while because we have to throttle our request rate')\n doi_pmid_cvt={}\n doi_pmids=[]\n bad_cvt=[]\n for id in doi_records.keys():\n\n time.sleep(0.5) # slow down reques...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }