query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
The courses to which a person has participated should appear on this person's detail page.
def test_templates_person_detail_related_courses(self): user = UserFactory(is_staff=True, is_superuser=True) self.client.login(username=user.username, password="password") person = PersonFactory() course = CourseFactory(fill_team=[person]) url = person.extended_object.get_absol...
[ "def get_courses(self) -> Dict[str, Course]:\n return self.courses", "def get_courses(self):\n if not self.is_course_based_activity():\n raise IllegalState()\n else:\n raise Unimplemented()", "def see_teaching_courses(self, username: str, token: str) -> List[Dict[str, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make sure the person detail page does not display too many courses, even when a large number are related to the current person, as this can cause the page to load very slowly and is not a great experience for the user anyway.
def test_templates_person_detail_related_max_courses(self, _mock_page_url): # Create our dummy person and the 3 courses we'll attach to it person = PersonFactory(should_publish=True) courses = CourseFactory.create_batch(3, fill_team=[person], should_publish=True) # Link the 3 courses wit...
[ "def test_templates_person_detail_related_courses(self):\n user = UserFactory(is_staff=True, is_superuser=True)\n self.client.login(username=user.username, password=\"password\")\n\n person = PersonFactory()\n course = CourseFactory(fill_team=[person])\n\n url = person.extended_ob...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The blog posts written by a person should appear on this person's detail page.
def test_templates_person_detail_related_blog_posts(self): user = UserFactory(is_staff=True, is_superuser=True) self.client.login(username=user.username, password="password") person = PersonFactory() blog_post = BlogPostFactory(fill_author=[person]) url = person.extended_object...
[ "def posts(self):\n if(len(self.getPosts()) <= 0):\n print \"No hi ha cap post\"\n return\n\n for post in self.getPosts().values():\n print post\n print", "def post_list(request):\n posts = get_object_or_404(date_published_lte = timezone.now()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A person template page without attached person should show an error banner explaining to the user that he/she is misusing the template.
def test_template_person_detail_without_person(self): page = PageFactory( template="courses/cms/person_detail.html", title__language="en", should_publish=True, ) with self.assertTemplateUsed( "courses/cms/fragment_error_detail_template_banner.html...
[ "def page_not_found(e):\n message = \"This page dos'not exist\"\n\n return render_template(\"errors.html\", title=\"Not Exist\", message=message)", "def error_page(request, template, status=None):\n return render(request, '%d.html' % template, status=(status or template))", "def errorview(request):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The person meta description should show meta_description placeholder if defined
def test_templates_person_detail_meta_description(self): person = PersonFactory() page = person.extended_object title_obj = page.get_title_obj(language="en") title_obj.meta_description = "A custom description of the person" title_obj.save() page.publish("en") u...
[ "def test_templates_person_detail_meta_description_empty(self):\n person = PersonFactory()\n page = person.extended_object\n page.publish(\"en\")\n\n url = person.extended_object.get_absolute_url()\n response = self.client.get(url)\n self.assertEqual(response.status_code, 2...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The person meta description should show the bio if no meta_description is specified
def test_templates_person_detail_meta_description_bio(self): person = PersonFactory() page = person.extended_object # Add a bio to a person placeholder = person.extended_object.placeholders.get(slot="bio") add_plugin( language="en", placeholder=placeholde...
[ "def test_templates_person_detail_meta_description_bio_exceeds_max_length(self):\n person = PersonFactory()\n page = person.extended_object\n placeholder_value = (\n \"Long description that describes the page with a summary. \"\n \"Long description that describes the page ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The person meta description should be cut if it exceeds more than 160 caracters
def test_templates_person_detail_meta_description_bio_exceeds_max_length(self): person = PersonFactory() page = person.extended_object placeholder_value = ( "Long description that describes the page with a summary. " "Long description that describes the page with a summar...
[ "def limit_description_size(issue):\n description = issue.fields.description\n if description != None:\n description = demoji(description)\n if len(description) > 10000:\n return description[0:10000]\n return description", "def clean_description(self):\n description = self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The person meta description should not be present if neither the meta_description field on the page, nor the `bio` placeholder are filled
def test_templates_person_detail_meta_description_empty(self): person = PersonFactory() page = person.extended_object page.publish("en") url = person.extended_object.get_absolute_url() response = self.client.get(url) self.assertEqual(response.status_code, 200) s...
[ "def test_templates_person_detail_meta_description_bio_exceeds_max_length(self):\n person = PersonFactory()\n page = person.extended_object\n placeholder_value = (\n \"Long description that describes the page with a summary. \"\n \"Long description that describes the page ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function list neighbour entries attached to the given device
def showNeighboursByDevice(logger, device, version=None): args = [] if version: if version == 4: args.append(IpConstant.IPV4) elif version == 6: args.append(IpConstant.IPV6) args += [IpOption.NEIGHBOUR, IpAction.SHOW, IpConstant.DEV, dev...
[ "def display_neighbour_table(self):\n for key in self._ngh_ids:\n print key\n for node_id in self._ngh_ids[key]:\n print \" \", node_id", "def find_neighbors(self):\n #checked#\n ###your code here###\n for address in self.homes:\n for i ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method defines the mesh points for a rectangle, i.e., the position of all mesh points, position of internal mesh ooints and the position of mesh points on the boundary The origin of a rectangular cooerdinate is set on the lower left vertex
def defineRectangleLayout(self): #--- Define a 2-D mesh --- # Divide x- and y-axis self.xPoints = self.frange(0,self.Lx,self.h) self.yPoints = self.frange(0,self.Ly,self.h) # Position (xy-coordinate) of boundary points boundary_xyCoord = [(0,j) for j in self.yPoints] + ...
[ "def update_boundary_positions(self):\n # set the boundary variables for the chair\n self.x1 = self.xPos - self.width / 2\n self.y1 = self.yPos - self.height / 2\n self.x2 = self.xPos + self.width / 2\n self.y2 = self.yPos + self.height / 2", "def defineCircleLayout(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method defines the mesh points for a circle, i.e., the position of all mesh points, position of internal mesh ooints and the position of mesh points on boundary The circle is assumed to be circumvented in a square whose side is 2R, where R is the radius of the circle. The origin of coordinate is put on the lower l...
def defineCircleLayout(self): # Define a 2-D array representing the position of each mesh point self.xPoints = self.frange(0,self.R,self.h) self.yPoints = self.frange(0,self.R,self.h) # Position of internal mesh points internal_xyCoord = [(i,j) for i in self.xPoints for j in sel...
[ "def project_points_to_circle(point_list, circle):\n circle_plane = (circle^einf).normal()\n planar_points = project_points_to_plane(point_list,circle_plane)\n circle_points = project_points_to_sphere(planar_points, -circle*circle_plane*I5)\n return circle_points", "def gen_circle(r_):\n global mes...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds the label of a point in the mesh. Here, label simply means numbering of the points. x and y are the x and ycoordinates of the mesh point
def findLabel(self, x, y): #- xLabel - if x in self.xPoints: xLabel = self.xPoints.index(self.boundary_xyCoord[k][0]) else: # Find the points on the left and right of this point in xPoints done = 0 k = 0 while done == 0: ...
[ "def point_label(word, x, y):\n plt.text(x, y, word, horizontalalignment='center', verticalalignment='bottom')", "def point_label_3d(ax, word, x, y, z):\n ax.text(x, y, z, word)", "def label(self, nodeid):\n return self._eps[nodeid][2]", "def get_label(self, label):\n return self.labels[label]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes fE, fW, fN and fS for each mesh point. These are used to calcualte the coefficients needed to computing the Laplacian
def fCalc(self): # A dictionary composed of all internal and boundary points allPoints = dict(self.internalPoints.items() + self.boundaryPoints.items()) for pointLabel in allPoints.keys(): # Compute fE, fW, fN and fW only for internal mesh points if allPoints[pointLabel]...
[ "def compute_mesh_laplacian(mesh, weights=None, fem_b=None, lap_type=\"conformal\"):\n print(\" Computing Laplacian\")\n if weights is None:\n (weights, fem_b) = compute_mesh_weights(mesh, weight_type=lap_type)\n\n if lap_type == \"fem\":\n weights.data = weights.data / 2\n\n N = weights....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method defines the mesh points for a given layoutType
def run(self): # Dictionaries whose keys are labels of the points in a 2-D grid and values # are an instance of the class meshPoint holding the informaiton about # that mesh point self.boundaryPoints = {} self.internalPoints = {} # Rectangle if self.layoutTyp...
[ "def setup_kpoints(self):\n kpoints_mesh = KpointsData()\n kpoints_mesh.set_cell_from_structure(self.inputs.structure)\n kpoints_mesh.set_kpoints_mesh_from_density(\n distance=self.ctx.protocol['kpoints_mesh_density'],\n offset=self.ctx.protocol['kpoints_mesh_offset']\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of sharded queries for the given Cloud Datastore query. This will create up to the desired number of splits, however it may return less splits if the desired number of splits is unavailable. This will happen if the number of split points provided by the underlying Datastore is less than the desired numbe...
def get_splits(datastore, query, num_splits, partition=None): # Validate that the number of splits is not out of bounds. if num_splits < 1: raise ValueError('The number of splits must be greater than 0.') if num_splits == 1: return [query] _validate_query(query) splits = [] scatter_keys = _get_s...
[ "def _create_scatter_query(query, num_splits):\n\n scatter_query = query_pb2.Query()\n for kind in query.kind:\n scatter_kind = scatter_query.kind.add()\n scatter_kind.CopyFrom(kind)\n\n # ascending order\n datastore_helper.add_property_orders(scatter_query, SCATTER_PROPERTY_NAME)\n\n # There is a split ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verifies that the given query can be properly scattered.
def _validate_query(query): if len(query.kind) != 1: raise ValueError('Query must have exactly one kind.') if query.order: raise ValueError('Query cannot have any sort orders.') if query.HasField('limit'): raise ValueError('Query cannot have a limit set.') if query.offset > 0: raise ValueErr...
[ "def _verify_query_segregation(query, auth_project=None):\r\n auth_project = (auth_project or\r\n acl.get_limited_to_project(pecan.request.headers))\r\n\r\n if not auth_project:\r\n return\r\n\r\n for q in query:\r\n if q.field in ('project', 'project_id') and auth_project ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validates that we only have allowable filters. Note that equality and ancestor filters are allowed, however they may result in inefficient sharding.
def _validate_filter(filter): if filter.HasField('composite_filter'): for sub_filter in filter.composite_filter.filters: _validate_filter(sub_filter) elif filter.HasField('property_filter'): if filter.property_filter.op in UNSUPPORTED_OPERATORS: raise ValueError('Query cannot have any inequalit...
[ "def _validate_filters(cls, filters):\r\n for k in filters.iterkeys():\r\n if k not in cls.filters:\r\n # Mirror \"unexpected keyword argument\" message:\r\n raise TypeError(\"%s got an unsupported filter type '%s'\" %\r\n (cls.__name__,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a scatter query from the given user query.
def _create_scatter_query(query, num_splits): scatter_query = query_pb2.Query() for kind in query.kind: scatter_kind = scatter_query.kind.add() scatter_kind.CopyFrom(kind) # ascending order datastore_helper.add_property_orders(scatter_query, SCATTER_PROPERTY_NAME) # There is a split containing enti...
[ "def construct_query(self):\n self.query = (\"select salesperson, sum(amt) \" +\n \" from Sales group by salesperson\")", "def construct_query(self):\n raise NotImplementedError() # override this method", "def generate_similar_density_query(query):\n similar_start_date = g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a list of keys and a number of splits find the keys to split on.
def _get_split_key(keys, num_splits): # If the number of keys is less than the number of splits, we are limited # in the number of splits we can make. if not keys or (len(keys) < (num_splits - 1)): return keys # Calculate the number of keys per split. This should be KEYS_PER_SPLIT, # but may be less if ...
[ "def _choose_split_points(cls, sorted_keys, shard_count):\n assert len(sorted_keys) >= shard_count\n index_stride = len(sorted_keys) / float(shard_count)\n return [sorted_keys[int(round(index_stride * i))]\n for i in range(1, shard_count)]", "def possible_splits(z):\n splits = []\n for k in ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Board must count number of connections to origin properly.
def test_count_connected(self): data = [[0, 1, 0], [1, 0, 0], [0, 0, 1]] board = Board(data) self.assertEquals(board.count_connected(), 1) data = [[1, 1, 0], [1, 0, 0], [0, 0, 1]] board = Board(data) self.as...
[ "def play_round_Conway_Cell(self):\n for x in self.board:\n for f in x:\n f.live_neighbors = 0\n\n for i in range(1, self.cols - 1):\n for j in range(1, self.rows - 1):\n status = self.board[i][j].status\n assert type(status)==int \n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load the dictionary from the filename
def load_dictionary(cls, filename, non_lang_syms=None): return AsrDictionary.load(filename, f_non_lang_syms=non_lang_syms)
[ "def load_dictionary(filepath):\r\n # context manager read binary\r\n with open(filepath, 'rb') as file:\r\n # pickle load\r\n return pickle.load(file)", "def load(self, filename, names=None):\n if names is None:\n with open(filename, 'rb') as f:\n self.dicty =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
View used when Nginx Upload Progress module is enabled. When the Nginx Upload Progress module is used, we get to the WSGI application (and thus to this view) only when the file has been completely written to disk by Nginx. So here we merely copy it to the final upload directory and that is all.
def upload_with_nginx_upload_progress(request): input_file, file_size, filename = get_file_from_request(request) upload_dir = request.registry.settings['poulda.upload_dir'] path = os.path.join(upload_dir, filename) with open(path, 'w') as output: # We must read only 'file_size' bytes from the 'i...
[ "def progress(request):\n file_id = request.GET['X-Progress-ID']\n session = DBSession()\n u = session.query(Upload).filter_by(id=file_id).one()\n data = {'state': u.state}\n if u.state == 'uploading':\n if not os.path.exists(u.tmp_path):\n # The temporary file has not been created ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
View used only when the Nginx Upload Progress support has been disabled. When the Nginx Upload Progress support is enabled, this view is never called at all, since the Nginx module takes care of returning progress information.
def progress(request): file_id = request.GET['X-Progress-ID'] session = DBSession() u = session.query(Upload).filter_by(id=file_id).one() data = {'state': u.state} if u.state == 'uploading': if not os.path.exists(u.tmp_path): # The temporary file has not been created yet or it ha...
[ "def incremental_status(request):\n\n upload_process = None\n\n if TaskComm.USE_CELERY:\n # print 'getting process id: ' + request.session['upload_process']\n upload_process = get_celery_process(request)\n if not upload_process:\n retval = json.dumps({'state': 'waiting', 'resu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return score for a subj, obj pair of entities.
def get_fact_score(extracted_scores, subj, obj, freq_dict, score_type='FREQ_SCORE'): score_types = set('FREQ_SCORE', 'MIN_SCORE') # Min of Page Rank scores of both Entities # Upweight facts where both have high scores min_score = min( ...
[ "def get_score(self, obj):\n ctype = ContentType.objects.get_for_model(obj)\n result = self.filter(object_id=obj._get_pk_val(),\n content_type=ctype).extra(\n select={\n 'score': 'COALESCE(SUM(vote), 0)',\n 'num_votes': 'COALESCE(COU...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
barcode_header test for Jan 1 2016 and £1 (1.0)
def test_header_20160104_10(self): date = datetime(2016, 1, 4) price = 1.0 header = star_barcode.barcode_header(date, price) self.assertEqual( header, 'MSTAR 2016-01-04 MON 1.0')
[ "def test_header_20161112_12(self):\n date = datetime(2016, 11, 12)\n price = 1.2\n header = star_barcode.barcode_header(date, price)\n self.assertEqual(\n header,\n 'MSTAR 2016-11-12 SAT 1.2')", "def test_year_boundary(self):\n date = datetime(2017, 1, 1)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
barcode_header test for Nov 12 2016 and £1.20 (1.2)
def test_header_20161112_12(self): date = datetime(2016, 11, 12) price = 1.2 header = star_barcode.barcode_header(date, price) self.assertEqual( header, 'MSTAR 2016-11-12 SAT 1.2')
[ "def test_header_20160104_10(self):\n date = datetime(2016, 1, 4)\n price = 1.0\n header = star_barcode.barcode_header(date, price)\n self.assertEqual(\n header,\n 'MSTAR 2016-01-04 MON 1.0')", "def is_valid_header(header):\n\n return (len(header) == 8 ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
barcode_filename should throw when sequence is wrong A ValueError exception should be raised if the second digit of the sequence (sequence % 10) is not the same as the ISO weekday number (%u).
def test_wrong_sequence(self): date = datetime(2016, 11, 12) seq = 31 with self.assertRaises(ValueError): star_barcode.barcode_filename(date, seq)
[ "def test_year_boundary(self):\n date = datetime(2017, 1, 1)\n seq = 27\n name = star_barcode.barcode_filename(date, seq)\n self.assertEqual(\n name,\n 'Barcode_2016-W52-7_27.pdf'\n )", "def test_issn_incorrect_length(self):\n issns = ['0307-15',...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
barcode_filename should use ISO week year not standard year January 1 2017 is the final ISO day (Sunday) in the final ISO
def test_year_boundary(self): date = datetime(2017, 1, 1) seq = 27 name = star_barcode.barcode_filename(date, seq) self.assertEqual( name, 'Barcode_2016-W52-7_27.pdf' )
[ "def file_year(self, filename):\n try:\n return int(filename[:4])\n except ValueError:\n self.logger.warning(\"Missing year from %s\" % filename)", "def get_year(self, filename):\n year = self.file.replace('s24_', '').replace('.vrt', '')\n self.logger.info(f'This ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
date_to_sequence_and_week handles a typical case Given a datetime object for 20161115 (a Tuesday) and a 7long list of the integer 2 the sequence returned should be 22 and the week 46.
def test_standard_seq_week(self): date = datetime(2016, 11, 15) prices = [2] * 7 expected_sequence = 22 expected_week = 46 self.assertEqual( star_barcode.date_to_sequence_and_week( date=date, price_codes=prices), (expected_sequence, expecte...
[ "def weeks_to_string(original_weeks: List[int]) -> str:\n\n def odd(num: int) -> bool:\n return num % 2 == 1\n\n def int_type_to_string(typ: int) -> str:\n if typ == 0:\n return \"/周\"\n elif typ == 1:\n return \"/单周\"\n elif typ == 2:\n return \"/双...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
date_to_sequence_and_week handles a short price code list Given a datetime object for 20161115 (a Tuesday) and a 2long list of the integer 2 the sequence returned should be 22 and the week 46.
def test_short_prices(self): date = datetime(2016, 11, 15) prices = [2] * 2 expected_sequence = 22 expected_week = 46 self.assertEqual( star_barcode.date_to_sequence_and_week( date=date, price_codes=prices), (expected_sequence, expected_wee...
[ "def test_standard_seq_week(self):\n date = datetime(2016, 11, 15)\n prices = [2] * 7\n expected_sequence = 22\n expected_week = 46\n self.assertEqual(\n star_barcode.date_to_sequence_and_week(\n date=date, price_codes=prices),\n (expected_sequ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
date_to_sequence_and_week correctly uses price code list Given a price code list that increments by 1 each day (in line with the ISO weekday number), date_to_sequence_and_week should return corresponding sequences (11, 22, 33 … 77)
def test_incrementing_codes(self): date = datetime(2016, 11, 14) prices = list(range(1, 8)) week = 46 for i in range(7): with self.subTest(i=i): self.assertEqual( star_barcode.date_to_sequence_and_week( date + timede...
[ "def test_standard_seq_week(self):\n date = datetime(2016, 11, 15)\n prices = [2] * 7\n expected_sequence = 22\n expected_week = 46\n self.assertEqual(\n star_barcode.date_to_sequence_and_week(\n date=date, price_codes=prices),\n (expected_sequ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
construct_postscript raises ValueError if bwipp is missing If the location passed to construct_postscript for the location of the bwipp postscript library does not exist, then it should raise ValueError.
def test_missing_bwipp(self): seq = 21 week = 46 header = 'MSTAR 2016-11-14 MON 1.0' with self.assertRaisesRegex(ValueError, 'BWIPP'): star_barcode.construct_postscript( bwipp_location=Path('/fake-path/not-here.ps'), issn=self.issn, ...
[ "def _buildScript(self):\n\t\tscript = self.config.script.strip()\n\t\tif not script:\n\t\t\tlogger.warning('No script specified', proc = self.id)\n\n\t\tif script.startswith ('file:'):\n\t\t\ttplfile = Path(script[5:])\n\t\t\tif not fs.exists (tplfile):\n\t\t\t\traise ProcScriptError(tplfile, 'No such template fil...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
construct_postscript raises ValueError for ISSN of incorrect length ISSNs are either 7 or 8 digits long (8 being the optional check digit), with a mandatory (for BWIPP) hyphen in the fifth place. construct_postscript should raise a ValueError if the ISSN is not of the form \d{4}\d{3,4}.
def test_issn_incorrect_length(self): issns = ['0307-15', '0307-15789', '03071758', '0307175'] for num in issns: with self.subTest(num=num): with self.assertRaisesRegex(ValueError, num): star_barcode.construct_postscript( issn=num, ...
[ "def test_missing_bwipp(self):\n seq = 21\n week = 46\n header = 'MSTAR 2016-11-14 MON 1.0'\n with self.assertRaisesRegex(ValueError, 'BWIPP'):\n star_barcode.construct_postscript(\n bwipp_location=Path('/fake-path/not-here.ps'),\n issn=self.issn,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
construct_postscript must not raise for sequences 0009 As all possible sequences run 0099, they can be adequately represented by an integer rather than a string. But the construct_postscript function must not raise for integers 09, even though as (unformatted) strings they are of length 1.
def test_sequence_0_to_9(self): seqs = list(range(10)) for seq in seqs: with self.subTest(seq=seq): result = star_barcode.construct_postscript( sequence=seq, bwipp_location=self.bwipp, issn=self.issn, ...
[ "def test_sequence_specials(self):\n special_digits = [0, 8, 9]\n for t in range(0, 10):\n for special in special_digits:\n seq = t * 10 + special\n with self.subTest(seq=seq):\n result = star_barcode.construct_postscript(\n sequen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
construct_postscript must not raise for special sequences While the paper only uses sequences 0107 through 9197, the missing numbers are valid (00, 08, 09 … 90, 98, 99) and should be accepted by construct_postscript.
def test_sequence_specials(self): special_digits = [0, 8, 9] for t in range(0, 10): for special in special_digits: seq = t * 10 + special with self.subTest(seq=seq): result = star_barcode.construct_postscript( sequence=seq, ...
[ "def test_sequence_0_to_9(self):\n seqs = list(range(10))\n for seq in seqs:\n with self.subTest(seq=seq):\n result = star_barcode.construct_postscript(\n sequence=seq,\n bwipp_location=self.bwipp,\n issn=self.issn,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
construct_postscript raises ValueError if 0 < week < 54 ISO weeks must be between 1 and 53.
def test_week_wrong(self): weeks = [0, 54] for week in weeks: with self.subTest(week=week): with self.assertRaisesRegex(ValueError, str(week)): star_barcode.construct_postscript( week=week, bwipp_location=sel...
[ "def test_week_in_range(self):\n weeks = list(range(1, 54))\n seq = 21\n for week in weeks:\n with self.subTest(week=week):\n result = star_barcode.construct_postscript(\n week=week,\n bwipp_location=self.bwipp,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
construct_postscript accepts week >= 1, <= 53
def test_week_in_range(self): weeks = list(range(1, 54)) seq = 21 for week in weeks: with self.subTest(week=week): result = star_barcode.construct_postscript( week=week, bwipp_location=self.bwipp, issn=self.i...
[ "def weekly():", "def test_week_wrong(self):\n weeks = [0, 54]\n for week in weeks:\n with self.subTest(week=week):\n with self.assertRaisesRegex(ValueError, str(week)):\n star_barcode.construct_postscript(\n week=week,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
process_arguments turns date into datetime
def test_date_only(self): args = { '--directory': './', '<date>': '2016-11-15', '<header>': None, '<seq>': None, '<week>': None } expected = { '--directory': Path('./'), '<date>': datetime(2016, 11, 15), ...
[ "def parse_date_args(self):\n # Check that a start argument was passed to the spider\n if hasattr(self, 'start'):\n # Convert the start date string into a date object\n self.date_range_start = dtparse(self.start, dayfirst=True).date()\n else:\n log.msg(\"No star...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a Connectable Observable. A multicasted Observable (rx_publish) uses a Subject under the hood to make multiple Observers see the same Observable execution.
def rx_publish( an_observable: Observable, subject_handler: Optional[SubjectHandler] = None, connection_handler: Optional[ConnectableObservableHandler] = None, subject_factory: SubjectFactory = rx_subject, ) -> ConnectableObservable: _ref_count_activated = False # Flag to enable auto-connect _r...
[ "def _multicast(subject: Optional[Subject] = None,\n subject_factory: Optional[Callable[[Optional[Scheduler]], Subject]] = None,\n mapper: Optional[Callable[[ConnectableObservable], Observable]] = None\n ) -> Callable[[Observable], Union[Observable, ConnectableObservable]]:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a hex string to an real application tag.
def real_tag(x): if _debug: real_tag._debug("real_tag %r", x) b = xtob(x) tag = Tag(Tag.applicationTagClass, Tag.realAppTag, len(b), b) if _debug: real_tag._debug(" - tag: %r", tag) return tag
[ "def xx(data):\n if sys.version_info < (3, 5):\n return binascii.hexlify(data).decode('ascii')\n return data.hex()", "def hex2bin(hexstr: str, padding: int) -> str:\n if not hexstr.lower().startswith(\"0x\"):\n raise ValueError(\"Input hexadecimal string must have '0x' as the prefix...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Encode an Real object into a tag.
def real_encode(obj): if _debug: real_encode._debug("real_encode %r", obj) tag = Tag() obj.encode(tag) if _debug: real_encode._debug(" - tag: %r, %r", tag, tag.tagData) return tag
[ "def encode(obj):\n raise NotImplementedError(\"This method has to be overwritten\")", "def encode(self, obj):\n encoder = self._find_encoder(obj)\n if not encoder:\n raise CBOREncodeError('cannot serialize type %s' % type(obj))\n encoder(self, obj)", "def encode(obj, **kw...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decode an real application tag into an real.
def real_decode(tag): if _debug: real_decode._debug("real_decode %r", tag) obj = Real(tag) if _debug: real_decode._debug(" - obj: %r, %r", obj, obj.value) return obj
[ "def real_tag(x):\n if _debug: real_tag._debug(\"real_tag %r\", x)\n\n b = xtob(x)\n tag = Tag(Tag.applicationTagClass, Tag.realAppTag, len(b), b)\n if _debug: real_tag._debug(\" - tag: %r\", tag)\n\n return tag", "def Decode(self, encoded_data):", "def decode(self, encoded):", "def decode(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write the cfg, bnd and all results in working dir. prefix is a string that will determine the name of the created files. If there is a conflict with existing files, the existing files will be replaced or not, depending on the value of the replace argument.
def save(self, prefix, replace=False): if not _check_prefix(prefix): return # Create the results directory try: os.makedirs(prefix) except OSError: if not replace: print('Error directory already exists: %s' % prefix, ...
[ "def create(self, basedir, outdir, name, prefix=None):", "def prefix(args):\n\n args.suppress_verify_output = True\n if verify(args) != 0:\n # restore stdout\n sys.stdout = sys.__stdout__\n print(\"Config file not valid, please use the verify function to debug\")\n return 1\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Carga los chatbots que se han creado con el MetaChatBot y los pone en la variable lista de chatbots.
def loadChatbots(self): pathChatbots = os.path.dirname(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))) # ruta donde se guardarán los chatbots listAllChatbots = os.listdir(pathChatbots) # lista de chatbots en la ruta if len(listAllChatbots) ==...
[ "def bots():\n return get_bots(\"botsunlimited.settings\")", "async def bot_list(self) -> list:\n return await self._do_request(\"get\", botlist_address, self._user_auth)", "def list(self):\n\n result = []\n for i in self.bots:\n result.append(i.name)\n return result", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inicializa las rutas del MetaChatbot para saber dónde está el fichero de errores, la ruta donde guardar el modelo, etc...
def initializePaths(self): strSplit = (os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))).split(os.path.sep) # nombre de los directorios que contiene este fichero self.nameTransformed = strSplit[len(strSplit)-1] ...
[ "def init_error_files(self): \n \n dir_path = self.init_logs_directory()\n log_errors = self.join_path(dir_path, PATH_FOR_LOG_ERRORS)\n \n return log_errors", "def test_init_non_existent_paths():\n with pytest.raises(IOError) as ioe:\n mmb = MaliciousMacroBot(benign_path='madeuppath', mal...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Elimina un chatbot de la lista
def deleteStructureChatbotDict(self,sentence): if sentence in self.dictChatBots: del self.dictChatBots[sentence] if not(self.currentStructureChatBot is None) and sentence == self.currentStructureChatBot.name: self.currentStructureChatBot = None # se reestablec...
[ "def del_memes(context):\n\n for meme_sent in MEMES_SENT:\n meme_sent[0].delete() # Delete the photo sent\n\n # for meme_sent in MEMES_SENT: # Edit the message sent\n # edited_text = f\"i sent a meme for {meme_sent[3]} but its deleted now. sent such a coolio meme and you missed it? lol better ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Estimate sample Lmoments, based on Fortran code written for inclusion in IBM Research Report RC20525, 'FORTRAN ROUTINES FOR USE WITH THE METHOD OF LMOMENTS, VERSION 3' by J. R. M. Hosking, IBM Research Division, T. J. Watson Research Center, Yorktown Heights, NY 10598, Version 3 August 1996.
def _estimate_lmoments(values): # we need to have at least four values in order to make a sample L-moments estimation number_of_values = np.count_nonzero(~np.isnan(values)) if number_of_values < 4: message = 'Insufficient number of values to perform sample L-moments estimation' _logge...
[ "def test_estimate_moments():\n random_state = check_random_state(0)\n actual_mean = np.array([0.0, 1.0])\n actual_covariance = np.array([[0.5, -1.0], [-1.0, 5.0]])\n X = random_state.multivariate_normal(actual_mean, actual_covariance,\n size=(100000,))\n mvn =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Universal function (ufunc) used to perform fitting of a value to a Pearson Type III distribution as described by the Pearson Type III parameters and probability of zero arguments.
def _pearson_fit_ufunc(value_to_fit, pearson_param_1, pearson_param_2, pearson_param_3, probability_of_zero): fitted_value = np.NaN # only fit to the distribution if the value is valid/not missing if not m...
[ "def fitfunc(p,x):\n return p[1]*x**p[2] + p[0]", "def fu_fit(fu, v):\n popt, pcov = curve_fit(\n lambda v, a : beta.cdf(v, a, 1),\n v, fu,\n p0 = (1,)\n )\n chi2 = np.sum((beta.cdf(v, *popt, 1) - fu)**2 / (len(v)-2))\n res = np.zeros(len(popt)+1)\n res[0:1] = popt\n res[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the __init__ method when parameter 'mac' is None. Should raise an AttributeError.
def test_init_no_mac(self): # mocks of files rsa_ca_priv_file, rsa_priv_file, rsa_cert_file = range(3) with self.assertRaises(ValueError): ap = APInfo(port_id=1, ip="2.2.2.2", mac=None, radio_mac="bb:bb:bb:bb:bb:00", udp_port=12345, wlc_ip='1.1.1.1', gateway_...
[ "def test_init_no_mac(self):\n with self.assertRaises(ValueError):\n client = ClientInfo(None, ip=\"3.3.3.3\", ap_info=self.ap)", "def test_init_valid(self):\n payload = payloads.MACRequestPayload(\n self.unique_identifier,\n self.cryptographic_parameters,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the __init__ method when parameter 'ip' is None. Since the field is optional, it should pass.
def test_init_no_ip(self): # mocks of files rsa_ca_priv_file, rsa_priv_file, rsa_cert_file = range(3) ap = APInfo(port_id=1, ip=None, mac="bb:bb:bb:bb:bb:bb", radio_mac="bb:bb:bb:bb:bb:00", udp_port=12345, wlc_ip='1.1.1.1', gateway_ip='1.1.1.2', ap_mode=APMode.LOCAL, rsa_ca_...
[ "def test_init_no_ip(self):\n client = ClientInfo(\"cc:cc:cc:cc:cc:cc\", ip=None, ap_info=self.ap)\n self.assertEqual(client.ip, None)\n self.assertEqual(client.ip_bytes, None)", "def test_validate_ip_ok():\n ip = '1.1.1.1'\n assert howisresolved.validate_ip(ip) is None", "def test_fi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the __init__ method when mandatory parameter 'mac' is None.
def test_init_no_mac(self): with self.assertRaises(ValueError): client = ClientInfo(None, ip="3.3.3.3", ap_info=self.ap)
[ "def test_init_no_mac(self):\n # mocks of files\n rsa_ca_priv_file, rsa_priv_file, rsa_cert_file = range(3)\n\n with self.assertRaises(ValueError):\n ap = APInfo(port_id=1, ip=\"2.2.2.2\", mac=None, radio_mac=\"bb:bb:bb:bb:bb:00\", udp_port=12345, wlc_ip='1.1.1.1',\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the __init__ method when parameter 'ip' is None. Since the field is optional, it should pass.
def test_init_no_ip(self): client = ClientInfo("cc:cc:cc:cc:cc:cc", ip=None, ap_info=self.ap) self.assertEqual(client.ip, None) self.assertEqual(client.ip_bytes, None)
[ "def test_init_no_ip(self):\n # mocks of files\n rsa_ca_priv_file, rsa_priv_file, rsa_cert_file = range(3)\n\n ap = APInfo(port_id=1, ip=None, mac=\"bb:bb:bb:bb:bb:bb\", radio_mac=\"bb:bb:bb:bb:bb:00\", udp_port=12345, wlc_ip='1.1.1.1',\n gateway_ip='1.1.1.2', ap_mode=APMode....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the __init__ method when mandatory parameter 'ap_info' is of wrnong type.
def test_init_wrong_ap_type(self): ap_wrong = object() with self.assertRaises(ValueError): client = ClientInfo("cc:cc:cc:cc:cc:cc", ip="3.3.3.3", ap_info=ap_wrong)
[ "def test_accepts_init_with_strict_subset_of_args(self):\n\n class API(platform.PlatformAPI):\n def __init__(self, base_url):\n pass\n\n api = API(\"some-url\")\n assert isinstance(api, platform.PlatformAPI)", "def test_urlinfo_init():\n # When I initialise an Ale...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generator that randomly picks a banner.
def p_banner(): return random.choice([banner, banner_two, banner_three, banner_four, banner_five])
[ "def choose_banner(banners):\n # simple random\n n = random.randint(0, len(banners)-1)\n return banners[n]", "def banner(self, *args, **kwargs) -> Banner:\n return self._retrieve_singular(self.banners, *args, **kwargs)", "def random_bg(self):\n # TODO: Add support for differen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the estimation of the frequncy of _item
def estimate(self, item): return self.A[item] if item in self.A.keys() else 0
[ "def getSupport(item):\n return float(freqSet[item]) / len(transactionList)", "def getSupport(item):\n return float(freqSet[item]) / len(transactionList)", "def frequency(my_list, item):\n return float(my_list.count(item)) / float(len(my_list))", "def probability(self, item):\n count...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create two sidewalk nodes from three nodes in a street.
def make_sidewalk_nodes(street, prev_node, curr_node, next_node): if prev_node is None: v = - curr_node.vector_to(next_node, normalize=False) vec_prev = curr_node.vector() + v prev_node = Node(None, vec_prev[0], vec_prev[1]) elif next_node is None: v = - curr_node.vector_to(prev_...
[ "def connect_crosswalk_nodes(sidewalk_network, crosswalk_node_ids):\n # crosswalk_node_ids = crosswalk.get_node_ids()[:-1] # Crosswalk has a redundant node at the end.\n\n for crosswalk_node_id in crosswalk_node_ids[:-1]:\n try:\n # Get the intersection node and two nodes that created the i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sort nodes around the center_node in clockwise
def sort_nodes(center_node, nodes): def cmp(n1, n2): angle1 = (math.degrees(center_node.angle_to(n1)) + 360.) % 360 angle2 = (math.degrees(center_node.angle_to(n2)) + 360.) % 360 if angle1 < angle2: return -1 elif angle1 == angle2: return 0 else: ...
[ "def sort_nodes_asc(self, nodes):\n raise NotImplementedError", "def sort_clusters_by_nodes(clusters, nodes):\n new_order = []\n for node in nodes:\n for cidx, cluster in enumerate(clusters):\n if node in cluster:\n new_order.append(cluster)\n break\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make a crosswalk node from three nodes. The first one is a pivot node and two other nodes are ones that are connected to the pivot node. The new node is created between the two nodes.
def make_crosswalk_node(node, n1, n2): v_curr = node.vector() v1 = node.vector_to(n1, normalize=True) v2 = node.vector_to(n2, normalize=True) v = v1 + v2 v /= np.linalg.norm(v) # Normalize the vector v_new = v_curr + v * 0.00011 # v_new = v_curr + np.array(latlng_offset(v_curr[0], vector=v...
[ "def make_sidewalk_nodes(street, prev_node, curr_node, next_node):\n if prev_node is None:\n v = - curr_node.vector_to(next_node, normalize=False)\n vec_prev = curr_node.vector() + v\n prev_node = Node(None, vec_prev[0], vec_prev[1])\n elif next_node is None:\n v = - curr_node.vect...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Connect crosswalk nodes to sidewalk nodes. Then remove redundant sidewalk nodes around the intersection.
def connect_crosswalk_nodes(sidewalk_network, crosswalk_node_ids): # crosswalk_node_ids = crosswalk.get_node_ids()[:-1] # Crosswalk has a redundant node at the end. for crosswalk_node_id in crosswalk_node_ids[:-1]: try: # Get the intersection node and two nodes that created the intersectio...
[ "def merge_sidewalks(sidewalk_network1, sidewalk_network2):\n\n for node in sidewalk_network1.nodes.get_list():\n node.confirmed = True\n\n '''\n # add new nodes from sidewalk_network2 to sidewalk_network1\n for sidewalk_node in sidewalk_network2.nodes.get_list():\n in_other = False\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Splits a large OSM files
def split_large_osm_file(filename): command = "java -Xmx4000M -jar ./lib/splitter.jar --output=xml --output-dir=data --max-nodes=15000 " + filename + " > splitter.log" os.system(command)
[ "def split_file(self, input_file):\r\n file_list = [] \r\n with open(input_file, 'r', encoding='GB18030', errors='ignore') as f_in:\r\n data = f_in.readlines()\r\n lines_num = len(data)\r\n size = lines_num // self.num_workers # lines splitted in a chunk\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a merged sidewalk network Takes two sidewalk networks and merges them without duplicating sidewalk data
def merge_sidewalks(sidewalk_network1, sidewalk_network2): for node in sidewalk_network1.nodes.get_list(): node.confirmed = True ''' # add new nodes from sidewalk_network2 to sidewalk_network1 for sidewalk_node in sidewalk_network2.nodes.get_list(): in_other = False same_node =...
[ "def merge_networks_in_series(n1, n2):\n new_l_size = n1.l_size + n2.l_size + 1 # One additional vertex in between.\n new_u_size = n1.u_size + n2.u_size\n\n # Connect the 0-pole and the inf-pole in the result network.\n new_link_edge = n1.zero_pole.insert_before()\n new_link_edge_opp = n2.inf_pole.i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a Java object of `SparseVectorWrapper` to a scipy sparse matrix whose number of rows is 1. `j_obj.getSize()` must return a positive number.
def j_sparse_vector_wrapper_to_scipy_spmatrix(j_obj: JavaObject): indices = np.frombuffer(j_obj.getIndicesBytes(), dtype="<i4") values = np.frombuffer(j_obj.getValuesBytes(), dtype="<f8") size = j_obj.getSize() indptr = np.array([0, indices.shape[0]], dtype=np.int32) return csr_m...
[ "def to_sparse(self):\n from divisi2.sparse import SparseVector\n return SparseVector(self, self.labels)", "def to_sparse(self):\n from divisi2.sparse import SparseMatrix\n return SparseMatrix(self, self.row_labels, self.col_labels)", "def _to_sparse(x):\n sparse_tensortype = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
User not logged in returns 403
def test_not_logged_in(self): response = self.c.get(reverse(submit_point), {'lat': 34.0, 'lng': 45.3, 'zoom': 13}) self.assertEqual(response.status_code, 403)
[ "def authenticated_403(self):\n if self.get_current_user() is None:\n raise web.HTTPError(403)", "def authenticated_403(self):\n if self.current_user is None:\n raise web.HTTPError(403)", "def test_not_logged_user_cannot_access(self):\n\n utils.test_not_logged_cannot_access(self, self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The same point is not submitted twice
def test_same_point_not_submitted(self): self.c.force_login(self.u) data = {'lat': 34.0, 'lng': 45.3, 'zoom': 13} response = self.c.get(reverse(submit_point), data) response = self.c.get(reverse(submit_point), data) response = self.c.get(reverse(submit_point), data) respo...
[ "def submitClicked(self):\n pass", "def post_duplicate_question(self):\n\n self.post_question()\n return self.post_question()", "def submit(self):\n pass", "def post_duplicate_meetup(self):\n\n self.post_meetup()\n return self.post_meetup()", "def test_create_single...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return thumbnail for image.
def get_thumbnail(img_path): thumb = JPEGImage(unicode(img_path)).exif_thumbnail.as_blob() if thumb: logger.debug("Using EXIF thumbnail for {0}".format(img_path)) return thumb else: logger.debug("Generating thumbnail for {0}".format(img_path)) return scale_image(unicode(img_p...
[ "def get_thumbnail(self) -> Image.Image:\n logging.info(\"Getting thumbnail...\")\n t = sorted(\n self._thumbnails.items(), key=lambda x: x[1][\"width\"], reverse=True\n )[0][1]\n logging.info(f\"Highest resolution: {t['width']}x{t['height']}\")\n with requests.get(t[\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Context Manager that mounts the first available partition on a USB drive, yields its path and then unmounts it.
def mount_stick(stick): mount = stick.get_dbus_method( "FilesystemMount", dbus_interface="org.freedesktop.UDisks.Device") path = mount('', []) try: yield path except Exception as e: raise e finally: unmount = stick.get_dbus_method( ...
[ "def active_mountpoint(mount_point):\n execute('mount', mount_point, sudo=True)\n yield\n execute('umount', mount_point, sudo=True)", "def unmountdmg(mountpoint):\n proc = subprocess.Popen(['/usr/bin/hdiutil', 'detach', mountpoint],\n bufsize=-1, stdout=subprocess.PIPE,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Move axis at 1 cm/s toward the home limit. Arguments
def home(self, max_dist=150, reset_pos=True): while not self.lim_cw: self.move_cm(True, max_dist, velocity=1) if reset_pos: self.step_position = 0 self.homed = True
[ "def MoveCurrentSpace(self):\n if self.facing == 0:\n self.y -= 1\n elif self.facing == 1:\n self.x += 1\n elif self.facing == 2:\n self.y += 1\n elif self.facing == 3:\n self.x -= 1", "def move_car(self):\n a = self.h / 50\n se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Side bar filters save
def get_sidebar_filter_save(self): return [ dbc.FormGroup( children=[ dbc.Label("Filter name", className="mr-2"), dbc.Input( type="text", placeholder="filter name", id="fil...
[ "def get_sidebar_saved_filter_names(self):\n radio_options = [\n {\"label\": f\"{x['name']}\", \"value\": f\"{x['name']}\"} for x in self._filters\n ]\n radio_options.insert(0, {\"label\": \"None\", \"value\": \"None\"})\n return [\n dbc.FormGroup(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show already saved filter names
def get_sidebar_saved_filter_names(self): radio_options = [ {"label": f"{x['name']}", "value": f"{x['name']}"} for x in self._filters ] radio_options.insert(0, {"label": "None", "value": "None"}) return [ dbc.FormGroup( children=[ ...
[ "def filters_show():\n log = slog()\n log.title_set('Filters applied')\n if self.args['table3D']: log.render3D()\n log('Input directory: %s\\n' % self.str_inputDir)\n log('Output directory: %s\\n' % self.str_outputDir)\n for filter...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Side bar layout for filters
def get_sidebar_layout(self): return [ dbc.Card(children=self.get_sidebar_filters(), body=True), dbc.Card(children=self.get_sidebar_filter_save(), body=True, className="mt-2"), dbc.Card(children=self.get_sidebar_saved_filter_names(), body=True, className="mt-2") ]
[ "def render_product_ranking_filters_as_sidebar() -> None:\n st.radio(\n label=\"Select product family:\",\n options=[\"all\", \"electronics\", \"fashion\"],\n key=\"radio\",\n on_change=update_categories,\n )\n\n st.session_state[\"number_of_products_to_fetch\"] = st.number_inpu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show or hide the year options
def show_hide_year_options(n_clicks, is_open): if n_clicks: return not is_open return is_open
[ "def showNextYear(self):\n pass", "def showPreviousYear(self):\n pass", "def set_start_year(self, year):\n return self.form.set_value(\"output period \\\"year from\\\"\", str(year))", "def search_year():\n date_editor.find_element_by_xpath(\".//*[contains(@id, 'DateEditorLa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Filter potential deals table data
def filter_potential_deal_table(apply_n_clicks, potential_deal_table_data, selected_year, selected_make, selected_model, min_odometer, max_odometer, min_price, max_price, min_offer_price, max_offer_price): ...
[ "def _data_filtering(self):\n self._filter_nan_user_or_item()\n self._remove_duplication()\n self._filter_by_field_value()\n self._filter_inter_by_user_or_item()\n self._filter_by_inter_num()\n self._reset_index()", "def _filter(self):", "def filter_data(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verify the data by read from mindrecord If in 1.x.x version, use old version to receive that iteration
def verify_data(transformer, reader): if tf.__version__ < '2.0.0': tf_iter = transformer.tfrecord_iterator_oldversion() else: tf_iter = transformer.tfrecord_iterator() mr_iter = reader.get_next() count = 0 for tf_item, mr_item in zip(tf_iter, mr_iter): count = count + 1 ...
[ "def test_reading_legacy_dataset(legacy_dataset_url):\n with make_reader(legacy_dataset_url, workers_count=1) as reader:\n all_data = list(reader)\n\n # Some basic check on the data\n assert len(all_data) == 100\n assert len(all_data[0]._fields) > 5\n assert all_data[0].matrix....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test transform tfrecord to mindrecord.
def test_tfrecord_to_mindrecord(): if not tf or tf.__version__ < SupportedTensorFlowVersion: # skip the test logger.warning("Module tensorflow is not found or version wrong, \ please use pip install it / reinstall version >= {}.".format(SupportedTensorFlowVersion)) return fi...
[ "def test_tfrecord_to_mindrecord_with_special_field_name():\n if not tf or tf.__version__ < SupportedTensorFlowVersion:\n # skip the test\n logger.warning(\"Module tensorflow is not found or version wrong, \\\n please use pip install it / reinstall version >= {}.\".format(SupportedTensor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test transform tfrecord to mindrecord.
def test_tfrecord_to_mindrecord_with_special_field_name(): if not tf or tf.__version__ < SupportedTensorFlowVersion: # skip the test logger.warning("Module tensorflow is not found or version wrong, \ please use pip install it / reinstall version >= {}.".format(SupportedTensorFlowVersion)...
[ "def test_tfrecord_to_mindrecord():\n if not tf or tf.__version__ < SupportedTensorFlowVersion:\n # skip the test\n logger.warning(\"Module tensorflow is not found or version wrong, \\\n please use pip install it / reinstall version >= {}.\".format(SupportedTensorFlowVersion))\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Start on the device the application specified in the desired capabilities.
def launch_app(self): os.system ("adb shell am start -n com.tencent.mm/com.tencent.mm.ui.LauncherUI/") time.sleep (5)
[ "def start_app(package, activity=None):\n G.DEVICE.start_app(package, activity)", "def open_app(device, package_name):\n\n device.shell('am start -n ' + package_name + '/' + package_name +\n '.MainActivity')", "def open_app(device, package_name):\n\n device.shell('am start -n ' + packag...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Close on the device the application specified in the desired capabilities.
def close_app(self): os.system ('adb shell am force-stop com.tencent.mm')
[ "def close_driver(self):\n package_dict = self.config['PACKAGE']\n try:\n self.driver.terminate_app(package_dict[self.app_name]) # Kill app\n self.driver.quit() # Kill drivers\n except WebDriverException:\n pass\n finally:\n LOGGER.info(\"Clo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add sample (stddev,corrcoeff) to the Taylor diagram. args and kwargs are directly propagated to the Figure.plot command.
def add_sample(self, stddev, corrcoef, *args, **kwargs): l, = self.ax.plot(NP.arccos(corrcoef), stddev, *args, **kwargs) # (theta,radius) self.samplePoints.append(l) return l
[ "def add_sample(self, stddev, corrcoef, *args, **kwargs):\n\t\n l, = self.ax.plot(np.arccos(corrcoef), stddev, *args, **kwargs) # (theta, radius)\n self.samplePoints.append(l)\n \n return l", "def add_sample(self, stddev, corrcoef, *args, **kwargs):\n\n l, = self.ax.plot(np.arccos(c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set core to run perf app on
def set_core(self, core): self.core = core mask = 1 << core self.cmd += ' --cores {}'.format(str(hex(mask)))
[ "def SetPerfProfilingMode(self):\n self._ForceAllCpusOnline(True)\n self._SetScalingGovernorInternal('performance')\n if not self._AllCpusAreOnline():\n if not self._device.old_interface.IsRootEnabled():\n raise RuntimeError('Need root to force CPUs online.')\n raise RuntimeError('Failed t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get system and app info from perf app output
def get_info(): global PERF_APP archs = None best_arch = None cipher_algos = None hash_algos = None aead_algos = None cmd = PERF_APP + ' --print-info' try: res = subprocess.run(cmd, stdout=subprocess.PIPE, \ stderr=subprocess.STDOUT, \ ...
[ "def print_app_info(out=sys.stderr):\n print(\"System info:\", file=out)\n print(App, file=out)\n print(\"Python %(version)s on %(platform)s\" %\n {\"version\": sys.version, \"platform\": sys.platform}, file=out)\n print(\"libxml2 version: %i.%i.%i\" % lxml.etree.LIBXML_VERSION, file=out)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse core list passed through command line
def parse_cores(core_str): num_cores = os.cpu_count() cores = [] # remove spaces core_str.replace(" ", "") # check if not a range if '-' not in core_str: cores = list(map(int, core_str.strip().split(','))) else: # parse range e.g. 2-8 core_str = core_str.strip().spl...
[ "def parse_cores(core_string):\n result = CORE_RANGE.fullmatch(core_string)\n if result is not None:\n return range(int(result.group(1)), int(result.group(2)) + 1)\n return [int(core_string)]", "def _get_core_membind_info():\n args = [\"lscpu\", \"--parse=CPU,Core,Socket,Nod...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse output of perf app for variant
def parse_results(variants): out = [] # set header lines = variants[0].get_output().split('\n') for line in lines[:-1]: out.append(line.split('\t')[0]) # append output for all variants to single list for var in variants: lines = var.get_output().split('\n') for i in ran...
[ "def parse_vina_docking_output(output):\n out = []\n r = re.compile(r'^\\s+\\d\\s+')\n for line in output.decode('ascii').split('\\n')[13:]: # skip some output\n if r.match(line):\n s = line.split()\n out.append({'vina_affinity': s[1],\n 'vina_rmsd_lb': ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get learning rate scheduler.
def get_lr_scheduler(self): try: scheduler_name = self.configs.OPTIM.LR_SCHEDULER.SCHEDULER_NAME except AttributeError: scheduler_name = None if scheduler_name is None: lr_scheduler = None elif scheduler_name == 'plateau': factor = self.c...
[ "def get_scheduler(optimizer, opt):\n \n epochs_no_decay = opt.epochs - opt.lr_linear\n lr_policy = opt.lr_policy\n \n if lr_policy == 'linear':\n def lr_lambda(epoch):\n return 1. - max(0, epoch - epochs_no_decay) / float(opt.lr_linear + 1)\n scheduler = lr_scheduler.LambdaL...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deploy computation graph on devices.
def deploy_to_device(self): if self.device_ids is not None and len(self.device_ids) > 1: if not isinstance(self.model, torch.nn.DataParallel): self.model = torch.nn.DataParallel(self.model, self.device_ids) self.model = self.model.to(self.device) self.criterion = sel...
[ "def build_computational_graph():\n pass", "def _publish(self):\n self.framework.create().parents_if_needed().as_ephemeral().with_data(\n '%s:%d' % (self.address, self.port)).for_path(\n os.path.join('nodes', self.localnode.id))", "def ggml_metal_graph_compute(ctx: ffi.CData,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Poincare map plot. Для использования этой функции необходимо определить свою динамическую систему, задав функцию calcODE(args, initial_conditions)
def poincare(args, parameter, initial_conditions=(-1.5, -1.5, 0.5, 0.5, 0.5, 0.5), ts=4000, nt=2 ** 20, show=True): xs = [] periods = [] if show: plt.figure(figsize=(10, 10)) sol, t = calcODE(args, *initial_conditions, ts=ts, nt=nt) sol = sol[-len(sol) // 2:, :] x0 = sol[0, :] t ...
[ "def draw_inner_centrality_info(p_var):\n var_inner_df = pd.read_csv(BaseConfig.OUT_PATH + 'InnerNetworkCSV//' +\n p_var + '_filtered.csv')\n var_inner_net = build_net_by_links_df(var_inner_df)\n\n # draw degree map\n fig = plt.figure(figsize=(20, 12), dpi=500)\n geoagen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Bifurcation diagram plot for BPsystem.
def bifurcation_diagram(args, Bpbmin, Bpbmax, ylim=(-1, 0.6)): xs = [] Bpb_list = np.linspace(Bpbmin, Bpbmax, 100) Iext, G, Ein, Eex, eps, a, b, A, Bpb, Bbp, vsl = args sol, t = calcODE(args, -1.5, -1.5, 0.5, 0.5, 0.5, 0.5, ts=4000, nt=2 ** 25) sol = sol[-len(sol) // 2:, :] t = t[-len(t) // 2:...
[ "def test_bilogplot(self):\n f0 = 1./8\n OSR = 64\n order = 8\n N = 8192\n H = ds.synthesizeNTF(order, OSR, 1, 1.5, f0)\n fB = int(np.ceil(N/(2. * OSR)))\n ftest = int(np.round(f0*N + 1./3 * fB))\n u = 0.5*np.sin(2*np.pi*ftest/N*np.arange(N))\n v, xn, x...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Posts the dispatcher name to redis every 20 seconds.
def post(host): redis.setex('dispatcher',host,60) timer = threading.Timer(20.0, post, args=[host]) timer.daemon = True timer.start()
[ "def mark_redis(self):\n module_name = self.__module__.split(\".\")[-1]\n redis_cache.set(module_name, \"--end poll_alarm--\", settings.POLL_INTERVAL * 60 * 3)", "def register_server(self, server_name):\n if server_name not in self.server_queues.keys():\n print(\"Server '{}' regist...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Connects to a dispatcher at ip address `host` and pushes the records to a ZMQ socket.
def push(host): dispatcher = Dispatch(host) post(host) context = zmq.Context() zmq_socket = context.socket(zmq.PUSH) zmq_socket.bind('tcp://127.0.0.1:5560') for record in dispatcher: zmq_socket.send_pyobj((int(time.time()),record.raw))
[ "def connect(self):\n self.context = zmq.Context()\n self.socket = self.context.socket(self.socket_type)\n\n for host in self.upstream_hosts:\n self.socket.connect(host)\n\n self.connected = True", "def connect(self, host):\n if not self.app.connect(host):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When attempting to correct without the id When there's only 1 correction available under this session
def test_missing_id_one_suggestion(self): errors = self.response.data["errors"] errors[0]["correction"] = "שתיתי" self.response2 = self.client.post( reverse("correct"), {"errors": errors}, format="json" ) self.assertEqual( self.response2.data, "You need to...
[ "def test_missing_one_correction(self):\n errors = self.response.data[\"errors\"]\n errors[0][\"correction\"] = []\n self.response2 = self.client.post(\n reverse(\"correct\"), {\"id\": 1, \"errors\": errors}, format=\"json\"\n )\n\n self.assertEqual(\n self.r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When one correction is missing
def test_missing_one_correction(self): errors = self.response.data["errors"] errors[0]["correction"] = [] self.response2 = self.client.post( reverse("correct"), {"id": 1, "errors": errors}, format="json" ) self.assertEqual( self.response2.data, ...
[ "def is_optional(self):\n return None in self.corrections", "def test_correct_barcode_no_error_correction(self):\r\n barcode = \"GGAGACAAGGGT\"\r\n barcode_to_sample_id = {\r\n \"GGAGACAAGGGA\": \"s1\",\r\n \"ACACCTGGTGAT\": \"s2\"}\r\n correction_fn = None\r\n\r\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert string to valid identifier
def to_identifier(val: Any): val = str(val).strip() # Replaces spaces, dashes, and slashes to underscores val = re.sub(r"[\s\-/\\]", "_", val) # Remove remaining invalid characters val = re.sub(r"[^0-9a-zA-Z_]", "", val) # Identifier can't start with digits val = re.sub(r"^[^a-zA-Z_]+", "", ...
[ "def make_valid_identifier(string: str) -> str:\n string = str(string).strip()\n string = string.replace(\"-\", \"_\")\n string = string.replace(\" \", \"_\")\n string = re.sub(\"[^_a-zA-Z0-9]\", \"\", string)\n string = string.lower()\n if is_valid_identifier(string):\n return string\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return default if value is None.
def if_none(value: Any, default: Any): return value if value is not None else default
[ "def _default(value, default):\n if value is None:\n return default\n return value", "def notNone(value, default):\n if value is None:\n return default\n else:\n return value", "def if_none_then(value: Optional[T], default: T) -> T:\n if value is not None:\n return val...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize table with another table.
def _init_table(self, table: "Table"): if not self.columns: self.columns = table.columns self._data = table.data
[ "def set_table(self,new_table):\n self.table = new_table", "def init_table_obj(self):\n # Check the existence of original table\n if not self.table_exists(self.table_name):\n raise OSCError(\n \"TABLE_NOT_EXIST\", {\"db\": self._current_db, \"table\": self.table_name...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate that given column names can be used.
def _validate_columns(self, names): if not is_list_like(names): raise ValueError("Columns should be list-like") if len(set(names)) != len(names): raise ValueError("Duplicate column names") if self._data and len(names) != len(self._data[0]): raise ValueError(...
[ "def _check_columns(df: pd.DataFrame, names: typing.Sequence[str]) -> None:\n for expected in names:\n if expected not in df.columns:\n raise ValueError(f\"'{expected}' column not found in input\")\n return", "def check_columns(self, column_names):\n expected_set = set(self.expected...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create callable that returns column names for given obj types.
def _column_name_getter(self, obj): if is_namedtuple(obj): # Use namedtuple fields as columns def get(obj): return list(obj._fields) elif is_dict_like(obj): # Use dictionary keys as columns def get(obj): return list(obj.key...
[ "def get_obj_cols(df):\n obj_cols = []\n for idx, dt in enumerate(df.dtypes):\n if dt == 'object' or is_category(dt):\n obj_cols.append(df.columns.values[idx])\n\n return obj_cols", "def get_obj_cols(df):\n obj_cols = []\n for idx, dt in enumerate(df.dtypes):\n if dt == 'ob...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sort columns to match given order.
def _sort_columns(self, order): unknown = set(self._columns) - set(order) if unknown: names = ", ".join(str(name) for name in unknown) raise ValueError(f"Unknown columns: {names}") cols = [self.column_location(column) for column in order] self._columns = [self._...
[ "def sort_columns_by_list(self, df, cols):\n\n pass", "def sort(self,*cols):\r\n for c in cols[::-1]:\r\n reverse = c[0] == \"-\"\r\n if reverse:\r\n v = c[1:]\r\n else:\r\n v = c\r\n self.data.sort(key = lambda x:x[self.col_t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find location for column value.
def column_location(self, value): # Try to use as-is try: return self._columns.index(value) except ValueError: pass # Try as integer index try: value = int(value) if value in self._columns: location = self._column...
[ "def get_column(location):\r\n return location[1]", "def column_location(self, column_name):\n if column_name not in self.metadata:\n write_error(\"The column {} could not be found in table {}\", column_name, self.name)\n return self.metadata[column_name][0]", "def _value_column(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create list of index values from slice object.
def _slice_index(self, slicer): start = self.index_location(slicer.start) if slicer.start is not None else 0 end = self.index_location(slicer.stop) if slicer.stop is not None else self.size return list(range(start, end))
[ "def _transform_slice_to_indices(i):\n if type(i) is slice:\n if i.step is None:\n step = 1\n else:\n step = i.step\n idxs = list(range(i.start, i.stop, step))\n else:\n idxs = [i]\n return idxs", "def _conv_slice_to_li...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return last n rows of table.
def tail(self, rows, as_list=False): indexes = self.index[-int(rows) :] return self.get_table(indexes, as_list=as_list)
[ "def tail(a, n=5):\n return DataFrameIloc(a)[-n:]", "def tail(self, n: int = 5) -> AbstractColumn:\n return self.lz[-n:]", "def tail(self, n=None, **kwargs):\n if n is None:\n n = options.display.max_rows\n return self._handle_delay_call('execute', self, tail=n, **kwargs)", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a new table from all cells matching indexes and columns.
def get_table(self, indexes=None, columns=None, as_list=False): indexes = if_none(indexes, self.index) columns = if_none(columns, self._columns) if indexes == self.index and columns == self._columns: return self.copy() idxs = [self.index_location(index) for index in indexes...
[ "def select(self, labels):\n indexs = []\n \n for i in range(len(labels)):\n indexs.append(self.column_labels.index(labels[i]))\n new_rows = []\n for x in self.rows:\n new_row = []\n for index in indexs:\n new_row.append(x[index])\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }