query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Attempts to parse episode title from filename. Will strip out separators at start of string. If no title is found, returns empty string
def parse_anime_episode_title(filename): print_info('Attempting to parse episode title from {0}'.format(filename)) for regex in ANIME_EPISODE_TITLE_REGEXS: m = re.search(regex, filename) if m is None: continue extracted_title = m.group('EpisodeTitle') return clean_e...
[ "def parse_episode_title(filename):\n print_info('Attempting to parse episode title from {0}'.format(filename))\n for regex in EPISODE_TITLE_REGEX:\n m = re.search(regex, filename)\n\n if m is None:\n continue\n\n extracted_title = m.group('EpisodeTitle')\n return clean_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Attempts to parse Volume from filename. If no season is found, returns Volume 0.
def parse_volume(filename): print_info('Extracting volume from {0}'.format(filename)) for regex in MANGA_VOLUME_REGEX: m = re.search(regex, filename) if m is None: continue extracted_season = m.group('Volume').lower() print_info('Extracted volume: {0}'.format(extrac...
[ "def parse_season(filename):\n print_info('Attempting to parse {0}'.format(filename))\n print_info('Extracting season from {0}'.format(filename))\n for regex in SEASON_REGEX:\n m = re.search(regex, filename)\n\n if m is None:\n continue\n\n extracted_season = m.group('Season...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Attempts to parse manga title from filename. Will strip out separators at start of string. If no title is found, returns empty string
def parse_manga_title(filename): print_info('Attempting to parse manga title from {0}'.format(filename)) for regex in MANGA_TITLE_REGEX: m = re.search(regex, filename) if m is None: continue extracted_title = m.group('Series') return clean_episode_title(extracted_ti...
[ "def parse_movie_title(file_name):\n\tmovie_name = os.path.basename(file_name)\n\tmovie_name = parsers.remove_extension(file_name)\n\tmovie_name = movie_name.lower()\n\tmovie_name = parsers.fix_word_seperators(movie_name)\n\tmovie_name = parsers.remove_tags(movie_name)\n\tmovie_name = parsers.remove_resolution(movi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a filename, matches chapter and returns episode in Chapter 01 format. This will ignore episode parts. Returns None if no matches.
def parse_chapter(filename): print_info('Extracting chapter from {0}'.format(filename)) for regex in MANGA_CHAPTER_REGEX: m = re.search(regex, filename) if m is None: continue extracted_ep = m.group('Chapter') print_info('Extracted chapter: {0}'.format(extracted_ep)...
[ "def parse_episode(filename):\n print_info('Extracting episode from {0}'.format(filename))\n for regex in EPISODE_NUM_REGEXS:\n m = re.search(regex, filename)\n\n if m is None:\n continue\n\n extracted_ep = m.group('Episode').lower()\n print_info('Extracted episode: {0}'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a filename, match media info and return MediaInfo object. Returns empty MediaInfo if no matches.
def parse_media_info(filename): print_info('Extracting hash from {0}'.format(filename)) media_info = MediaInfo() for media_info_type in MEDIA_INFO_REGEXS: #print_info('Parsing for {0}'.format(media_info_type)) for regex in MEDIA_INFO_REGEXS[media_info_type]: m = re.search(regex, ...
[ "def getinfo(file_name):\n print(file_name)\n extension = file_name.split('.')[-1]\n if extension not in __AVAILABLE_EXTENSION:\n return False\n\n # Separate the filename in parts\n file_name_parts = _get_filename_parts(file_name)\n print(file_name_parts)\n media = MediaRespond()\n me...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns True if Season is formated as Special (ie S00)
def is_special_season(season_str): return season_str == 'S00'
[ "def is_winter(self):\n return self.semester == 'z'", "def season_exists (self, title, season):\n title=re.sub(r'[?|$|!|:|#]',r'',title)\n if self.show_exists(title) == False:\n return False\n show_entry = self.db[self.series_label][title]\n return season in show_entr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if file is a known media extension. This list is selfmaintained.
def is_media_file(file): return file.lower().endswith(MEDIA_EXTENSIONS)
[ "def is_media_file(media_file_extensions: list, file_name: str) -> bool:\n file_extension = Path(file_name).suffix\n if file_extension in media_file_extensions:\n return True\n return False", "def is_media_file(path):\n return os.path.splitext(path)[1][1:] in MEDIA_FORMATS", "def have_mpeg_ex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if file is a known subtitle extension. This list is selfmaintained.
def is_subtitle(file): return file.lower().endswith(SUBTITLE_EXTENSIONS)
[ "def is_parser_for(cls, extension):\n\t\t# Since Default is the catch all parser for subtitles, return true if it is any subtitle ext\n\t\treturn extension in SUBTITLE_EXTS", "def have_txt_extension(l):\r\n if \".txt\" in str(l):\r\n return 1\r\n else:\r\n return 0", "def txtExtensionCheck(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if file is a known manga file extension. This list is selfmaintained.
def is_manga(file): return file.lower().endswith(MANGA_EXTENSIONS)
[ "def check_file_ext(f_name):\n global im_ext_\n for ext_ in im_ext_:\n if f_name.lower().endswith(ext_):\n return True\n return False", "def is_good_file(filename):\n for e in extensions:\n if filename.endswith(e):\n return True\n return False", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Formats a number to have leading 0 if below 10
def format_num(num): if num is None: return num if (num < 10): return '0' + str(num) return str(num)
[ "def add_leading_zero(num):\n formated = \"\"\n if num <= 9:\n formated = \"0\" + str(num)\n else:\n formated = str(num)\n \n return formated", "def fmt(n):\n if n < 10:\n return \"0\" + str(n)\n else:\n return str(n)", "def format_number(number, num_digits=3):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
defined_timepoints should be an array the length of the t with True at timepoints that are defined and False at timepoints that are not defined. signal should also be an array of length t. Timepoints at defined as False will be overwritten. This script supports extrapolation at beginning/end of the time signal. As a qu...
def interpolate(timepoint_defined, signal, interp_type, TR): timepoint_defined = np.array(timepoint_defined) true_inds = np.where(timepoint_defined == True)[0] false_inds = np.where(timepoint_defined == False)[0] signal_copy = np.array(signal) if interp_type == 'linear': #Still need to...
[ "def interpolate(tSup, t, y):\n import numpy as np\n\n if ((np.isnan(tSup)).any()):\n raise ValueError('NaN in input argument tSup.')\n if ((np.isnan(t)).any()):\n raise ValueError('NaN in time values of data.')\n if ((np.isnan(y)).any()):\n raise ValueEr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes input_matrix . Returns the num_dimensions top PCs from the input_matrix which are derived excluding n_skip_vols, but zeros are padded to the beginning of the time series in place of the n_skip_vols.
def reduce_ics(input_matrix, num_dimensions, n_skip_vols): if input_matrix.shape[0] > input_matrix.shape[1]: raise NameError('Error: input_matrix should have longer dim1 than dim0') if input_matrix.shape[0] <= 1: raise NameError('Error: input matrix must have multiple matrices') input_...
[ "def matrix_dim(CT):\r\n if CT[0]==0 and CT[-1]==0:\r\n return 2\r\n elif CT[0]!=0 and CT[-1]!=0:\r\n return 4", "def number_of_my_pieces_on_top_of_column(column):\n return number_pieces_on_top_of_column(column, ME)", "def nrows(self):\n \n return self.ccdRows + self.overRow...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get Server Stats Retrieves statistics from specified virtual server on remote ESX host. Middleware See SETTINGS for active Middleware. Decorators request.method must be POST request.is_ajax() must be True request.user.is_authenticated() must be True service_id must belong to request.user.company.services service.vars i...
def get_stats(request, server_ids, server_id): try: if int(server_id) not in server_ids: raise Exception("Forbidden: specified Server does not belong to specified Service.") server = Server.objects.get(pk=server_id) pysph = Vsphere(settings.VMWARE["address"], settings.VMWA...
[ "def server_agent_statistics(ctx):\n data = ctx.obj.get_agent_statistics()\n output_json_data(data)", "def get_host_stats(self):\n status, data, errors, messages = self._make_get_request(CraftyAPIRoutes.SERVER_STATS)\n \n if status == 200:\n return data\n elif status =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get ISO's Retrieves available ISO's from remote ESX server. Middleware See SETTINGS for active Middleware. Decorators request.method must be POST request.is_ajax() must be True request.user.is_authenticated() must be True service_id must belong to request.user.company.services service.vars is injected into view paramet...
def get_isos(request, server_ids, server_id): try: if int(server_id) not in server_ids: raise Exception("Forbidden: specified Server does not belong to specified Service.") server = Server.objects.get(pk=server_id) pysph = Vsphere(settings.VMWARE["address"], settings.VMWARE...
[ "def mount_iso(request, server_ids, server_id):\n try:\n if int(server_id) not in server_ids:\n raise Exception(\"Forbidden: specified Server does not belong to specified Service.\")\n\n server = Server.objects.get(pk=server_id) \n\n pysph = Vsphere(settings.VMWARE[\"address...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get Snapshots Retrieves current snapshots from specified virtual server on remote ESX host. Middleware See SETTINGS for active Middleware. Decorators request.method must be POST request.is_ajax() must be True request.user.is_authenticated() must be True service_id must belong to request.user.company.services service.va...
def get_snapshots(request, server_ids, server_id): try: if int(server_id) not in server_ids: raise Exception("Forbidden: specified Server does not belong to specified Service.") server = Server.objects.get(pk=server_id) pysph = Vsphere(settings.VMWARE["address"], s...
[ "def v2_detailTenantVolumesSnapshots(request):\n token_id = 'e839a2fd51844fffaba95443bc0f25f0'\n\n head = [\n \"X-Auth-Token: %s\" % token_id,\n ]\n parms = {\n 'servername': '192.168.30.127',\n 'port': 8776,\n 'uri': '/v2/%(tenant_id)s/snapshots/detail' % {\n \"te...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reboot virtual server Reboots specified guest virtual server on remote Vmware ESX host server. Middleware See SETTINGS for active Middleware. Decorators request.method must be POST request.is_ajax() must be True request.user.is_authenticated() must be True service_id must belong to request.user.company.services service...
def reboot(request, server_ids, server_id): try: if int(server_id) not in server_ids: raise Exception("Forbidden: specified Server does not belong to specified Service.") server = Server.objects.get(pk=server_id) graceful = (False, True)[request.POST["graceful"]==1] ...
[ "def boot(request, server_ids, server_id):\n try:\n if int(server_id) not in server_ids:\n raise Exception(\"Forbidden: specified Server does not belong to specified Service.\")\n\n server = Server.objects.get(pk=server_id) \n\n pysph = Vsphere(settings.VMWARE[\"address\"], set...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shutdown virtual server Shuts down specified virtual server on remote ESX server. Middleware See SETTINGS for active Middleware. Decorators request.method must be POST request.is_ajax() must be True request.user.is_authenticated() must be True service_id must belong to request.user.company.services service.vars is inje...
def shutdown(request, server_ids, server_id): try: if int(server_id) not in server_ids: raise Exception("Forbidden: specified Server does not belong to specified Service.") server = Server.objects.get(pk=server_id) graceful = (False, True)[request.POST["graceful"]==1] ...
[ "def cmd_web_service_shutdown(self, arg):\n server_app.web_shutdown()", "def iscsi_service_stop(self):\n return self.request( \"iscsi-service-stop\", {\n }, {\n } )", "def close(self):\n if self.render_app:\n requests.post('http://127.0.0.1:8050/shutdown')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Boot virtual server Starts specified virtual server on remote ESX server. Middleware See SETTINGS for active Middleware. Decorators request.method must be POST request.is_ajax() must be True request.user.is_authenticated() must be True service_id must belong to request.user.company.services service.vars is injected int...
def boot(request, server_ids, server_id): try: if int(server_id) not in server_ids: raise Exception("Forbidden: specified Server does not belong to specified Service.") server = Server.objects.get(pk=server_id) pysph = Vsphere(settings.VMWARE["address"], settings.VMWARE["us...
[ "def launch(port=DEFAULT_PORT):\n\n server = VBSPServer(port, PT_TYPES, PT_TYPES_HANDLERS)\n\n rest_server = RUNTIME.components[RESTServer.__module__]\n rest_server.add_handler_class(TenantVBSHandler, server)\n rest_server.add_handler_class(VBSHandler, server)\n rest_server.add_handler_class(UEHandle...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mount ISO Mounts ISO image to specified virtual server on remote ESX host. Middleware See SETTINGS for active Middleware. Decorators request.POST must validated against MountISOForm request.method must be POST request.is_ajax() must be True request.user.is_authenticated() must be True service_id must belong to request....
def mount_iso(request, server_ids, server_id): try: if int(server_id) not in server_ids: raise Exception("Forbidden: specified Server does not belong to specified Service.") server = Server.objects.get(pk=server_id) pysph = Vsphere(settings.VMWARE["address"], settings.VM...
[ "def mount_iso(self):\n\n # Mounting ISO on /mnt and on http server\n mount_point = '/mnt'\n http_mnt_point = '/var/www/html/stx'\n tmp_mnt_point = '/tmp'\n\n if os.listdir(mount_point):\n LOG.info('%s is busy umounting', mount_point)\n umounting_attempts = 3...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete Snapshot Deletes specified snapshot from specified virtual server on remote ESX host. Middleware See SETTINGS for active Middleware. Decorators request.POST must validated against SnapshotPathForm request.method must be POST request.is_ajax() must be True request.user.is_authenticated() must be True service_id m...
def delete_snapshot(request, server_ids, server_id): try: if int(server_id) not in server_ids: raise Exception("Forbidden: specified Server does not belong to specified Service.") server = Server.objects.get(pk=server_id) pysph = Vsphere(settings.VMWARE["address"], settin...
[ "def _delete_snapshot(self, vol_id, snap_id, **kwargs):\n\n return self._snap_api_submit(vol_id, snap_id, method='DELETE',\n **kwargs)", "def snap_delete(self, uri, domain, snapshot):\n\t\treturn protocol.Request_DOMAIN_SNAPSHOT_DELETE(uri=uri, domain=domain, snapshot=sn...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Revert to Snapshot Loads specified snapshot onto specified virtual server on remote ESX host. Middleware See SETTINGS for active Middleware. Decorators request.POST must validated against SnapshotPathForm request.method must be POST request.is_ajax() must be True request.user.is_authenticated() must be True service_id ...
def revert_snapshot(request, server_ids, server_id): try: if int(server_id) not in server_ids: raise Exception("Forbidden: specified Server does not belong to specified Service.") server = Server.objects.get(pk=server_id) pysph = Vsphere(settings.VMWARE["address"], settings....
[ "def delete_snapshot(request, server_ids, server_id):\n try:\n if int(server_id) not in server_ids:\n raise Exception(\"Forbidden: specified Server does not belong to specified Service.\")\n\n server = Server.objects.get(pk=server_id) \n\n pysph = Vsphere(settings.VMWARE[\"ad...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create Snapshot Creates snapshot for specified virtual server on remote ESX host. Middleware See SETTINGS for active Middleware. Decorators request.POST must validated against CreateSnapshotForm request.method must be POST request.is_ajax() must be True request.user.is_authenticated() must be True. service_id must belo...
def create_snapshot(request, server_ids, server_id): try: if int(server_id) not in server_ids: raise Exception("Forbidden: specified Server does not belong to specified Service.") server = Server.objects.get(pk=server_id) pysph = Vsphere(settings.VMWARE["address"], settings....
[ "def create_snapshot(self, **kwargs):\n post_body = json.dumps({'snapshot': kwargs})\n resp, body = self.post('snapshots', post_body)\n body = json.loads(body)\n self.validate_response(schema.create_snapshot, resp, body)\n return rest_client.ResponseBody(resp, body)", "def test_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calls an external service to get the 512 dimensional vector representation of a piece of text.
def getVector(text): url = cfg.use_vectoriser res = requests.post(url, json={'text': text, 'access_key': cfg.vectoriser_access_key}) res_dictionary = res.json() return res_dictionary['vectors']
[ "def getvector(self, shorttext):\n if not self.trained:\n raise e.ModelNotTrainedException()\n return self.topicmodeler.retrieve_topicvec(shorttext)", "def get_vector(filename):\n\n command = 'tokenizer -l Java ' + filename\n process = subprocess.Popen(command.split(), stdout=subpro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calls an external service to check if an ontology based similarity measures exist.
def checkOntoSimilarity(ontology_id): # print('checkOntoSimilarity() =>', ontology_id) url = cfg.ontology_sim + '/status' res = requests.post(url, json={'ontologyId': ontology_id}) resp = res.json() resp['statusCode'] = res.status_code return resp #resp['statusCode'] = 200 if ontology exists and 404 otherw...
[ "def test_get_similarity():\n for similarity_enum in SimilarityEnum:\n similarity = get_similarity(similarity=similarity_enum)", "def _do_action_calculate_similarity_cosine_express(self):\n self._run_express_job(\"com.directv.recommend.express.CosineCFTrainer\")\n self._scan_table(\"conten...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calls an external service to get ontology based similarity values for concept comparisons.
def getOntoSimilarity(ontology_id, key): # print('getOntoSimilarity() =>', ontology_id) url = cfg.ontology_sim + '/query' res = requests.post(url, json={'ontologyId': ontology_id, 'key': key}) res_dictionary = res.json() return res_dictionary.get('map', {})
[ "def test_get_similarity():\n for similarity_enum in SimilarityEnum:\n similarity = get_similarity(similarity=similarity_enum)", "def checkOntoSimilarity(ontology_id):\n # print('checkOntoSimilarity() =>', ontology_id)\n url = cfg.ontology_sim + '/status'\n res = requests.post(url, json={'ontologyId'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calls an external service to remove an ontology index of similarity measures.
def removeOntoIndex(ontology_id): # print('removeOntoIndex() =>', ontology_id) url = cfg.ontology_sim + '/delete' body = { "ontologyId": ontology_id } try: res = requests.post(url, json=body) return res.json() except: print("Could not remove details for ontology with id " + ontology_id) ...
[ "def deleteDataInSolr(iannSolrUrl):\n # solrUrl = 'http://localhost:8982/solr/iann'\n solr = pysolr.Solr(iannSolrUrl, timeout=10)\n query = '*:*'\n solr.delete(q='%s' % query)", "def delete_index(self):\n if self.index_module:\n self.index_module = None\n gc.collect()", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Expand data values to include vector fields.
def add_vector_fields(attributes, data): for attrib in attributes: if attrib['similarity'] == 'Semantic USE': value = data.get(attrib['name']) if value is not None: newVal = {} newVal['name'] = value newVal['rep'] = getVector(value) data[attrib['name']] = newVal eli...
[ "def _expand_vector_cols(columns, datatypes, values=None):\n columns_expanded = list()\n datatypes_expanded = dict()\n values_expanded = list()\n\n # iterate over the columns and look for vectors\n for i, column in enumerate(columns):\n # non vectors are simply added to...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Change values for fields of EqualIgnoreCase to lowercase.
def add_lowercase_fields(attributes, data): for attrib in attributes: if attrib['similarity'] == 'EqualIgnoreCase': value = data.get(attrib['name']) if value is not None: data[attrib['name']] = value.lower() return data
[ "def force_case(self):\n if self.get_field('name'):\n self.set_field('name', self.get_field('name').lower())\n if self.get_field('type'):\n self.set_field('type', self.get_field('type').upper())", "def to_lower(self):\n\n print('Converting to lowercase...')\n self.__data[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves an attribute by name from list of attributes.
def get_attribute_by_name(attributes, attributeName): for attrib in attributes: if attrib['name'] == attributeName: return attrib return None
[ "def get_attribute_by_name(self, name):\n if name in self._attributes:\n return self._attributes[name]", "def getattr_from_list(adict, attributes):\n for attribute in attributes:\n try:\n result = adict[attribute]\n if result is masked:\n raise KeyE...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extracts the field names and local similarity values from explanations.
def get_explain_details2(match_explanation): expl = [] matchers = match_explanation["details"] # at times the explanation is not in 'details' list!! if len(matchers) <= 1: # not more than one explanation then match attribute in the entire string txt = str(match_explanation) m0 = re.search("attrib=([a-zA-...
[ "def get_explain_details(match_explanation):\n expl = []\n for x in match_explanation[\"details\"]:\n if len(re.findall(\"attrib=([a-zA-Z0-9_\\-\\s]+)\", str(x))) > 1:\n expl.extend(get_explain_details(x))\n elif len(re.findall(\"attrib=([a-zA-Z0-9_\\-\\s]+)\", str(x))) == 1:\n expl.append({\"fiel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extracts the field names and local similarity values from explanations.
def get_explain_details(match_explanation): expl = [] for x in match_explanation["details"]: if len(re.findall("attrib=([a-zA-Z0-9_\-\s]+)", str(x))) > 1: expl.extend(get_explain_details(x)) elif len(re.findall("attrib=([a-zA-Z0-9_\-\s]+)", str(x))) == 1: expl.append({"field": re.search("attrib=...
[ "def get_explain_details2(match_explanation):\n expl = []\n matchers = match_explanation[\"details\"] # at times the explanation is not in 'details' list!!\n if len(matchers) <= 1: # not more than one explanation then match attribute in the entire string\n txt = str(match_explanation)\n m0 = re.search(\"a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine query function to use base on attribute specification and retrieval features. Add new query functions in the if..else statement as elif.
def getQueryFunction(projId, caseAttrib, queryValue, type, weight, simMetric, options): # print("all info: ", projId, caseAttrib, queryValue, weight, simMetric, options) # minVal = kwargs.get('minVal', None) # optional parameter, minVal (name 'minVal' in function params when calling function e.g. minVal=5) if sim...
[ "def choose_query_function(self, query_function):\n while query_function not in self.dispatcher.keys():\n query_function = input(\n '''invalid algorihm choice, try one of the following strings:\n variation_ratio\n predictive_entropy\n mut...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the documents whose attribute values have the closest date to the query date. The date field field is indexed as 'keyword' to enable use of this similarity metric.
def ClosestDate(caseAttrib, queryValue, weight, scale, decay): # format 'dd-MM-yyyy' e.g. '01-02-2020' # format = "%d-%m-%Y"'T'"%H:%M:%SZ" # qd = dateutil.parser.isoparse(queryValue) # queryValue = qd.strftime(format) # enforce query conversion to a known date format # build query string queryFnc = { ...
[ "def get_closest_document(self, sentiment):\n # variables to hold closest document\n closest = {}\n closest_value = 10000000\n\n # find closest difference\n for i in self.relevant_documents['hits']['hits']:\n current_diff = math.sqrt(math.pow(i['_source']['documentSenti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the documents whose attribute values have the closest number to the query value.
def ClosestNumber(caseAttrib, queryValue, weight, scale, decay): # build query string queryFnc = { "script_score": { "query": { "exists": { "field": caseAttrib } }, "script": { "params": { "attrib": caseAttrib, "origin": queryValue, ...
[ "def get_closest_document(self, sentiment):\n # variables to hold closest document\n closest = {}\n closest_value = 10000000\n\n # find closest difference\n for i in self.relevant_documents['hits']['hits']:\n current_diff = math.sqrt(math.pow(i['_source']['documentSenti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Implements Table local similarity function. Returns the similarity of two categorical values as specified in a similarity table.
def TableSimilarity(caseAttrib, queryValue, weight, options): # stores enum as array # build query string queryFnc = { "script_score": { "query": { "exists": { "field": caseAttrib } }, "script": { "params": { "attrib": caseAttrib, "queryVa...
[ "def tuple_similarity(t1, t2, var_attr, cat_sim, num_dis_norm, agg_col):\n sim = 0.0\n cnt = 0\n for v_col in var_attr:\n col = v_col.replace(' ', '')\n \n if t1[col] is None or t2[col] is None:\n continue\n if cat_sim.is_categorical(col):\n t1_key = t1[col...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gathered columns collects all the rules for column types into a single rule
def test_gather_columns(self): expected_gathered_columns = [ """ unusable_col: "DUMMYVALUNUSABLECOL" date.1: date_0 | extra_date_rule | "(" + date + ")" datetime.2: datetime_0 | extra_datetime_rule | "(" + datetime + ")" datetime_end.1: datetime_0 | da...
[ "def columns_by_type(self, coltype=\"numeric\"):\n assert_is_type(coltype, \"numeric\", \"categorical\", \"string\", \"time\", \"uuid\", \"bad\")\n assert_is_type(self, H2OFrame)\n return ExprNode(\"columnsByType\", self, coltype)._eager_scalar()", "def column_types(self):\n already_yi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Take input where each line looks like field > expected_sql field > expected_sql (commented out)
def examples(self, input_rows): for row in input_rows.split("\n"): row = row.strip() if row == "" or row.startswith("#"): continue if "->" in row: field, expected_sql = row.split("->") else: field = row ...
[ "def parse_sql_script(sql_script: str) -> Iterator[Iterator[str]]:\n\tsql = []\n\n\tfor line in sql_script.splitlines():\n\n\t\tif is_comment(line):\n\t\t\tpass\n\n\t\tif DELIM in line:\n\n\t\t\tsql.append(line.split(DELIM)[0])\n\t\t\tyield [s.strip() for s in sql if s.strip()]\n\n\t\t\t# Initialize sql\n\t\t\t# TO...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Take input where each input is separated by three equals field > expected_error === field > expected_error === field > expected_error (commented out)
def bad_examples(self, input_rows): for row in input_rows.split("==="): row = row.strip() if row == "" or row.startswith("#"): continue if "->" in row: field, expected_error = row.split("->") else: field = row ...
[ "def test_nl_separated_values(self, test_input, expected, sc):\n assert sc.add(test_input) == expected", "def check_format(data):\n\n try:\n if not minmax_regex.match(data[0]):\n raise Exception(\n 'ERROR: Linear Problem type is not valid.\\nTry adding min/max in front o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test a selectable that is a recipe
def test_selectable_recipe(self): recipe = ( self.recipe(shelf=self.mytable_shelf).metrics("age").dimensions("first") ) b = SQLAlchemyBuilder(selectable=recipe) type_examples = """ [age] -> num [first] -> str ...
[ "def test_visualize_recipe_equipment_by_id(self):\n pass", "def test_choice(self):\n elt = random.choice(self.liste)\n self.assertIn(elt, self.liste)", "def test_framework_selections_post(self):\n pass", "def test_boolean_and_selection(self):\n\n # The selection loop:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test a selectable that is a orm class
def test_selectable_orm(self): b = SQLAlchemyBuilder(selectable=self.datatypes_table) type_examples = """ [score] -> num score -> num [testid] -> str [username] > "foo" -> bool s...
[ "def test_selectable_recipe(self):\n recipe = (\n self.recipe(shelf=self.mytable_shelf).metrics(\"age\").dimensions(\"first\")\n )\n b = SQLAlchemyBuilder(selectable=recipe)\n type_examples = \"\"\"\n [age] -> num\n [first] ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Vertices are equivalent if they are sufficiently close. Use the "is" operator to test if they are identical.
def __eq__(self, other): return abs(self.x - other.x) + abs(self.y - other.y) < Vertex.epsilon
[ "def verticesEqual(self, v1, v2, eps=1e-8):\n if abs(v1[0] - v2[0]) > eps:\n return False\n if abs(v1[1] - v2[1]) > eps:\n return False\n if abs(v1[2] - v2[2]) > eps:\n return False\n return True", "def _vertices_are_equal(\n vertices1: List[np.ndarr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an element with Gst Element Factory make. Return the element if successfully created, otherwise print to stderr and return None.
def make_elm_or_print_err(factoryname, name, printedname, detail=""): print("Creating", printedname) elm = Gst.ElementFactory.make(factoryname, name) if not elm: sys.stderr.write("Unable to create " + printedname + " \n") if detail: sys.stderr.write(detail) return elm
[ "def make_add_element(self, gst_element_name, name):\n gst_element = Gst.ElementFactory.make(gst_element_name, name)\n self.pipeline.add(gst_element)\n return gst_element", "def do_create_element(self, url):\n return Gst.parse_launch(self.launch_string)", "def makeelement(self, _tag,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
``connection.extra_dejson`` but where keys are converted to lower case. This is used internally for caseinsensitive access of jdbc params.
def connection_extra_lower(self) -> dict: conn = self.get_connection(getattr(self, self.conn_name_attr)) return {k.lower(): v for k, v in conn.extra_dejson.items()}
[ "def extra_dejson(self):\n obj = {}\n if self.extra:\n try:\n obj = json.loads(self.extra)\n except Exception as e:\n self.log.exception(e)\n self.log.error(\"Failed parsing the json for conn_id %s\", self.conn_id)\n\n return ob...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set autocommit for the given connection.
def set_autocommit(self, conn: jaydebeapi.Connection, autocommit: bool) -> None: conn.jconn.setAutoCommit(autocommit)
[ "def _set_autocommit(self, value):\n self.connection.autocommit = value", "def autocommit(self, value):\n\n self._ensure_connection()\n log.debug(\"Setting autocommit to {} for the connection \"\n \"to {} database.\".format(value, self.dbname))\n\n self._set_autocommit...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get autocommit setting for the provided connection.
def get_autocommit(self, conn: jaydebeapi.Connection) -> bool: return conn.jconn.getAutoCommit()
[ "def get_auto_commit(self):\n return self.__aceQLHttpApi.get_auto_commit()", "def autocommit(self):\n\n return self._autocommit", "def _set_autocommit(self, value):\n self.connection.autocommit = value", "def set_autocommit(self, conn: jaydebeapi.Connection, autocommit: bool) -> None:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this function finds the amplitude and time of flight value of the 1st echo peak for a single file the function reads a single file and saves the data into a numpy array all peaks are found using scipy function and peaks appearing after 7.5 microseconds are selected the highest peak (with highest amplitude value) within...
def find_echo(file_name): #define a function data_list = [] #variable for storing data from a single file with open(file_name, 'r') as file: #read the file text = file.read().replace('\n','') items = text.split(',') items_array = np.array(items) #put the data into a numpy a...
[ "def FindHighestPeak(sp,PeakFunction='Gaussian', tofRange=(2000,5000), dx=1.0):\n\n def compareLines(line,peaks,targetWidth,tofRange):\n \"\"\" Parse the results from FindPeaks in order to retrieve the best peak candidate,\n then compare to current best peak \"\"\"\n nRows = peaks.rowCount()\n for iRow...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the translated sentiment values for all the words with their contexts and pos tags.
def translate_and_get_lexicon_sentiment(self, word, context=None, pos_tag=None): #Translate word translated_word = self.translater.translate(word) return self.sentiment_lexicon.get_values(translated_word, context, pos_tag)
[ "def translate_sentence_and_get_lexicon_sentiment(self, sentence):\n #Translate word\n translated_sentence = self.translater.translate(sentence)\n translated_words = tokenizer(translated_sentence)\n sentiments = []\n for word in translated_words:\n sentiment = self.sent...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the translated sentiment values for a whole sentence.
def translate_sentence_and_get_lexicon_sentiment(self, sentence): #Translate word translated_sentence = self.translater.translate(sentence) translated_words = tokenizer(translated_sentence) sentiments = [] for word in translated_words: sentiment = self.sentiment_lexic...
[ "def get_sentiment(self): \n # need to change the condition according to the structure of model result\n\n classifier = pipeline('sentiment-analysis', model='distilbert-base-uncased-finetuned-sst-2-english')\n text_dict = self.read_text()\n\n trans_sent = {}\n for k, v in text_dic...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Translate word using a translation API Perform sentence contezt translation on google web interface Perform word translation using Bing > get all alternatives anc check for a mathc in the google translation, if match choose it as translation if not then choose the bing translation that best matches using POS tag?
def translate(self, word, context=None, pos_tag=None): #Get contextual translation from google translate par = {"text": word, "raw": "raw"} r = requests.post(self.translation_url, data=par) results = r.text translated_word = get_from_html_text(results, 'TRANSLATED_TEXT') ...
[ "def translate(sentence,target,api_key):\n #translate without using googletrans wrapper library\n URL = \"https://translation.googleapis.com/language/translate/v2?target=\"+target+\"&key=\"+api_key+\"&q=\"+sentence\n # sending get request and saving the response as response object \n r = requests.get(ur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the value of a variable target from a html result set from a request.
def get_from_html_text(resultset, target): index = resultset.find(target)+len(target)+2 return resultset[index:index+140].split("'")[0].lower()
[ "def get_html_soup(url_target, getter=1):\n if getter == 1:\n response = requests.get(url_target) # getter == 1\n status_code = response.status_code\n markup = response.text\n else:\n response = urlopen(url_target)\n status_code = response.getcode()\n markup = respo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Performs sentiment lexicon lookup on the tweets, and stores it in the objects.
def perform_bing_sentiment_lexicon_lookup(tweets): words = [] for t in tweets: for phrase in t.tagged_words: for word in phrase: try: if word["pos"] in TYPECRAFT_SENTIWORDNET: words.append(word['word']) except KeyErr...
[ "def performLexiconBasedSentimentAnalysis(data):\n opinions = data[0]\n taggedTweets = data[3]\n sentiments_mapping = lexiconBasedSentimentPrediction(\n taggedTweets) # identify the sentiment orientation of each tweet\n for key in sentiments_mapping:\n opinions[key].setSO(sentiments_mappi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if an object is an instance of an LCM type LCM offers no official way to do this, so test for a uniquelynamed method that is present in all LCM types
def is_lcm_message(obj): return '_get_packed_fingerprint' in dir(obj)
[ "def _is_run_type(cls, object_):\n # Do a string comparison instead of using isinstance() to avoid needing\n # to import lyse or other modules with these classes.\n return (type(object_).__name__ in cls._RUN_TYPES)", "def ismethod(obj):\n return isinstance(obj, types.MethodType)", "def i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prettyprints an LCM message to the console
def print_lcm_msg(msg, indent='', indent_increment=' '): print indent + msg.__module__ + ":" for slot in msg.__slots__: value = msg.__getattribute__(slot) if is_lcm_message(value): print indent + indent_increment + slot + ":" print_lcm_msg(value, indent + indent_incremen...
[ "def print_message(message):\r\n return print(message)", "def print_message(message):\n print(message)", "def display_message(message):\n \n print '%s %s' % (timestamp(), message)", "def _box_print(msg):\n max_len = max(78, len(msg) + 10)\n print('{}'.format('-' * (max_len + 2)))\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns users, who liked a given object.
def get_users_who_liked_object(*, obj: 'Model'): ct = ContentType.objects.get_for_model(obj) return ( User.objects .filter( likes__content_type=ct, likes__object_id=obj.pk ) )
[ "def get_all_likes(obj):\n\t\tobj_type = ContentType.objects.get_for_model(obj)\n\t\treturn User.objects.filter(\n\t\t\tlikes_content_type=obj_type, likes_object_id=obj.id)", "def is_liked(obj, user) ->bool:\n\tif not user.is_authenticated:\n\t\treturn False\n\tobj_type = ContentType.objects.get_for_model(obj):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the square around the face that should be used to crop the image.
def get_face_square(left, top, width, height, scale_factor): right = left+width bottom = top+height center_x = (left + right)/2 center_y = (top + bottom)/2 # Make the size of the square slightly bigger than in the ROI data square_len = scale_factor*max(width, height) half_len = square_len/2 new_left...
[ "def get_face_area(face):\n return (face.left() - face.right()) * (face.bottom() - face.top())", "def crop_to_face(self):\n original = self.images['original']\n original.generate_borders(sigma=self.sigma)\n contours, hierarchy = cv2.findContours(\n original.borders,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes all the facial landmarks of every frame in the given dataset.
def extract_all_face_landmarks(x_data, verbose=True): # Initialize dlib's face detector and create the facial landmark predictor detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor(face_predictor_path) x_int = np.uint8(np.multiply(x_data, 256)) face_landmarks = [] for i, frame i...
[ "def findFacialLandmarks(self, image):\n \n #find the face\n faceBox = self.faceDetector.detectFace(image)\n \n if faceBox != None:\n # Get the landmarks/parts for the face in box d.\n #find the landmarks\n \n points = self.predictor(image, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Normalize facial landmarks by subtracting the coordinates corresponding to the nose, and dividing by the standard deviation.
def normalize_face_landmarks(face_landmarks): face_landmarks_norm = np.zeros(face_landmarks.shape) for (i, lm) in enumerate(face_landmarks): face_landmarks_norm[i] = lm - lm[nose_center_idx] std_x = np.std(face_landmarks_norm[:,:,0].reshape((-1,))) std_y = np.std(face_landmarks_norm[:,:,1].reshape((-...
[ "def _normalize_pose_landmarks(self, landmarks):\n landmarks = np.copy(landmarks)\n\n # Normalize translation.\n pose_center = self._get_pose_center(landmarks)\n landmarks -= pose_center\n\n # Normalize scale.\n pose_size = self._get_pose_size(landmarks, self._torso_size_multiplier)\n landmarks...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the weigths of first convolutional layer of VGGFace (conv_1_1).
def get_conv_1_1_weights(vgg_weights_path): temp_mod = Sequential() temp_mod.add(ZeroPadding2D((1,1),input_shape=(224, 224, 3))) temp_mod.add(Convolution2D(64, (3, 3), activation='relu', name='conv1_1')) temp_mod.load_weights(vgg_weights_path, by_name=True) conv1_1_weigths = temp_mod.get_layer('conv1_1').get_...
[ "def _get_conv_weight(model):\n layer_name = 'conv2d_1'\n weights = model.get_layer(layer_name).get_weights()\n # weights[0] --- kernel weights\n # weights[1] --- kernel biases\n weights = np.asarray(weights[0])\n mean_weights = np.mean(weights, axis=0)\n mean_weights = np.reshape(mean_weights,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the bottom part of the VGG16 TCNN.
def create_tcnn_bottom(vgg_weights_path, conv1_1_weigths): # Create inputs for the 5 frames input_shape=(224, 224, 3) frame1 = Input(shape=input_shape) frame2 = Input(shape=input_shape) frame3 = Input(shape=input_shape) frame4 = Input(shape=input_shape) frame5 = Input(shape=input_shape) # Convolution...
[ "def vgg16(self):\n\n base_model = VGG16(weights=self.weights, include_top=self.include_top,\n pooling=self.pooling)\n x = base_model.layers[-1]\n out = Dense(self.num_classes, activation=self.activation, name='output', use_bias=True)(\n x.output)\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the weights of first convolutional layer of Squeezenet (conv_1).
def get_conv1_weights(squeezenet_weights_path): temp_mod = Sequential() temp_mod.add(Convolution2D(64, (3, 3), strides=(2, 2), padding='valid', name='conv1',input_shape=(227, 227, 3))) temp_mod.load_weights(squeezenet_weights_path, by_name=True) conv1_weights = temp_mod.get_layer('conv1').get_weights() return...
[ "def get_conv_1_1_weights(vgg_weights_path):\r\n\ttemp_mod = Sequential()\r\n\ttemp_mod.add(ZeroPadding2D((1,1),input_shape=(224, 224, 3)))\r\n\ttemp_mod.add(Convolution2D(64, (3, 3), activation='relu', name='conv1_1'))\r\n\ttemp_mod.load_weights(vgg_weights_path, by_name=True)\r\n\tconv1_1_weigths = temp_mod.get_l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the bottom part of the Squeezenet TCNN.
def create_squeezenet_tcnn_bottom(squeezenet_weights_path, conv1_weights): # Create inputs for the 5 frames input_shape=(227, 227, 3) frame1 = Input(shape=input_shape, name='frame1') frame2 = Input(shape=input_shape, name='frame2') frame3 = Input(shape=input_shape, name='frame3') frame4 = Input(shape=input_...
[ "def make_bottom_text( self ):\n return None", "def _IDTtopbottombox(self):\n if self.wbox==0.0:\n wr=self.ft_mult*2*self.Np*(self.a+self.g) +self.ft_mult*self.a+self.ft_mult*2*self.ef*(self.a+self.g)+(self.ft_mult-1)*self.g\n else:\n wr=self.wbox\n self.C(self.xo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of requested prefixes using show_available, show_assigned filters. If available prefixes are requested, create fake Prefix objects for all unallocated space within a prefix.
def add_requested_prefixes(parent, prefix_list, show_available=True, show_assigned=True): child_prefixes = [] # Add available prefixes to the table if requested if prefix_list and show_available: # Find all unallocated space, add fake Prefix objects to child_prefixes. available_prefixes = ...
[ "async def process_prefix_list(\n guild: disnake.Guild,\n ctx: commands.Context = None,\n inter: AppCmdInter = None,\n allowed_mentions=None,\n):\n await create_guild_model(guild)\n guild = await Guild.get(guild.id)\n msg = f\"The following are the custom prefixes for {guild.name}:\\n\" + \", \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Annotate ranges of available IP addresses within a given prefix. If is_pool is True, the first and last IP will be considered usable (regardless of mask length).
def add_available_ipaddresses(prefix, ipaddress_list, is_pool=False): output = [] prev_ip = None # Ignore the network and broadcast addresses for non-pool IPv4 prefixes larger than /31. if prefix.version == 4 and prefix.prefixlen < 31 and not is_pool: first_ip_in_prefix = netaddr.IPAddress(pre...
[ "def ip_range(input_string):\r\n octets = input_string.split('.')\r\n chunks = [list(map(int, octet.split('-'))) for octet in octets]\r\n ranges = [range(c[0], c[1] + 1) if len(list(c)) == 2 else c for c in chunks]\r\n addrs = ['.'.join(list(map(str, address))) for address in itertools.product(*ranges)]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Rebuild the prefix hierarchy for all prefixes in the specified VRF (or global table).
def rebuild_prefixes(vrf): def contains(parent, child): return child in parent and child != parent def push_to_stack(prefix): # Increment child count on parent nodes for n in stack: n['children'] += 1 stack.append({ 'pk': [prefix['pk']], 'pref...
[ "def rebase(self, vrf, new_prefix):\n b = IP.prefix(self.prefix)\n nb = IP.prefix(new_prefix)\n # Rebase prefix and all nested prefixes\n # Parents are left untouched\n for p in Prefix.objects.filter(vrf=self.vrf, afi=self.afi).extra(\n where=[\"prefix <<= %s\"], params...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is to view product delete form
def delete_product(request, id): return render(request, "core/delete_product.html", { "object": Product.objects.get(id=id) })
[ "def __delete_product(self):\n id = input(\"Barecode of the product you want to delete: \")\n self.__product_service.delete_product(id)\n print(\"Product deleted successfully!\")", "def product_to_delete():\n if request.method == \"POST\":\n product = request.form[\"product\"]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is to view the list of categories
def category(request): return render(request, "core/category_list.html", { "category_list": Category.objects.all() })
[ "def list_categories(self):\n raise NotImplementedError()", "def showCategories():\n\n # Retrieve all the categories from the database\n categories = database_session.query(Category).order_by(asc(Category.name))\n\n # Render the homepage template containing all the categories\n return render_te...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get user details from users_file_name. Create users if they doesn't exist.
def create_users (users_file_name = 'lookup.csv'): users_file = open (users_file_name, 'r') for line in users_file: # user_fields = line.split () user_data_list = parse_user_info_list (line.split (',')) print user_data_list create_user (*user_data_list) users_file.close () ...
[ "def create_users (users_file_name = 'users.txt'):\n users_file = open (users_file_name, 'r')\n for line in users_file:\n # user_fields = line.split ()\n user_data_list = parse_user_info_list (line.split ())\n create_user (*user_data_list)\n users_file.close ()\n print 'All users cr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return True if the given distro is a debian.
def is_debian(distro): name = distro.lower() return name in debain
[ "def debian_exist(self):\n if os.path.isdir(self._repo_dir):\n for filename in os.listdir(self._repo_dir):\n if filename == \"debian\":\n return True\n return False", "def is_redhat(distro):\n name = distro.lower()\n return name in red_hat", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return True if the given distro is a redhat linux.
def is_redhat(distro): name = distro.lower() return name in red_hat
[ "def is_linux():\n return guess_os() == 'linux'", "def is_linux():\n if os.name == 'posix':\n return True\n return False", "def osname_is_linux():\n return (\"Linux\" == g_osname)", "def os_is_linux():\n return platform.system() == \"Linux\" and \"raspberrypi\" not in platform.uname()", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Auto detect os flavor.
def auto_detect_os(distro): if is_debian(distro): return "Debian" if is_redhat(distro): return "Redhat" return "Unknown"
[ "def get_flavor():\n flavors = {\n 'cygwin': 'win',\n 'win32': 'win',\n 'darwin': 'mac',\n 'sunos5': 'solaris',\n 'freebsd7': 'freebsd',\n 'freebsd8': 'freebsd',\n }\n return flavors.get(sys.platform, 'linux')", "def GetFlavor(params):\n flavors = {\n 'win32': 'win',\n 'darwin': 'mac',...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Scans a given directory
def scan_dir(self, directory="."): for root, dirs, files in os.walk(directory, topdown=False): for name in files: for filetype in self.allowed_file_types: if name.split(".")[-1] == filetype: self.song_list.append(os.path.join(root, name))
[ "def scan_directory(self, directory):\n for dirpath, dirnames, filenames in os.walk(directory):\n self.filter_subdirs(dirnames)\n\n for filename in filenames:\n if filename.endswith(('.py', '.pyw')):\n filepath = os.path.join(dirpath, filename)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of all songs
def get_song_list(self): return self.song_list
[ "def get_all_songs():\r\n return [Song.song_json(song) for song in Song.query.all()]", "def get_all_songs(self, artist: Artist) -> list:\n return [song for song in artist.songs]", "def get_songs(db: Session = Depends(get_db)):\n songs = crud.get_songs(db)\n return [song.title for song in son...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a random song form the library
def get_random_song(self): return random.choice(self.song_list)
[ "def get_random_song(self):\n songs = self.get_all_song_names()\n song_name = songs[random.randrange(len(songs))]\n hits = self.get_song_data(song_name=song_name)\n if len(hits) == 0:\n # Just return Oops! I did it again by Britney\n return 'spotify:track:6naxalmIoL...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of all allowed file types
def get_allowed_file_types(self): return self.allowed_file_types
[ "def file_types(self) -> Optional[List[str]]:\n return pulumi.get(self, \"file_types\")", "def get_allowed_file_extensions():\n return get_allowed_file_extensions.allowed_file_extensions", "def listTypes(cls):\n typeList = os.listdir(cls._allConfigs)\n typeList = set(typeList) - set([\"....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Construct a full path to a TFRecord file to be stored in the data_directory. Will also ensure the data directory exists
def _data_path(data_directory: str, name: str) -> str: if not os.path.isdir(data_directory): os.makedirs(data_directory) return os.path.join(data_directory, '{}.tfrecords'.format(name))
[ "def form_tf_record_cache_path(self, dataset):\n total_samples = self.config[\"niters\"] * self.config[\"itersize\"]\n if self.tpu:\n return \"{0}/capreolus_tfrecords/{1}_{2}\".format(self.config[\"storage\"], dataset.get_hash(), total_samples)\n else:\n base_path = self.g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert the TF MNIST Dataset to TFRecord formats
def convert_to_tf_record(_): mnist = input_data.read_data_sets( "/tmp/tensorflow/mnist/input_data", reshape=False ) convert_to(mnist.validation, 'validation', FLAGS.data_directory) convert_to(mnist.train, 'train', FLAGS.data_directory, num_shards=10) convert_to(mnist.test, 'test', ...
[ "def convert_data_tfrecords(all_data, all_labels, list_num_labels, data_directory):\n\n # Loop through [train, valid, test] for all number of labeled images\n for num_labels in list_num_labels:\n for d in range(len(all_data)):\n\n # Initialize\n data = all_data[d]\n lab...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compare winds between two different runs, looking at vertically binned averages first row shows model run 1 (and figures are saved under this run) second row shows model run 2 final row(s) show density or cumulative density from averaged metric
def compare_winds(mr1='waroona_run2', mr2='waroona_run2uc', hour=datetime(2016,1,5,15), extent=None, subsubdir=None): extentname = mr1.split('_')[0] if extent is None: extent = constants.extents[extentname] cubes1 = fio.read_model_run(mr1,...
[ "def plot_runmean_comparison(basin_id, permodel_dict, window_yrs=30, cmaps=('Blues', 'Wistia'), show_labels=True, show_plot=True, save_plot=False):\n window_size = 12 * window_yrs # size of window given monthly data\n basin_runavg_w = [np.convolve(permodel_dict[m]['WRunoff'][basin_id], np.ones((window_size,))...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
examine some transects side by side for two runs
def compare_transects(run1, run2, hours=[12,], extent=None, ztop=1000, columntitles=['coupled','uncoupled'], subsubdir=None, third_transect=False): ltoffset=fio.run_info[run1]['UTC_offset'] if extent is None: extent = constants.extents[ru...
[ "def target_intersection(self, runid):\n\n def targeting(shuffledict, seg_copy_array, cell_name):\n bedstring = \"\"\n seg_counts_dict = defaultdict(int)\n breakpoint_counts = 0\n sum_counts = 0\n for cell in shuffledict:\n with suppress(I...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints the 3 most popular articles for the assignment
def print_popular_articles(): print("3 most popular articles\n") popularity_data = get_query_results(POPULARITY_QUERY) article_row_format = '"{}" — {} views' for title, views in popularity_data: print(article_row_format.format(title, views))
[ "def most_popular_articles():\n\n connection, cursor = db_connect()\n cursor.execute(POPULAR_ARTICLES)\n result = cursor.fetchall()\n db_close(connection)\n print \"What are the most popular three articles of all time?\"\n for item in result:\n print '\"' + item[0] + '\"--' + str(item[1]) +...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function is called periodically when disabled.
def disabledPeriodic(self): self.putData()
[ "def disabledPeriodic(self):", "def disabled(self):\n while self.isDisabled():\n wpilib.Timer.delay(0.01)", "def _disable(self):\n self.enabled = False", "def on_disable(self) -> None:\n if HANDLE_TICK in self.data:\n handle = self.data.pop(HANDLE_TICK)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a list of lists of training sequences for random walks.
def take_a_walk(num_steps, start_step, seq_per_set, num_sets, seed=-1): # Set the random seed, if supplied if seed > 0: np.random.seed(seed) # Preallocate the entire training data list of lists of NumPy arrays training = num_sets * [seq_per_set * [None]] # Iterate to build the training data ...
[ "def get_training_seqs(self):\r\n # Rdp requires unique sequence IDs without whitespace. Can't\r\n # trust user IDs to not have whitespace, so we replace all\r\n # whitespace with an underscore. Classification may fail if\r\n # the replacement method generates a name collision.\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Encrypt each of the current initialization vector (iv), the nodeid, and the sensor_data using (staticiv, ivkey) for iv and (iv, datakey) for nodeid and sensor_data
def encrypt(self, sensor_data): # set encryption parameters encryption1 = aes(self.ivkey, 2, self.staticiv) encryption2 = aes(self.datakey, 2, self.iv) # encrypt data self.encrypted_data = encryption2.encrypt(sensor_data) self.encrypted_iv = encryption1.e...
[ "def encrypt_data ( aes_key, data ) :\n salt = Crypto.Random.new( ).read( Crypto.Cipher.AES.block_size )\n cipher = Crypto.Cipher.AES.new( aes_key, Crypto.Cipher.AES.MODE_CFB, salt )\n encrypted_data = cipher.encrypt( data )\n\n return encode_data( salt + encrypted_data )", "def encrypt(self, input, iv):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate HMAC by using passphrase, and combination of encrypted iv, encrypted nodeid, encrypted data, received sessionID.
def sign_hmac(self, sessionID): self.new_hmac = hmac.new(bytes(self.passphrase), self.encrypted_iv, hashlib.sha224) self.new_hmac.update(self.encrypted_nodeid) self.new_hmac.update(self.encrypted_data) self.new_hmac.update(sessionID) return self.new_hmac
[ "def get_hmac(bot, data):\n mac = hmac.new(generate_secret_key(bot), digestmod=DIGEST)\n mac.update(data)\n return mac.digest()", "def make_hmac(self, msg):\r\n return hmac.new(self.hmacKey, msg, sha256).digest()", "def _hmac_create(self, password, shared_key):\n hmac_value = base64.b64en...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prepare the message for MQTT transfer using all of encrypted iv, encrypted nodeid, encrypted data, HMAC. Create the message in JSON format.
def send_mqtt(self, hmac_signed): message = b'{"eiv": "' + ubinascii.hexlify(self.encrypted_iv) + b'", "enid": "' + ubinascii.hexlify(self.encrypted_nodeid) + \ b'", "ed": "' + ubinascii.hexlify(self.encrypted_data) + b'", "hmac": "' + ubinascii.hexlify(hmac_signed.digest()) + b'"}' ...
[ "def construct_message(self):\n data = {}\n data['message'] = self.username + '-> ' + message_to_send\n data[constants.PACKET_NONCE_1_KEY] = utility_functions.random_number_generator(constants.NONCE_BITS)\n data[constants.PACKET_NONCE_2_KEY] = utility_functions.random_number_generator(co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Authenticates the received MQTT message. Generate HMAC using passphrase, sessionID, RECEIVED encrypted iv, encrypted nodeid, encrypted data and compare with received hmac inside payload to authenticate.
def verify_hmac(self, payload): new_hmac = hmac.new(bytes(self.passphrase), b'%s'%(payload['eiv']) , hashlib.sha224) new_hmac.update(b'%s'%(payload['enid'])) new_hmac.update(b'%s'%(payload['ed'])) new_hmac.update(self.sessionID) #print(new_hmac.digest()) #pri...
[ "def send_mqtt(self, hmac_signed):\r\n message = b'{\"eiv\": \"' + ubinascii.hexlify(self.encrypted_iv) + b'\", \"enid\": \"' + ubinascii.hexlify(self.encrypted_nodeid) + \\\r\n b'\", \"ed\": \"' + ubinascii.hexlify(self.encrypted_data) + b'\", \"hmac\": \"' + ubinascii.hexlify(hmac_signed.d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function reads a positive real number a and integer n. Then it calls power2() function with the read parameters and prints its result.
def exponentiation(): print("Problem: Exponentiation") a = float(input()) n = int(input()) result = power_v2(a, n) print(result)
[ "def power(num, n=2):\n new_value = num ** n\n return (new_value)", "def power(x, n):\n if n == 0:\n return 1\n result = power(x, math.floor(n / 2))\n if n % 2 > 0:\n return x * result * result\n else:\n return result * result", "def _pow_(self, n):\n assert n >...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deprecated; use 'sitemaps' instead. Returns the sitemap URL present in the robots.txt, if any. Defaults to None. Read only.
def sitemap(self): _raise_error(DeprecationWarning, "The sitemap property is deprecated. Use 'sitemaps' instead.")
[ "def get_sitemap_url(self) -> str:\n return self.sitemap_url", "def _get_sitemap(self, url, robot_data):\r\n\r\n # Check for sitemap uri in robot_data\r\n robot_dict = {}\r\n if robot_data:\r\n robot = robot_data.split('\\n')\r\n for elem in robot:\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
True if the user agent is permitted to visit the URL. The syntax parameter can be GYM2008 (the default) or MK1996 for strict adherence to the traditional standard.
def is_allowed(self, user_agent, url, syntax=GYM2008): if PY_MAJOR_VERSION < 3: # The robot rules are stored internally as Unicode. The two lines # below ensure that the parameters passed to this function are # also Unicode. If those lines were not present and the c...
[ "def allowed(cls, url, user_agent=\"python-requests\", request_kwargs=None):\n if not request_kwargs:\n request_kwargs = {}\n robots_url = cls.get_robots_url(url)\n robots = cls.fetch_robots(robots_url, **request_kwargs)\n return robots.allowed(url, user_agent)", "def _check...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a float representing the crawl delay specified for this user agent, or None if the crawl delay was unspecified or not a float.
def get_crawl_delay(self, user_agent): # See is_allowed() comment about the explicit unicode conversion. if (PY_MAJOR_VERSION < 3) and (not isinstance(user_agent, unicode)): user_agent = user_agent.decode() for ruleset in self.__rulesets: if ruleset.does_user_agent_m...
[ "def get_crawl_delay(self, useragent=\"*\"):\n crawl_delay = None\n try:\n crawl_delay = self.rp.crawl_delay(useragent=useragent)\n logger.info(\"Crawl delay is %s\" % crawl_delay)\n except Exception as e:\n logger.error(\"get_crawl_delay:\\n%s\" % e)\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses the passed string as a set of robots.txt rules.
def parse(self, s): self._sitemaps = [ ] self.__rulesets = [ ] if (PY_MAJOR_VERSION > 2) and (isinstance(s, bytes) or isinstance(s, bytearray)) or \ (PY_MAJOR_VERSION == 2) and (not isinstance(s, unicode)): s = s.decode("iso-8859-1") # Nor...
[ "def parse_robots(self):\n self.task.update_robots_flag('start')\n robotsUrl = f\"{self.domain}\"+ \"robots.txt\"\n try:\n response = request.request(robotsUrl)\n if not response:\n return\n lines = response.text.splitlines() \n for lin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This tests function return_only_filenames_under_ext(filenames, ppath, externsion) that receives a list of files and return those that have the extension given and are files
def test_return_only_filenames_under_ext(): hardcodedpath = "/home/dados/VideoAudio/Yt videos/Soc Sams vi/Lang Sams vi/Chinese Sams vi/" \ "Harbin Mandarin yu/BMC 19v 12' 2018 4h Beginning Mandarin Chinese Lessons yu Harbin ytpl/a" path_in_arg_if_any = None for arg in sys.argv: if arg.startswith('-ppath...
[ "def filter_by_extensions(files: tp.Sequence[pathlib.Path],\n extensions: tp.List[str]) -> tp.List[pathlib.Path]:\n return [file for file in files if \"\".join(file.suffixes) in extensions]", "def filter_files_by_extension(\n files: list ,\n extensions: list\n):\n filtered_file...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads the feature flag states into the internal cache.
def load(self): all_ = self._fetch_features() features = {f.name: f for f in all_} self._cache = {n: self._state(features.get(n)) for n in FEATURES.keys()}
[ "def load_features(self, features):\n pass\n # self.features = features", "def get_cached_features(self):\n\t\tfeatures = []\n\t\tfeature_pattern = \"%s_features_\" % self.cache_prefix\n\t\tfor cache_name in sorted(self.cache.keys()):\n\t\t\tif re.search(feature_pattern, cache_name):\n\t\t\t\tcache_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine if the named feature is enabled for the current request. If the feature has no override in the database, it will default to False. Features must be documented, and an UnknownFeatureError will be thrown if an undocumented feature is interrogated. When the internal cache is empty, it will automatically load the...
def enabled(self, name): if name not in FEATURES: raise UnknownFeatureError( '{0} is not a valid feature name'.format(name)) if not self._cache: self.load() return self._cache[name]
[ "def IsEnabled(feature_name, default=False):\n try:\n\n return feature_name in __builtin__._APPENGINE_FEATURE_FLAGS\n except AttributeError:\n return default", "def is_enabled(self, feature_name):\n\n cache_key = self.FEATURE_CACHE_KEY.format(feature_name=feature_name)\n\n # Try to fetch the...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove old/unknown data from the feature table. When a feature flag is removed from the codebase, it will remain in the database. This could potentially cause very surprising issues in the event that a feature flag with the same name (but a different meaning) is added at some point in the future. This function removes ...
def remove_old_flags(): # N.B. We remove only those features we know absolutely nothing about, # which means that FEATURES_PENDING_REMOVAL are left alone. known = set(FEATURES) | set(FEATURES_PENDING_REMOVAL) unknown_flags = Feature.query.filter(sa.not_(Feature.name.in_(known))) count = unknown_flag...
[ "def delete_features(self):\n self.data = self.data.drop('Utilities', axis=1)\n self.data = self.data.drop('Condition2', axis=1)\n self.data = self.data.drop('RoofMatl', axis=1)\n self.data = self.data.drop('LowQualFinSF', axis=1)\n self.data = self.data.drop('MiscFeature', axis=1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove old feature flags from the database on startup.
def remove_old_flags_on_boot(event): # Skip this if we're in a script, not actual app startup. See the comment # in h.script:main for an explanation. if 'H_SCRIPT' in os.environ: return remove_old_flags() transaction.commit()
[ "def remove_old_flags():\n # N.B. We remove only those features we know absolutely nothing about,\n # which means that FEATURES_PENDING_REMOVAL are left alone.\n known = set(FEATURES) | set(FEATURES_PENDING_REMOVAL)\n unknown_flags = Feature.query.filter(sa.not_(Feature.name.in_(known)))\n count = un...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Should be able to properly create an entry within a model form
def test_form_create(self): create = { 'title': 'Last Post (Final)', 'content': '### Goodbye!', 'is_published': False, } form = self.form_cls(create) print(form.errors) form.save() actual = models.Entry.objects.get(slug='last-post-fi...
[ "def new_entry():\r\n form = forms.NewEntryForm()\r\n if form.validate_on_submit():\r\n entry = models.Journal.create(\r\n title = form.title.data,\r\n date = datetime.datetime.strptime(form.date.data, \r\n '%d/%m/%Y'),\r\n t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get vehicle annual data by calendar year.
def get_vehicle_annual_data_by_calendar_year(self, calendar_year): return [v for v in self._dict.values() if v['calendar_year'] == calendar_year]
[ "def get_adjusted_vehicle_annual_data_by_calendar_year(self, calendar_year):\n return [v for v in self.adjusted_vads.values() if v['calendar_year'] == calendar_year]", "def get_year(data):", "def calc_base_year_data(base_year_vehicles_df):\n pass", "def YEAR(data):\n A=data.shape[0]\n annd...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get adjusted vehicle annual data by calendar year.
def get_adjusted_vehicle_annual_data_by_calendar_year(self, calendar_year): return [v for v in self.adjusted_vads.values() if v['calendar_year'] == calendar_year]
[ "def get_vehicle_annual_data_by_calendar_year(self, calendar_year):\n return [v for v in self._dict.values() if v['calendar_year'] == calendar_year]", "def calc_base_year_data(base_year_vehicles_df):\n pass", "def YEAR(data):\n A=data.shape[0]\n anndata0=nanarray(data.shape)\n cnt=-1\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get vehicle annual data by vehicle id.
def get_vehicle_annual_data_by_vehicle_id(self, calendar_year, vehicle_id, *attribute_names): attribute_list = list() for attribute_name in attribute_names: attribute_list.append(self._dict[(vehicle_id, calendar_year)][attribute_name]) if len(attribute_list) == 1: return ...
[ "def get(self, vehicle_id=None):\n raise NotImplementedError()", "def get(self, vehicle_id):\n vehicle = VehicleServices(public_id=vehicle_id).get_an_item()\n if not vehicle:\n api.abort(404)\n else:\n return vehicle", "def get_vehicle(self, v_id):\r\n \r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
grab the file at and make a local copy at If filename is none, the basename of the url is used. urlgrab returns the filename of the local file, which may be different from the passedin filename if copy_local == 0.
def urlgrab(self, url, filename=None, **kwargs): opts = self.opts.derive(**kwargs) (url,parts) = opts.urlparser.parse(url, opts) (scheme, host, path, parm, query, frag) = parts if 'file:///' in url: return self._orig_urlgrab(url, filename, **kwargs) fsize = ...
[ "def urlgrab(self, url, filename=None, **kwargs):\r\n opts = self.opts.derive(**kwargs)\r\n (url,parts) = opts.urlparser.parse(url, opts) \r\n (scheme, host, path, parm, query, frag) = parts\r\n if filename is None:\r\n filename = os.path.basename( urllib.unquote(path) )\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }