query
stringlengths 9
9.05k
| document
stringlengths 10
222k
| negatives
listlengths 19
20
| metadata
dict |
---|---|---|---|
Return all image assets associated with a facet and the forms to associate more.
|
def facet_image_assets(self):
self.object = self.get_object()
images = self.object.get_facet_images()
org_images = self.object.organization.get_org_image_library()
uploadform = ImageAssetForm()
return {'images': images, 'org_images': org_images, 'uploadform': uploadform}
|
[
"def facet_document_assets(self):\r\n\r\n self.object = self.get_object()\r\n documents = self.object.get_facet_documents()\r\n org_documents = self.object.organization.get_org_document_library()\r\n uploadform = DocumentAssetForm()\r\n return {'documents': documents, 'org_documents': org_documents, 'uploadform': uploadform}",
"def facet_video_assets(self):\r\n\r\n self.object = self.get_object()\r\n videos = self.object.get_facet_video()\r\n org_videos = self.object.organization.get_org_video_library()\r\n uploadform = VideoAssetForm()\r\n return {'videos': videos, 'org_videos': org_videos, 'uploadform': uploadform}",
"def images(self):\n context = aq_inner(self.context)\n results = []\n for field in self.fields():\n full = context.getField(field).tag(context)\n item = {\n 'full-image': '{0} id=\"cropbox\" {1}'.format(full[:4], full[5:]),\n 'select': self.select(),\n 'field': field,\n 'previews': self.previews(field),\n }\n results.append(item)\n return results",
"def facet_audio_assets(self):\r\n\r\n self.object = self.get_object()\r\n audio = self.object.get_facet_audio()\r\n org_audio = self.object.organization.get_org_audio_library()\r\n uploadform = AudioAssetForm()\r\n return {'audio': audio, 'org_audio': org_audio, 'uploadform': uploadform}",
"def get_images(self):\n pass",
"def get_image_srcs(page, templ_vars):\n if 'type' in page.meta and page.meta['type'] == 'album':\n album = page.meta\n\n # get paths of all of the images in the album\n srcs = []\n\n # get absolute paths of images in album for each file type\n for file_type in FILE_TYPES:\n imgs = glob.glob(GALLERY_DIR + album['slug'] + '/*.' + file_type)\n\n for img in imgs:\n img_rel_path = REL_GALLERY_DIR + album['slug'] + '/' + img.split('/')[-1]\n srcs.append(img_rel_path)\n\n # split full srcs and thumb srcs from srcs into two lists\n full_srcs = []\n thumb_srcs = []\n for src in srcs:\n if src.split('/')[-1].startswith(THUMB_PREFIX):\n thumb_srcs.append(src)\n else:\n full_srcs.append(src)\n\n # bind to template via json\n templ_vars['site']['srcs'] = simplejson.dumps(sorted(full_srcs))\n templ_vars['site']['thumb_srcs'] = simplejson.dumps(sorted(thumb_srcs))",
"def get_images(self):\n return [env.render(mode='rgb_array') for env in self.list_env]",
"def extract_images():\r\n model_list = []\r\n for p in prod_col.find():\r\n model_list.append(p['model'])\r\n for model in model_list:\r\n fill_images_one(model)",
"def get_annotation_related_images(self):\n return self.annotation_related_images",
"def image_scatter_facets(im: Image, facets=1, overlap=0, taper=None) -> List[Image]:\n return [flat_facet for flat_facet in image_raster_iter(im, facets=facets, overlap=overlap,\n taper=taper)]",
"def facet(self):\n facet_values = self.get_feature('facet')\n return facet_values",
"def get_assets(self) -> list[Asset]:",
"def get_images(self, analyses):\n raise NotImplementedError(\"Getting images is not yet supported.\")",
"def plot_facets(self):\r\n for i in self.sides:\r\n i.regularise_grid()\r\n\r\n fig = plt.figure()\r\n for i, facet in enumerate(self.sides):\r\n print(i)\r\n fig.add_subplot(16, 1, i + 1)\r\n plt.imshow(facet.regular_grid[2], cmap='gray')\r\n plt.title(str(i)), plt.xticks([]), plt.yticks([])",
"def getOGTagsImage(self):",
"def image_gather_facets(image_list: List[Image], im: Image, facets=1, overlap=0, taper=None,\n return_flat=False):\n out = create_empty_image_like(im)\n if overlap > 0:\n flat = create_empty_image_like(im)\n flat.data[...] = 1.0\n flats = [f for f in image_raster_iter(flat, facets=facets, overlap=overlap, taper=taper, make_flat=True)]\n \n sum_flats = create_empty_image_like(im)\n \n if return_flat:\n i = 0\n for sum_flat_facet in image_raster_iter(sum_flats, facets=facets, overlap=overlap, taper=taper):\n sum_flat_facet.data[...] += flats[i].data[...]\n i += 1\n \n return sum_flats\n else:\n i = 0\n for out_facet, sum_flat_facet in zip(image_raster_iter(out, facets=facets, overlap=overlap, taper=taper),\n image_raster_iter(sum_flats, facets=facets, overlap=overlap,\n taper=taper)):\n out_facet.data[...] += flats[i].data * image_list[i].data[...]\n sum_flat_facet.data[...] += flats[i].data[...]\n i += 1\n \n out.data[sum_flats.data > 0.0] /= sum_flats.data[sum_flats.data > 0.0]\n out.data[sum_flats.data <= 0.0] = 0.0\n \n return out\n else:\n flat = create_empty_image_like(im)\n flat.data[...] = 1.0\n \n if return_flat:\n return flat\n else:\n for i, facet in enumerate(image_raster_iter(out, facets=facets, overlap=overlap, taper=taper)):\n facet.data[...] += image_list[i].data[...]\n \n return out",
"def index_subset(subset):\n images = []\n print('Indexing {}...'.format(subset))\n # Quick first pass to find total for tqdm bar\n subset_len = 0\n for root, folders, files in os.walk(\n DATA_PATH + '/Omniglot/images_{}/'.format(subset)):\n subset_len += len([f for f in files if f.endswith('.png')])\n\n progress_bar = tqdm(total=subset_len)\n for root, folders, files in os.walk(\n DATA_PATH + '/Omniglot/images_{}/'.format(subset)):\n if len(files) == 0:\n continue\n\n alphabet = root.split('/')[-2]\n class_name = '{}.{}'.format(alphabet, root.split('/')[-1])\n\n for f in files:\n progress_bar.update(1)\n images.append({\n 'subset': subset,\n 'alphabet': alphabet,\n 'class_name': class_name,\n 'filepath': os.path.join(root, f)\n })\n\n progress_bar.close()\n return images",
"def get_analyses_by_images(self):\n raise NotImplementedError(\"Getting analyses by images is not yet supported.\")",
"def getFaces(faceType, nodeTags):"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Return all document assets associated with a facet and the forms to associate more.
|
def facet_document_assets(self):
self.object = self.get_object()
documents = self.object.get_facet_documents()
org_documents = self.object.organization.get_org_document_library()
uploadform = DocumentAssetForm()
return {'documents': documents, 'org_documents': org_documents, 'uploadform': uploadform}
|
[
"def facet_image_assets(self):\r\n\r\n self.object = self.get_object()\r\n images = self.object.get_facet_images()\r\n org_images = self.object.organization.get_org_image_library()\r\n uploadform = ImageAssetForm()\r\n return {'images': images, 'org_images': org_images, 'uploadform': uploadform}",
"def facet_video_assets(self):\r\n\r\n self.object = self.get_object()\r\n videos = self.object.get_facet_video()\r\n org_videos = self.object.organization.get_org_video_library()\r\n uploadform = VideoAssetForm()\r\n return {'videos': videos, 'org_videos': org_videos, 'uploadform': uploadform}",
"def facet_audio_assets(self):\r\n\r\n self.object = self.get_object()\r\n audio = self.object.get_facet_audio()\r\n org_audio = self.object.organization.get_org_audio_library()\r\n uploadform = AudioAssetForm()\r\n return {'audio': audio, 'org_audio': org_audio, 'uploadform': uploadform}",
"def findFacets(self):\n facets = []\n content = self.soup.find(id='page-container')\n text = content.find(id='js-article-text')\n for facet in text.find('ul', {\"class\":\"mol-bullets-with-font\"}):\n facet.text.replace(\"\\xa0\", \" \")\n facets.append(facet.text)\n return facets",
"def facet(self):\n facet_values = self.get_feature('facet')\n return facet_values",
"def set_facets(facets, used_filters, query, principals):\n for field, _ in facets:\n if field == 'type':\n query_field = '_type'\n elif field.startswith('audit'):\n query_field = field\n else:\n query_field = 'embedded.' + field + '.raw'\n agg_name = field.replace('.', '-')\n\n terms = []\n # Adding facets based on filters\n for q_field, q_terms in used_filters.items():\n if q_field != field and q_field.startswith('audit'):\n terms.append({'terms': {q_field: q_terms}})\n elif q_field != field and not q_field.endswith('!'):\n terms.append({'terms': {'embedded.' + q_field + '.raw': q_terms}})\n elif q_field != field and q_field.endswith('!'):\n terms.append({'not': {'terms': {'embedded.' + q_field[:-1] + '.raw': q_terms}}})\n\n terms.append(\n {'terms': {'principals_allowed.view': principals}}\n )\n query['aggs'][agg_name] = {\n 'aggs': {\n agg_name: {\n 'terms': {\n 'field': query_field,\n 'min_doc_count': 0,\n 'size': 100\n }\n }\n },\n 'filter': {\n 'bool': {\n 'must': terms,\n },\n },\n }",
"def _tag_facets(request, parsed_query=None):\n return (parsed_query or _parsed_query(request)).getall('tag')",
"def zip_facet_fields(self): \n if self.facets.has_key('facet_fields'):\n for field,counts in self.facets['facet_fields'].items():\n zipped = zip(counts[0::2], counts[1::2])\n self.facets['facet_fields'][field] = zipped",
"def facets(self, *args, **kwargs) -> Any:\n pass",
"def publication_facet( self ) :\r\n return self.get_facet( \"publication_id, author\" )",
"def pre_facet_sqs(self):\n sqs = SearchQuerySet()\n\n if self.query:\n sqs = sqs.filter(\n SQ(content=AutoQuery(self.query)) | # Search `text` document\n SQ(get_title=AutoQuery(self.query)) | # boosted field\n SQ(boosted_search_terms=AutoQuery(self.query)) # boosted field\n )\n\n return sqs",
"def get_forms(self):\n metadata = self.get_metadata()\n\n MetadataForm = self.get_metadata_form_class()\n metadata_form = MetadataForm(\n self.form_data,\n instance=metadata,\n category=self.trs_import.doc_category)\n\n revision_num = self.csv_data['revision']\n revision = metadata.get_revision(revision_num) if metadata else None\n\n RevisionForm = self.get_revision_form_class()\n revision_form = RevisionForm(\n self.form_data,\n instance=revision,\n category=self.trs_import.doc_category)\n\n return metadata_form, revision_form",
"def get_assets(self) -> list[Asset]:",
"def facets(self):\n facets = {}\n for k, v in self._query:\n if k.startswith(\"cb.fq.\"):\n facets[k[6:]] = v\n\n return facets",
"def find_all(self):\n return self.documents",
"def _default_child_facets(self) -> dict:\n facets = {}\n for k, v in (\n (consts.FACET_COLLECTION, self.facets.get(consts.FACET_COLLECTION)),\n (consts.FACET_ITEM_TYPE, self.facets.get(consts.FACET_ITEM_TYPE)),\n (consts.FACET_ITEM_VARIANT, self.facets.get(consts.FACET_ITEM_VARIANT)),\n (\"version\", \"%s\" % self.version),\n ):\n if not v:\n continue\n\n facets[k] = v\n return facets",
"def document_sets(self):\n return self._document_sets",
"def get_search_results(self, req, resource_realm, terms):\r\n db = self.env.get_db_cnx()\r\n sql_query, args = search_to_sql(db, ['filename', 'description', \r\n 'author'], terms)\r\n cursor = db.cursor()\r\n cursor.execute(\"SELECT id,time,filename,description,author \"\r\n \"FROM attachment \"\r\n \"WHERE type = %s \"\r\n \"AND \" + sql_query, (resource_realm.realm, ) + args)\r\n \r\n for id, time, filename, desc, author in cursor:\r\n attachment = resource_realm(id=id).child('attachment', filename)\r\n if 'ATTACHMENT_VIEW' in req.perm(attachment):\r\n yield (get_resource_url(self.env, attachment, req.href),\r\n get_resource_shortname(self.env, attachment),\r\n datetime.fromtimestamp(time, utc), author,\r\n shorten_result(desc, terms))",
"def extract_facets(raw_json_response):\n facets_dict = {}\n\n for f in raw_json_response[\"facets\"]:\n facets_dict[f[\"field\"]] = f[\"items\"]\n\n return facets_dict"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Return all audio assets associated with a facet and the forms to associate more.
|
def facet_audio_assets(self):
self.object = self.get_object()
audio = self.object.get_facet_audio()
org_audio = self.object.organization.get_org_audio_library()
uploadform = AudioAssetForm()
return {'audio': audio, 'org_audio': org_audio, 'uploadform': uploadform}
|
[
"def facet_document_assets(self):\r\n\r\n self.object = self.get_object()\r\n documents = self.object.get_facet_documents()\r\n org_documents = self.object.organization.get_org_document_library()\r\n uploadform = DocumentAssetForm()\r\n return {'documents': documents, 'org_documents': org_documents, 'uploadform': uploadform}",
"def facet_image_assets(self):\r\n\r\n self.object = self.get_object()\r\n images = self.object.get_facet_images()\r\n org_images = self.object.organization.get_org_image_library()\r\n uploadform = ImageAssetForm()\r\n return {'images': images, 'org_images': org_images, 'uploadform': uploadform}",
"def facet_video_assets(self):\r\n\r\n self.object = self.get_object()\r\n videos = self.object.get_facet_video()\r\n org_videos = self.object.organization.get_org_video_library()\r\n uploadform = VideoAssetForm()\r\n return {'videos': videos, 'org_videos': org_videos, 'uploadform': uploadform}",
"def get_all_audio(self):\n return [x.file for x in self.audio_data.values()]",
"def get_tracks_for_audio_analysis(self) -> List[str]:\n \n l.debug(\"Finding Tracks without audio analysis, this can take some time.\")\n q = {}\n cols = {\"_id\": 1, \"audio_analysis_flag\": 1}\n r = list(self._tracks.find(q, cols))\n\n # Only append artists who need collection in result\n result = []\n for track in r:\n if \"audio_analysis_flag\" not in track.keys():\n result.append(track[\"_id\"])\n else:\n if not track[\"audio_analysis_flag\"]:\n result.append(track[\"_id\"])\n return result",
"def search( sp, track, lim=1 ):\n\n identifier = sp.search( q=\"track: \" + track, limit=lim, type=\"track\" )['tracks']['items'][0]['id']\n features = sp.audio_features( identifier )\n analisys = sp.audio_analysis( identifier )\n\n return identifier, features, analisys",
"def findFacets(self):\n facets = []\n content = self.soup.find(id='page-container')\n text = content.find(id='js-article-text')\n for facet in text.find('ul', {\"class\":\"mol-bullets-with-font\"}):\n facet.text.replace(\"\\xa0\", \" \")\n facets.append(facet.text)\n return facets",
"def get(self): \n return getAllAlbums()",
"def get_assets(self) -> list[Asset]:",
"def get_audios(self) -> List[Dict[str, str]]:\n with self.cursor(dictionary=True) as cur:\n cur.execute(self.SELECT_AUDIOS)\n return list(cur)",
"def objects_in_group(root_object):\n yield root_object\n for comp_audio_object in root_object.audioComplementaryObjects:\n yield comp_audio_object",
"def get_search_queries(self):\n artists_songs = []\n\n # Iterating through the playlist track objects inside the paging object.\n for playlist_track in self.playlist[\"tracks\"][\"items\"]:\n # Getting the track itself from the playlist track object.\n track = playlist_track[\"track\"]\n\n # Extracting the list of artists and track name and creating the corresponding string.\n artists_song_str = \", \".join([artists[\"name\"] for artists in track[\"artists\"]]) + \" - \" + track[\"name\"]\n\n artists_songs.append(artists_song_str)\n\n # Adding the duration of the track to the total duration of the playlist.\n self.duration_ms += track[\"duration_ms\"]\n\n return artists_songs",
"def get_tracks_audio_features(track_ids):\n connect()\n url = 'https://api.spotify.com/v1/audio-features/'\n # Max that can be submitted to this endpoint is 100 at a time\n track_groups = make_chunks(track_ids, 100)\n audio_features = []\n for group in track_groups:\n query_params = {'ids': ','.join(group)}\n response = requests.get(\n url, params=query_params, headers=get_header()\n )\n resp_json = response.json()\n if resp_json.get('audio_features'):\n audio_features.extend(resp_json['audio_features'])\n return audio_features",
"def albums(self):\n\n c.artist = request.GET.get('artist', u'')\n c.album = request.GET.get('album', u'')\n\n try:\n self.m = g.p.connect()\n except (NoMPDConnection, ConnectionClosed):\n return render('/null.html')\n c.albums = self.m.albums(c.artist)\n\n aa = AlbumArt()\n c.album_imgs = aa.artist_art(c.artist)\n random.shuffle(c.album_imgs)\n return render('/albums.html')",
"def get_tracks_audio_features_from_category(category):\n tracks_meta = get_all_songs_in_category(category)\n track_ids = parse_track_ids_from_metadata(tracks_meta)\n return get_tracks_audio_features(track_ids)",
"def mergeAudio(self, audiolist, name):\n self.file = AudioSegment.empty()\n for audio in audiolist:\n self.file += AudioSegment.from_mp3(audio)\n self.file.export(name)",
"def get_albums(self, search, start=0, max_items=100):\r\n return self.get_music_service_information('albums', search, start,\r\n max_items)",
"def facet(self):\n facet_values = self.get_feature('facet')\n return facet_values",
"def load_all(self) -> AssetTankResult:\n return self.search()"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Return all video assets associated with a facet and the forms to associate more.
|
def facet_video_assets(self):
self.object = self.get_object()
videos = self.object.get_facet_video()
org_videos = self.object.organization.get_org_video_library()
uploadform = VideoAssetForm()
return {'videos': videos, 'org_videos': org_videos, 'uploadform': uploadform}
|
[
"def facet_image_assets(self):\r\n\r\n self.object = self.get_object()\r\n images = self.object.get_facet_images()\r\n org_images = self.object.organization.get_org_image_library()\r\n uploadform = ImageAssetForm()\r\n return {'images': images, 'org_images': org_images, 'uploadform': uploadform}",
"def videos(self):\n return [x.video for x in self.section_set.exclude(video=None).order_by('order', 'name')]",
"def get_videos(self):\n matchups = models.Matchup.objects.select_related('home', 'away').all()\n matchup_prefetch = Prefetch('matchups', queryset=matchups)\n return models.Video.objects.prefetch_related(matchup_prefetch)\\\n .filter(is_visible=True)",
"def facet_audio_assets(self):\r\n\r\n self.object = self.get_object()\r\n audio = self.object.get_facet_audio()\r\n org_audio = self.object.organization.get_org_audio_library()\r\n uploadform = AudioAssetForm()\r\n return {'audio': audio, 'org_audio': org_audio, 'uploadform': uploadform}",
"def facet_document_assets(self):\r\n\r\n self.object = self.get_object()\r\n documents = self.object.get_facet_documents()\r\n org_documents = self.object.organization.get_org_document_library()\r\n uploadform = DocumentAssetForm()\r\n return {'documents': documents, 'org_documents': org_documents, 'uploadform': uploadform}",
"def videos(self) -> Dict[str, Video]:\n return self._videos",
"def videos(self):\n self.__vi = []\n for etq in raiz[0]:\n # print(depurar1(etq.text))\n self.__vi.append(self.depurar1(etq.text))\n self.__vi.sort()\n return self.__vi",
"def get_metas():\n get_video_meta_class_key_values()",
"def GetVideoFields(self, account_id: str='') -> Response:\n url = f'{self.base_url}/video_fields'.format(account_id=account_id or self.oauth.account_id)\n return self.session.get(url=url, headers=self.oauth.headers)",
"def facet(self):\n facet_values = self.get_feature('facet')\n return facet_values",
"def filter_video_info(file_name: str) -> list:\n json_content = get_data(file_name)\n videos_info = []\n for entry in json_content:\n video = {}\n data = entry['gridVideoRenderer']\n video['id'] = data['videoId']\n video['name'] = data['title']['runs'][0]['text']\n video['date'] = data['publishedTimeText']['simpleText']\n split_str = video['date'].split()\n if 'Streamed' in split_str:\n video['date'] = \" \".join(split_str[1:])\n video['time'] = data['thumbnailOverlays'][0][\n 'thumbnailOverlayTimeStatusRenderer']['text']['simpleText']\n videos_info.append(video)\n return videos_info",
"def featured_videos(parser, token):\n return featured_attachments(Video, parser, token)",
"def findFacets(self):\n facets = []\n content = self.soup.find(id='page-container')\n text = content.find(id='js-article-text')\n for facet in text.find('ul', {\"class\":\"mol-bullets-with-font\"}):\n facet.text.replace(\"\\xa0\", \" \")\n facets.append(facet.text)\n return facets",
"def GetAssets(self, video_id: str, account_id: str='') -> Response:\n url = f'{self.base_url}/videos/{video_id}/assets'.format(account_id=account_id or self.oauth.account_id)\n return self.session.get(url, headers=self.oauth.headers)",
"def get_assets(self) -> list[Asset]:",
"def getFriendsVideos(self):\n return self.base.get(\"friends_videos\", [])",
"def facets(self, *args, **kwargs) -> Any:\n pass",
"def retrive_relevant_videos_info(keyword, candidates):\n print(\"\\n\\n----------------------------------------------------------\")\n logger.info(\"Retriving candidate video information and filtering...\\n\\n\")\n filtered_video_info = {}\n for i, url in enumerate(candidates):\n bv = re.findall(r\"^https://www.bilibili.com/video/BV([0-9a-zA-Z]*).*$\", url)[0]\n src_html = requests.get(url).text\n soup = BeautifulSoup(src_html, \"lxml\")\n print_progress(i, len(candidates), per=5)\n author_dict = extract_video_authors(soup)\n tags = extract_video_tags(soup)\n description = extract_video_description(soup)\n video_title = extract_video_title(soup)\n # only extract av and oid for relevant videos\n \n if judge_is_video_related(keyword, tags, description, author_dict, video_title):\n oid = extract_video_oid(src_html)\n av = extract_video_av(soup)\n if oid is None or av is None:\n continue # ignore videos whose av or oid are not found\n filtered_video_info[bv] = {\n \"av\": av,\n \"oid\": oid,\n \"tags\": tags,\n \"description\": description,\n \"title\": video_title\n } \n\n return filtered_video_info",
"def update_videos(self):\n def _create_video_frame(key, height, width):\n frame_text = (\n f'<iframe width=\"width\" height=\"height\" id=\"key\"'\n f'src=\"{BASE_YOUTUBE_URL}/embed/{key}\"></iframe>')\n return models.Div(text=frame_text)\n\n video_keys = [video['key']\n for video in self.match_data.score['videos']]\n video_divs = [_create_video_frame(key, VIDEO_HEIGHT, VIDEO_WIDTH)\n for key in video_keys]\n self.video_row.children = video_divs"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Query the given host for the given kf_id
|
def run_kf_id_query(ctx, kf_id, key):
host = ctx.obj["host"]
for e in yield_entities_from_kfids(host, [kf_id], show_progress=False):
entity_handler(e, key)
|
[
"def get_host_by_id(self, host_id):\n raise NotImplementedError('override me')",
"def test_clusterhost_get_by_id(self):\n # 1. Get host sucessfully\n url = '/clusterhosts/1'\n return_value = self.test_client.get(url)\n self.assertEqual(200, return_value.status_code)\n hostname = json.loads(return_value.get_data())[\n 'cluster_host']['hostname']\n self.assertEqual('host_01', hostname)\n\n # 2. Get a non-existing host\n url = '/clusterhosts/1000'\n return_value = self.test_client.get(url)\n self.assertEqual(404, return_value.status_code)",
"def get_host_by_pk(api_ip, api_port, pk):\n\n url = \"http://\" + api_ip + \":\" + str(api_port) + \"/\" + API_VERSION + \\\n \"/hosts/\" + str(pk)\n try:\n req = requests.get(url=url)\n result = req.json()\n status = req.status_code\n return (status, '', result)\n except Exception, e:\n return (-1, e, '')",
"def _nfvi_host_query_callback():\n response = (yield)\n DLOG.verbose(\"Query-Host callback, response=%s.\" % response)\n\n if response['completed']:\n nfvi_host = response['result-data']\n host_table = tables.tables_get_host_table()\n host = host_table.get(nfvi_host.name, None)\n if host is None:\n host = objects.Host(nfvi_host)\n host_table[host.name] = host\n\n host.nfvi_host_update(nfvi_host)\n else:\n DLOG.error(\"Query-Host callback, not completed, responses=%s.\"\n % response)",
"def hosts_id_get(id): # noqa: E501\n\n\n return query_manager.get_resource(id=id,\n rdf_type_uri=HOST_TYPE_URI,\n rdf_type_name=HOST_TYPE_NAME, \n kls=Host)",
"def cddb_query(): # cd_id\n pass",
"def query_foo1(self, log_func, id, params):\n\n key = params[\"key\"]\n log_func(\"Begin query_foo1.\")\n\n try:\n data = self.__db.get_in_query(key.encode())\n\n result = {\"data\": data.decode(\"utf-8\")}\n log_func(f'Queried data: {result}')\n return SCOREResponse.succeed(\"Succeed to query.\", result)\n\n except TypeError:\n return SCOREResponse.exception(\"Key or value is not byte-like data.\")\n\n except KeyError:\n return SCOREResponse.exception(\"DB do not Have such a key.\")",
"def dig(host):\n from sh import dig as shCmd\n return run_async(shCmd, host)",
"def read_hosts_by_query(query):\n client = MongoClient(DB_HOST, DB_PORT)\n db = client[DB_NAME]\n collection = db[HOSTS_COLLECTION]\n res = collection.find({'query': query})\n client.close()\n return res",
"def get_host(self, hostname):\n result = self.query(hostname=hostname)\n if 'clients' in result:\n if len(result['clients']) > 1:\n self.logger.error(\"More than one result for query by hostname\")\n return result['client']\n elif len(result['clients']) == 1:\n return result['clients'][0]\n else:\n self.logger.info(\"No lerc found by this hostname: {}\".format(hostname))\n return False",
"def _nfvi_host_services_query_callback(nfvi_host_name):\n DLOG.debug(\"Host-Services query, host_name=%s.\" % nfvi_host_name)\n\n host_table = tables.tables_get_host_table()\n host = host_table.get(nfvi_host_name, None)\n if host is None:\n return False, None\n\n if host.nfvi_host_is_enabled():\n host_oper_state = nfvi.objects.v1.HOST_OPER_STATE.ENABLED\n else:\n host_oper_state = nfvi.objects.v1.HOST_OPER_STATE.DISABLED\n\n return True, host_oper_state",
"def dnsquery( fqdn ):\n\n # Set name of logger with calling details\n ls = \"%s by %s\" % ( __name__ , '__dnsquery__' )\n logger = logging.getLogger( ls )\n\n # DNS retrieve we'll be ensure with dig.\n cmd_to_query = \"/usr/bin/dig +short\"\n\n # Determine wheter or not we belong to caisse-epargne.\n if ( re.search( \"caisse-epargne.fr\", fqdn ) ):\n \n ans_host = fqdn \n\n elif ( re.search( \"dom103\" , fqdn ) ):\n \n # Take care of bunker also...\n ans_host1 = re.sub( \"dom103\", \"dom101\", fqdn )\n ans_host = \"a-%s\" % ( ans_host1 )\n\n else:\n\n ans_host = \"a-%s\" % ( fqdn )\n\n # Query and read output !\n string = \"%s %s\" % ( cmd_to_query, ans_host )\n dnsquery = os.popen ( string ).read()\n\n # If query result is void, set ansible_host to none.\n # And log it as an issue...\n if ( dnsquery == \"\" ):\n\n string = \"Empty DNS reply for %s\" % ( ans_host )\n logger.warning( string )\n ans_host = None\n\n return ans_host",
"def get_host_by_name(self, host_name):\n LOG.info(\"Getting host details by name: '%s'\" % host_name)\n return self.client.request(\n constants.GET,\n constants.GET_HOST_BY_NAME_URL.format(self.server_ip),\n payload=None, querystring=helpers.prepare_querystring(\n constants.SELECT_ALL_HOST, name=constants.EQUALS + host_name\n )\n )",
"def search_host(self, host):\n collection = self._get_collection('host')\n host = collection.find_one({'url': {'$regex': 'http(s)?://' + host}})\n return host",
"def get_ihost_by_hostname(self, context, ihost_hostname):\n\n return self.call(context,\n self.make_msg('get_ihost_by_hostname',\n ihost_hostname=ihost_hostname))",
"def _run_query (self, query):\n self._login()\n return self.api_obj.query(query)",
"def test_querytask_byid(self):\n response = self.client.query_task()\n logger.info(response)\n if isinstance(self.check_schema(resp=response), str):\n self.assertTrue(False, \"jsonschema check failed\")\n id = response.get(\"data\").get(\"data\")[0][\"id\"]\n response = self.client.query_task(query=\"id=%d\" % id)\n logger.info(response)\n if isinstance(self.check_schema(resp=response), str):\n self.assertTrue(False, \"jsonschema check failed\")\n self.assertEqual(response.get(\"data\").get(\"totalRows\"), 1, msg=\"expect total rows = 1\")\n self.assertEqual(response.get(\"data\").get(\"data\")[0].get(\"id\"), id, msg=\"epxect id=%d\" % id)",
"def _get_host_id(self, hostname, hostgroupid):\n cli_cmd = 'showhost -group %(groupid)s' % {'groupid': hostgroupid}\n out = self._execute_cli(cli_cmd)\n if re.search('Host Information', out):\n try:\n for line in out.split('\\r\\n')[6:-2]:\n tmp_line = line.split()\n if len(tmp_line) < 2:\n continue\n if tmp_line[1] == hostname:\n return tmp_line[0]\n except Exception:\n err_msg = (_('CLI out is not normal. CLI out: %s') % out)\n LOG.error(err_msg)\n raise exception.VolumeBackendAPIException(data=err_msg)\n return None",
"async def _get(self, key):\n uid = pack(key)\n queried = set()\n while True:\n # retrieve the k nearest peers and remove already queried peers\n peers = await self.peers((None, None), uid)\n peers = [address for address in peers if address not in queried]\n # no more peer to query, the key is not found in the dht\n if not peers:\n raise KeyError(unpack(uid))\n # query selected peers\n queries = dict()\n for address in peers:\n query = self._protocol.rpc(address, \"value\", uid)\n queries[address] = query\n responses = await gather(queries, return_exceptions=True)\n for (address, response) in responses.items():\n queried.add(address)\n if isinstance(response, Exception):\n continue\n elif response[0] == b\"VALUE\":\n value = response[1]\n if hash(value) == unpack(uid):\n # store it\n @h.transactional\n def add(tr, key, value):\n tr.add(\"QADOM:MAPPING\", key, \"value\", value)\n\n await self._run(add, self._hoply, key, value)\n # at last!\n return value\n else:\n log.warning(\n \"[%r] bad value returned from %r\", self._uid, address\n )\n await self.blacklist(address)\n continue\n elif response[0] == b\"PEERS\":\n await self._welcome_peers(response[1])\n else:\n await self.blacklist(address)\n log.warning(\n \"[%r] unknown response %r from %r\",\n self._uid,\n response[0],\n address,\n )"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Query the given host using the given filter
|
def run_filter_query(ctx, endpoint, filter, key):
host = ctx.obj["host"]
filter_dict = literal_eval(filter)
for e in yield_entities_from_filter(
host, endpoint, filter_dict, show_progress=False
):
entity_handler(e, key)
|
[
"def search_host(self, host):\n collection = self._get_collection('host')\n host = collection.find_one({'url': {'$regex': 'http(s)?://' + host}})\n return host",
"def scantarget(host,status_filter):\n user_agent = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\n 'Accept-Language': 'en-US,en;q=0.8',\n 'Accept-Encoding': 'gzip'\n }\n scan = requests.get(host, headers=user_agent)\n if (verb):\n print(\"[\"+str(scan.status_code)+\"] \"+host)\n else:\n if scan.status_code in status_filter:\n print(\"[\"+str(scan.status_code)+\"] \"+host)",
"def host_search(self, query, from_ind=None, to_ind=None):\n raise NotImplementedError('override me')",
"def send_query(selector, query, host, port = 0):\r\n return send_selector(selector + '\\t' + query, host, port)",
"def read_hosts_by_query(query):\n client = MongoClient(DB_HOST, DB_PORT)\n db = client[DB_NAME]\n collection = db[HOSTS_COLLECTION]\n res = collection.find({'query': query})\n client.close()\n return res",
"def _nfvi_host_query_callback():\n response = (yield)\n DLOG.verbose(\"Query-Host callback, response=%s.\" % response)\n\n if response['completed']:\n nfvi_host = response['result-data']\n host_table = tables.tables_get_host_table()\n host = host_table.get(nfvi_host.name, None)\n if host is None:\n host = objects.Host(nfvi_host)\n host_table[host.name] = host\n\n host.nfvi_host_update(nfvi_host)\n else:\n DLOG.error(\"Query-Host callback, not completed, responses=%s.\"\n % response)",
"def queryhost(self,qhost):\n import os,math\n\n c = None\n conn = None\n if self.mysql_config:\n if args.mysql_max and self.mysql_execute_count > args.mysql_max:\n self.mysql_reconnect() \n \n conn = self.mysql_connect(cache=True)\n c = conn.cursor()\n\n for wt in self.webtime(qhost,c):\n # Note if the webtime is off.\n if webtime_record(wt):\n if args.verbose: \n print(\"{:35} {:20} {:30} {}\".format(wt.qhost,wt.qipaddr,wt.pdiff(),wt.rdatetime))\n self.mysql_execute(c,\"insert ignore into times (host,ipaddr,qdatetime,qduration,rdatetime,offset) \"+\n \"values (%s,%s,%s,%s,%s,timestampdiff(second,%s,%s))\",\n (wt.qhost,wt.qipaddr,wt.qdatetime_iso(),\n wt.qduration,wt.rdatetime_iso(),\n wt.qdatetime_iso(),wt.rdatetime_iso()))\n if conn: conn.commit()",
"def do_query(self):\n print(\"[*] Beginning HackerTarget Query\")\n try:\n res = requests.get(self.ENDPOINT, verify=False, proxies=self.proxies)\n self._print(f\"Making request to url {self.ENDPOINT}\" + \n f\"with proxies {self.proxies}\")\n lines = res.content.splitlines()\n if len(lines) < 2: #Assuming anything greater than 1 is a valid domain for our purposes\n print(\"Domain not found on hackertarget\")\n return\n for line in res.content.split():\n unused_hostname, ip = str(line, 'utf-8').split(',')\n self.results += [ip.strip()]\n self._write_results()\n except requests.exceptions.ConnectionError as er:\n logger.error(f\"[!] Connection Error check network configuration {er}\")\n print(f\"[!] Connection Error check network configuration {er}\")\n except requests.exceptions.RequestException as er:\n logger.error(f\"[!] Request failed {er}\")\n print(f\"[!] Request failed {er}\")\n except OSError as er:\n logger.exception(\"OSError in HackerTarget\")\n print(f\"[!] Writing to file failed {er}\")\n print(\"[*] End HackerTarget Query\")",
"def test_accept_make_query_param_to_filter(self):",
"def select_hosts(self, context, request_spec, filter_properties):\n instance_uuids = request_spec.get('instance_uuids')\n hosts = [host.obj.host for host in self._schedule(context, request_spec, filter_properties, instance_uuids)]\n if not hosts:\n raise exception.NoValidHost(reason=\"\")\n return hosts",
"def get_filtered(cls, client, filter_) :\n\t\ttry :\n\t\t\tobj = onlinkipv6prefix()\n\t\t\toption_ = options()\n\t\t\toption_.filter = filter_\n\t\t\tresponse = obj.getfiltered(client, option_)\n\t\t\treturn response\n\t\texcept Exception as e :\n\t\t\traise e",
"def test_accept_vin_query_param_to_filter(self):",
"def get_hosts(limit=None, columns=None, extra_filter=None):\n return query(\"GET hosts\\n\", limit=limit, columns=columns,\n item_type=\"hosts\" , extra_filter=extra_filter)",
"def ex_query(self, type, filter=None, page=1, page_size=100, sort_asc=None,\r\n sort_desc=None):\r\n # This is a workaround for filter parameter encoding\r\n # the urllib encodes (name==Developers%20Only) into\r\n # %28name%3D%3DDevelopers%20Only%29) which is not accepted by vCloud\r\n params = {\r\n 'type': type,\r\n 'pageSize': page_size,\r\n 'page': page,\r\n }\r\n if sort_asc:\r\n params['sortAsc'] = sort_asc\r\n if sort_desc:\r\n params['sortDesc'] = sort_desc\r\n\r\n url = '/api/query?' + urlencode(params)\r\n if filter:\r\n if not filter.startswith('('):\r\n filter = '(' + filter + ')'\r\n url += '&filter=' + filter.replace(' ', '+')\r\n\r\n results = []\r\n res = self.connection.request(url)\r\n for elem in res.object:\r\n if not elem.tag.endswith('Link'):\r\n result = elem.attrib\r\n result['type'] = elem.tag.split('}')[1]\r\n results.append(result)\r\n return results",
"def getHostFrom(fromHost):",
"def _run_query (self, query):\n self._login()\n return self.api_obj.query(query)",
"def filter_query(filters, request):\n for filter_name, db_filter in filters.items():\n if db_filter == \"all\":\n continue\n\n if filter_name == \"status\":\n # doesn't do += because query is a parameter of the function\n Agent.filter_agents_by_status(db_filter, request)\n elif filter_name == \"older_than\":\n # doesn't do += because query is a parameter of the function\n Agent.filter_agents_by_timeframe(db_filter, request)\n else:\n filter_con = {}\n filter_con[filter_name] = {}\n if isinstance(db_filter, list):\n filter_con[filter_name] = {\n }\n filter_con[filter_name][\"$in\"] = [re.compile(name.lower(), re.IGNORECASE) if filter_name != \"version\"\n else re.compile(re.sub( r'([a-zA-Z])([v])', r'\\1 \\2', name), re.IGNORECASE)\n for name in db_filter]\n else: # str\n filter_con[filter_name] = re.compile(name.lower(), re.IGNORECASE) if filter_name != \"version\" \\\n else re.compile(re.sub( r'([a-zA-Z])([v])', r'\\1 \\2', name), re.IGNORECASE)\n if filter_con:\n request[\"$and\"].append(filter_con)",
"def dnsquery( fqdn ):\n\n # Set name of logger with calling details\n ls = \"%s by %s\" % ( __name__ , '__dnsquery__' )\n logger = logging.getLogger( ls )\n\n # DNS retrieve we'll be ensure with dig.\n cmd_to_query = \"/usr/bin/dig +short\"\n\n # Determine wheter or not we belong to caisse-epargne.\n if ( re.search( \"caisse-epargne.fr\", fqdn ) ):\n \n ans_host = fqdn \n\n elif ( re.search( \"dom103\" , fqdn ) ):\n \n # Take care of bunker also...\n ans_host1 = re.sub( \"dom103\", \"dom101\", fqdn )\n ans_host = \"a-%s\" % ( ans_host1 )\n\n else:\n\n ans_host = \"a-%s\" % ( fqdn )\n\n # Query and read output !\n string = \"%s %s\" % ( cmd_to_query, ans_host )\n dnsquery = os.popen ( string ).read()\n\n # If query result is void, set ansible_host to none.\n # And log it as an issue...\n if ( dnsquery == \"\" ):\n\n string = \"Empty DNS reply for %s\" % ( ans_host )\n logger.warning( string )\n ans_host = None\n\n return ans_host",
"def filter_request(query, username, firstreq):\r\n try:\r\n keyword = query.split(\";\")[0].split(\" \")[0]\r\n validate_user(username)\r\n if _show_all_report(keyword):\r\n query = query.split(\"~\")[0]\r\n data = _init_report_load(query)\r\n else:\r\n filter_url = _fetch_service_filter_url(keyword)\r\n if \"dashboard_url\" == filter_url[\"format\"]:\r\n data = dashboard_url(filter_url[\"service_url\"], query)\r\n data[\"format\"] = \"url\"\r\n else:\r\n query = query.split(\"~\")[0]\r\n if len(filter_url['url'].strip()) > 0:\r\n data = _call_rest_api(filter_url[\"url\"], query, 'post')\r\n else:\r\n data = _create_rest_error_output(\"No Such element\", 500)\r\n data[\"format\"] = filter_url[\"format\"]\r\n out_list = [filter_url[\"label\"]]\r\n in_list = [data]\r\n response_list = [out_list, in_list]\r\n data = response_list\r\n except Exception as e:\r\n logger.error(\"Exception in _filter_request : \" + str(e))\r\n data = {\"success\": \"\", \"data\": {}, \"error\": {\"Message\": str(e)}}\r\n data = jsonify(data)\r\n return data"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Tries to parse out an ``Emoji`` from the inputted text. This emoji can be custom and unicode emoji as well. If the parsing fails the function returns `None`.
|
def parse_emoji(text):
parsed = EMOJI_RP.fullmatch(text)
if (parsed is not None):
animated, name, emoji_id = parsed.groups()
animated = (animated is not None)
emoji_id = int(emoji_id)
return Emoji._create_partial(emoji_id, name, animated)
try:
return UNICODE_TO_EMOJI[text]
except KeyError:
pass
if text.startswith(':') and text.endswith(':') and not text.endswith(VARIATION_SELECTOR_16_POSTFIX_WITH_COLON):
try:
return BUILTIN_EMOJIS[text[1:-1]]
except KeyError:
pass
return None
|
[
"def parse_reaction(text):\n try:\n emoji = UNICODE_TO_EMOJI[text]\n except KeyError:\n parsed = REACTION_RP.fullmatch(text)\n if parsed is None:\n emoji = None\n else:\n name, emoji_id = parsed.groups()\n emoji_id = int(emoji_id)\n emoji = Emoji._create_partial(emoji_id, name, False)\n \n return emoji",
"def extract_emoji(text):\n the_emoji = None\n for emoji_type, code_point, emoji_list, name, parent in EMOJIS:\n for emoji in emoji_list:\n if emoji in text:\n the_emoji = emoji_type\n text = re.sub(emoji, ' ', text)\n text, stripped = strip_emojis(text)\n text = re.sub('[ \\t\\r\\n]+', ' ', text)\n return text, the_emoji, stripped",
"def normalize_emoji(text):\n # Translate textual smilies to color emoji.\n text = re.sub(TEXT_TO_EMOJI_PATTERN, text_to_emoji_callback, text)\n # Translate hollow smilies to color emoji.\n text = re.sub(WHITE_TO_EMOJI_PATTERN, white_to_emoji_callback, text)\n # Translate text macros to color emoji.\n return emoji.emojize(text, use_aliases=True)",
"def extract_emojis(txt, emoji_list):\n # extract normal unicode emoji\n emojis = list(c for c in txt if c in emoji.UNICODE_EMOJI)\n\n # extract IDs of custom emoji\n emojis += list(re.findall(\"<:[a-zA-Z]+:[0-9]+>\", txt))\n\n return tuple(emojis)",
"def extract_emojis(text):\n result = re.findall(EMOJI_REGEX, text)\n return result",
"def text_has_emoji(text):\n for character in text:\n if character in emoji.UNICODE_EMOJI:\n return 1\n return 0",
"def is_emoji(self):\n if self.token in emoji.UNICODE_EMOJI:\n return [True, '<neutralface>']\n else:\n return [False, None]",
"def parse_custom_emojis(text):\n if text is None:\n return set()\n \n return {*_iter_parse_custom_emojis(text)}",
"def test__parse_custom_emojis():\n emojis = {\n BUILTIN_EMOJIS['heart'],\n Emoji.precreate(202301010080, name = 'haru', animated = True),\n BUILTIN_EMOJIS['knife'],\n Emoji.precreate(202301010081, name = 'kuroi'),\n }\n text = ' '.join([emoji.as_emoji for emoji in emojis] * 2)\n \n expected_output = {emoji for emoji in emojis if emoji.is_custom_emoji()}\n \n parsed_emojis = parse_custom_emojis(text)\n vampytest.assert_eq(expected_output, parsed_emojis)",
"def trans_emoji(text):\n def _emoji(matched):\n hex = matched.group(1)\n return ('\\\\U%08x' % int(hex, 16)).decode('unicode-escape').encode('utf-8')\n\n replace_t = re.sub(Constant.REGEX_EMOJI, _emoji, text)\n return replace_t",
"def remove_emoji(text):",
"def extract_emojis(str):\n return ''.join(c for c in str if c in emoji.UNICODE_EMOJI)",
"def is_emoji(s):\n\treturn s in UNICODE_EMOJI",
"def parse_with_error_handling(self, text):\n\n # Check for non-string\n if not isinstance(text, str) and not isinstance(text, unicode):\n project_logger.warning(\"Parser got a non-string argument: %s\", text)\n return None\n\n # Check for non-unicode\n if not isinstance(text, unicode):\n\n # Try to convert the string to unicode if possible\n # Unit test: should fail with this example:\n # http://stackoverflow.com/questions/6257647/convert-string-to-unicode\n\n try:\n text = unicode(text)\n except(UnicodeDecodeError):\n project_logger.warning(\"The following sentence text is \"\n \"not unicode; convertion failed.\")\n project_logger.info(text)\n\n # Skip sentence if flag is True\n if app.config[\"SKIP_SENTENCE_ON_ERROR\"]:\n return None\n else:\n # Try to parse the sentence anyway\n project_logger.warning(\"Attempting to parse \"\n \"non-unicode sentence.\")\n\n # Check for empty or nonexistent text\n if text == \"\" or text == None:\n return None\n\n # Check for irregular characters\n # TODO: what are considered irregular characters?\n\n # Try to parse, catch errors\n parsed_text = None\n try:\n parsed_text = self.parser.raw_parse(text)\n # TODO: handle all errors properly\n # ProcessError, TimeoutError, OutOfMemoryError\n except TimeoutError as e:\n project_logger.error(\"Got a TimeoutError: %s\", str(e))\n return None\n except ProcessError as e:\n project_logger.error(\"Got a ProcessError: %s\", str(e))\n return None\n except:\n project_logger.error(\"Unknown error\")\n return None\n\n # Parse successful, return parsed text\n return parsed_text",
"def get_emoji(self, emoji):\n\t\tif emoji == \"?\":\n\t\t\treturn \"\\u2753 \"\n\t\telif emoji == \"i\":\n\t\t\treturn \"\\u2139 \"\n\t\telif emoji == \"ok\":\n\t\t\treturn \"\\u2714 \"\n\t\treturn \"\"",
"def find_custom_emojis(text):\n emoji_list = []\n data = regex.findall(r\"<(a?):([a-zA-Z0-9\\_]+):([0-9]+)>\", text)\n for a, emoji_name, emoji_id in data:\n emoji_list.append(f\"<{a}:{emoji_name}:{emoji_id}>\")\n\n return emoji_list",
"def _iter_parse_custom_emojis(text):\n for groups in EMOJI_RP.findall(text):\n \n animated, name, emoji_id = groups\n animated = (True if animated else False)\n emoji_id = int(emoji_id)\n \n yield Emoji._create_partial(emoji_id, name, animated)",
"def _iter_parse_all_emojis(text):\n for groups in EMOJI_ALL_RP.findall(text):\n \n unicode_value, unicode_name, custom_animated, custom_name, custom_emoji_id = groups\n if unicode_value:\n yield UNICODE_TO_EMOJI[unicode_value]\n continue\n \n if unicode_name:\n yield BUILTIN_EMOJIS[unicode_name]\n continue\n \n yield Emoji._create_partial(\n int(custom_emoji_id),\n custom_name,\n (True if custom_animated else False),\n )\n continue",
"def _parse_unicode(self, unicode_element):\n if unicode_element.text is not None:\n return unicode_element.text\n else:\n return TextType()"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Iterates over all the custom emojis in the text as they appear. This function is an iterable generator.
|
def _iter_parse_custom_emojis(text):
for groups in EMOJI_RP.findall(text):
animated, name, emoji_id = groups
animated = (True if animated else False)
emoji_id = int(emoji_id)
yield Emoji._create_partial(emoji_id, name, animated)
|
[
"def _iter_parse_all_emojis(text):\n for groups in EMOJI_ALL_RP.findall(text):\n \n unicode_value, unicode_name, custom_animated, custom_name, custom_emoji_id = groups\n if unicode_value:\n yield UNICODE_TO_EMOJI[unicode_value]\n continue\n \n if unicode_name:\n yield BUILTIN_EMOJIS[unicode_name]\n continue\n \n yield Emoji._create_partial(\n int(custom_emoji_id),\n custom_name,\n (True if custom_animated else False),\n )\n continue",
"def parse_custom_emojis(text):\n if text is None:\n return set()\n \n return {*_iter_parse_custom_emojis(text)}",
"def find_custom_emojis(text):\n emoji_list = []\n data = regex.findall(r\"<(a?):([a-zA-Z0-9\\_]+):([0-9]+)>\", text)\n for a, emoji_name, emoji_id in data:\n emoji_list.append(f\"<{a}:{emoji_name}:{emoji_id}>\")\n\n return emoji_list",
"def test__parse_custom_emojis():\n emojis = {\n BUILTIN_EMOJIS['heart'],\n Emoji.precreate(202301010080, name = 'haru', animated = True),\n BUILTIN_EMOJIS['knife'],\n Emoji.precreate(202301010081, name = 'kuroi'),\n }\n text = ' '.join([emoji.as_emoji for emoji in emojis] * 2)\n \n expected_output = {emoji for emoji in emojis if emoji.is_custom_emoji()}\n \n parsed_emojis = parse_custom_emojis(text)\n vampytest.assert_eq(expected_output, parsed_emojis)",
"def list_emojis(to_get=None):\n emojis_to_list = get_emojis(to_get)\n for name, emoji in emojis_to_list.items():\n yield emoji",
"def extract_emojis(text):\n result = re.findall(EMOJI_REGEX, text)\n return result",
"def test_emoji_only_in_text(self):\n def e() -> str: # pylint: disable=invalid-name\n return next(self.emoji_iterator)\n\n self.assert_modified_html(\n b\"qwerty<!-- qwerty -->qwerty\",\n f'qwerty{e()}<!-- qwerty -->qwerty{e()}'.encode()\n )\n self.assert_modified_html(\n b\"qwerty<style>a.qwerty{position: absolute}</style>forbes\",\n f\"qwerty{e()}<style>a.qwerty{{position: absolute}}</style>forbes{e()}\".encode()\n )\n script = b'<script>const intvar = 5;</script>'\n self.assert_modified_html(script, script)",
"def find_unicode_emojis(text):\n emoji_list = []\n data = regex.findall(r\"\\X\", text)\n flags = regex.findall(\"[\\U0001F1E6-\\U0001F1FF]\", text)\n for word in data:\n if any(char in emoji.UNICODE_EMOJI for char in word):\n if word in flags:\n continue\n emoji_list.append(emoji.demojize(word))\n\n for i in range(math.floor(len(flags) / 2)):\n emoji_list.append(\"\".join(emoji.demojize(x) for x in flags[i : i + 2]))\n\n return emoji_list",
"def parse_custom_emojis_ordered(text):\n return _parse_emojis_ordered(text, _iter_parse_custom_emojis)",
"def extract_emoji(text):\n the_emoji = None\n for emoji_type, code_point, emoji_list, name, parent in EMOJIS:\n for emoji in emoji_list:\n if emoji in text:\n the_emoji = emoji_type\n text = re.sub(emoji, ' ', text)\n text, stripped = strip_emojis(text)\n text = re.sub('[ \\t\\r\\n]+', ' ', text)\n return text, the_emoji, stripped",
"def get_reaction_emojis(self):\n return [option.emoji.unicode for option in self.options]",
"def extract_emojis(txt, emoji_list):\n # extract normal unicode emoji\n emojis = list(c for c in txt if c in emoji.UNICODE_EMOJI)\n\n # extract IDs of custom emoji\n emojis += list(re.findall(\"<:[a-zA-Z]+:[0-9]+>\", txt))\n\n return tuple(emojis)",
"def remove_emoji(text):",
"def text_has_emoji(text):\n for character in text:\n if character in emoji.UNICODE_EMOJI:\n return 1\n return 0",
"def show_emojis():\n messaging = CONF[\"messaging\"]\n\n for emoji in messaging[\"emojis\"]:\n print(emoji)\n print(repr(emoji))\n print()",
"def is_emoji(self):\n if self.token in emoji.UNICODE_EMOJI:\n return [True, '<neutralface>']\n else:\n return [False, None]",
"def parse_all_emojis_ordered(text):\n return _parse_emojis_ordered(text, _iter_parse_all_emojis)",
"def get_emoji_indices(text: str) -> List[int]:\n pass",
"def demoji(tokens):\n emoji_description = []\n for token in tokens:\n detect = emoji.demojize(token)\n emoji_description.append(detect)\n return emoji_description"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Iterates over all emojis in the text as they appear. This function is an iterable generator.
|
def _iter_parse_all_emojis(text):
for groups in EMOJI_ALL_RP.findall(text):
unicode_value, unicode_name, custom_animated, custom_name, custom_emoji_id = groups
if unicode_value:
yield UNICODE_TO_EMOJI[unicode_value]
continue
if unicode_name:
yield BUILTIN_EMOJIS[unicode_name]
continue
yield Emoji._create_partial(
int(custom_emoji_id),
custom_name,
(True if custom_animated else False),
)
continue
|
[
"def _iter_parse_custom_emojis(text):\n for groups in EMOJI_RP.findall(text):\n \n animated, name, emoji_id = groups\n animated = (True if animated else False)\n emoji_id = int(emoji_id)\n \n yield Emoji._create_partial(emoji_id, name, animated)",
"def extract_emojis(text):\n result = re.findall(EMOJI_REGEX, text)\n return result",
"def list_emojis(to_get=None):\n emojis_to_list = get_emojis(to_get)\n for name, emoji in emojis_to_list.items():\n yield emoji",
"def parse_custom_emojis(text):\n if text is None:\n return set()\n \n return {*_iter_parse_custom_emojis(text)}",
"def test_emoji_only_in_text(self):\n def e() -> str: # pylint: disable=invalid-name\n return next(self.emoji_iterator)\n\n self.assert_modified_html(\n b\"qwerty<!-- qwerty -->qwerty\",\n f'qwerty{e()}<!-- qwerty -->qwerty{e()}'.encode()\n )\n self.assert_modified_html(\n b\"qwerty<style>a.qwerty{position: absolute}</style>forbes\",\n f\"qwerty{e()}<style>a.qwerty{{position: absolute}}</style>forbes{e()}\".encode()\n )\n script = b'<script>const intvar = 5;</script>'\n self.assert_modified_html(script, script)",
"def extract_emoji(text):\n the_emoji = None\n for emoji_type, code_point, emoji_list, name, parent in EMOJIS:\n for emoji in emoji_list:\n if emoji in text:\n the_emoji = emoji_type\n text = re.sub(emoji, ' ', text)\n text, stripped = strip_emojis(text)\n text = re.sub('[ \\t\\r\\n]+', ' ', text)\n return text, the_emoji, stripped",
"def find_unicode_emojis(text):\n emoji_list = []\n data = regex.findall(r\"\\X\", text)\n flags = regex.findall(\"[\\U0001F1E6-\\U0001F1FF]\", text)\n for word in data:\n if any(char in emoji.UNICODE_EMOJI for char in word):\n if word in flags:\n continue\n emoji_list.append(emoji.demojize(word))\n\n for i in range(math.floor(len(flags) / 2)):\n emoji_list.append(\"\".join(emoji.demojize(x) for x in flags[i : i + 2]))\n\n return emoji_list",
"def text_has_emoji(text):\n for character in text:\n if character in emoji.UNICODE_EMOJI:\n return 1\n return 0",
"def parse_all_emojis_ordered(text):\n return _parse_emojis_ordered(text, _iter_parse_all_emojis)",
"def get_emoji_indices(text: str) -> List[int]:\n pass",
"def find_custom_emojis(text):\n emoji_list = []\n data = regex.findall(r\"<(a?):([a-zA-Z0-9\\_]+):([0-9]+)>\", text)\n for a, emoji_name, emoji_id in data:\n emoji_list.append(f\"<{a}:{emoji_name}:{emoji_id}>\")\n\n return emoji_list",
"async def emoji_all(ctx: commands.Context, days: int = 30, anim: bool = False):\n oldest = datetime.utcnow().date() - timedelta(days=days)\n\n emoji_ids = {e.id: e for e in ctx.guild.emojis} # type: Dict[int, discord.Emoji]\n animated_emojis = {e.id for e in ctx.guild.emojis if e.animated}\n\n session = session_maker()\n\n total_counts = session.query(es.EmojiCount.emoji_id, func.sum(es.EmojiCount.count)).filter_by(\n server_id=ctx.guild.id).filter(\n func.DATE(es.EmojiCount.date) > oldest).group_by(\n es.EmojiCount.emoji_id).order_by(\n func.sum(es.EmojiCount.count).desc()).all() # type: List[int, int]\n\n # total_counts = total_counts[:num]\n\n emoji_counts = {em: ct for em, ct in total_counts} # type: Dict[int, int]\n for em_id in emoji_ids:\n if em_id not in emoji_counts:\n emoji_counts[em_id] = 0\n\n total_counts = list(emoji_counts.items())\n if not anim:\n total_counts = [e for e in total_counts if e[0] not in animated_emojis]\n\n reply = f'__**All used emojis in the past `{days}` days for {ctx.guild}:**__\\n'\n emoji_ls = []\n for i, entry in enumerate(total_counts):\n em = emoji_ids.get(entry[0])\n if em is None:\n em = NoneEmoji()\n emoji_ls.append(f'{em} : {entry[1]} uses')\n await ctx.send(reply)\n await utils.menu.menu_list(ctx, emoji_ls) # we don't actually care to select anything",
"async def list(self, ctx):\n\n output = \"\"\n for e in self.bot.emojis:\n if not e.animated:\n continue\n output += '**`:{}:`** -> {}\\n'.format(e.name, str(e))\n await ctx.send(\"__List of animated emojis :__\\n\\n\" + output)",
"def emojis_freq(self, text):\r\n df_emojis = [i for i in text if i in UNICODE_EMOJI]\r\n df_emojis = pd.Series(df_emojis).value_counts()\r\n df_emojis = df_emojis.sort_values(ascending = False)\r\n \r\n return df_emojis",
"def show_emojis():\n messaging = CONF[\"messaging\"]\n\n for emoji in messaging[\"emojis\"]:\n print(emoji)\n print(repr(emoji))\n print()",
"def __iter__(self):\n for i, line in enumerate(self.text):\n for j, letter in enumerate(line):\n if letter != ' ':\n yield i, j, letter",
"def extract_emojis(txt, emoji_list):\n # extract normal unicode emoji\n emojis = list(c for c in txt if c in emoji.UNICODE_EMOJI)\n\n # extract IDs of custom emoji\n emojis += list(re.findall(\"<:[a-zA-Z]+:[0-9]+>\", txt))\n\n return tuple(emojis)",
"def remove_emoji(text):",
"def number_of_emojies(self, text):\r\n counter = 0\r\n for character in text:\r\n if character in UNICODE_EMOJI:\r\n counter += 1\r\n return counter"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Parses out every custom emoji from the given text.
|
def parse_custom_emojis(text):
if text is None:
return set()
return {*_iter_parse_custom_emojis(text)}
|
[
"def find_custom_emojis(text):\n emoji_list = []\n data = regex.findall(r\"<(a?):([a-zA-Z0-9\\_]+):([0-9]+)>\", text)\n for a, emoji_name, emoji_id in data:\n emoji_list.append(f\"<{a}:{emoji_name}:{emoji_id}>\")\n\n return emoji_list",
"def _iter_parse_custom_emojis(text):\n for groups in EMOJI_RP.findall(text):\n \n animated, name, emoji_id = groups\n animated = (True if animated else False)\n emoji_id = int(emoji_id)\n \n yield Emoji._create_partial(emoji_id, name, animated)",
"def extract_emojis(text):\n result = re.findall(EMOJI_REGEX, text)\n return result",
"def extract_emoji(text):\n the_emoji = None\n for emoji_type, code_point, emoji_list, name, parent in EMOJIS:\n for emoji in emoji_list:\n if emoji in text:\n the_emoji = emoji_type\n text = re.sub(emoji, ' ', text)\n text, stripped = strip_emojis(text)\n text = re.sub('[ \\t\\r\\n]+', ' ', text)\n return text, the_emoji, stripped",
"def _iter_parse_all_emojis(text):\n for groups in EMOJI_ALL_RP.findall(text):\n \n unicode_value, unicode_name, custom_animated, custom_name, custom_emoji_id = groups\n if unicode_value:\n yield UNICODE_TO_EMOJI[unicode_value]\n continue\n \n if unicode_name:\n yield BUILTIN_EMOJIS[unicode_name]\n continue\n \n yield Emoji._create_partial(\n int(custom_emoji_id),\n custom_name,\n (True if custom_animated else False),\n )\n continue",
"def test__parse_custom_emojis():\n emojis = {\n BUILTIN_EMOJIS['heart'],\n Emoji.precreate(202301010080, name = 'haru', animated = True),\n BUILTIN_EMOJIS['knife'],\n Emoji.precreate(202301010081, name = 'kuroi'),\n }\n text = ' '.join([emoji.as_emoji for emoji in emojis] * 2)\n \n expected_output = {emoji for emoji in emojis if emoji.is_custom_emoji()}\n \n parsed_emojis = parse_custom_emojis(text)\n vampytest.assert_eq(expected_output, parsed_emojis)",
"def extract_emojis(txt, emoji_list):\n # extract normal unicode emoji\n emojis = list(c for c in txt if c in emoji.UNICODE_EMOJI)\n\n # extract IDs of custom emoji\n emojis += list(re.findall(\"<:[a-zA-Z]+:[0-9]+>\", txt))\n\n return tuple(emojis)",
"def parse_reaction(text):\n try:\n emoji = UNICODE_TO_EMOJI[text]\n except KeyError:\n parsed = REACTION_RP.fullmatch(text)\n if parsed is None:\n emoji = None\n else:\n name, emoji_id = parsed.groups()\n emoji_id = int(emoji_id)\n emoji = Emoji._create_partial(emoji_id, name, False)\n \n return emoji",
"def parse_emoji(text):\n parsed = EMOJI_RP.fullmatch(text)\n if (parsed is not None):\n animated, name, emoji_id = parsed.groups()\n animated = (animated is not None)\n emoji_id = int(emoji_id)\n return Emoji._create_partial(emoji_id, name, animated)\n \n try:\n return UNICODE_TO_EMOJI[text]\n except KeyError:\n pass\n \n if text.startswith(':') and text.endswith(':') and not text.endswith(VARIATION_SELECTOR_16_POSTFIX_WITH_COLON):\n try:\n return BUILTIN_EMOJIS[text[1:-1]]\n except KeyError:\n pass\n \n return None",
"def parse_custom_emojis_ordered(text):\n return _parse_emojis_ordered(text, _iter_parse_custom_emojis)",
"def find_unicode_emojis(text):\n emoji_list = []\n data = regex.findall(r\"\\X\", text)\n flags = regex.findall(\"[\\U0001F1E6-\\U0001F1FF]\", text)\n for word in data:\n if any(char in emoji.UNICODE_EMOJI for char in word):\n if word in flags:\n continue\n emoji_list.append(emoji.demojize(word))\n\n for i in range(math.floor(len(flags) / 2)):\n emoji_list.append(\"\".join(emoji.demojize(x) for x in flags[i : i + 2]))\n\n return emoji_list",
"def remove_emoji(text):",
"def normalize_emoji(text):\n # Translate textual smilies to color emoji.\n text = re.sub(TEXT_TO_EMOJI_PATTERN, text_to_emoji_callback, text)\n # Translate hollow smilies to color emoji.\n text = re.sub(WHITE_TO_EMOJI_PATTERN, white_to_emoji_callback, text)\n # Translate text macros to color emoji.\n return emoji.emojize(text, use_aliases=True)",
"def text_has_emoji(text):\n for character in text:\n if character in emoji.UNICODE_EMOJI:\n return 1\n return 0",
"def get_emoji_indices(text: str) -> List[int]:\n pass",
"def get_emoji_tokens(tokens):\n emoji_tokens = []\n emoji_tokens = emoji_tokens + [term for term in tokens\n if text_has_emoji(term)]\n return emoji_tokens",
"def extract_emojis(str):\n return ''.join(c for c in str if c in emoji.UNICODE_EMOJI)",
"def parse_all_emojis_ordered(text):\n return _parse_emojis_ordered(text, _iter_parse_all_emojis)",
"def __get_emoji_list(name):\n # return re.findall(emoji_codes, name, re.UNICODE)\n res = list()\n splitted = name.split(' ')\n if len(splitted) > 1 and len(splitted[0]) <= 4:\n res.append(splitted[0])\n return res"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Parses emojis of the given `text` with the given `parser`. Returns them ordered based on their appearance in the text.
|
def _parse_emojis_ordered(text, parser):
emojis_ordered = []
if (text is not None):
emojis_unique = set()
for emoji in parser(text):
if emoji not in emojis_unique:
emojis_ordered.append(emoji)
emojis_unique.add(emoji)
return emojis_ordered
|
[
"def parse_all_emojis_ordered(text):\n return _parse_emojis_ordered(text, _iter_parse_all_emojis)",
"def parse_custom_emojis_ordered(text):\n return _parse_emojis_ordered(text, _iter_parse_custom_emojis)",
"def parse_custom_emojis(text):\n if text is None:\n return set()\n \n return {*_iter_parse_custom_emojis(text)}",
"def extract_emojis(text):\n result = re.findall(EMOJI_REGEX, text)\n return result",
"def _iter_parse_all_emojis(text):\n for groups in EMOJI_ALL_RP.findall(text):\n \n unicode_value, unicode_name, custom_animated, custom_name, custom_emoji_id = groups\n if unicode_value:\n yield UNICODE_TO_EMOJI[unicode_value]\n continue\n \n if unicode_name:\n yield BUILTIN_EMOJIS[unicode_name]\n continue\n \n yield Emoji._create_partial(\n int(custom_emoji_id),\n custom_name,\n (True if custom_animated else False),\n )\n continue",
"def extract_emojis(txt, emoji_list):\n # extract normal unicode emoji\n emojis = list(c for c in txt if c in emoji.UNICODE_EMOJI)\n\n # extract IDs of custom emoji\n emojis += list(re.findall(\"<:[a-zA-Z]+:[0-9]+>\", txt))\n\n return tuple(emojis)",
"def _iter_parse_custom_emojis(text):\n for groups in EMOJI_RP.findall(text):\n \n animated, name, emoji_id = groups\n animated = (True if animated else False)\n emoji_id = int(emoji_id)\n \n yield Emoji._create_partial(emoji_id, name, animated)",
"def get_emoji_indices(text: str) -> List[int]:\n pass",
"def extract_emoji(text):\n the_emoji = None\n for emoji_type, code_point, emoji_list, name, parent in EMOJIS:\n for emoji in emoji_list:\n if emoji in text:\n the_emoji = emoji_type\n text = re.sub(emoji, ' ', text)\n text, stripped = strip_emojis(text)\n text = re.sub('[ \\t\\r\\n]+', ' ', text)\n return text, the_emoji, stripped",
"def parse_emoji(text):\n parsed = EMOJI_RP.fullmatch(text)\n if (parsed is not None):\n animated, name, emoji_id = parsed.groups()\n animated = (animated is not None)\n emoji_id = int(emoji_id)\n return Emoji._create_partial(emoji_id, name, animated)\n \n try:\n return UNICODE_TO_EMOJI[text]\n except KeyError:\n pass\n \n if text.startswith(':') and text.endswith(':') and not text.endswith(VARIATION_SELECTOR_16_POSTFIX_WITH_COLON):\n try:\n return BUILTIN_EMOJIS[text[1:-1]]\n except KeyError:\n pass\n \n return None",
"def find_unicode_emojis(text):\n emoji_list = []\n data = regex.findall(r\"\\X\", text)\n flags = regex.findall(\"[\\U0001F1E6-\\U0001F1FF]\", text)\n for word in data:\n if any(char in emoji.UNICODE_EMOJI for char in word):\n if word in flags:\n continue\n emoji_list.append(emoji.demojize(word))\n\n for i in range(math.floor(len(flags) / 2)):\n emoji_list.append(\"\".join(emoji.demojize(x) for x in flags[i : i + 2]))\n\n return emoji_list",
"def parseText(self, text):\n results = []\n for tag in self.iterTags(text):\n results.append(self.tagToMarkdown(tag, \n self.cards))\n return '\\n\\n'.join(results)",
"def find_custom_emojis(text):\n emoji_list = []\n data = regex.findall(r\"<(a?):([a-zA-Z0-9\\_]+):([0-9]+)>\", text)\n for a, emoji_name, emoji_id in data:\n emoji_list.append(f\"<{a}:{emoji_name}:{emoji_id}>\")\n\n return emoji_list",
"def parse_reaction(text):\n try:\n emoji = UNICODE_TO_EMOJI[text]\n except KeyError:\n parsed = REACTION_RP.fullmatch(text)\n if parsed is None:\n emoji = None\n else:\n name, emoji_id = parsed.groups()\n emoji_id = int(emoji_id)\n emoji = Emoji._create_partial(emoji_id, name, False)\n \n return emoji",
"def normalize_emoji(text):\n # Translate textual smilies to color emoji.\n text = re.sub(TEXT_TO_EMOJI_PATTERN, text_to_emoji_callback, text)\n # Translate hollow smilies to color emoji.\n text = re.sub(WHITE_TO_EMOJI_PATTERN, white_to_emoji_callback, text)\n # Translate text macros to color emoji.\n return emoji.emojize(text, use_aliases=True)",
"def parse_dialog(raw_text):\n stripped = raw_text.strip()\n raw_split = (line.split(\":\", 1) for line in stripped.split(\"\\n\"))\n return [\n SpokenText(speaker=speaker.strip(), text=text.strip())\n for speaker, text in raw_split\n ]",
"def emojis_freq(self, text):\r\n df_emojis = [i for i in text if i in UNICODE_EMOJI]\r\n df_emojis = pd.Series(df_emojis).value_counts()\r\n df_emojis = df_emojis.sort_values(ascending = False)\r\n \r\n return df_emojis",
"def get_emoji_tokens(tokens):\n emoji_tokens = []\n emoji_tokens = emoji_tokens + [term for term in tokens\n if text_has_emoji(term)]\n return emoji_tokens",
"def text_has_emoji(text):\n for character in text:\n if character in emoji.UNICODE_EMOJI:\n return 1\n return 0"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Parses out every custom emoji from the given text. Returns them ordered based on their appearance in the text.
|
def parse_custom_emojis_ordered(text):
return _parse_emojis_ordered(text, _iter_parse_custom_emojis)
|
[
"def parse_all_emojis_ordered(text):\n return _parse_emojis_ordered(text, _iter_parse_all_emojis)",
"def parse_custom_emojis(text):\n if text is None:\n return set()\n \n return {*_iter_parse_custom_emojis(text)}",
"def _parse_emojis_ordered(text, parser):\n emojis_ordered = []\n if (text is not None):\n emojis_unique = set()\n \n for emoji in parser(text):\n if emoji not in emojis_unique:\n emojis_ordered.append(emoji)\n emojis_unique.add(emoji)\n \n return emojis_ordered",
"def find_custom_emojis(text):\n emoji_list = []\n data = regex.findall(r\"<(a?):([a-zA-Z0-9\\_]+):([0-9]+)>\", text)\n for a, emoji_name, emoji_id in data:\n emoji_list.append(f\"<{a}:{emoji_name}:{emoji_id}>\")\n\n return emoji_list",
"def _iter_parse_all_emojis(text):\n for groups in EMOJI_ALL_RP.findall(text):\n \n unicode_value, unicode_name, custom_animated, custom_name, custom_emoji_id = groups\n if unicode_value:\n yield UNICODE_TO_EMOJI[unicode_value]\n continue\n \n if unicode_name:\n yield BUILTIN_EMOJIS[unicode_name]\n continue\n \n yield Emoji._create_partial(\n int(custom_emoji_id),\n custom_name,\n (True if custom_animated else False),\n )\n continue",
"def _iter_parse_custom_emojis(text):\n for groups in EMOJI_RP.findall(text):\n \n animated, name, emoji_id = groups\n animated = (True if animated else False)\n emoji_id = int(emoji_id)\n \n yield Emoji._create_partial(emoji_id, name, animated)",
"def extract_emoji(text):\n the_emoji = None\n for emoji_type, code_point, emoji_list, name, parent in EMOJIS:\n for emoji in emoji_list:\n if emoji in text:\n the_emoji = emoji_type\n text = re.sub(emoji, ' ', text)\n text, stripped = strip_emojis(text)\n text = re.sub('[ \\t\\r\\n]+', ' ', text)\n return text, the_emoji, stripped",
"def extract_emojis(txt, emoji_list):\n # extract normal unicode emoji\n emojis = list(c for c in txt if c in emoji.UNICODE_EMOJI)\n\n # extract IDs of custom emoji\n emojis += list(re.findall(\"<:[a-zA-Z]+:[0-9]+>\", txt))\n\n return tuple(emojis)",
"def find_unicode_emojis(text):\n emoji_list = []\n data = regex.findall(r\"\\X\", text)\n flags = regex.findall(\"[\\U0001F1E6-\\U0001F1FF]\", text)\n for word in data:\n if any(char in emoji.UNICODE_EMOJI for char in word):\n if word in flags:\n continue\n emoji_list.append(emoji.demojize(word))\n\n for i in range(math.floor(len(flags) / 2)):\n emoji_list.append(\"\".join(emoji.demojize(x) for x in flags[i : i + 2]))\n\n return emoji_list",
"def test__parse_custom_emojis():\n emojis = {\n BUILTIN_EMOJIS['heart'],\n Emoji.precreate(202301010080, name = 'haru', animated = True),\n BUILTIN_EMOJIS['knife'],\n Emoji.precreate(202301010081, name = 'kuroi'),\n }\n text = ' '.join([emoji.as_emoji for emoji in emojis] * 2)\n \n expected_output = {emoji for emoji in emojis if emoji.is_custom_emoji()}\n \n parsed_emojis = parse_custom_emojis(text)\n vampytest.assert_eq(expected_output, parsed_emojis)",
"def extract_emojis(text):\n result = re.findall(EMOJI_REGEX, text)\n return result",
"def get_emoji_indices(text: str) -> List[int]:\n pass",
"def parse_reaction(text):\n try:\n emoji = UNICODE_TO_EMOJI[text]\n except KeyError:\n parsed = REACTION_RP.fullmatch(text)\n if parsed is None:\n emoji = None\n else:\n name, emoji_id = parsed.groups()\n emoji_id = int(emoji_id)\n emoji = Emoji._create_partial(emoji_id, name, False)\n \n return emoji",
"def normalize_emoji(text):\n # Translate textual smilies to color emoji.\n text = re.sub(TEXT_TO_EMOJI_PATTERN, text_to_emoji_callback, text)\n # Translate hollow smilies to color emoji.\n text = re.sub(WHITE_TO_EMOJI_PATTERN, white_to_emoji_callback, text)\n # Translate text macros to color emoji.\n return emoji.emojize(text, use_aliases=True)",
"def remove_emoji(text):",
"def emojis_freq(self, text):\r\n df_emojis = [i for i in text if i in UNICODE_EMOJI]\r\n df_emojis = pd.Series(df_emojis).value_counts()\r\n df_emojis = df_emojis.sort_values(ascending = False)\r\n \r\n return df_emojis",
"def parse_emoji(text):\n parsed = EMOJI_RP.fullmatch(text)\n if (parsed is not None):\n animated, name, emoji_id = parsed.groups()\n animated = (animated is not None)\n emoji_id = int(emoji_id)\n return Emoji._create_partial(emoji_id, name, animated)\n \n try:\n return UNICODE_TO_EMOJI[text]\n except KeyError:\n pass\n \n if text.startswith(':') and text.endswith(':') and not text.endswith(VARIATION_SELECTOR_16_POSTFIX_WITH_COLON):\n try:\n return BUILTIN_EMOJIS[text[1:-1]]\n except KeyError:\n pass\n \n return None",
"def __get_emoji_list(name):\n # return re.findall(emoji_codes, name, re.UNICODE)\n res = list()\n splitted = name.split(' ')\n if len(splitted) > 1 and len(splitted[0]) <= 4:\n res.append(splitted[0])\n return res",
"def get_emoji_tokens(tokens):\n emoji_tokens = []\n emoji_tokens = emoji_tokens + [term for term in tokens\n if text_has_emoji(term)]\n return emoji_tokens"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Parses out every emoji from the given text. Returns them ordered based on their appearance in the text.
|
def parse_all_emojis_ordered(text):
return _parse_emojis_ordered(text, _iter_parse_all_emojis)
|
[
"def _parse_emojis_ordered(text, parser):\n emojis_ordered = []\n if (text is not None):\n emojis_unique = set()\n \n for emoji in parser(text):\n if emoji not in emojis_unique:\n emojis_ordered.append(emoji)\n emojis_unique.add(emoji)\n \n return emojis_ordered",
"def parse_custom_emojis_ordered(text):\n return _parse_emojis_ordered(text, _iter_parse_custom_emojis)",
"def extract_emoji(text):\n the_emoji = None\n for emoji_type, code_point, emoji_list, name, parent in EMOJIS:\n for emoji in emoji_list:\n if emoji in text:\n the_emoji = emoji_type\n text = re.sub(emoji, ' ', text)\n text, stripped = strip_emojis(text)\n text = re.sub('[ \\t\\r\\n]+', ' ', text)\n return text, the_emoji, stripped",
"def _iter_parse_all_emojis(text):\n for groups in EMOJI_ALL_RP.findall(text):\n \n unicode_value, unicode_name, custom_animated, custom_name, custom_emoji_id = groups\n if unicode_value:\n yield UNICODE_TO_EMOJI[unicode_value]\n continue\n \n if unicode_name:\n yield BUILTIN_EMOJIS[unicode_name]\n continue\n \n yield Emoji._create_partial(\n int(custom_emoji_id),\n custom_name,\n (True if custom_animated else False),\n )\n continue",
"def extract_emojis(text):\n result = re.findall(EMOJI_REGEX, text)\n return result",
"def get_emoji_indices(text: str) -> List[int]:\n pass",
"def parse_custom_emojis(text):\n if text is None:\n return set()\n \n return {*_iter_parse_custom_emojis(text)}",
"def extract_emojis(txt, emoji_list):\n # extract normal unicode emoji\n emojis = list(c for c in txt if c in emoji.UNICODE_EMOJI)\n\n # extract IDs of custom emoji\n emojis += list(re.findall(\"<:[a-zA-Z]+:[0-9]+>\", txt))\n\n return tuple(emojis)",
"def find_unicode_emojis(text):\n emoji_list = []\n data = regex.findall(r\"\\X\", text)\n flags = regex.findall(\"[\\U0001F1E6-\\U0001F1FF]\", text)\n for word in data:\n if any(char in emoji.UNICODE_EMOJI for char in word):\n if word in flags:\n continue\n emoji_list.append(emoji.demojize(word))\n\n for i in range(math.floor(len(flags) / 2)):\n emoji_list.append(\"\".join(emoji.demojize(x) for x in flags[i : i + 2]))\n\n return emoji_list",
"def find_custom_emojis(text):\n emoji_list = []\n data = regex.findall(r\"<(a?):([a-zA-Z0-9\\_]+):([0-9]+)>\", text)\n for a, emoji_name, emoji_id in data:\n emoji_list.append(f\"<{a}:{emoji_name}:{emoji_id}>\")\n\n return emoji_list",
"def parse_reaction(text):\n try:\n emoji = UNICODE_TO_EMOJI[text]\n except KeyError:\n parsed = REACTION_RP.fullmatch(text)\n if parsed is None:\n emoji = None\n else:\n name, emoji_id = parsed.groups()\n emoji_id = int(emoji_id)\n emoji = Emoji._create_partial(emoji_id, name, False)\n \n return emoji",
"def emojis_freq(self, text):\r\n df_emojis = [i for i in text if i in UNICODE_EMOJI]\r\n df_emojis = pd.Series(df_emojis).value_counts()\r\n df_emojis = df_emojis.sort_values(ascending = False)\r\n \r\n return df_emojis",
"def _iter_parse_custom_emojis(text):\n for groups in EMOJI_RP.findall(text):\n \n animated, name, emoji_id = groups\n animated = (True if animated else False)\n emoji_id = int(emoji_id)\n \n yield Emoji._create_partial(emoji_id, name, animated)",
"def normalize_emoji(text):\n # Translate textual smilies to color emoji.\n text = re.sub(TEXT_TO_EMOJI_PATTERN, text_to_emoji_callback, text)\n # Translate hollow smilies to color emoji.\n text = re.sub(WHITE_TO_EMOJI_PATTERN, white_to_emoji_callback, text)\n # Translate text macros to color emoji.\n return emoji.emojize(text, use_aliases=True)",
"def remove_emoji(text):",
"def parse_emoji(text):\n parsed = EMOJI_RP.fullmatch(text)\n if (parsed is not None):\n animated, name, emoji_id = parsed.groups()\n animated = (animated is not None)\n emoji_id = int(emoji_id)\n return Emoji._create_partial(emoji_id, name, animated)\n \n try:\n return UNICODE_TO_EMOJI[text]\n except KeyError:\n pass\n \n if text.startswith(':') and text.endswith(':') and not text.endswith(VARIATION_SELECTOR_16_POSTFIX_WITH_COLON):\n try:\n return BUILTIN_EMOJIS[text[1:-1]]\n except KeyError:\n pass\n \n return None",
"def get_emoji_tokens(tokens):\n emoji_tokens = []\n emoji_tokens = emoji_tokens + [term for term in tokens\n if text_has_emoji(term)]\n return emoji_tokens",
"def __get_emoji_list(name):\n # return re.findall(emoji_codes, name, re.UNICODE)\n res = list()\n splitted = name.split(' ')\n if len(splitted) > 1 and len(splitted[0]) <= 4:\n res.append(splitted[0])\n return res",
"def text_has_emoji(text):\n for character in text:\n if character in emoji.UNICODE_EMOJI:\n return 1\n return 0"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Parses out an emoji from the given reaction string.
|
def parse_reaction(text):
try:
emoji = UNICODE_TO_EMOJI[text]
except KeyError:
parsed = REACTION_RP.fullmatch(text)
if parsed is None:
emoji = None
else:
name, emoji_id = parsed.groups()
emoji_id = int(emoji_id)
emoji = Emoji._create_partial(emoji_id, name, False)
return emoji
|
[
"def parse_emoji(text):\n parsed = EMOJI_RP.fullmatch(text)\n if (parsed is not None):\n animated, name, emoji_id = parsed.groups()\n animated = (animated is not None)\n emoji_id = int(emoji_id)\n return Emoji._create_partial(emoji_id, name, animated)\n \n try:\n return UNICODE_TO_EMOJI[text]\n except KeyError:\n pass\n \n if text.startswith(':') and text.endswith(':') and not text.endswith(VARIATION_SELECTOR_16_POSTFIX_WITH_COLON):\n try:\n return BUILTIN_EMOJIS[text[1:-1]]\n except KeyError:\n pass\n \n return None",
"def extract_emojis(str):\n return ''.join(c for c in str if c in emoji.UNICODE_EMOJI)",
"def extract_emoji(text):\n the_emoji = None\n for emoji_type, code_point, emoji_list, name, parent in EMOJIS:\n for emoji in emoji_list:\n if emoji in text:\n the_emoji = emoji_type\n text = re.sub(emoji, ' ', text)\n text, stripped = strip_emojis(text)\n text = re.sub('[ \\t\\r\\n]+', ' ', text)\n return text, the_emoji, stripped",
"def get_emoji(self, emoji):\n\t\tif emoji == \"?\":\n\t\t\treturn \"\\u2753 \"\n\t\telif emoji == \"i\":\n\t\t\treturn \"\\u2139 \"\n\t\telif emoji == \"ok\":\n\t\t\treturn \"\\u2714 \"\n\t\treturn \"\"",
"def is_emoji(s):\n\treturn s in UNICODE_EMOJI",
"async def add_reaction_to_message(self, ctx, message: discord.Message, emoji):\n try:\n # add initial reaction to the course to make it easier on users to add it\n await message.add_reaction(emoji)\n except discord.InvalidArgument:\n logger.exception(f\"Emoji was not a valid emoji.\")\n except discord.Forbidden:\n logger.exception(\"Forbidden action\")\n except discord.NotFound:\n logger.exception(f\"The requested emoji was not found on the server.\")\n except discord.HTTPException:\n logger.exception(f\"There was an issue with the webserver.\")",
"def normalize_emoji(text):\n # Translate textual smilies to color emoji.\n text = re.sub(TEXT_TO_EMOJI_PATTERN, text_to_emoji_callback, text)\n # Translate hollow smilies to color emoji.\n text = re.sub(WHITE_TO_EMOJI_PATTERN, white_to_emoji_callback, text)\n # Translate text macros to color emoji.\n return emoji.emojize(text, use_aliases=True)",
"def remove_emoji(text):",
"def extract_emojis(txt, emoji_list):\n # extract normal unicode emoji\n emojis = list(c for c in txt if c in emoji.UNICODE_EMOJI)\n\n # extract IDs of custom emoji\n emojis += list(re.findall(\"<:[a-zA-Z]+:[0-9]+>\", txt))\n\n return tuple(emojis)",
"def get_emoji(i):\n if i < 0 or i >= len(map_id_to_emoji):\n raise KeyError('Invalid Emoji ID')\n return map_id_to_emoji[i]",
"def trans_emoji(text):\n def _emoji(matched):\n hex = matched.group(1)\n return ('\\\\U%08x' % int(hex, 16)).decode('unicode-escape').encode('utf-8')\n\n replace_t = re.sub(Constant.REGEX_EMOJI, _emoji, text)\n return replace_t",
"def extract_emojis(text):\n result = re.findall(EMOJI_REGEX, text)\n return result",
"def parse_reaction_added(event):\n reaction = {\n 'reaction': event['reaction'],\n 'channel': event['item']['channel'],\n 'to_id': event['item']['ts'],\n 'type': 'reaction',\n 'user': event['user'],\n 'to_user': event['item_user']\n }\n\n return reaction",
"async def unicode_emoji(self, ctx: Context, emoji: str) -> None:\n\n await ctx.send(f\"`{emoji.encode('unicode-escape').decode('ASCII')}`\")",
"def test_five_emoji(self):\n string = '\\U0001f480\\U0001f60d\\U0001f9a5\\U0001F453\\u3299'\n mirror = Mirror('https://', 'lifehacker.ru', string)\n for _ in range(5):\n for char in string:\n self.assertEqual(mirror.emoji, char)",
"def to_ascii(reaction: discord.Reaction):\n if reaction.emoji not in UNICODE_LETTERS:\n raise ValueError\n\n return string.ascii_lowercase[UNICODE_LETTERS.index(reaction.emoji)]",
"def is_emoji(self):\n if self.token in emoji.UNICODE_EMOJI:\n return [True, '<neutralface>']\n else:\n return [False, None]",
"def text_has_emoji(text):\n for character in text:\n if character in emoji.UNICODE_EMOJI:\n return 1\n return 0",
"def emoji(self):\n role_name = self.name\n\n for db in (SMASH_CHARACTERS, SPANISH_REGIONS, DEFAULT_TIERS):\n if role := db.get(role_name, False):\n return role.get(\"emoji\", \"\")\n \n return \"\""
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Calculates the concentration of DPX at each quenching step.
|
def calc_dpx_concs(dpx_vol_steps, dpx_stock_conc=0.1, starting_well_vol=102.):
# The cumulative volumes of stock DPX added at each step
dpx_vols_added = np.cumsum(dpx_vol_steps)
# The number of points in the standard curve
num_dilutions = len(dpx_vols_added)
dpx_concs = np.zeros(num_dilutions)
# Calculate the concentrations at each quenching step
for i in range(num_dilutions):
total_vol = starting_well_vol + dpx_vols_added[i]
dpx_concs[i] = (dpx_stock_conc * dpx_vols_added[i]) / total_vol
return dpx_concs
|
[
"def concentration_final(self) -> float:\n return self.cell_per_well / (self.volume_per_well / 1000)",
"def _calc_concentration(self):\n total_mol_conc = self._pressure \\\n / (self.gas_constant * self._temperature)\n return self._mole_fraction * total_mol_conc",
"def cdf(self, x) -> float:\n cdf_result = 0\n\n for distribution_amplitude, distribution in zip(self.distribution_amplitudes, self.distributions):\n cdf_result += (distribution_amplitude * distribution.cdf(x))\n\n return cdf_result",
"def cdf(self) -> xr.DataArray:\n if not self._is_memoized('_cdf'):\n # ecfd = sm.distributions.ECDF(self._ds)\n x = np.linspace(min(self._ds), max(self._ds))\n self._cdf = sm.distributions.ECDF(self._ds)(x)\n\n return self._cdf",
"def _calc_concentration(self):\n r_t = self.gas.gas_constant * self._temperature\n total_gas_conc = self._pressure / r_t\n conc = self._mole_fraction * total_gas_conc\n # all_conc = np.copy(conc)\n sat_conc = self.saturation_pressure / r_t\n dry_mole_fraction = np.copy(self.mole_fraction)\n dry_mole_fraction[self.id_pc] = 0.0\n dry_mole_fraction = self._calc_fraction(dry_mole_fraction)\n for i in range(self.n_species):\n if i == self.id_pc:\n conc[self.id_pc] = np.where(conc[self.id_pc] > sat_conc,\n sat_conc, conc[self.id_pc])\n else:\n try:\n conc[i] = \\\n np.where(conc[self.id_pc] > sat_conc,\n (total_gas_conc - sat_conc)\n * dry_mole_fraction[i],\n conc[i])\n except FloatingPointError:\n raise FloatingPointError\n return np.maximum(conc, 0.0)",
"def calculate_concentration_Cs_seed(concentrations_Cs_seed_p):\n return np.sum(concentrations_Cs_seed_p)",
"def getCavityQ(self, double: float) -> float:\n ...",
"def cash(self):\n return self.cents / 100",
"def cdf(self, x):\n\n if x < 0:\n return 0\n\n e = 2.7182818285\n lambtha = self.lambtha\n\n cdf = 1 - (e ** (-1 * lambtha * x))\n\n return cdf",
"def extract_qubit_E_c(qubit: QuDev_transmon) -> float:\n # TODO Implement this method to give a meaningful value! (from the\n # design DB?)\n log.warning(\"Implement the `extract_qubit_E_c()` method to give a\"\n \"meaningful value!\")\n return 165e6",
"def cdf(self, k):\n if not isinstance(k, int):\n k = int(k)\n if k < 0:\n return 0\n # print(self.pmf(k))\n e = 2.7182818285\n const = (e ** (-1 * self.lambtha))\n return self.pmf(k) + self.cdf(k - 1)",
"def CruiseEnergyConsumption(self):\n return ( self.CruiseFuelBurn * \n self.Fuel.lower_heating_value / self.Aircraft['Cruise Speed'] / \n self.Aircraft['Max Seats'] / ureg['passenger'] ).to('kWh/km/passenger')",
"def cdf(x, iterations=300):\r\n product = 1.0\r\n taylor_exp = [x]\r\n for i in range(3, iterations, 2):\r\n product *= i\r\n taylor_exp.append(float(x**i)/product)\r\n taylor_fact = sum(taylor_exp)\r\n\r\n return (0.5 + (taylor_fact * std_normal_pdf.pdf(x, mean=0, std_dev=1)))",
"def CLs(qobs,MAGqA):\n qA = np.abs(MAGqA)\n psb = 1 - rv.cdf(0.5*(qobs + qA)/np.sqrt(qA)) \n pb = rv.cdf(0.5*(qobs - qA)/np.sqrt(qA)) \n return psb/(1-pb)",
"def AggregateDampingDer(self):\n dcda = DcDalpha(self.damp, self.rho)\n\n # zero out the contribution from the zero frequency mode if present\n for i in range(self.freq.size):\n if abs(self.freq[i]) < 1e-7:\n dcda[i] = 0.0\n dcdl = DalphaDlamTrans(dcda, self.lam, self.dt)\n dcdA = DlamDATrans(dcdl, self.W, self.V)\n dcdV1T = dAdV1Trans(dcdA, self.V1T, self.V1inv, self.V2T)\n dcdV2T = dAdV2Trans(dcdA, self.V1inv)\n dcdVhat = dV12dVhatTrans(dcdV1T, dcdV2T)\n dcdY = dVhatdYTrans(dcdVhat, self.U, self.s, self.VT)\n dcdX = dYdXTrans(dcdY)\n dcdx = self.H.T.dot(dcdX)\n\n return dcdx",
"def _concentration(self, mass):\n return self.c0*(mass/self.mass.m_star)**self.beta",
"def test_comp_CDO(self):\n A = 8\n CL = 1\n e = 0.8\n CD = 0.4\n # Got value from a hand computation\n self.assertAlmostEqual(Aircraft.comp_CD0(CL, A, e, CD), 0.3503, places=4)",
"def cdq4(f, x, h=1e-5):\n return (f(x-2*h) - 8*f(x-h) + 8*f(x+h) - f(x+2*h))/(12*h)",
"def cdf(self, x) -> float:\n try:\n index = get_index_in_list_with_bool(self.choice_list, x)\n except ValueError:\n raise ValueError(\n \"Item not found in list. Make sure the item is in the choice list and a correct method __eq__ is defined for all item in the list.\")\n except (NotImplementedError, NotImplemented):\n raise ValueError(\"A correct method for __eq__ should be defined for all item in the list.\")\n except AttributeError:\n raise ValueError(\"choice_list param should be a list.\")\n else:\n probas = np.array(self.probas)\n return np.sum(probas[0:index + 1])"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Calculating the TTA output logits out of the inputs, transforms, to the tta_dir
|
def get_tta_logits(dataset, args, net, X, y, tta_size, num_classes):
tta_transforms = get_tta_transforms(dataset, args.gaussian_std, args.soft_transforms, args.clip_inputs)
tta_dataset = TTADataset(
torch.from_numpy(X),
torch.from_numpy(y),
tta_size,
transform=tta_transforms)
tta_loader = torch.utils.data.DataLoader(
tta_dataset, batch_size=1, shuffle=False,
num_workers=args.num_workers, pin_memory=torch.cuda.is_available())
logger = logging.getLogger()
start = time()
with torch.no_grad():
tta_logits = pytorch_evaluate(net, tta_loader, ['logits'],
(-1,) + tta_dataset.img_shape, {'logits': (-1, tta_size, num_classes)},
verbose=True)[0]
logger.info('Finished running DNN inference to fetch all the TTA logits. It took {} seconds'.format(time() - start))
return tta_logits
|
[
"def transformer(inputs):\n X = inputs\n n_files = X[0]\n total_mb = X[1]\n # apply power transformer normalization to continuous vars\n x = np.array([[n_files], [total_mb]]).reshape(1, -1)\n pt = PowerTransformer(standardize=False)\n pt.lambdas_ = np.array([-1.51, -0.12])\n xt = pt.transform(x)\n # normalization (zero mean, unit variance)\n f_mean, f_sigma = 0.5682815234265285, 0.04222565843608133\n s_mean, s_sigma = 1.6250374589283951, 1.0396138451086632\n x_files = np.round(((xt[0, 0] - f_mean) / f_sigma), 5)\n x_size = np.round(((xt[0, 1] - s_mean) / s_sigma), 5)\n # print(f\"Power Transformed variables: {x_files}, {x_size}\")\n X_values = {\n \"x_files\": x_files,\n \"x_size\": x_size,\n \"drizcorr\": X[2],\n \"pctecorr\": X[3],\n \"crsplit\": X[4],\n \"subarray\": X[5],\n \"detector\": X[6],\n \"dtype\": X[7],\n \"instr\": X[8],\n }\n # X = np.array([x_files, x_size, X[2], X[3], X[4], X[5], X[6], X[7], X[8]])\n return X_values",
"def make_log_outputs(expt_dir, outputs_fname, scaled_psct):\n # load outputs\n outputs = proc.load_outputs(outputs_fname)\n # add scaled pseudocount, log transform outputs\n log_outputs = proc.log_transform_outputs(outputs, scaled_psct)\n # write log transformed pseudocounts\n log_out_fname = expt_dir +\\\n \"/process/log_outputs.scaled_psct_{0}.txt\".format(scaled_psct)\n proc.write_outputs(log_outputs, log_out_fname)",
"def train_output():\n output = [config['out']+\"/{sample}/model.rda\", config['out']+\"/{sample}/variable_importance.tsv\"]\n if check_config('tune'):\n output.append(config['out']+\"/{sample}/tune_matrix.tsv\")\n return output",
"def transform_logits(self, logits):",
"def TAAtoTM(self):\n self.TAA = self.TAA.reshape((6, 1))\n #self.TAA = self.TAA.reshape((6))\n mres = mr.MatrixExp3(mr.VecToso3(self.TAA[3:6].flatten()))\n #return mr.RpToTrans(mres, self.TAA[0:3])\n #self.TAA = self.TAA.reshape((6, 1))\n self.TM = np.vstack((np.hstack((mres, self.TAA[0:3])), np.array([0, 0, 0, 1])))\n #self.AngleMod()\n\n #print(tm)",
"def set_output_dir(self, inputfile):\r\n\t\tprint('******* Output Directory *******')\r\n\t\tif not os.path.exists(inputfile.DirOutput):\r\n\t\t\tos.mkdir(inputfile.DirOutput)\r\n\t\t\tprint(\"Directory \", inputfile.DirOutput, \" Created \")\r\n\t\telse:\r\n\t\t\tprint(\"Directory \", inputfile.DirOutput, \" already exists\")\r\n\t\t\r\n\t\toutput_dir_nc = inputfile.DirOutput+'/TimeFrames'\r\n\t\t\r\n\t\tif not os.path.exists(output_dir_nc):\r\n\t\t\tos.mkdir(output_dir_nc)\r\n\t\t\tprint(\"Directory \", output_dir_nc, \" Created \")\r\n\t\telse:\r\n\t\t\tprint(\"Directory \", output_dir_nc, \" already exists\")\r\n\t\t\r\n\t\t# Output filenames\r\n\t\tself.fnameTS_avg = inputfile.DirOutput+'/' + inputfile.Mname + '_avg'\r\n\t\tself.fnameTS_OF = inputfile.DirOutput+'/' + inputfile.Mname + '_OF_'\r\n\t\tself.fnameTS_UZ = inputfile.DirOutput+'/' + inputfile.Mname + '_UZ_'\r\n\t\tself.fnameTS_GW = inputfile.DirOutput+'/' + inputfile.Mname + '_GW_'",
"def ln_assay_results(assay_file, input_dir):\n assay_results_path = input_dir + assay_file\n assay_results = pd.read_csv(assay_results_path,\n sep='\\t',\n index_col=0,\n header=0,\n na_values = 'nd')\n log_fcs = np.log(assay_results.ix[:,:12])\n log_fcs.to_csv(input_dir + 'assay_results_log.tsv',\n sep='\\t',\n na_rep='NaN')\n\n return log_fcs",
"def conv_corr_to_t(log, workdir, inputf, outname):\n log.info('Doing convert corr to t')\n log.info('work directory: {}'.format(workdir))\n cmd = split(\"3dcalc -a {} -expr 'a / (sqrt(((1-a^2) / (18-2))))' \\\n -prefix {}\".format(inputf, outname))\n log.info('cmd: \\n%s', cmd)\n proc = Popen(cmd, stdout=PIPE, stderr=STDOUT)\n log.info(proc.stdout.read())",
"def TMtoTAA(self):\n rotation, transformation = mr.TransToRp(self.TM)\n rotation_euler = mr.so3ToVec(mr.MatrixLog3(rotation))\n self.TAA = np.vstack((transformation.reshape((3, 1)), (rotation_euler.reshape((3, 1)))))",
"def build_outputs(self):\n with tf.variable_scope(\"build_baseline_outputs\"):\n self.semantic_tgt = self.upsample_semantic(self.pred_semantic_logits_tgt)\n self.depth_tgt = self.prepare_depth(self.pred_disp_tgt[0])\n self.disp_tgt = self.prepare_disp(self.pred_disp_tgt[0])",
"def makeProcessedTFiles(self,analDirPaths=None,updateProcTFilesDic=False):\n # will return this dictionary of analysisDirPath:[TFile1,TFileN... ]:\n allAnalDirs = {}\n \n # if user has provided a string we turn it to a list of length 1\n if isinstance(analDirPaths,str):\n analDirPaths = [analDirPaths]\n \n # if user didn't supply a list of analysis directories to use then\n # we look for any directories with the XFold analysis 'signature' \n # in the parent folder of the xfold\n if not analDirPaths:\n xPath = self.XPath\n xSig = XFold.OutDirSig\n analDirPaths = list(genF.getProcessedDataDs(xPath,xSig))\n \n # loop over all analysis directories\n for adp in analDirPaths:\n # find all tif paths in that directory\n walk = [(dp,fn) for (dp,dn,fn) in os.walk(adp)]\n allTPaths = [os.path.join(dp,f) for (dp,fp) in walk for f in fp]\n allTPaths = [f for f in allTPaths if '.tif' in f]\n allTPaths = [f for f in allTPaths if genF.savedByXFoldQ(f)]\n \n # this sorts the files according to their s and t tags\n # otherwise it would be alphabetical which isn't reliable\n sTagsOfAll = [genF.tagIntFromTifName(tp,'s') for tp in allTPaths]\n tTagsOfAll = [genF.tagIntFromTifName(tp,'t') for tp in allTPaths]\n sortedPaths = sorted(zip(sTagsOfAll,tTagsOfAll,allTPaths))\n allTPaths = [tp for s,t,tp in sortedPaths]\n \n # these contain the lengths of the files for each tag\n # i.e. element with index i in this list = Q_i\n # then files with tag q_000i have Q_i Q-points \n # (t-points/fields etc)\n Tag2FileLengthT = []\n Tag2FileLengthF = []\n Tag2FileLengthM = []\n \n allTFiles = []\n # cycle over all TFilesPaths in the session\n for tf in allTPaths:\n # get the dimensions of the TFile data from the metadata\n with tifffile.TiffFile(tf) as tif:\n try:\n _dims = genF.tif2Dims(tif) \n nt = _dims[0]\n nf = _dims[1]\n nm = _dims[2]\n nz = _dims[3]\n nc = _dims[4]\n except UnknownTifMeta as error:\n errMess = 'Error in makeProcessedTFiles() while '\\\n 'importing metadata from file {file}. '\n print(errMess.format(file=tf),error)\n raise\n \n # get the tag number (as an int) from the file name tags\n TTag = genF.tagIntFromTifName(tf,'t')\n FTag = genF.tagIntFromTifName(tf,'f')\n MTag = genF.tagIntFromTifName(tf,'m')\n \n # update the Tag2Length registers if it's a new tag\n if TTag!=None:\n if TTag+1 > len(Tag2FileLengthT):\n Tag2FileLengthT.append(nt)\n if FTag!=None:\n if FTag+1 > len(Tag2FileLengthF):\n Tag2FileLengthF.append(nf)\n if MTag!=None:\n if MTag+1 > len(Tag2FileLengthM):\n Tag2FileLengthM.append(nm)\n \n # build the SeshQs of this TFile (see TFile for details)\n # they give the real Q-points of the TFile w.r.t to session\n T = [sum(Tag2FileLengthT[:TTag]) + i for i in range(nt)]\n F = [sum(Tag2FileLengthF[:FTag]) + i for i in range(nf)]\n M = [sum(Tag2FileLengthM[:MTag]) + i for i in range(nm)]\n Z = list(range(nz))\n C = list(range(nc))\n \n # this TFile isn't in the Session.TFileList:\n tFileN = None\n \n # find what session it came from\n seshTag = r'_s(\\d+)'\n if re.search(seshTag,tf):\n seshN = int(re.search(seshTag,tf).group(1))\n seshTF = self.SessionsList[seshN]\n else:\n errMess = 'Failed to make processed files dictionary for'\\\n ' xfold because there weren\\'t session tags '\\\n '(e.g. _s0004) on the tiff files names in the '\\\n 'processed data directory {dirc}.'\n raise Exception(errMess.format(dirc=adp))\n \n # add the TFile to our list:\n allTFiles.append(TFile(seshTF,tFileN,tf,T,F,M,Z,C))\n \n # add the new entry of the dictionary\n allAnalDirs.update({adp:allTFiles})\n \n if updateProcTFilesDic:\n self.ProcessedTFilesDic.update(allAnalDirs)\n \n return allAnalDirs",
"def calculate_TEPs(self, pce):\n # Retrieve the mf-indexed arrays.\n # Note these are 1xn_mf, already selected by band id.\n DLBO = self.tof.map_pce(pce).DLBO\n DLBW = self.tof.map_pce(pce).DLBW\n RWS = self.tof.map_pce(pce).RWS\n RWS_T = self.tof.map_pce(pce).RWS_T\n # Retrieve the Rx-indexed arrays.\n TOF = self.tof.map_pce(pce).TOF.all\n tof_flag = self.tof.map_pce(pce).tof_flag\n DeltaTime_ll = self.tod.map_pce(pce).DeltaTime_ll\n\n if self.verbose:\n print(\"pce: \", pce)\n print(\"DLBO: \", len(DLBO), DLBO)\n print(\"DLBW: \", len(DLBW), DLBW)\n print(\"RWS: \", len(RWS), RWS)\n print(\"RWS_T: \", len(RWS_T), RWS_T)\n print(\"TOF: \", len(TOF), TOF)\n print(\"tof_flag: \", len(tof_flag), tof_flag)\n\n # Initialize master ID; this will get indexed down same as TOF,\n # so in the end, I should be able to map directly back to the original\n # ATL01 photons.\n master_ids = np.arange(len(TOF))\n\n # Retrieve the Tx-indexed arrays.\n TX_T_ll = np.nan_to_num(self.tof.map_pce(pce).aligned.TX_T_ll)\n TX_T_other = np.nan_to_num(self.tof.map_pce(pce).aligned.TX_T_other)\n T_center = self.tof.T_center\n\n # Create an array of ints the length of Tx's\n transmits = np.arange(len(TX_T_ll))\n\n # Create an array of ints the length of Rx's, whose values map directly back to transmits.\n receives = self.aligner.maptx2rx(pce=pce, aligned_data=transmits)\n\n # Shift so that no zero values are included.\n nonzeros = np.where(TX_T_ll != 0)[0]\n transmits = transmits[nonzeros]\n\n # Initialize first index of receives.\n start_receive = 0\n\n if self.verbose:\n print(\"len(TX_T_ll): \", len(TX_T_ll))\n print(\"transmits: \", len(transmits), transmits)\n print(\"receives: \", len(receives), receives)\n\n # Find indexes of strong spot returns.\n strong_ind = np.where(self.tof.map_pce(pce).channel < 17)[0]\n # Index receives, TOF, and master_ids to include only strongs.\n strong_receives = receives[strong_ind]\n strong_TOF = TOF[strong_ind]\n strong_master_ids = master_ids[strong_ind]\n\n if self.verbose:\n print(\"strong_TOF: \", len(strong_TOF), strong_TOF)\n print(\"strong_receives: \", len(strong_receives), strong_receives)\n print(\"strong_master_ids: \", len(strong_master_ids), strong_master_ids)\n\n # Need to map RWS and DLBO first from MF to returns.\n RWS_rx = map_mf2rx(RWS, self.atl01_dict[pce].raw_pce_mframe_cnt_ph)\n RWS_T_rx = map_mf2rx(RWS_T, self.atl01_dict[pce].raw_pce_mframe_cnt_ph)\n DLBO_rx = map_mf2rx(DLBO, self.atl01_dict[pce].raw_pce_mframe_cnt_ph)\n DLBW_rx = map_mf2rx(DLBW, self.atl01_dict[pce].raw_pce_mframe_cnt_ph)\n\n # Then map to transmit space.\n RWS_tx = np.nan_to_num(self.aligner.align2timetags(pce, RWS_rx))\n RWS_T_tx = np.nan_to_num(self.aligner.align2timetags(pce, RWS_T_rx))\n DLBO_tx = np.nan_to_num(self.aligner.align2timetags(pce, DLBO_rx))\n DLBW_tx = np.nan_to_num(self.aligner.align2timetags(pce, DLBW_rx))\n\n if self.verbose:\n print(\"RWS_tx: \", len(RWS_tx), RWS_tx)\n print(\"DLBO_tx: \", len(DLBO_tx), DLBO_tx)\n print(\"DLBW_tx: \", len(DLBW_tx), DLBW_tx)\n\n # Initialize output lists and arrays.\n # 'j+N' is the real location of the TEP; j is where is recorded\n TX_CENT_T_j_list = []\n TX_CENT_T_jplusN_list = []\n TX_T_ll_jplusN_list = np.zeros(len(strong_receives))\n TX_T_other_jplusN_list = np.zeros(len(strong_receives))\n Elapsed_T_list = []\n # TOF TEP and N need be length of strong receives.\n N_list = np.zeros(len(strong_receives))\n TOF_TEP = np.zeros(len(strong_receives))\n # And initialize a delta_time list.\n delta_time = np.copy(DeltaTime_ll)\n\n # Calculate equations 4-6 to 4-9 per Tx. Then for each Rx in that\n # Tx, calculate equation 4-10.\n\n # j starts at transmit index of whatever is the first non-zero value\n # from the aligned TX_T_ll. Therefore, all the tx-space arrays that\n # were filled using the 'aligner' object don't need to be filtered\n # to remove pre- and post-pended zeros (which were present so that\n # arrays are same size across PCEs).\n for j in transmits:\n\n ## This should only be done for the first event in MF?\n RWS_j = RWS_tx[j]\n RWS_T_j = RWS_T_tx[j]\n DLBO_j = DLBO_tx[j]\n DLBW_j = DLBW_tx[j]\n\n # Determine N, the integer value that indicates there may\n # be a TE return in the down link band.\n # N is calculated once per major frame.\n N0, N1 = self.N(RWS_j, DLBO_j, DLBW_j) \n\n if (N0 == N1) and ((N0+j) < len(transmits)):\n\n N = N0\n\n # Equation 4-7\n TX_CENT_T_j = (TX_T_ll[j] + T_center[j]) \n\n # Equation 4-8\n TX_CENT_T_jplusN = (TX_T_ll[j+N] + T_center[j+N])\n\n # Return and the one it was improperly associated with.\n Elapsed_T = self.Elapsed_T(N)\n\n # Count how many Rx's are in the jth Tx.\n receives_in_transmit = (strong_receives == j).sum()\n\n if self.very_verbose:\n print(\"N: {}, j: {}\".format(N,j))\n print(\"TX_T_ll[j]: \", TX_T_ll[j])\n print(\"T_center[j]: \", T_center[j])\n print(\"TX_CENT_T_j: \", TX_CENT_T_j)\n print(\"TX_T_ll[j+N]: \", TX_T_ll[j+N])\n print(\"T_center[j+N]: \", T_center[j+N])\n print(\"TX_CENT_T_jplusN: \", TX_CENT_T_jplusN)\n print(\"Elapsed_T: \", Elapsed_T)\n print(\"start_receive: {}, receives_in_transmit: {}\"\\\n .format(start_receive, receives_in_transmit))\n\n # Equation 4-10.\n # Index over all Rx's in the jth Tx to calculate TEP TOF.\n TOF_TEP[start_receive:start_receive+receives_in_transmit] = \\\n strong_TOF[start_receive:start_receive+receives_in_transmit] - \\\n (TX_CENT_T_jplusN - TX_CENT_T_j) - Elapsed_T\n\n # Likewise index N_list, TX_T_ll_jplusN, and TX_T_other_jplusN, \n # for record-keeping's sake.\n N_list[start_receive:start_receive+receives_in_transmit] = N\n TX_T_ll_jplusN_list[start_receive:start_receive+receives_in_transmit] = TX_T_ll[j+N]\n TX_T_other_jplusN_list[start_receive:start_receive+receives_in_transmit] = TX_T_other[j+N]\n\n # Add the MF-specific RWS to the delta_time.\n delta_time[start_receive:start_receive+receives_in_transmit] += RWS_T_j\n\n # Increment the start receive so it will fall at the next transmit.\n start_receive += receives_in_transmit\n\n # Append intermediate-value lists.\n TX_CENT_T_j_list.append(TX_CENT_T_j)\n TX_CENT_T_jplusN_list.append(TX_CENT_T_jplusN)\n\n Elapsed_T_list.append(Elapsed_T)\n\n else:\n # End the loop.\n N_list[start_receive:] = N\n TX_T_ll_jplusN_list[start_receive:] = TX_T_ll[j+N]\n TX_T_other_jplusN_list[start_receive:] = TX_T_other[j+N]\n delta_time[start_receive:] += RWS_T_j\n\n # Filter so only include values between 0 and 100 ns.\n filtered_ind = self.filter_indices(TOF_TEP)\n filtered_TOF_TEP = self.__filter(TOF_TEP, filtered_ind)\n if self.verbose:\n print(\"filtered_ind: \", len(filtered_ind), filtered_ind)\n print(\"filtered_TOF_TEP: \", len(filtered_TOF_TEP), filtered_TOF_TEP)\n\n # Filter remainder of receive arrays so same shape.\n filtered_N = self.__filter(N_list, filtered_ind)\n filtered_master_ids = self.__filter(strong_master_ids, filtered_ind)\n filtered_delta_time = self.__filter(delta_time, filtered_ind)\n filtered_TX_T_ll_jplusN = self.__filter(TX_T_ll_jplusN_list, filtered_ind)\n filtered_TX_T_other_jplusN = self.__filter(TX_T_other_jplusN_list, filtered_ind)\n if self.verbose:\n print(\"filtered_N: \", len(filtered_N), filtered_N)\n print(\"filtered_master_ids: \", len(filtered_master_ids), filtered_master_ids)\n print(\"filtered_delta_times: \", len(filtered_delta_time), filtered_delta_time)\n print(\"filtered_TX_T_ll_jplusN: \", len(filtered_TX_T_ll_jplusN), filtered_TX_T_ll_jplusN)\n print(\"filtered_TX_T_other_jplusN: \", len(filtered_TX_T_other_jplusN), filtered_TX_T_other_jplusN)\n\n # To filter the aligned-transmit arrays, need first fill them out to\n # receive space. \n TX_T_ll_rx = self.aligner.maptx2rx(pce, TX_T_ll) \n TX_T_other_rx = self.aligner.maptx2rx(pce, TX_T_other)\n if self.verbose:\n print(\"TX_T_ll_rx: \", len(TX_T_ll_rx), TX_T_ll_rx)\n print(\"TX_T_other_rx: \", len(TX_T_other_rx), TX_T_other_rx)\n # Then index down to strong-only receives.\n TX_T_ll_rx_strong = TX_T_ll_rx[strong_ind]\n TX_T_other_rx_strong = TX_T_other_rx[strong_ind]\n if self.verbose:\n print(\"TX_T_ll_rx_strong: \", len(TX_T_ll_rx_strong), TX_T_ll_rx_strong)\n print(\"TX_T_other_rx_strong: \", len(TX_T_other_rx_strong), TX_T_other_rx_strong)\n # Finally filter them.\n filtered_TX_T_ll = self.__filter(TX_T_ll_rx_strong, filtered_ind)\n filtered_TX_T_other = self.__filter(TX_T_other_rx_strong, filtered_ind)\n if self.verbose:\n print(\"filtered_TX_T_ll\", len(filtered_TX_T_ll), filtered_TX_T_ll)\n print(\"filtered_TX_T_other\", len(filtered_TX_T_other), filtered_TX_T_other)\n\n # Update the tof_flag.\n print(\"master_ids: \", len(master_ids), master_ids)\n print(\"strong_ind: \", len(strong_ind), strong_ind)\n print(\"filtered_ind: \", len(filtered_ind), filtered_ind)\n tep_ids = strong_ind[filtered_ind]\n print(\"tep_ids = strong_ind[filtered_ind]: \", len(tep_ids), tep_ids)\n filtered_tof_flag = np.copy(tof_flag)\n filtered_tof_flag[tep_ids] += 10\n print(\"filtered_tof_flag: \", len(filtered_tof_flag), filtered_tof_flag)\n # strong_ids, strong_arr, rx_arr\n tof_flag = map_tep2rx(tep_ids=tep_ids, tep_arr=filtered_tof_flag[tep_ids], rx_arr=tof_flag)\n print(\"tof_flag: \", len(tof_flag), tof_flag)\n\n # Store values for return.\n pce_variables = PCEVariables(\n TX_CENT_T_j = np.array(TX_CENT_T_j_list),\n TX_CENT_T_jplusN = np.array(TX_CENT_T_jplusN_list),\n TX_T_ll_jplusN = np.array(TX_T_ll_jplusN_list),\n TX_T_other_jplusN = np.array(TX_T_other_jplusN_list),\n N = N_list,\n TX_T_ll=TX_T_ll_rx_strong,\n TX_T_other=TX_T_other_rx_strong,\n Elapsed_T = np.array(Elapsed_T_list),\n TOF_TEP = np.array(TOF_TEP, dtype=np.float64),\n delta_time = np.array(delta_time, dtype=np.float64),\n master_ids = strong_master_ids,\n tof_flag = tof_flag,\n filtered_TOF_TEP = np.array(filtered_TOF_TEP, dtype=np.float64),\n filtered_N = np.array(filtered_N),\n filtered_delta_time = np.array(filtered_delta_time, dtype=np.float64),\n filtered_TX_T_ll = np.array(filtered_TX_T_ll, dtype=np.float64),\n filtered_TX_T_other = np.array(filtered_TX_T_other, dtype=np.float64),\n filtered_TX_T_ll_jplusN = np.array(filtered_TX_T_ll_jplusN, dtype=np.float64),\n filtered_TX_T_other_jplusN = np.array(filtered_TX_T_other_jplusN, dtype=np.float64),\n filtered_master_ids = filtered_master_ids,\n filtered_tof_flag = filtered_tof_flag)\n\n return pce_variables",
"def makeProcessedTFiles(self,analDirPaths=None,updateProcTFilesDic=False): \n # processed tifs belonging to this session will have this tag\n seshTag = '_s' + str(self.SessionN).zfill(4)\n \n # will return this dictionary of analysisDirPath:[TFile1,TFileN... ]:\n allAnalDirs = {}\n \n # if user has provided a string we turn it to a list of length 1\n if isinstance(analDirPaths,str):\n analDirPaths = [analDirPaths]\n \n # if user didn't supply a list of analysis directories to use then\n # we look for any directories with the XFold analysis 'signature' \n # in the parent folder of the xfold\n if not analDirPaths:\n xPath = self.ParentXFold.XPath\n xSig = XFold.OutDirSig\n analDirPaths = list(genF.getProcessedDataDs(xPath,xSig))\n \n # loop over all analysis directories\n for adp in analDirPaths:\n # find all tif paths in that directory\n walk = [(dp,fn) for (dp,dn,fn) in os.walk(adp)]\n allTPaths = [os.path.join(dp,f) for (dp,fp) in walk for f in fp]\n allTPaths = [f for f in allTPaths if '.tif' in f]\n # filter for only sessions corresponding to this one\n allTPaths = [f for f in allTPaths if seshTag in f]\n \n # these contain the lengths of the files for each tag\n # i.e. element with index i in this list = Q_i\n # then files with tag q_000i have Q_i Q-points \n # (t-points/fields etc)\n Tag2FileLengthT = []\n Tag2FileLengthF = []\n Tag2FileLengthM = []\n \n allTFiles = []\n # cycle over all TFilesPaths in the session\n for tf in allTPaths:\n # get the dimensions of the TFile data from the metadata\n with tifffile.TiffFile(tf) as tif:\n try:\n _dims = genF.tif2Dims(tif) \n nt = _dims[0]\n nf = _dims[1]\n nm = _dims[2]\n nz = _dims[3]\n nc = _dims[4]\n except UnknownTifMeta as error:\n errMess = 'Error in makeProcessedTFiles() while '\\\n 'importing metadata from file {file}. '\n print(errMess.format(file=tf),error)\n raise\n \n # get the tag number (as an int) from the file name tags\n TTag = genF.tagIntFromTifName(tf,'t')\n FTag = genF.tagIntFromTifName(tf,'f')\n MTag = genF.tagIntFromTifName(tf,'m')\n \n # update the Tag2Length registers if it's a new tag\n if TTag!=None:\n if TTag+1 > len(Tag2FileLengthT):\n Tag2FileLengthT.append(nt)\n if FTag!=None:\n if FTag+1 > len(Tag2FileLengthF):\n Tag2FileLengthF.append(nf)\n if MTag!=None:\n if MTag+1 > len(Tag2FileLengthM):\n Tag2FileLengthM.append(nm)\n \n # build the SeshQs of this TFile (see TFile for details)\n # they give the real Q-points of the TFile w.r.t to session\n T = [sum(Tag2FileLengthT[:TTag]) + i for i in range(nt)]\n F = [sum(Tag2FileLengthF[:FTag]) + i for i in range(nf)]\n M = [sum(Tag2FileLengthM[:MTag]) + i for i in range(nm)]\n Z = list(range(nz))\n C = list(range(nc))\n \n # this TFile isn't in the Session.TFileList:\n tFileN = None\n \n # add the TFile to our list:\n allTFiles.append(TFile(self,tFileN,tf,T,F,M,Z,C))\n \n # add the new entry of the dictionary\n allAnalDirs.update({adp:allTFiles})\n \n if updateProcTFilesDic:\n self.ProcessedTFilesDic.update(allAnalDirs)\n \n return allAnalDirs",
"def get_t_out(self):\n E1, E2 = self.eccentric_anomalies()\n M1 = E1 - self.eccentricity * np.sin(E1)\n # t - tau = time since/until first pericenter passage = t_now\n t_now = M1 / np.sqrt((self.G * self.Mass1_scaled) / self.semi_major_axis**3)\n print(\"tnow:\" + str(t_now.to(u.Gyr)))\n print(\"\")\n # desired time - current time = run time\n # if current time is negative it is additive\n t_since_passage_obs = (self.time).to(u.s)\n t_out = + t_since_passage_obs - (t_now).to(u.s)\n\n return t_out",
"def ctc_align_targets(outputs,targets,threshold=100.0,verbose=0,debug=0,lo=1e-5):\n\n outputs = np.maximum(lo,outputs)\n outputs = outputs * 1.0/np.sum(outputs,axis=1)[:,np.newaxis]\n\n # first, we compute the match between the outputs and the targets\n # and put the result in the log domain\n match = np.dot(outputs,targets.T)\n lmatch = np.log(match)\n\n if debug:\n import matplotlib.pyplot as plt\n plt.figure(\"ctcalign\"); plt.clf();\n plt.subplot(411); plt.imshow(outputs.T,interpolation='nearest',cmap=plt.cm.hot)\n plt.subplot(412); plt.imshow(lmatch.T,interpolation='nearest',cmap=plt.cm.hot)\n assert not np.isnan(lmatch).any()\n\n # Now, we compute a forward-backward algorithm over the matches between\n # the input and the output states.\n both = forwardbackward(lmatch)\n\n # We need posterior probabilities for the states, so we need to normalize\n # the output. Instead of keeping track of the normalization\n # factors, we just normalize the posterior distribution directly.\n epath = np.exp(both-np.amax(both))\n l = np.sum(epath,axis=0)[np.newaxis,:]\n epath /= np.where(l==0.0,1e-9,l)\n\n # The previous computation gives us an alignment between input time\n # and output sequence position as posteriors over states.\n # However, we actually want the posterior probability distribution over\n # output classes at each time step. This dot product gives\n # us that result. We renormalize again afterwards.\n aligned = np.maximum(lo,np.dot(epath,targets))\n l = np.sum(aligned,axis=1)[:,np.newaxis]\n aligned /= np.where(l==0.0,1e-9,l)\n\n if debug:\n plt.subplot(413); plt.imshow(epath.T,cmap=plt.cm.hot,interpolation='nearest')\n plt.subplot(414); plt.imshow(aligned.T,cmap=plt.cm.hot,interpolation='nearest')\n plt.ginput(1,0.01);\n return aligned",
"def io(self, inputs): \n\n yout, _, xout = lsim(self.current_mode, U=[self.last_input, inputs], T=[self.t, self.t+self.dt], X0=self.state)\n self.last_input = inputs[-1]\n self.t += self.dt\n self.state = xout[-1]\n self.yout = yout[-1]\n self.last_input = inputs\n self.track_out.append(self.yout)\n\n return self.yout",
"def setup_timeseries_outputs(self, phase):\n pass",
"def transformLogarithm(pT):\n return _almathswig.transformLogarithm(pT)",
"def trajs_to_tracked_mat_directory(\n directory_with_traj_files,\n out_dir=None,\n matlabexec = '/Applications/MATLAB_R2014b.app/bin/matlab',\n run_conversion=True,\n):\n\n # Get all *.trajs files in this directory\n traj_files = glob(\"%s/*.trajs\" % directory_with_traj_files)\n\n # Specify output directory\n if out_dir is None:\n out_dir = directory_with_traj_files\n\n # Create output directory, if doesn't exist\n if not os.path.isdir(out_dir):\n os.mkdir(out_dir)\n\n # Run on every individual *.trajs file\n for traj_file_idx, traj_file in tqdm(enumerate(traj_files)):\n\n # Generate output file name\n out_tracked_mat = '%s/%s' % (\n out_dir, os.path.basename(traj_file).replace('.trajs', '_Tracked.mat')\n )\n\n # Save to that file name\n trajs_to_tracked_mat(\n traj_file,\n out_tracked_mat,\n )\n\n # Do hard file conversion from within MATLAB. \n # this requires a little trickery (aka bullshit)\n if run_conversion:\n import imp \n curr_dir = os.getcwd()\n os.chdir(out_dir)\n convert_trajs_to_mat_path = '%s/convert_trajs_to_mat.m' % imp.find_module('pyspaz')[1]\n os.system('cp %s convert_trajs_to_mat.m' % convert_trajs_to_mat_path)\n os.system('%s -r -nodesktop -nosplash -nodisplay convert_trajs_to_mat' % matlabexec)\n os.chdir(curr_dir)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Ensures that useless nodes are forbidden.
|
def test_useless_nodes(
assert_errors,
parse_ast_tree,
code,
statement,
default_options,
mode,
):
tree = parse_ast_tree(mode(code.format(statement)))
visitor = StatementsWithBodiesVisitor(default_options, tree=tree)
visitor.run()
assert_errors(visitor, [UselessNodeViolation])
|
[
"def test_useless_try_nodes(\n assert_errors,\n assert_error_text,\n parse_ast_tree,\n code,\n statement,\n default_options,\n mode,\n):\n tree = parse_ast_tree(mode(code.format(statement)))\n\n visitor = StatementsWithBodiesVisitor(default_options, tree=tree)\n visitor.run()\n\n assert_errors(visitor, [UselessNodeViolation])\n assert_error_text(visitor, 'try')",
"def susceptible(self):\r\n self.state = NodeState.SUSCEPTIBLE",
"def remove_unreachable_nodes(graph):\n\n for node in graph.nodes():\n if all(graph.edge_weight((node, other)) == 0 for other in graph.neighbors(node)):\n graph.del_node(node)",
"def testInactivatedNodesReallyUseless(self):\n\t\ti_nodes = self.som_hands.activation_response(self.som_hands.data)\n\t\tidx_inact = np.where(i_nodes.flatten()==0)[0]\n\t\t_, w = self.som_hands.get_weights()\n\t\t\n\t\tact = np.setdiff1d(np.arange(w.shape[0]), idx_inact)\t\t\n\t\ti_w = w[idx_inact, :]\n\t\ta_w = w[act, :]\n\n\t\tfor i, dp in enumerate(self.som_hands.data):\n\t\t\ts, _ = get_similar_vector(w, dp)\n\t\t\t\n\t\t\t# make sure the closest vector is not in i_w\n\t\t\t# too many for loops here.. ugly!\n\t\t\t_, qi, _ = get_similar_vector(i_w, s[0])\n\t\t\t_, qa, _ = get_similar_vector(a_w, s[0])\n\t\t\tself.assertGreater(qi[0], qa[0])",
"def remove_useless_nodes(self):\n if isinstance(self.elements, dict):\n useful_node_ids = np.unique(np.concatenate([\n np.ravel(v.data) for v in self.elements.values()]))\n else:\n useful_node_ids = np.unique(self.elements.data)\n original_sorted_indices = np.argsort(self.nodes.ids)\n original_node_ids = self.nodes.ids[original_sorted_indices]\n if len(original_node_ids) == len(useful_node_ids):\n if np.all(useful_node_ids == original_node_ids):\n return\n else:\n raise ValueError('Node IDs are inconsistent with elements')\n print('Nodes not used in elements found. Removing.')\n\n filter_useful_nodes = np.ones(len(original_node_ids), dtype=bool)\n original_node_index = 0\n useful_node_index = 0\n while useful_node_index < len(useful_node_ids):\n if original_node_ids[original_node_index] != useful_node_ids[\n useful_node_index]:\n filter_useful_nodes[original_node_index] = False\n original_node_index += 1\n continue\n\n original_node_index += 1\n useful_node_index += 1\n filter_useful_nodes[original_node_index:] = False\n useful_indices = original_sorted_indices[filter_useful_nodes]\n\n # Overwrite data\n self.nodes = FEMAttribute(\n self.nodes.name, self.nodes.ids[useful_indices],\n self.nodes.data[useful_indices])\n for key, value in self.nodal_data.items():\n self.nodal_data[key] = FEMAttribute(\n value.name, self.nodes.ids, value.data[useful_indices])\n return",
"def _mark_nodes_as_dead(self):\n for node in self._nodes.itervalues():\n node.status = NodeStatus.DEAD",
"def set_forbidden_edges(self, edges):\n self.forbidden_edges = edges",
"def prune_orphaned_nodes(nx_graph): \n\n # Search through graph for every node w/ degree\n unconnected_nodes = [node for node,deg in nx_graph.degree_iter() if deg<1 ]\n \n nx_graph.remove_nodes_from(unconnected_nodes)\n \n return nx_graph",
"def removeUnusedEdges():\n\n mod = False\n for e in graphEdges.keys(): # use key as iterator so we can modify the dict\n if graphEdges[e].amount <= 0:\n del graphEdges[e]\n mod = True\n return mod",
"def _is_unused(self, path):\n for node in path:\n if node.ns.fingerprint in self._nodes_processing:\n return False\n return True",
"def protect_busy_nodes(username, password, url):\n\n global was_building # global because we are using it to persist the state of nodes across separate function calls\n # normal Jenkins API doesn't work https://bugs.launchpad.net/python-jenkins/+bug/1787430\n response = requests.get(\"{}/computer/api/json?tree=computer[idle,displayName]\".format(url), auth=(username, password)).json()\n nodes = [node for node in response['computer'] if node['displayName'] != 'master']\n for node in nodes:\n idle = node['idle']\n if not idle:\n print(json.dumps({\"message\": \"node is building\", \"node\": node['displayName']}))\n if was_building.get(node['displayName'], False) == False:\n print(json.dumps({\"message\": \"protecting node\", \"node\": node['displayName']}))\n set_protection_from_displayname(node['displayName'], True)\n was_building[node['displayName']] = True\n else:\n print(json.dumps({\"message\": \"node is not building\", \"node\": node['displayName']}))\n if was_building.get(node['displayName'], False) == True:\n print(json.dumps({\"message\": \"unprotecting node\", \"node\": node['displayName']}))\n set_protection_from_displayname(node['displayName'], False)\n was_building[node['displayName']] = False",
"def noWordLadders(G):\r\n for n in G.nodes:\r\n if G.degree(n) == 0:\r\n yield n",
"def test_useless_loop_nodes(\n assert_errors,\n parse_ast_tree,\n code,\n statement,\n default_options,\n mode,\n):\n tree = parse_ast_tree(mode(code.format(statement)))\n\n visitor = StatementsWithBodiesVisitor(default_options, tree=tree)\n visitor.run()\n\n assert_errors(visitor, [UselessNodeViolation])",
"def cleanNodes() :\n\tfrom tool.utils import mayaTools \n\treload(mayaTools)\n\n\tmayaTools.cleanDefaultRenderLayer()\n\tmayaTools.cleanTurtleRender()\n\tmayaTools.cleanUnKnownNode()",
"def _dead_nodes(self):\n nodes = self.dsm.allDataSets()\n outputs = [n for n in nodes if n.isSmvOutput()]\n in_flow = set([n for o in outputs for n in self._ds_ancestors(o)])\n return [n for n in nodes if n not in in_flow and n not in outputs]",
"def keepUnknownNodes(self, flag: 'SbBool') -> \"void\":\n return _coin.SoToVRMLAction_keepUnknownNodes(self, flag)",
"def _detect_illegal_cycles(node: NodeBase, visited_nodes: List[NodeBase], low_priority_edge_found: bool = False):\n if node in visited_nodes:\n if low_priority_edge_found:\n return\n else:\n raise IllegalCycleException(visited_nodes)\n\n visited_nodes.append(node)\n for block in node.outputs:\n for connection in block.connections:\n _detect_illegal_cycles(connection.target.owner, list(visited_nodes),\n low_priority_edge_found or connection.is_backward)",
"def dangerously_suppress_transaction_safety_checks():\n with _transaction_policy('ts-enforce-none'):\n yield",
"def empty_safe_curie(node, options, state) :\n\tdef prune_safe_curie(node,name) :\n\t\tif node.hasAttribute(name) :\n\t\t\tav = node.getAttribute(name)\n\t\t\tif av == '[]' :\n\t\t\t\tnode.removeAttribute(name)\n\t\t\t\tnode.setAttribute(name+'_pruned','')\n\t\t\t\tmsg = \"Attribute @%s uses an empty safe CURIE; the attribute is ignored\" % name\n\t\t\t\toptions.add_warning(msg, node=node)\n\n\tprune_safe_curie(node, \"about\")\n\tprune_safe_curie(node, \"resource\")\n\tfor n in node.childNodes :\n\t\tif n.nodeType == node.ELEMENT_NODE :\n\t\t\tempty_safe_curie(n, options, state)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Ensures that useless loop nodes are forbidden.
|
def test_useless_loop_nodes(
assert_errors,
parse_ast_tree,
code,
statement,
default_options,
mode,
):
tree = parse_ast_tree(mode(code.format(statement)))
visitor = StatementsWithBodiesVisitor(default_options, tree=tree)
visitor.run()
assert_errors(visitor, [UselessNodeViolation])
|
[
"def test_useless_nodes(\n assert_errors,\n parse_ast_tree,\n code,\n statement,\n default_options,\n mode,\n):\n tree = parse_ast_tree(mode(code.format(statement)))\n\n visitor = StatementsWithBodiesVisitor(default_options, tree=tree)\n visitor.run()\n\n assert_errors(visitor, [UselessNodeViolation])",
"def test_useless_try_nodes(\n assert_errors,\n assert_error_text,\n parse_ast_tree,\n code,\n statement,\n default_options,\n mode,\n):\n tree = parse_ast_tree(mode(code.format(statement)))\n\n visitor = StatementsWithBodiesVisitor(default_options, tree=tree)\n visitor.run()\n\n assert_errors(visitor, [UselessNodeViolation])\n assert_error_text(visitor, 'try')",
"def _detect_illegal_cycles(node: NodeBase, visited_nodes: List[NodeBase], low_priority_edge_found: bool = False):\n if node in visited_nodes:\n if low_priority_edge_found:\n return\n else:\n raise IllegalCycleException(visited_nodes)\n\n visited_nodes.append(node)\n for block in node.outputs:\n for connection in block.connections:\n _detect_illegal_cycles(connection.target.owner, list(visited_nodes),\n low_priority_edge_found or connection.is_backward)",
"def noWordLadders(G):\r\n for n in G.nodes:\r\n if G.degree(n) == 0:\r\n yield n",
"def test_correct_sync_for_loop(\n assert_errors,\n parse_ast_tree,\n code,\n template,\n default_options,\n):\n tree = parse_ast_tree(template.format(code))\n\n visitor = WrongLoopDefinitionVisitor(default_options, tree=tree)\n visitor.run()\n\n assert_errors(visitor, [])",
"def test_correct_for_loop(\n assert_errors,\n parse_ast_tree,\n code,\n template,\n default_options,\n mode,\n):\n tree = parse_ast_tree(mode(template.format(code)))\n\n visitor = WrongLoopDefinitionVisitor(default_options, tree=tree)\n visitor.run()\n\n assert_errors(visitor, [])",
"def tricky_bad_cycle():\n nodes = _create_graph(n_nodes=4, connections=[((0, 0), (1, 0)),\n ((1, 0), (2, 0)),\n ((2, 0), (3, 0)),\n ((3, 0), (1, 1))], low_priority=[True, False, False, False])\n\n with pytest.raises(IllegalCycleException):\n order_nodes(nodes)",
"def _mark_nodes_as_dead(self):\n for node in self._nodes.itervalues():\n node.status = NodeStatus.DEAD",
"def remove_self_loops(self):\n not_self_loops = self.connection_graph[0][0] != self.connection_graph[0][1]\n return Graph(self.take_connections(not_self_loops))",
"def remove_unreachable_nodes(graph):\n\n for node in graph.nodes():\n if all(graph.edge_weight((node, other)) == 0 for other in graph.neighbors(node)):\n graph.del_node(node)",
"def miss_check_3():\n valid_read = cpu_wbs.cyc_i and cpu_wbs.stb_i and not cpu_wbs.we_i\n miss.next = miss_w_and and valid_read and not invalidate",
"def _del_selfloops(self):\n for key in self.graph:\n # while key in self.graph[key]:\n # self.graph[key].remove(key)\n self.graph[key] = [value for value in self.graph[key] if value != key]",
"def _dead_nodes(self):\n nodes = self.dsm.allDataSets()\n outputs = [n for n in nodes if n.isSmvOutput()]\n in_flow = set([n for o in outputs for n in self._ds_ancestors(o)])\n return [n for n in nodes if n not in in_flow and n not in outputs]",
"def check_nocycles(Adj: np.ndarray, verbosity: int = 2) -> bool:\n dim = Adj.shape[0]\n for g in range(dim):\n v = np.zeros(dim)\n v[g] = 1\n for i in range(dim):\n v = Adj.dot(v)\n if v[g] > 1e-10:\n if verbosity > 2:\n settings.m(0, Adj)\n settings.m(\n 0,\n 'contains a cycle of length',\n i + 1,\n 'starting from node',\n g,\n '-> reject',\n )\n return False\n return True",
"def susceptible(self):\r\n self.state = NodeState.SUSCEPTIBLE",
"def check_distance_of_loops(self) -> None:\n for bed in self.bed_loops:\n for needle, needle_loops in enumerate(bed):\n for loop in needle_loops:\n if self.course - loop.src_course >= MAX_LOOP_HOLD_WARN_THRESH:\n self.create_problem(LoopHoldWarning(self.course, needle))\n if self.course - loop.src_course >= MAX_LOOP_HOLD_ERR_THRESH:\n self.create_problem(LoopHoldError(self.course, needle))",
"def is_self_loop(self):\n return torch.all(self.connection_graph[0][0] != self.connection_graph[0][1])",
"def disable():\n global ideep_enabled\n old = ideep_enabled\n ideep_enabled = False\n try:\n yield\n finally:\n ideep_enabled = old",
"def visit_While(self, node):\n raise ScriptSyntaxError('while statements are not allowed')"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Ensures that useless try nodes are forbidden.
|
def test_useless_try_nodes(
assert_errors,
assert_error_text,
parse_ast_tree,
code,
statement,
default_options,
mode,
):
tree = parse_ast_tree(mode(code.format(statement)))
visitor = StatementsWithBodiesVisitor(default_options, tree=tree)
visitor.run()
assert_errors(visitor, [UselessNodeViolation])
assert_error_text(visitor, 'try')
|
[
"def susceptible(self):\r\n self.state = NodeState.SUSCEPTIBLE",
"def _detect_illegal_cycles(node: NodeBase, visited_nodes: List[NodeBase], low_priority_edge_found: bool = False):\n if node in visited_nodes:\n if low_priority_edge_found:\n return\n else:\n raise IllegalCycleException(visited_nodes)\n\n visited_nodes.append(node)\n for block in node.outputs:\n for connection in block.connections:\n _detect_illegal_cycles(connection.target.owner, list(visited_nodes),\n low_priority_edge_found or connection.is_backward)",
"def _mark_nodes_as_dead(self):\n for node in self._nodes.itervalues():\n node.status = NodeStatus.DEAD",
"def remove_unreachable_nodes(graph):\n\n for node in graph.nodes():\n if all(graph.edge_weight((node, other)) == 0 for other in graph.neighbors(node)):\n graph.del_node(node)",
"def testUntrustedBlockableWithImproperGlobalWhitelistRules(self):\n santa_blockable = test_utils.CreateSantaBlockable()\n santa_blockable.state = constants.STATE.UNTRUSTED\n santa_blockable.put()\n\n test_rule = rule_models.SantaRule(\n parent=santa_blockable.key,\n rule_type=constants.RULE_TYPE.BINARY,\n policy=constants.RULE_POLICY.WHITELIST,\n in_effect=True)\n test_rule.put()\n\n ballot_box = api.SantaBallotBox(santa_blockable.key.id())\n ballot_box.blockable = santa_blockable\n\n ballot_box._CheckRules()\n\n rule_query = rule_models.SantaRule.query()\n\n self.assertEqual(rule_query.count(), 1)\n\n rule = rule_query.get()\n\n self.assertFalse(rule.in_effect)",
"def dangerously_suppress_transaction_safety_checks():\n with _transaction_policy('ts-enforce-none'):\n yield",
"def protect_busy_nodes(username, password, url):\n\n global was_building # global because we are using it to persist the state of nodes across separate function calls\n # normal Jenkins API doesn't work https://bugs.launchpad.net/python-jenkins/+bug/1787430\n response = requests.get(\"{}/computer/api/json?tree=computer[idle,displayName]\".format(url), auth=(username, password)).json()\n nodes = [node for node in response['computer'] if node['displayName'] != 'master']\n for node in nodes:\n idle = node['idle']\n if not idle:\n print(json.dumps({\"message\": \"node is building\", \"node\": node['displayName']}))\n if was_building.get(node['displayName'], False) == False:\n print(json.dumps({\"message\": \"protecting node\", \"node\": node['displayName']}))\n set_protection_from_displayname(node['displayName'], True)\n was_building[node['displayName']] = True\n else:\n print(json.dumps({\"message\": \"node is not building\", \"node\": node['displayName']}))\n if was_building.get(node['displayName'], False) == True:\n print(json.dumps({\"message\": \"unprotecting node\", \"node\": node['displayName']}))\n set_protection_from_displayname(node['displayName'], False)\n was_building[node['displayName']] = False",
"def filter_permit_warnings(self):\n with warnings.catch_warnings():\n \n warnings.filterwarnings(\n 'ignore', message='Collecting projections with shutters closed.')\n warnings.filterwarnings(\n 'ignore', message='Shutters not closed because TXM does not have permit')\n warnings.filterwarnings(\n 'ignore', message='Could not cast 32ida:BraggEAO.VAL = None')\n yield",
"def testTryNoContent(self):\n data_in = {'indent': 0, 'body': 'try:', 'filename': '', 'line': 0}\n res = TryToken.make(data_in)\n self.assertTrue(res)\n self.assertFalse(res.content)",
"def test_useless_nodes(\n assert_errors,\n parse_ast_tree,\n code,\n statement,\n default_options,\n mode,\n):\n tree = parse_ast_tree(mode(code.format(statement)))\n\n visitor = StatementsWithBodiesVisitor(default_options, tree=tree)\n visitor.run()\n\n assert_errors(visitor, [UselessNodeViolation])",
"def keepUnknownNodes(self, flag: 'SbBool') -> \"void\":\n return _coin.SoToVRMLAction_keepUnknownNodes(self, flag)",
"def noExceptions(self) :\n inhibitExceptions = True",
"def _is_unused(self, path):\n for node in path:\n if node.ns.fingerprint in self._nodes_processing:\n return False\n return True",
"def testInactivatedNodesReallyUseless(self):\n\t\ti_nodes = self.som_hands.activation_response(self.som_hands.data)\n\t\tidx_inact = np.where(i_nodes.flatten()==0)[0]\n\t\t_, w = self.som_hands.get_weights()\n\t\t\n\t\tact = np.setdiff1d(np.arange(w.shape[0]), idx_inact)\t\t\n\t\ti_w = w[idx_inact, :]\n\t\ta_w = w[act, :]\n\n\t\tfor i, dp in enumerate(self.som_hands.data):\n\t\t\ts, _ = get_similar_vector(w, dp)\n\t\t\t\n\t\t\t# make sure the closest vector is not in i_w\n\t\t\t# too many for loops here.. ugly!\n\t\t\t_, qi, _ = get_similar_vector(i_w, s[0])\n\t\t\t_, qa, _ = get_similar_vector(a_w, s[0])\n\t\t\tself.assertGreater(qi[0], qa[0])",
"def set_forbidden_edges(self, edges):\n self.forbidden_edges = edges",
"def at_failed_traverse(self, traversing_object):\r\n traversing_object.msg(\"You cannot go there.\")",
"def miss_check_3():\n valid_read = cpu_wbs.cyc_i and cpu_wbs.stb_i and not cpu_wbs.we_i\n miss.next = miss_w_and and valid_read and not invalidate",
"def tricky_bad_cycle():\n nodes = _create_graph(n_nodes=4, connections=[((0, 0), (1, 0)),\n ((1, 0), (2, 0)),\n ((2, 0), (3, 0)),\n ((3, 0), (1, 1))], low_priority=[True, False, False, False])\n\n with pytest.raises(IllegalCycleException):\n order_nodes(nodes)",
"def empty_safe_curie(node, options, state) :\n\tdef prune_safe_curie(node,name) :\n\t\tif node.hasAttribute(name) :\n\t\t\tav = node.getAttribute(name)\n\t\t\tif av == '[]' :\n\t\t\t\tnode.removeAttribute(name)\n\t\t\t\tnode.setAttribute(name+'_pruned','')\n\t\t\t\tmsg = \"Attribute @%s uses an empty safe CURIE; the attribute is ignored\" % name\n\t\t\t\toptions.add_warning(msg, node=node)\n\n\tprune_safe_curie(node, \"about\")\n\tprune_safe_curie(node, \"resource\")\n\tfor n in node.childNodes :\n\t\tif n.nodeType == node.ELEMENT_NODE :\n\t\t\tempty_safe_curie(n, options, state)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Creates a new PythonPlugin object. tool The tool associated with this plugin.
|
def __init__(self, tool: ghidra.framework.plugintool.PluginTool):
...
|
[
"def instantiatePlugin(pluginClass: java.lang.Class, tool: ghidra.framework.plugintool.PluginTool) -> object:\n ...",
"def load_tool(tool_module: str) -> HammerTool:\n mod = importlib.import_module(tool_module)\n tool_class = getattr(mod, \"tool\")\n tool: HammerTool = tool_class()\n tool.package = tool_module\n return tool",
"def creator():\n\n return Plugin()",
"def setup_pycodestyle_tool_plugin():\n arg_parser = argparse.ArgumentParser()\n\n resources = Resources(\n [os.path.join(os.path.dirname(statick_tool.__file__), \"plugins\")]\n )\n config = Config(resources.get_file(\"config.yaml\"))\n plugin_context = PluginContext(arg_parser.parse_args([]), resources, config)\n plugin_context.args.output_directory = os.path.dirname(__file__)\n pcstp = PycodestyleToolPlugin()\n pcstp.set_plugin_context(plugin_context)\n return pcstp",
"def toolChanged(self, tool: ghidra.framework.plugintool.PluginTool) -> None:\n ...",
"def addPublicTool( self, tool, stageName = 'undefined' ):\n\n try:\n # Try to access the ToolSvc, to see whethet we're in Athena mode:\n from AthenaCommon.AppMgr import ToolSvc\n except ImportError:\n\n # We're not, so let's remember this as a \"normal\" algorithm:\n self.append( tool, inputPropName = None, stageName = stageName )\n pass\n return",
"def tool_proxy(tool_path):\n ensure_cwltool_available()\n tool = to_cwl_tool_object(tool_path)\n return tool",
"def setup_cmakelint_tool_plugin():\n arg_parser = argparse.ArgumentParser()\n\n resources = Resources(\n [os.path.join(os.path.dirname(statick_tool.__file__), \"plugins\")]\n )\n config = Config(resources.get_file(\"config.yaml\"))\n plugin_context = PluginContext(arg_parser.parse_args([]), resources, config)\n plugin_context.args.output_directory = os.path.dirname(__file__)\n cmltp = CMakelintToolPlugin()\n cmltp.set_plugin_context(plugin_context)\n return cmltp",
"def __init__( self, config_file ):\n # Determine the full path of the directory where the tool config is\n self.config_file = config_file\n self.tool_dir = os.path.dirname( config_file )\n # Parse XML configuration file and get the root element\n tree = util.parse_xml( self.config_file )\n root = tree.getroot()\n # Get the (user visible) name of the tool\n self.name = root.get(\"name\")\n if not self.name: raise Exception, \"Missing tool 'name'\"\n # Get the UNIQUE id for the tool \n # TODO: can this be generated automatically?\n self.id = root.get(\"id\")\n if not self.id: raise Exception, \"Missing tool 'id'\" \n # Command line (template). Optional for tools that do not invoke a \n # local program \n command = root.find(\"command\")\n if command is not None:\n self.command = util.xml_text(root, \"command\") # get rid of whitespace\n interpreter = command.get(\"interpreter\")\n if interpreter:\n self.command = interpreter + \" \" + os.path.join(self.tool_dir, self.command)\n else:\n self.command = ''\n # Short description of the tool\n self.description = util.xml_text(root, \"description\")\n # Load any tool specific code (optional)\n self.code_namespace = dict()\n for code_elem in root.findall(\"code\"):\n file_name = code_elem.get(\"file\")\n code_path = os.path.join( self.tool_dir, file_name )\n execfile( code_path, self.code_namespace )\n # Load parameters (optional)\n input_elem = root.find(\"inputs\")\n if input_elem:\n # Handle properties of the input form\n self.check_values = util.string_as_bool( input_elem.get(\"check_values\", \"true\") )\n self.action = input_elem.get( \"action\", \"/tool_runner/index\")\n self.target = input_elem.get( \"target\", \"galaxy_main\" )\n self.method = input_elem.get( \"method\", \"post\" )\n # Parse the actual parameters\n self.param_map = odict()\n self.param_map_by_page = list()\n self.display_by_page = list()\n enctypes = set()\n # Handle multiple page case\n pages = input_elem.findall( \"page\" )\n for page in ( pages or [ input_elem ] ):\n display, param_map = self.parse_page( page, enctypes )\n self.param_map_by_page.append( param_map )\n self.param_map.update( param_map )\n self.display_by_page.append( display )\n self.display = self.display_by_page[0]\n self.npages = len( self.param_map_by_page )\n self.last_page = len( self.param_map_by_page ) - 1\n self.has_multiple_pages = bool( self.last_page )\n # Determine the needed enctype for the form\n if len( enctypes ) == 0:\n self.enctype = \"application/x-www-form-urlencoded\"\n elif len( enctypes ) == 1:\n self.enctype = enctypes.pop()\n else:\n raise Exception, \"Conflicting required enctypes: %s\" % str( enctypes )\n # Check if the tool either has no parameters or only hidden (and\n # thus hardcoded) parameters. FIXME: hidden parameters aren't\n # parameters at all really, and should be passed in a different\n # way, making this check easier.\n self.input_required = False\n for param in self.param_map.values():\n if not isinstance( param, ( HiddenToolParameter, BaseURLToolParameter ) ):\n self.input_required = True\n break\n # Longer help text for the tool. Formatted in RST\n # TODO: Allow raw HTML or an external link.\n self.help = root.find(\"help\")\n self.help_by_page = list()\n help_header = \"\"\n help_footer = \"\"\n if self.help is not None:\n help_pages = self.help.findall( \"page\" )\n help_header = self.help.text\n try:\n self.help = util.rst_to_html(self.help.text)\n except:\n log.exception( \"error in help for tool %s\" % self.name )\n # Multiple help page case\n if help_pages:\n for help_page in help_pages:\n self.help_by_page.append( help_page.text )\n help_footer = help_footer + help_page.tail\n # Each page has to rendered all-together because of backreferences allowed by rst\n try:\n self.help_by_page = [ \\\n util.rst_to_html(help_header + x + help_footer) for x in self.help_by_page \\\n ]\n except:\n log.exception( \"error in multi-page help for tool %s\" % self.name )\n # Pad out help pages to match npages ... could this be done better?\n while len(self.help_by_page) < self.npages: self.help_by_page.append( self.help )\n # FIXME: This is not used anywhere, what does it do?\n # url redirection to ougoings\n self.redir_url = root.find(\"url\")\n # Description of outputs produced by an invocation of the tool\n self.outputs = {}\n out_elem = root.find(\"outputs\")\n if out_elem:\n for data_elem in out_elem.findall(\"data\"):\n name = data_elem.get(\"name\")\n format = data_elem.get(\"format\", \"data\")\n metadata_source = data_elem.get(\"metadata_source\", \"\")\n parent = data_elem.get(\"parent\", None)\n self.outputs[name] = (format, metadata_source, parent) \n # Action\n action_elem = root.find( \"action\" )\n if action_elem is None:\n self.tool_action = DefaultToolAction()\n else:\n module = action_elem.get( 'module' )\n cls = action_elem.get( 'class' )\n mod = __import__( module, globals(), locals(), [cls])\n self.tool_action = getattr( mod, cls )()\n # Tests\n tests_elem = root.find( \"tests\" )\n if tests_elem:\n try:\n self.parse_tests( tests_elem )\n except:\n log.exception( \"Failed to parse tool tests\" )\n else:\n self.tests = None",
"def setup_do_nothing_tool_plugin():\n plugin = DoNothingToolPlugin()\n return plugin",
"def parse( self, root ):\n # Get the (user visible) name of the tool\n self.name = root.get( \"name\" )\n if not self.name: \n raise Exception, \"Missing tool 'name'\"\n # Get the UNIQUE id for the tool \n # TODO: can this be generated automatically?\n self.id = root.get( \"id\" )\n if not self.id: \n raise Exception, \"Missing tool 'id'\" \n self.version = root.get( \"version\" )\n if not self.version: \n # For backward compatibility, some tools may not have versions yet.\n self.version = \"1.0.0\"\n # Support multi-byte tools\n self.is_multi_byte = util.string_as_bool( root.get( \"is_multi_byte\", False ) )\n #Force history to fully refresh after job execution for this tool. Useful i.e. when an indeterminate number of outputs are created by a tool.\n self.force_history_refresh = util.string_as_bool( root.get( 'force_history_refresh', 'False' ) )\n #load input translator, used by datasource tools to change names/values of incoming parameters\n self.input_translator = root.find( \"request_param_translation\" )\n if self.input_translator:\n self.input_translator = ToolInputTranslator.from_element( self.input_translator )\n # Command line (template). Optional for tools that do not invoke a local program \n command = root.find(\"command\")\n if command is not None and command.text is not None:\n self.command = command.text.lstrip() # get rid of leading whitespace\n interpreter = command.get(\"interpreter\")\n if interpreter:\n # TODO: path munging for cluster/dataset server relocatability\n executable = self.command.split()[0]\n abs_executable = os.path.abspath(os.path.join(self.tool_dir, executable))\n self.command = self.command.replace(executable, abs_executable, 1)\n self.command = interpreter + \" \" + self.command\n else:\n self.command = ''\n # Parameters used to build URL for redirection to external app\n redirect_url_params = root.find( \"redirect_url_params\" )\n if redirect_url_params is not None and redirect_url_params.text is not None:\n # get rid of leading / trailing white space\n redirect_url_params = redirect_url_params.text.strip()\n # Replace remaining white space with something we can safely split on later\n # when we are building the params\n self.redirect_url_params = redirect_url_params.replace( ' ', '**^**' )\n else:\n self.redirect_url_params = ''\n # Short description of the tool\n self.description = util.xml_text(root, \"description\")\n # Job runner\n if self.app.config.start_job_runners is None:\n # Jobs are always local regardless of tool config if no additional\n # runners are started\n self.job_runner = \"local:///\"\n else:\n # Set job runner to the cluster default\n self.job_runner = self.app.config.default_cluster_job_runner\n for tup in self.app.config.tool_runners:\n if tup[0] == self.id.lower():\n self.job_runner = tup[1]\n break\n # Is this a 'hidden' tool (hidden in tool menu)\n self.hidden = util.xml_text(root, \"hidden\")\n if self.hidden: self.hidden = util.string_as_bool(self.hidden)\n # Load any tool specific code (optional) Edit: INS 5/29/2007,\n # allow code files to have access to the individual tool's\n # \"module\" if it has one. Allows us to reuse code files, etc.\n self.code_namespace = dict()\n self.hook_map = {}\n for code_elem in root.findall(\"code\"):\n for hook_elem in code_elem.findall(\"hook\"):\n for key, value in hook_elem.items():\n # map hook to function\n self.hook_map[key]=value\n file_name = code_elem.get(\"file\")\n code_path = os.path.join( self.tool_dir, file_name )\n execfile( code_path, self.code_namespace )\n # Load any tool specific options (optional)\n self.options = dict( sanitize=True, refresh=False )\n for option_elem in root.findall(\"options\"):\n for option, value in self.options.copy().items():\n if isinstance(value, type(False)):\n self.options[option] = util.string_as_bool(option_elem.get(option, str(value)))\n else:\n self.options[option] = option_elem.get(option, str(value))\n self.options = Bunch(** self.options)\n # Parse tool inputs (if there are any required)\n self.parse_inputs( root )\n # Parse tool help\n self.parse_help( root )\n # Description of outputs produced by an invocation of the tool\n self.outputs = {}\n out_elem = root.find(\"outputs\")\n if out_elem:\n for data_elem in out_elem.findall(\"data\"):\n output = ToolOutput( data_elem.get(\"name\") )\n output.format = data_elem.get(\"format\", \"data\")\n output.change_format = data_elem.findall(\"change_format\")\n output.metadata_source = data_elem.get(\"metadata_source\", \"\")\n output.parent = data_elem.get(\"parent\", None)\n output.label = util.xml_text( data_elem, \"label\" )\n output.count = int( data_elem.get(\"count\", 1) )\n output.filters = data_elem.findall( 'filter' )\n self.outputs[ output.name ] = output\n # Any extra generated config files for the tool\n self.config_files = []\n conf_parent_elem = root.find(\"configfiles\")\n if conf_parent_elem:\n for conf_elem in conf_parent_elem.findall( \"configfile\" ):\n name = conf_elem.get( \"name\" )\n filename = conf_elem.get( \"filename\", None )\n text = conf_elem.text\n self.config_files.append( ( name, filename, text ) )\n # Action\n action_elem = root.find( \"action\" )\n if action_elem is None:\n self.tool_action = DefaultToolAction()\n else:\n module = action_elem.get( 'module' )\n cls = action_elem.get( 'class' )\n mod = __import__( module, globals(), locals(), [cls])\n self.tool_action = getattr( mod, cls )()\n # User interface hints\n self.uihints = {}\n uihints_elem = root.find( \"uihints\" )\n if uihints_elem is not None:\n for key, value in uihints_elem.attrib.iteritems():\n self.uihints[ key ] = value\n # Tests\n tests_elem = root.find( \"tests\" )\n if tests_elem:\n try:\n self.parse_tests( tests_elem )\n except:\n log.exception( \"Failed to parse tool tests\" )\n else:\n self.tests = None\n # Determine if this tool can be used in workflows\n self.is_workflow_compatible = self.check_workflow_compatible()",
"def load_tool( self, config_file ):\n # Parse XML configuration file and get the root element\n tree = util.parse_xml( config_file )\n root = tree.getroot()\n # Allow specifying a different tool subclass to instantiate\n if root.find( \"type\" ) is not None:\n type_elem = root.find( \"type\" )\n module = type_elem.get( 'module', 'galaxy.tools' )\n cls = type_elem.get( 'class' )\n mod = __import__( module, globals(), locals(), [cls])\n ToolClass = getattr( mod, cls )\n elif root.get( 'tool_type', None ) is not None:\n ToolClass = tool_types.get( root.get( 'tool_type' ) )\n else:\n ToolClass = Tool\n return ToolClass( config_file, root, self.app )",
"def _create_hook_manager() -> PluginManager:\n manager = PluginManager(HOOK_NAMESPACE)\n manager.trace.root.setwriter(logger.debug)\n manager.enable_tracing()\n manager.add_hookspecs(NodeSpecs)\n manager.add_hookspecs(PipelineSpecs)\n manager.add_hookspecs(DataCatalogSpecs)\n manager.add_hookspecs(DatasetSpecs)\n manager.add_hookspecs(KedroContextSpecs)\n return manager",
"def create_tool_from_suggestion():\n pass",
"def _get_new_toolbox(app):\n from galaxy import tools\n from galaxy.tools.special_tools import load_lib_tools\n if hasattr(app, 'tool_shed_repository_cache'):\n app.tool_shed_repository_cache.rebuild()\n tool_configs = app.config.tool_configs\n if app.config.migrated_tools_config not in tool_configs:\n tool_configs.append(app.config.migrated_tools_config)\n\n new_toolbox = tools.ToolBox(tool_configs, app.config.tool_path, app)\n new_toolbox.data_manager_tools = app.toolbox.data_manager_tools\n app.datatypes_registry.load_datatype_converters(new_toolbox, use_cached=True)\n app.datatypes_registry.load_external_metadata_tool(new_toolbox)\n load_lib_tools(new_toolbox)\n [new_toolbox.register_tool(tool) for tool in new_toolbox.data_manager_tools.values()]\n app.toolbox = new_toolbox",
"def __new__(cls, plugin, deep):\n plugins = frozenset(_unwrap_plugin(plugin, deep))\n \n self = object.__new__(cls)\n self._plugins = plugins\n self._plugins_sorted = None\n return self",
"def getConnection(self, producer: ghidra.framework.plugintool.PluginTool, consumer: ghidra.framework.plugintool.PluginTool) -> ghidra.framework.model.ToolConnection:\n ...",
"def static_tool(self, static_tool):\n\n self._static_tool = static_tool",
"def dynamic_tool(self, dynamic_tool):\n\n self._dynamic_tool = dynamic_tool"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Returns a list of possible command completion values. cmd current command line (without prompt) A list of possible command completion values. Could be empty if there aren't any.
|
def getCompletions(self, cmd: unicode) -> List[ghidra.app.plugin.core.console.CodeCompletion]:
...
|
[
"def autocomplete(self):\n if self.completion_env_var_name not in os.environ:\n return\n cwords = os.environ['COMP_WORDS'].split()[1:]\n cword = int(os.environ['COMP_CWORD'])\n try:\n current = cwords[cword-1]\n except IndexError:\n current = ''\n cmd_names = self.get_commands().keys()\n\n if current:\n self.stdout.write(unicode(' '.join(\n [name for name in cmd_names if name.startswith(current)])))\n\n sys.exit(1)",
"def test_bashcompletion_all_commands():\n # get the line where all commands are specified in the completion file; this is custom\n # to our file, but simple and good enough\n completed_commands = None\n with open(\"completion.bash\", encoding=\"utf8\") as fh:\n completion_text = fh.read()\n m = re.search(r\"cmds=\\((.*?)\\)\", completion_text, re.DOTALL)\n if m:\n completed_commands = set(m.groups()[0].split())\n else:\n pytest.fail(\"Failed to find commands in the bash completion file\")\n\n real_command_names = set()\n for cgroup in main.COMMAND_GROUPS:\n real_command_names.update(cmd.name for cmd in cgroup.commands)\n\n assert completed_commands == real_command_names",
"def gen_cmd_and_param_completions(self):\n # if the user inputs space or 'az', provide recommendation instead of\n # default completion when recommender is enabled\n has_user_input = self.current_command or self.unfinished_word.strip()\n if not has_user_input and self.shell_ctx.recommender.enabled:\n return\n if self.complete_command:\n for param in self.command_param_info.get(self.current_command, []):\n if self.validate_param_completion(param, self.leftover_args):\n yield self.yield_param_completion(param, self.unfinished_word)\n elif not self.leftover_args:\n for child_command in self.subtree.children:\n if self.validate_completion(child_command):\n full_command = f'{self.current_command} {child_command}'.strip()\n yield Completion(child_command, -len(self.unfinished_word),\n display_meta=self.command_description.get(full_command))",
"def get_command_list (self):\r\n # Currently this is only used on Mac OS, for the Mac-only GUI\r\n # Distutils interface (by Jack Jansen)\r\n\r\n import distutils.command\r\n std_commands = distutils.command.__all__\r\n is_std = {}\r\n for cmd in std_commands:\r\n is_std[cmd] = 1\r\n\r\n extra_commands = []\r\n for cmd in self.cmdclass.keys():\r\n if not is_std.get(cmd):\r\n extra_commands.append(cmd)\r\n\r\n rv = []\r\n for cmd in (std_commands + extra_commands):\r\n klass = self.cmdclass.get(cmd)\r\n if not klass:\r\n klass = self.get_command_class(cmd)\r\n try:\r\n description = klass.description\r\n except AttributeError:\r\n description = \"(no description available)\"\r\n rv.append((cmd, description))\r\n return rv",
"def get_completions(self, info):\n return []",
"def test_bash_completion():\n out1 = commands(\"--format=bash\")\n\n # Make sure header not included\n assert \"_bash_completion_spack() {\" not in out1\n assert \"_all_packages() {\" not in out1\n\n # Make sure subcommands appear\n assert \"_spack_remove() {\" in out1\n assert \"_spack_compiler_find() {\" in out1\n\n # Make sure aliases don't appear\n assert \"_spack_rm() {\" not in out1\n assert \"_spack_compiler_add() {\" not in out1\n\n # Make sure options appear\n assert \"-h --help\" in out1\n\n # Make sure subcommands are called\n for function in _positional_to_subroutine.values():\n assert function in out1\n\n out2 = commands(\"--aliases\", \"--format=bash\")\n\n # Make sure aliases appear\n assert \"_spack_rm() {\" in out2\n assert \"_spack_compiler_add() {\" in out2",
"def get_command_list(self):\n return self._command_list",
"def get_completer():\n return readline.get_completer()",
"def argv(self):\n optlist = []\n for n in range(self.count):\n optlist.append(self.flag)\n if self.values is not None:\n optlist.append(self.values[n])\n return optlist",
"def global_cmdline_values():\n global _global_cmdline_values\n\n if not _global_cmdline_values:\n luigi_parser = luigi.cmdline_parser.CmdlineParser.get_instance()\n if not luigi_parser:\n return None\n\n # go through all actions of the full luigi parser and compare option strings\n # with the global cmdline args\n parser = full_parser()\n global_args = global_cmdline_args()\n _global_cmdline_values = {}\n for action in parser._actions:\n if any(arg in action.option_strings for arg in global_args):\n _global_cmdline_values[action.dest] = getattr(luigi_parser.known_args, action.dest)\n\n return _global_cmdline_values",
"def list_commands(self, ctx):\n return self.commands.keys()",
"def get_completions(self, document, _):\n word_before_cursor = document.get_word_before_cursor(WORD=True)\n words = self.text_utils.get_tokens(document.text)\n commands = []\n if len(words) == 0:\n return commands\n if self.completing_command(words, word_before_cursor):\n commands = ['gh']\n else:\n if 'gh' not in words:\n return commands\n if self.completing_subcommand(words, word_before_cursor):\n commands = list(SUBCOMMANDS.keys())\n else:\n if self.completing_arg(words, word_before_cursor):\n commands = self.arg_completions(words, word_before_cursor)\n else:\n commands = self.completing_subcommand_option(\n words,\n word_before_cursor)\n completions = self.text_utils.find_matches(\n word_before_cursor, commands, fuzzy=self.fuzzy_match)\n return completions",
"def getAutoCompleteList(command='', locals=None, includeMagic=1,\n includeSingle=1, includeDouble=1):\n attributes = []\n object = None\n # Get the proper chunk of code from the command.\n #root = getRoot(command, terminator='.')\n # and get the part of the completion we should filter on\n (root, filter) = getRootAndFilter(command, terminator='.')\n if root:\n jump_past_period = 1\n else:\n jump_past_period = 0\n\n #println(\"root='\" + root + \"'\")\n #println(\"filter='\" + filter + \"'\")\n \n if not root:\n # top-level?\n attributes = locals\n else:\n try:\n if locals is not None:\n object = eval(root, locals)\n else:\n object = eval(root)\n except:\n #print \"could not eval(\", root, \"):\", sys.exc_info()[0]\n pass\n else:\n attributes = getAttributeNames(object, includeMagic,\n includeSingle, includeDouble)\n completion_list = []\n for attribute in attributes:\n if attribute.lower().startswith(filter.lower()):\n try:\n if object is not None:\n pyObj = getattr(object, attribute)\n else:\n pyObj = locals[attribute]\n completion_list.append(PythonCodeCompletionFactory.\n newCodeCompletion(attribute,\n attribute, \n pyObj,\n filter))\n except:\n # hmm, problem evaluating? Examples of this include\n # inner classes, e.g. access$0, which aren't valid Python\n # anyway\n pass\n completion_list.sort(compare_completions)\n return completion_list",
"def get_option_values(self):\n \n class CommandLineOptions(object):\n def __getattr__(self, name):\n # if an attribute can not be found, this is the last function called\n all_option_names=\", \".join(vars(self).keys())\n error_message=\"Unable to find option '{0}' in command line options.\\n\".format(name)\n error_message+=\"The available options are: {0}\".format(all_option_names)\n raise AttributeError(error_message)\n \n # get arguments from the command line (will not run again if already parsed)\n if not self._user_asked:\n self.ask_user()\n \n args=CommandLineOptions()\n for option in list(self._user_arguments.keys()) + list(self._arguments.keys()):\n option = re.sub(r'-', '_', option)\n value = self.get(option)\n setattr(args,option,value)\n \n return args",
"def _parameters_for_complete(self):\r\n\r\n completions = []\r\n try:\r\n in_call = self.script.call_signatures()[0]\r\n except IndexError:\r\n in_call = None\r\n\r\n parameters = get_function_parameters(in_call)\r\n\r\n for parameter in parameters:\r\n try:\r\n name, value = parameter\r\n except ValueError:\r\n name = parameter[0]\r\n value = None\r\n\r\n if value is None:\r\n completions.append((name, '${1:%s}' % name))\r\n else:\r\n completions.append(\r\n (name + '\\t' + value, '%s=${1:%s}' % (name, value))\r\n )\r\n\r\n return completions",
"def completion(ctx, shell=None):\n completer = pycomplete.Completer(ctx)\n print(completer.render(shell))",
"def cmd(self, cmd):\r\n str_out = self.__get_stdout(cmd)\r\n return [x.strip() for x in str_out.split('\\n')]",
"def get_command_completers(self, namespace, command):\n # type: (str, str) -> CompletionInfo\n # Find the method (can raise a KeyError)\n method = self._commands[namespace][command]\n\n # Return the completer, if any\n return getattr(method, ATTR_COMPLETERS, None)",
"async def listCommands(self) -> None:\n embedVar:Embed = Embed(title=\"~help para ter os comandos\", description=\"Para voce infernizar seus amigos\", colour=Colour.from_rgb(255, 102, 102))\n \n comandos:list = list(allComands.keys())\n for x in range(len(allComands.keys())):\n cmd = comandos[x]\n embedVar.add_field(name=cmd, value=allComands[cmd], inline=False)\n\n await self.message.channel.send(embed=embedVar)\n\n embedVar = comandos = cmd = None\n del embedVar, comandos, cmd"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Handle a change in one of our options. options the options handle optionName name of the option changed oldValue the old value newValue the new value
|
def optionsChanged(self, options: ghidra.framework.options.ToolOptions, optionName: unicode, oldValue: object, newValue: object) -> None:
...
|
[
"def on_option_change(self, event):\n\t\telement = event.GetEventObject()\n\t\t_id = element.GetId()\n\t\tvar_name = self.var_ids[_id]\n\t\tif var_name == 'time_index' or var_name == 'pl_index':\n\t\t\tval = int(element.GetValue().split(\" \")[0])\n\t\telif var_name == 'preset':\n\t\t\tval = element.GetValue()\n\t\t\tself.display_map_preview(val)\n\t\telse:\n\t\t\tval = element.GetValue()\n\t\tself.update_option(var_name, val)\n\t\tevent.Skip()",
"def _choose_strategy_change(self, options):\n # TODO: implement 'change' strategy\n raise NotImplementedError",
"def handle_change_option(self, change):\n m = self.get_active_modal()\n m.current_option = (m.current_option + change) % len(m.option_labels)\n self.option_labels.set_highlight(m.current_option)",
"def apply_changes(self, closing=False):\n pass; LOG and print('APPLY_CHANGES')\n\n # check if current value in edit is changed, create option change if it is\n try:\n edit_val = self.val_eds.get_edited_value(self._cur_opt)\n except ValueError: # exception happens when trying to cast empty str to float|int\n edit_val = None\n if edit_val is not None and edit_val != '':\n self.add_opt_change(self._cur_opt_name, self.scope, edit_val)\n\n if not self._opt_changes and not closing:\n msg_status(_(\"No option changes has been made\"))\n return\n\n for i,change in enumerate(self._opt_changes):\n is_last = i == len(self._opt_changes) - 1\n if change.value is not None: # set value\n self.optman.set_opt(name=change.name, scope=change.scope, val=change.value,\n lexer=change.lexer, apply_=is_last)\n else: # removing value\n self.optman.reset_opt(name=change.name, scope=change.scope,\n lexer=change.lexer, apply_=is_last)\n\n self._opt_changes.clear()\n self.optman.on_opts_change()\n _opts = self.get_filtered_opts()\n self.update_list(_opts)",
"def on_opts_change(self):\n self._last_result = None",
"def update_option_frame(self, cfg):\n current = []\n for varname, value in cfg.items():\n bad_input_msg = (\n \"The following error occured when validating\"\n \" option with variable name '{}':\\n\\n{}\\n\\n\"\n \"Loading the specified configuration has been \"\n \"aborted. Please supply a correct configuration \"\n \"file before proceeding. No changes \"\n \"have been made.\"\n )\n try:\n option = self.options_frame.get_option_by_varname(varname)\n current.append((varname, option.get_value()))\n self.options_frame.set_option(varname, value)\n if option.choices:\n self.options_frame.set_variable(varname, option.get_choice_key())\n else:\n self.options_frame.set_variable(varname, option.get_value())\n except (KeyError, TclError, TypeError, ValueError) as error:\n for varname, old_val in current:\n self.options_frame.set_option(varname, old_val)\n option = self.options_frame.get_option_by_varname(varname)\n if option.choices:\n self.options_frame.set_variable(\n varname, option.get_choice_key()\n )\n else:\n self.options_frame.set_variable(varname, option.get_value())\n messagebox.showwarning(\n title=\"Error setting option!\",\n message=bad_input_msg.format(varname, error),\n )\n log_message(\n logging_callback=logging.exception,\n msg=error,\n extra={\"oname\": self.__class__.__name__},\n )\n return False\n return True",
"def add_opt_change(self, name, scope, val=None):\n _old_val = self.optman.get_scope_value(name, scope)\n\n # check if already have a opt_change for this option+scope -> ovewrite (delete old)\n for i,change in enumerate(self._opt_changes):\n if change.name == name and change.scope == scope:\n del self._opt_changes[i]\n break\n\n if val is not None: ### setting value\n if val == _old_val: # no change - ignore\n return\n else: ### removing value\n if _old_val is None: # no change - ignore\n return\n\n # if resetting value -- ask confirmation\n scam = app_proc(PROC_GET_KEYSTATE, '')\n if scam != 'c' and self.scope != 'f' and val is None:\n _scope_cap = self._scope_captions[self.scope]\n _jval = self.optman.get_opt_scope_value(self._cur_opt, scope=self.scope, is_ui=True)\n _msg = _('Remove option [{}]\\n {} = {!r}\\n?').format(_scope_cap, self._cur_opt_name, _jval)\n res = msg_box(_msg, MB_OKCANCEL + MB_ICONQUESTION)\n if res != ID_OK:\n return\n\n lex = ed.get_prop(PROP_LEXER_FILE) if scope == 'l' else None\n opt_change = OptChange(name, scope, val, lexer=lex, old_value=_old_val)\n pass; LOG and print('NOTE: new option change: '+str(opt_change))\n msg_status(_('Option: ') + format_opt_change(opt_change))\n self._opt_changes.append(opt_change)",
"def set_option (self,name,data):\n\n # Is the changing option the delay\n if name == 'delay': \n try:\n # Try to convert the data to a float\n self._delay = float(data)\n except ValueError:\n # Give error message and return if data conversion failed.\n print('set option delay went wrong')\n return\n \n # Else if the data type is a bool\n elif isinstance(data,bool):\n try:\n # Try to set the given option name \n self.options[name]['activated'].set(str(data))\n\n # If given a wrong option return\n except KeyError:\n return",
"def on_property_change(self, name, old_value, new_value):\n pass",
"def set_option(self, option, value):\n var_name = option['value'].replace('_values', '')\n setattr(self, var_name, value)\n # Logs.debug(\"set option \",self.get_option(option))",
"def process(self, opt, value, values, parser):\r\n result = optparse.Option.process(self, opt, value, values, parser)\r\n setting = self.dest\r\n if setting:\r\n if self.validator:\r\n value = getattr(values, setting)\r\n try:\r\n new_value = self.validator(setting, value, parser)\r\n except Exception, error:\r\n raise (optparse.OptionValueError(\r\n 'Error in option \"%s\":\\n %s'\r\n % (opt, ErrorString(error))),\r\n None, sys.exc_info()[2])\r\n setattr(values, setting, new_value)\r\n if self.overrides:\r\n setattr(values, self.overrides, None)\r\n return result",
"def process_options(self):\n data = self.receive()\n if 'option_selected' in data.keys() and 1 <= data['option_selected'] <= 6: # validates a valid option selected\n option = data['option_selected']\n if option == 1:\n self._send_user_list()\n elif option == 2:\n self._save_message(data)\n elif option == 3:\n self._send_messages()\n elif option == 4:\n self._create_chat(data)\n elif option == 5:\n self._join_chat(data)\n elif option == 6:\n self._disconnect_from_server()\n else:\n print(\"The option selected is invalid\")",
"def test_get_options_interval_movers_change(self):\n pass",
"async def _update_input_select(self, option=None):\n\n if self.hass.states.get(self._input_entity) is None:\n _LOGGER.error(\"%s is not a valid input_select entity.\", self._input_entity)\n return\n else:\n curr_state = self.hass.states.get(self._input_entity).state\n # _LOGGER.debug('{}, state: {}'.format(input_entity, curr_state))\n\n if not self._stream.service_name_list:\n if curr_state == 'Inactive':\n return\n data = {\"options\": [\"Inactive\"], \"entity_id\": self._input_entity}\n else:\n if curr_state == option:\n return\n data = {\"options\": self._reorder_list(\n self._stream.service_name_list, option),\n \"entity_id\": self._input_entity}\n\n _LOGGER.debug('Update input_select with: {}'.format(data))\n await self.hass.services.async_call(\n input_select.DOMAIN, input_select.SERVICE_SET_OPTIONS, data)\n\n if option:\n data = {\"option\": option, \"entity_id\": self._input_entity}\n if curr_state != option:\n await self.hass.services.async_call(\n input_select.DOMAIN, input_select.SERVICE_SELECT_OPTION, data)",
"def _on_option_clicked(self, *_):\n self.variable.set(True)",
"def apply_to_options(self):\n success = \"Successfully applied configuration file to plugin options.\"\n if not self.options_frame:\n messagebox.showwarning(\n \"Apply Configuration Warning\",\n \"No options have been defined in this plugin. Cannot apply\"\n \"loaded configuration.\",\n )\n return\n\n if not self.active_cfg:\n messagebox.showwarning(\n \"Apply Configuration Warning\",\n \"No configuration file has been loaded. Please load one first.\",\n )\n return\n\n warn_message = \"\"\n unused_keys = get_unused_options(self.active_cfg, self.options_frame.options)\n incomplete = self.options_file_incomplete()\n self.active_cfg = {\n k: v for (k, v) in self.active_cfg.items() if k not in unused_keys\n }\n\n if unused_keys:\n unused = \"\\n\".join([\"'{}'\".format(n) for n in unused_keys])\n warn_message += (\n \"The following options found in the configuration\"\n \"file are not defined in the current plugin and \"\n \"will not be used during analysis:\\n\\n{}\\n\\n\"\n )\n warn_message = warn_message.format(unused)\n\n if incomplete:\n incomplete = \"\\n\".join([\"'{}'\".format(n) for n in incomplete])\n warn_message += (\n \"The following options defined in the plugin \"\n \"could not be found in the configuration file:\"\n \"\\n\\n{}\\n\\nThese options will not been altered.\"\n )\n warn_message = warn_message.format(incomplete)\n\n if warn_message:\n messagebox.showwarning(\"Apply configuration to options.\", warn_message)\n\n applied_successfully = self.update_option_frame(self.active_cfg)\n if applied_successfully and not warn_message:\n messagebox.showinfo(\"Apply configuration to options.\", success)\n return",
"def onModified(self, mod):\n self.ignorechange = True\n self.setValue( self.setting.val )\n self.ignorechange = False",
"def on_options_app2project(self):\n\n self.defaults_read_form()\n self.options.update(self.defaults)\n self.options_write_form()",
"def updateFromReloaded(self, newCfg, log):\n newCfg.sanityCheck()\n newCfg.sanityCheckForStart()\n for option in self.keys():\n if self[option] == newCfg[option]:\n continue\n if option not in self._reloadable:\n if log:\n log.warning(\"Change of option %s requires a restart\", option)\n continue\n self[option] = newCfg[option]\n sio = StringIO()\n self.displayKey(option, sio)\n if log:\n log.info(\"Configuration changed: %s\", sio.getvalue().rstrip())"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Unwraps IMDB suggestions result from jsonp callback. Basically we ignore jsonp; what is interesting is suggestions json.
|
def _unwrap_jsonp(suggestions: str) -> [dict]:
return json.loads(suggestions.split("(", 1)[1].strip(")"))
|
[
"def handle_suggest_response(query, callback):\n def inner_callback(response):\n try:\n result = json.loads(response.body)\n except StandardError as e:\n log.error('Error handling search response: %s - %s' % (str(e),\n response.body))\n callback({'error': {'msg': str(e)}, 'result': response.body})\n else:\n if \"error\" in result:\n log.error('Error searching solr: %s' % response.body)\n callback(result)\n else:\n callback(query.response_mapper(result))\n return inner_callback",
"def _parse_suggestions(json: JiraIssueSuggestionJSON) -> list[IssueSuggestion]: # pragma: no feature-test-cover\n issues = json.get(\"issues\", [])\n return [IssueSuggestion(str(issue[\"key\"]), cast(dict, issue[\"fields\"])[\"summary\"]) for issue in issues]",
"def prune_keywords(keywords):\n keywords_parsed = json.loads(keywords)\n threshold = compute_threshold(keywords_parsed)\n num_keywords = len(keywords_parsed)\n valid_keywords = []\n print(keywords_parsed)\n for i in range(0, num_keywords):\n if (float(keywords_parsed[i]['relevance']) >= threshold):\n valid_keywords.append(keywords_parsed[i])\n print(json.dumps(valid_keywords))\n return json.dumps(valid_keywords)",
"def test_remove_intermediate_results_suggest(self):\n autocomp = Autocompleter('stock')\n autocomp.store_all()\n\n autocomp.suggest('aapl')\n keys = self.redis.keys('djac.results.*')\n self.assertEqual(len(keys), 0)",
"def jsonp_loads(jsonp):\n json_without_padding = jsonp[jsonp.index(\"(\") + 1: jsonp.rindex(\")\")]\n return json.loads(json_without_padding)",
"def test_remove_intermediate_results_exact_suggest(self):\n setattr(auto_settings, 'MAX_EXACT_MATCH_WORDS', 2)\n autocomp = Autocompleter('stock')\n autocomp.store_all()\n\n autocomp.exact_suggest('aapl')\n keys = self.redis.keys('djac.results.*')\n self.assertEqual(len(keys), 0)\n\n setattr(auto_settings, 'MAX_EXACT_MATCH_WORDS', 0)",
"def test_suggestion_none(self):\r\n search, suggestion = wikipedia.search(\"qmxjsudek\", suggestion=True)\r\n self.assertEqual(search, [])\r\n self.assertEqual(suggestion, None)",
"def _parse_json(self, json_response):\n\n ##TODO: break into parts\n\n # Catch and handle error-responses\n if json_response['_type'] == 'News':\n return [NewsResult(single_json_entry) for single_json_entry in json_response['value']]\n elif json_response['_type'] == 'SearchResponse':\n if not self.total_estimated_matches:\n try:\n print(('Bing says there are an estimated {} results matching your query'.format(\n json_response['webPages']['totalEstimatedMatches'])))\n self.total_estimated_matches = int(json_response['webPages']['totalEstimatedMatches'])\n\n #TODO: !!!!! MASSIVE ASSUMPTION BEING MADE THAT NO 'webPages' value during a web-search == no results\n except KeyError:\n Warning('No results')\n return None\n packaged_json = [WebResult(single_json_entry) for single_json_entry in json_response['webPages']['value']]\n return packaged_json\n elif 'webPages' not in json_response.keys():\n try:\n if bool(json_response['rankingResponse']) is False:\n if self._verbose:\n print('NO RESULTS RETURNED BY BING. RETURNING ORIGINAL JSON.')\n else: pass\n return json_response\n except KeyError:\n # print('unable to determine if empty, attempting WebResult extraction.')\n pass\n try:\n link_list = json_response[self.params['responseFilter']]['value']\n try:\n return [WebResult(single_json_entry) for single_json_entry in link_list]\n except Exception:\n print('unrecognized response format.\\n RETURNING LIST OF URLS, NOT WEBRESULT OBJECTS.')\n return [json_item['url'] for json_item in link_list]\n except KeyError:\n try:\n link_list = json_response['value']\n return [single_json_entry['url'] for single_json_entry in link_list]\n except KeyError:\n raise EnvironmentError('something is wrong with using responsefilter to id the json.\\n aka I\"m a bad coder')\n else: raise JsonParsingError('_parse_json in bingapipy did not parse correctly')",
"def vanillaParse(json_string):\n output = []\n jobj = None\n try:\n jobj = jdecoder.decode(json_string)\n except jdecoder.decoder_error, e:\n jobj = None\n sys.stderr.write(\"\\nJSON Decode error : {0}\".format(str(e)))\n\n #Only return a record when the json string represents the object of interest (should contain tweet object, not information messages)\n if(jobj and jobj.has_key(u'id')):\n for key in output_fields:\n output.append(jobj[key] if jobj.has_key(key) else '')\n return output\n else:\n return None",
"def ft_auto_retweet(ph, count=10, result_type=\"recent\"):\r\n\tsearch = ft_search_tweet(ph, count, result_type)\r\n\ttry:\r\n\t\tfor tweet in search[\"statuses\"]:\r\n\t\t\tft_retweet(tweet[\"id_str\"])\r\n\texcept Exception as e:\r\n\t\tprint(e)",
"def wrap_result(result):\n outer_deferred.callback(ReverseAnswer(result))",
"def _process_results(self, results):\n results = filter(lambda r: r[0] is not None, results)\n results = _DeepStringCoder('utf-8').decode(results)\n\n return results",
"def remove_retweets(func):\n return lambda text: re.sub(r\"([\\s]+|^)RT([\\s]+|$)\", \" \", func(text))",
"def process_spurious_words(self, speech_results, pos_results):\n new_results = []\n for i, result in enumerate(speech_results):\n # Check if word is on its own\n left_gap = result['start'] - speech_results[i - 1]['end']\n if i < len(speech_results) - 1:\n right_gap = result['end'] - speech_results[i + 1]['start']\n else:\n right_gap = 10\n if left_gap < 2 or right_gap < 2:\n new_results.append(result)\n continue\n # Remove if stop word\n if result['word'] in self.nlp.Defaults.stop_words:\n continue\n # Remove if interjection\n if self.get_type(result['start'], pos_results) == 'UH':\n continue\n new_results.append(result)\n return new_results",
"def _filter_movies(suggestions: [dict]) -> [dict]:\n return list(\n filter(lambda s: _has_attr('q', s) and ('feature' == s.get('q') or 'TV movie' == s.get('q')), suggestions['d'])\n )",
"def test_get_empty_recommendations(self):\n taste_dive_api = TasteDiveApi()\n parsed_response = taste_dive_api.get_recommendations(\"tochen\")\n self.assertTrue('Similar' in parsed_response)\n self.assertTrue('Info' in parsed_response.get('Similar'))\n self.assertTrue('Results' in parsed_response.get('Similar'))\n\n self.assertEqual(1, len(parsed_response.get('Similar').get('Info')))\n self.assertEqual(0, len(parsed_response.get('Similar').get('Results')))",
"def cleanse_parse_result(p_url):\n qp_list = parse_qsl(p_url.query)\n cleansed_qp_list = []\n clog.debug(qp_list)\n for qp in qp_list:\n if not qp[0].startswith(CLEANSE_PREFIXES):\n cleansed_qp_list.append(qp)\n return p_url._replace(query=urlencode(cleansed_qp_list))",
"def _parse_json(self, json_response):\n if not self.total_estimated_matches and self.endpoint_type == 'web':\n print(('Bing says there are an estimated {} results matching your query'.format(json_response['webPages']['totalEstimatedMatches'])))\n self.total_estimated_matches = int(json_response['webPages']['totalEstimatedMatches'])\n packaged_json = [WebResult(single_json_entry) for single_json_entry in json_response['webPages']['value']]\n return packaged_json",
"def parse_watson_result(result):\n if \"results\" not in result:\n raise ValueError(\"Result does not have \\\"results\\\" attribute\")\n ret_list = []\n for sen_item in result[\"results\"]:\n if len(sen_item) == 0:\n raise ValueError(\"No results\")\n # Watson by default return the first sentence\n sentence_dict = sen_item[\"alternatives\"][0]\n timestamps = sentence_dict[\"timestamps\"]\n confidence = sentence_dict[\"confidence\"]\n text = sentence_dict[\"transcript\"].strip()\n start_time = timestamps[0][1]\n end_time = timestamps[-1][2]\n sentence = {\"text\": text,\n \"confidence\": confidence,\n \"start_time\": start_time,\n \"end_time\": end_time\n }\n ret_list.append(sentence)\n return ret_list"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Filter only movies in IMDB suggestions.
|
def _filter_movies(suggestions: [dict]) -> [dict]:
return list(
filter(lambda s: _has_attr('q', s) and ('feature' == s.get('q') or 'TV movie' == s.get('q')), suggestions['d'])
)
|
[
"def movie_suggestions(self, movie_id):\n self.endpoint = 'movie_suggestions.json'\n self.payload = {'movie_id': movie_id}\n return self.__make_request()",
"def search_videos(self, search_term):\n results = []\n for video in self._video_library.get_all_videos():\n if search_term.lower() in video.title.lower():\n if not video.flag:\n results.append(video)\n self.display_search(results, search_term)",
"def movie_results_by_filter():\n### FROM random_movies_search.html\n\n genres = request.args.getlist(\"genre\")\n gte = request.args.get(\"gte\")\n lte = request.args.get(\"lte\")\n\n payload = get_movie_payload(genres, gte, lte)\n response = requests.get(MOVIEDB_URL + \"discover/movie\", params=payload)\n data = response.json()\n\n page = data['total_pages']\n if int(page)>1000:\n page = 50\n\n payload.update({'page': randint(1, page)})\n response = requests.get(MOVIEDB_URL + \"discover/movie\", params=payload)\n data = response.json()\n movies = data['results']\n\n return render_template(\"random_movies_search.html\", movies=movies)",
"def filter_recommendations(recommended_movies, movies_ratings_2019):\n filtered_recommendations = (\n movies_ratings_2019.filter(\n movies_ratings_2019.movieId.isin(recommended_movies)\n )\n .filter(movies_ratings_2019.genres.contains(top_genre))\n .filter(movies_ratings_2019.avg_rating > 3.5)\n .sort(desc(\"total_ratings\"))\n .limit(10)\n )\n filtered_recommended_movies = {\n row.movieId: row.title for row in filtered_recommendations.collect()\n }\n return filtered_recommended_movies",
"def search():\n app.logger.info('Searching for %s' % request.args.get('q'))\n movie = request.args.get('q')\n m = i.search_movie(movie)\n resp = make_response(json.dumps(\n [{\n 'value': mt['long imdb title'],\n 'id': mt.getID()\n } for mt in m if mt.get('kind') == 'movie']))\n resp.headers['Content-Type'] = 'application/json'\n resp.headers['Access-Control-Allow-Origin'] = '*'\n return resp",
"def search_videos(self, search_term: str) -> None:\n videos = self._get_sorted_videos()\n videos = [v for v in videos if search_term.lower() in v.title.lower()]\n\n self._print_search_results(search_term, videos)",
"def related(self, movie_id):\n url = \"https://yts.ag/api/v2/movie_suggestions.json?movie_id=%s\" % movie_id\n res = requests.get(url)\n dic = res.json()\n return dic['data']['movies']",
"def clean_tmdb_movies(tmdb_movies_df):\n tmdb_movies_df['genre_ids'] = tmdb_movies_df['genre_ids'].map(genre_ids_to_list)\n tmdb_movies_df['genre_ids'] = tmdb_movies_df['genre_ids'].map(recast_genre)\n tmdb_movies_df = remove_non_en(tmdb_movies_df)\n tmdb_movies_df = drop_tmdb_cols(tmdb_movies_df)\n tmdb_movies_df = tmdb_movies_df[tmdb_movies_df['vote_count'] > 100]\n \n return tmdb_movies_df",
"def search_movies(request):\n movie_title = request.data['title']\n search_movie_url = 'https://api.themoviedb.org/3/search/movie?api_key={}&query={}'.format(api_key, movie_title)\n connect = req.urlopen(search_movie_url)\n data = json.loads(connect.read())\n return JsonResponse({'search results': data['results']}, status= status.HTTP_200_OK)",
"def search_film(film_title=None, year=None, imdb_id=None, criticker_id=None,\n filmweb_id=None):\n from film20.utils.texts import normalized_text\n title_normalized = normalized_text(film_title)\n\n if imdb_id:\n try:\n film = Film.objects.get(imdb_code=imdb_id)\n if normalized_text(film.title) == title_normalized and (not year or\n year == film.release_year):\n return film\n else:\n logger.debug(\"WARN: not matching film! searching for: #%s %s (%s); found %s (%s)\" % (imdb_id,\n film_title.encode('utf-8'),\n year, film.title.encode('utf-8'),\n film.release_year))\n # fix for http://jira.filmaster.org/browse/FLM-491\n # fetch movie by this imdb_code and check if year is same\n # and title is in akas then return this film\n movie = imdb_fetcher.get_movie_by_id(imdb_id, \"http\")\n if movie:\n if movie.get('year') == year:\n akas = movie.get('akas')\n for aka in akas:\n t, c = aka.split('::')\n if t == film_title:\n logger.info(\" -- title is: %s\" % c)\n return film\n else:\n logger.error(\"ERROR: this imdb_code is probably wrong ...\")\n\n except Exception, e:\n logger.error(\"ERROR: %s\" % e)\n if criticker_id:\n try:\n return Film.objects.get(criticker_id=str(criticker_id))\n except:\n pass\n\n all_results = global_search_film( film_title )\n \n if year:\n all_results = [f for f in all_results if f.release_year == year]\n #print \"new all results for %s (%s): %s\" % (film_title, year, [\"%s (%s)\" % (f.title, f.release_year) for f in all_results])\n exact, normalized, fuzzy = [], [], []\n\n def filter_films():\n for film in all_results:\n e = n = f = False\n if film.title.lower() == title_lower:\n exact.append(film)\n e = True\n norm = normalized_text(film.title)\n if norm == title_normalized:\n normalized.append(film)\n n = True\n #if norm.startswith(title_normalized) or title_normalized.startswith(norm):\n if norm in title_normalized or title_normalized in norm:\n fuzzy.append(film)\n f = True\n if not e:\n for l in FilmLocalized.objects.filter(film=film.id):\n if not e and l.title.lower() == title_lower:\n exact.append(film)\n e = True\n norm = normalized_text(l.title)\n if not n and norm == title_normalized:\n normalized.append(film)\n n = True\n #if not f and (norm.startswith(title_normalized) or title_normalized.startswith(norm)):\n if not f and (norm in title_normalized or title_normalized in norm):\n fuzzy.append(film)\n f = True\n filter_films()\n\n if len(exact) == 1:\n return exact[0]\n if len(normalized) == 1:\n return normalized[0]\n #if year and len(fuzzy)==1:\n # try:\n # print \"INFO: returning fuzzy match for %s (%s): %s (%s)\" % (film_title, year, fuzzy[0].title, fuzzy[0].release_year)\n # except UnicodeEncodeError:\n # print \"INFO: fuzzy match for %s(imdb) %s(criticker) (and unicode encode error problem!)\" % (imdb_code, criticker_id)\n # return fuzzy[0]\n #if not normalized and len(all_results)==1:\n # return all_results[0]\n if year:\n all_results = [f for f in all_results if abs(f.release_year - int(year)) <= 1]\n filter_films()\n if len(exact) == 1:\n return exact[0]\n if len(normalized) == 1:\n return normalized[0]\n return None",
"def set_suggestions(request):\n if request.FILES:\n jsonfile = request.FILES['json_file']\n\n # Load JSON file\n movies = json.load(jsonfile.open())\n\n # Add all entries to the suggestions object\n for movie in movies:\n # Sanitize JSON\n for key, value in movie.items():\n if value == None:\n movie[key] = \"\"\n\n obj = Suggestion.objects.filter(name=movie[\"title\"], video=movie[\"ytid\"])\n\n # Avoid duplicates\n if obj:\n continue\n \n s = Suggestion(name=movie[\"title\"], video=movie[\"ytid\"],\n rated=movie[\"rated\"], released=movie[\"released\"],\n runtime=movie[\"runtime\"], genres=movie[\"genres\"],\n director=movie[\"director\"], writer=movie[\"writer\"],\n actors=movie[\"actors\"], plot=movie[\"plot\"],\n languages=movie[\"languages\"], country=movie[\"country\"],\n awards=movie[\"awards\"])\n\n s.save()\n \n return redirect(\"/suggestions/\")\n else:\n return HttpResponse('error')",
"def metadata_recommender_with_keywords(self, movie_id):\n logging.debug(\n f'[{self.metadata_recommender_with_keywords.__name__}] - start function with movie id: {movie_id}')\n if movie_id not in self.movie_metadata:\n return []\n genres = self.movie_metadata[movie_id][GENRES_COL]\n keywords = self.movie_metadata[movie_id][KEYWORDS_COL]\n\n movie_scores_ref = list()\n Recommender.add_score_to_list(genres, 2, movie_scores_ref)\n Recommender.add_score_to_list(keywords, 10, movie_scores_ref)\n\n movie_points_jaccard = dict()\n\n for key, movie in self.movie_metadata.items():\n if key == movie_id:\n continue\n movie_scores = list()\n Recommender.match_with_bias(movie[GENRES_COL], genres, 2, 0, movie_scores)\n Recommender.match_with_bias(movie[KEYWORDS_COL], keywords, 10, 5, movie_scores)\n\n movie_points_jaccard[key] = float(sm.jaccard_similarity(movie_scores_ref, movie_scores))\n recommendation = sorted(movie_points_jaccard, key=lambda x: movie_points_jaccard[x], reverse=True)\n return recommendation[:5]",
"def scan_movies(self, year_range):\n movies = []\n scan_kwargs = {\n 'FilterExpression': Key('year').between(year_range['first'], year_range['second']),\n 'ProjectionExpression': \"#yr, title, info.rating\",\n 'ExpressionAttributeNames': {\"#yr\": \"year\"}}\n try:\n done = False\n start_key = None\n while not done:\n if start_key:\n scan_kwargs['ExclusiveStartKey'] = start_key\n response = self.table.scan(**scan_kwargs)\n movies.extend(response.get('Items', []))\n start_key = response.get('LastEvaluatedKey', None)\n done = start_key is None\n except ClientError as err:\n logger.error(\n \"Couldn't scan for movies. Here's why: %s: %s\",\n err.response['Error']['Code'], err.response['Error']['Message'])\n raise\n\n return movies",
"def get_queryset(self):\n\n user = self.request.user\n\n # get all movies that user has not marked as seen nor added to their watchlist\n # remember that 'user_notes' is the related name defined on the Movie model for the m2m connection to User\n possible_movies = Movie.objects.exclude(user_notes=user, usermovielink__seen=True).exclude(user_notes=user,\n usermovielink__watch_list=True)\n\n # pick three movies from possible randomly (sample will not choose duplicates)\n three_chosen = sample(list(possible_movies), 3)\n\n return three_chosen",
"def test_notAddsMoviesFuzzilyContainedInMovieFile(self):\n\n self.__createFileWithMovies('testdata/ignoremovies.txt',\n [u'the shawshank - Redemption',\n u'12 angry MEN,:?'])\n\n consoleOutput = self.__runGoodMovies([\"--list=imdb_top250\",\n \"--count=10\",\n \"--ignorefile=testdata/ignoremovies.txt\",\n \"--ignorefuzzy\",\n \"--language=en-US\"])\n\n # we read 10 movies, but ignored 2 of them, so only 8 should be left\n self.assertEqual(len(consoleOutput),8)\n\n # the ignored movies should not occur in the output...\n self.assertEqual(consoleOutput.count(\"The Shawshank Redemption\"),0)\n self.assertEqual(consoleOutput.count(\"12 Angry Men\"),0)\n\n # ... while other movies should\n self.assertEqual(consoleOutput.count(\"The Godfather\"),1)",
"def movies(self, limit):\n url = \"https://yts.ag/api/v2/list_movies.json?sort=seeds&limit=%s&order_by=asc&quality=1080p\" % limit\n res = requests.get(url)\n dic = res.json()\n return dic['data']['movies']",
"def get_all_movies_from_quote(search_term):\n\n parsed_term = quote_plus(search_term)\n url = \"http://api.quodb.com/search/\" + parsed_term + \"?titles_per_page=100&phrases_per_title=1000&page=1\"\n movie_list = []\n http_output = get(url)\n try:\n json_data = json.loads(json.dumps(http_output.json()))\n search_term = search_term.translate(str.maketrans('', '', punctuation))\n iterations = len(json_data[\"docs\"])\n for i in range(iterations):\n title = json_data[\"docs\"][i][\"title\"]\n phrase = json_data[\"docs\"][i][\"phrase\"].translate(str.maketrans('', '', punctuation))\n if phrase.find(search_term) != -1:\n movie_list.append(title)\n return movie_list\n except:\n return \"None\"",
"def search(self, title):\n title = urllib.quote(title.encode(\"utf-8\"))\n url = config['urls']['movie.search'] % (title)\n etree = XmlHandler(url).getEt()\n search_results = SearchResults()\n for cur_result in etree.find(\"movies\").findall(\"movie\"):\n cur_movie = self._parseMovie(cur_result)\n search_results.append(cur_movie)\n return search_results",
"def get_movies_for_tag(self, tag):\n tag_specific_data = self.genre_data[self.genre_data[\"tag_string\"] == tag]\n movies_list = tag_specific_data[\"movieid\"].unique()\n\n return movies_list"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
A newly joined node is catching up and sends catchup requests to other nodes but one of the nodes does not reply and the newly joined node cannot complete the process till the timeout and then requests the missing transactions.
|
def testNodeRequestingTxns(reduced_catchup_timeout_conf, txnPoolNodeSet,
nodeCreatedAfterSomeTxns):
looper, newNode, client, wallet, _, _ = nodeCreatedAfterSomeTxns
new_node_ledger = newNode.ledgerManager.ledgerRegistry[DOMAIN_LEDGER_ID]
old_size = len(new_node_ledger.ledger)
old_size_others = txnPoolNodeSet[0].ledgerManager.ledgerRegistry[DOMAIN_LEDGER_ID].ledger.size
# So nodes wont tell the clients about the newly joined node so they
# dont send any request to the newly joined node
for node in txnPoolNodeSet:
node.sendPoolInfoToClients = types.MethodType(lambda x, y: None, node)
def ignoreCatchupReq(self, req, frm):
logger.info("{} being malicious and ignoring catchup request {} "
"from {}".format(self, req, frm))
# One of the node does not process catchup request.
npr = getNonPrimaryReplicas(txnPoolNodeSet, 0)
badReplica = npr[0]
badNode = badReplica.node
txnPoolNodeSet.append(newNode)
badNode.nodeMsgRouter.routes[CatchupReq] = types.MethodType(
ignoreCatchupReq, badNode.ledgerManager)
more_requests = 10
sendRandomRequests(wallet, client, more_requests)
looper.run(checkNodesConnected(txnPoolNodeSet))
# Since one of the nodes does not reply, this new node will experience a
# timeout and retry catchup requests, hence a long test timeout.
timeout = waits.expectedPoolGetReadyTimeout(len(txnPoolNodeSet)) + \
reduced_catchup_timeout_conf.CatchupTransactionsTimeout
waitNodeDataEquality(looper, newNode, *txnPoolNodeSet[:-1],
customTimeout=timeout)
new_size = len(new_node_ledger.ledger)
# The new node ledger might catchup some transactions from the batch of
# `more_request` transactions
assert old_size_others - \
old_size <= new_node_ledger.num_txns_caught_up <= new_size - old_size
sendRandomRequests(wallet, client, 2)
|
[
"def retry_notifier():\n if graph_copy.has_node(target.name):\n ready_nodes.append(target.name)\n produced_event.set()",
"def queuing_requests(self):\r\n\r\n for node in self.want_enter_to_cs:\r\n self.send_requests_to_root(node)",
"def rejoin(self):\n #read the cash file and get the last_ips\n re_join_request_dict = { 'Type' : \"re_Join_req\", \n 'Process_id' : (str(os.getpid())).strip(), \n 'IP_address' : self.IP_ADDRESS,\n 'Timestamp' : (str(datetime.now().isoformat(timespec='seconds'))).strip(),\n 'Port' : str(self.PORT)\n }\n re_join_request_json = json.dumps(re_join_request_dict)\n re_join_data = (re_join_request_json).encode('utf-8')\n with open(\"ip.txt\", 'r', encoding = 'utf-8') as f:\n ip_list = f.readlines()\n ip_list = [x.strip() for x in ip_list]\n print(\"Send out rejoin\")\n for target_ip_address in ip_list:\n self.socket.sendto(re_join_data, (target_ip_address, self.PORT))",
"def test_payment_timing_out_if_partner_does_not_respond( # pylint: disable=unused-argument\n raiden_network, token_addresses, reveal_timeout, retry_timeout\n):\n\n app0, app1 = raiden_network\n token_address = token_addresses[0]\n\n def fake_receive(room, event): # pylint: disable=unused-argument\n return True\n\n with patch.object(app1.raiden.transport, \"_handle_message\", side_effect=fake_receive):\n greenlet = gevent.spawn(\n RaidenAPI(app0.raiden).transfer,\n app0.raiden.default_registry.address,\n token_address,\n 1,\n target=app1.raiden.address,\n )\n waiting.wait_for_block(\n app0.raiden, app1.raiden.get_block_number() + 2 * reveal_timeout + 1, retry_timeout\n )\n greenlet.join(timeout=5)\n assert not greenlet.value",
"def join_finished(self, tp_link, peer_id, uri, is_orginator):\n # while a link is pending it is the responsibility of the transport layer, since\n # higher layers don't have any use for it anyway\n _log.analyze(self.node.id, \"+\", {'uri': uri, 'peer_id': peer_id,\n 'pending_joins': self.pending_joins,\n 'pending_joins_by_id': self.pending_joins_by_id},\n peer_node_id=peer_id, tb=True)\n if tp_link is None:\n # This is a failed join lets send it upwards\n if uri in self.pending_joins:\n cbs = self.pending_joins.pop(uri)\n if cbs:\n for cb in cbs:\n cb(status=response.CalvinResponse(response.SERVICE_UNAVAILABLE), uri=uri, peer_node_id=peer_id)\n return\n # Only support for one RT to RT communication link per peer\n if peer_id in self.links:\n # Likely simultaneous join requests, use the one requested by the node with highest id\n if is_orginator and self.node.id > peer_id:\n # We requested it and we have highest node id, hence the one in links is the peer's and we replace it\n _log.analyze(self.node.id, \"+ REPLACE ORGINATOR\", {'uri': uri, 'peer_id': peer_id}, peer_node_id=peer_id)\n self.links[peer_id] = CalvinLink(self.node.id, peer_id, tp_link, self.links[peer_id])\n self.links[peer_id].set_transport_category(tp_link.get_transport_category())\n elif is_orginator and self.node.id < peer_id:\n # We requested it and peer have highest node id, hence the one in links is peer's and we close this new\n _log.analyze(self.node.id, \"+ DROP ORGINATOR\", {'uri': uri, 'peer_id': peer_id}, peer_node_id=peer_id)\n tp_link.disconnect()\n elif not is_orginator and self.node.id > peer_id:\n # Peer requested it and we have highest node id, hence the one in links is ours and we close this new\n _log.analyze(self.node.id, \"+ DROP\", {'uri': uri, 'peer_id': peer_id}, peer_node_id=peer_id)\n tp_link.disconnect()\n elif not is_orginator and self.node.id < peer_id:\n # Peer requested it and peer have highest node id, hence the one in links is ours and we replace it\n _log.analyze(self.node.id, \"+ REPLACE\", {'uri': uri, 'peer_id': peer_id}, peer_node_id=peer_id)\n self.links[peer_id] = CalvinLink(self.node.id, peer_id, tp_link, self.f[peer_id])\n self.links[peer_id].set_transport_category(tp_link.get_transport_category())\n else:\n # No simultaneous join detected, just add the link\n _log.analyze(self.node.id, \"+ INSERT\", {'uri': uri, 'peer_id': peer_id}, peer_node_id=peer_id, tb=True)\n self.links[peer_id] = CalvinLink(self.node.id, peer_id, tp_link)\n self.links[peer_id].set_transport_category(tp_link.get_transport_category())\n\n # Find and call any callbacks registered for the uri or peer id\n _log.debug(\"%s: peer_id: %s, uri: %s\\npending_joins_by_id: %s\\npending_joins: %s\" % (self.node.id, peer_id,\n uri,\n self.pending_joins_by_id,\n self.pending_joins))\n if peer_id in self.pending_joins_by_id:\n peer_uri = self.pending_joins_by_id.pop(peer_id)\n if peer_uri in self.pending_joins:\n cbs = self.pending_joins.pop(peer_uri)\n if cbs:\n for cb in cbs:\n cb(status=response.CalvinResponse(True), uri=peer_uri, peer_node_id=peer_id)\n\n if uri in self.pending_joins:\n cbs = self.pending_joins.pop(uri)\n if cbs:\n for cb in cbs:\n cb(status=response.CalvinResponse(True), uri=uri, peer_node_id=peer_id)\n\n return",
"def gossip_style_check_time_out(self): \n #find failed then send the failure, set that failed heartbeat counter as -1, only delete failed at the next round\n mutex.acquire()\n all_ip = list(self.membership_dict.keys())\n for checking_ip_address in all_ip:\n if (checking_ip_address == self.IP_ADDRESS):\n continue\n #0.if heartbeat_counter==-1, delete since failed, continue\n if (self.membership_dict[checking_ip_address][2] == -1):\n fail_ip = checking_ip_address\n repair = threading.Thread(target = self.files_repair, args=(self.membership_dict[fail_ip][4].copy(), fail_ip))#do files_repair\n repair.start()\n self.membership_dict.pop(fail_ip)\n continue\n\n\n #check failure\n local_time = datetime.now()\n last_heartbeat_time_at_index = self.membership_dict[checking_ip_address][1]\n if (type(last_heartbeat_time_at_index) == str):\n last_heartbeat_time_at_index = datetime.strptime(last_heartbeat_time_at_index, '%Y-%m-%d %H:%M:%S.%f')\n if ((local_time - last_heartbeat_time_at_index).total_seconds() > max(1.1*math.log2(len(self.membership_dict.keys())), 3)):#larger than gossiping time == time for any node to quite safly\n #failes,\n #1.set that failed heartbeat counter as -1,deltete at the next round \n #2.append to known_gossiping_messages to avoid confusion \n #3.gossip this failure of checking_ip_address, \n fail_ip = checking_ip_address\n logging.info(f'Failure on ip:{fail_ip}')\n self.membership_dict[fail_ip][2] = -1\n #generate data of Type Failure to add on known_gossiping_messages and then gossip it\n failure_to_send = { 'Type' : \"Failure\", \n 'Failed_machine_ip' : fail_ip,\n 'Timestamp' : (str(datetime.now().isoformat(timespec='seconds'))).strip()\n }\n failure_to_send_json = json.dumps(failure_to_send)\n data = (failure_to_send_json).encode('utf-8')\n known_gossiping_messages.append(data)\n mutex.release()\n #gossip the data\n mutex_gossiping.acquire()\n gossiping_massages.append((data,datetime.now()))#add on list of messages to gossip\n #logging.info(f'Gossip {data} started')\n mutex_gossiping.release()\n mutex.acquire()\n #else no failure\n mutex.release()",
"def all_to_all_check_time_out(self): \n mutex.acquire()\n all_ip = list(self.membership_dict.keys())\n for checking_ip_address in all_ip:\n if (checking_ip_address == self.IP_ADDRESS):\n continue\n local_time = datetime.now()\n last_heartbeat_time_at_index = self.membership_dict[checking_ip_address][1]\n if (type(last_heartbeat_time_at_index) == str):\n last_heartbeat_time_at_index = datetime.strptime(last_heartbeat_time_at_index, '%Y-%m-%d %H:%M:%S.%f')\n if ((local_time - last_heartbeat_time_at_index).total_seconds() > max(1.1*math.log2(len(self.membership_dict.keys())), 3)):#larger than gossiping time == time for any node to quite safly\n #failes, 1.remove from membership list then 2.append to known_gossiping_messages to avoid confusion 3.gossip this failure of checking_ip_address\n fail_ip = checking_ip_address\n logging.info(f'Failure on ip:{fail_ip}')\n repair = threading.Thread(target = self.files_repair, args=(self.membership_dict[fail_ip][4].copy(), fail_ip))#do files_repair\n repair.start()\n self.membership_dict.pop(fail_ip)\n logging.info(f'update membership list : \\n')\n self.print_memTable()\n #generate data of Type Failure to add on known_gossiping_messages and then gossip it\n failure_to_send = { 'Type' : \"Failure\", \n 'Failed_machine_ip' : fail_ip,\n 'Timestamp' : (str(datetime.now().isoformat(timespec='seconds'))).strip()\n }\n failure_to_send_json = json.dumps(failure_to_send)\n data = (failure_to_send_json).encode('utf-8')\n known_gossiping_messages.append(data)\n mutex.release()\n #gossip the data\n mutex_gossiping.acquire()\n gossiping_massages.append((data,datetime.now()))#add on list of messages to gossip\n #logging.info(f'Gossip {data} started')\n mutex_gossiping.release()\n mutex.acquire()\n #else no failure\n mutex.release()",
"def test_process_online(self):\n\n self._no_cmd_tx_evts = self._no_requests\n self._no_queue_mod_evts = self._no_requests\n self._no_telem_evts = 2\n \n self.on_link_up()\n \n for i in range(self._no_requests):\n cmd = self.make_fake_command(i)\n cmd = self.te_client.enqueue_command(cmd)\n self._requests_sent[cmd.command_id] = cmd\n gevent.sleep(.2)\n\n self._done_queue_mod_evts.get(timeout=CFG.endpoint.receive.timeout)\n self._done_cmd_tx_evts.get(timeout=CFG.endpoint.receive.timeout)\n self._done_evt.get(timeout=CFG.endpoint.receive.timeout)\n \n pending = self.te_client.get_pending()\n self.assertEqual(len(pending), 0)\n \n self.on_link_down()\n\n self._done_telem_evts.get(timeout=CFG.endpoint.receive.timeout)\n\n self.assertItemsEqual(self._requests_sent.keys(),\n self._results_recv.keys())",
"def test_htlc_out_timeout(node_factory, bitcoind, executor):\n\n # HTLC 1->2, 1 fails after it's irrevocably committed, can't reconnect\n disconnects = ['-WIRE_REVOKE_AND_ACK']\n # Feerates identical so we don't get gratuitous commit to update them\n l1 = node_factory.get_node(disconnect=disconnects,\n options={'dev-no-reconnect': None},\n feerates=(7500, 7500, 7500, 7500))\n l2 = node_factory.get_node()\n\n l1.rpc.connect(l2.info['id'], 'localhost', l2.port)\n chanid, _ = l1.fundchannel(l2, 10**6)\n\n # Wait for route propagation.\n l1.wait_channel_active(chanid)\n\n amt = 200000000\n inv = l2.rpc.invoice(amt, 'test_htlc_out_timeout', 'desc')['bolt11']\n assert only_one(l2.rpc.listinvoices('test_htlc_out_timeout')['invoices'])['status'] == 'unpaid'\n\n executor.submit(l1.dev_pay, inv, use_shadow=False)\n\n # l1 will disconnect, and not reconnect.\n l1.daemon.wait_for_log('dev_disconnect: -WIRE_REVOKE_AND_ACK')\n\n # Takes 6 blocks to timeout (cltv-final + 1), but we also give grace period of 1 block.\n # shadow route can add extra blocks!\n status = only_one(l1.rpc.call('paystatus')['pay'])\n if 'shadow' in status:\n shadowlen = 6 * status['shadow'].count('Added 6 cltv delay for shadow')\n else:\n shadowlen = 0\n\n bitcoind.generate_block(5 + 1 + shadowlen)\n time.sleep(3)\n assert not l1.daemon.is_in_log('hit deadline')\n bitcoind.generate_block(1)\n\n l1.daemon.wait_for_log('Offered HTLC 0 SENT_ADD_ACK_REVOCATION cltv .* hit deadline')\n l1.daemon.wait_for_log('sendrawtx exit 0')\n l1.bitcoin.generate_block(1)\n l1.daemon.wait_for_log(' to ONCHAIN')\n l2.daemon.wait_for_log(' to ONCHAIN')\n\n # L1 will timeout HTLC immediately\n ((_, _, blocks1), (_, txid, blocks2)) = \\\n l1.wait_for_onchaind_txs(('OUR_DELAYED_RETURN_TO_WALLET',\n 'OUR_UNILATERAL/DELAYED_OUTPUT_TO_US'),\n ('OUR_HTLC_TIMEOUT_TX',\n 'OUR_UNILATERAL/OUR_HTLC'))\n assert blocks1 == 4\n # We hit deadline (we give 1 block grace), then mined another.\n assert blocks2 == -2\n\n bitcoind.generate_block(1, wait_for_mempool=txid)\n\n rawtx, txid, blocks = l1.wait_for_onchaind_tx('OUR_DELAYED_RETURN_TO_WALLET',\n 'OUR_HTLC_TIMEOUT_TX/DELAYED_OUTPUT_TO_US')\n assert blocks == 4\n bitcoind.generate_block(4)\n\n # It should now claim both the to-local and htlc-timeout-tx outputs.\n l1.daemon.wait_for_logs(['sendrawtx exit 0.*{}'.format(rawtx),\n 'sendrawtx exit 0'])\n\n # Now, 100 blocks it should be done.\n bitcoind.generate_block(100, wait_for_mempool=txid)\n l1.daemon.wait_for_log('onchaind complete, forgetting peer')\n l2.daemon.wait_for_log('onchaind complete, forgetting peer')",
"def test_reconnect_route_request(self):\n pass",
"async def MasterServer():\n\n for provider in providers: \n # Organize the servers for our providers.\n provider.servers = GrabServersForProvider(provider.ID)\n provider.servers = OrganizeProviderServers(provider.servers)\n provider.timeSinceLastUpdate = int(time.time())\n\n while True:\n # Grab our server list with an HTTP request.\n for provider in providers:\n # Has it been an hour and we need to do a check for new servers?\n if provider.timeSinceLastUpdate + hour < int(time.time()):\n print(Fore.YELLOW + f\"[PENDING] Grabbing new server information for {provider.ID}.\" + Fore.RESET)\n provider.servers = None\n\n # Grab and organize new servers.\n provider.servers = GrabServersForProvider(provider.ID)\n provider.servers = OrganizeProviderServers(provider.servers)\n\n provider.timeSinceLastUpdate = int(time.time())\n print(Fore.GREEN + f\"[SUCCESS] Grabbed {len(provider.servers)} for {provider.ID}.\" + Fore.RESET)\n \n provider.isCurrentlyPolling = True\n\n # We now have a list of servers. We're going to create blocks where we'll query\n # a block of servers and ship them off in a request. By default, we'll have\n # five servers in a block that we'll send off in a list. If we happen to have\n # less than five servers in a block because we've reached the end of a list for\n # a provider, that's alright, we'll send them anyways.\n serverBlock = []\n\n # If we've recently pinged this server with A2S, we'll add a delay\n # so we have the best chance of getting server information. Only the latest\n # four servers will be here.\n recentServers = []\n\n # Loop through all of our servers so we can query them.\n for server in provider.servers:\n serverUniqueID = server[\"ip\"][0:3] # Grab the first three characters of the IP as a unique identifier.\n if serverUniqueID in recentServers: # Add a delay of one second so we don't spam this IP too much.\n print(Fore.YELLOW + f\"[PENDING] Resting {server['ip']}:{server['port']} for one second.\" + Fore.RESET)\n await asyncio.sleep(1)\n\n # Okay, now lets send a query to the server asking for information.\n result = await QueryServer(server[\"id\"], (server[\"ip\"], server[\"port\"]))\n\n # If we're already at 5 entires in our recent servers list,\n # remove the first one and add in this servers unique ID.\n if serverUniqueID not in recentServers:\n recentServers.append(serverUniqueID)\n \n if len(recentServers) > 5:\n recentServers.remove(recentServers[0])\n\n # Do we have a block of ten servers we can ship off?\n if (len(serverBlock) < 10): # No? Append the list.\n if result != None:\n serverBlock.append(result)\n else: # We already have a block of five servers, ship it off.\n await SendServersToHeartbeat(serverBlock)\n serverBlock.clear()\n recentServers.clear()\n # Add this server to the list afterwards as well.\n if result != None:\n serverBlock.append(result)\n\n # If we have any servers remaining in our server block, just send them over.\n if (len(serverBlock) != 0):\n await SendServersToHeartbeat(serverBlock)\n recentServers.clear()\n\n provider.isCurrentlyPolling = False\n\n print(Fore.MAGENTA + f\"Sleeping for {int(sleeptime)} seconds...\" + Fore.RESET)\n await asyncio.sleep(int(sleeptime))\n recentServers.clear()",
"def on_peer_join(self, node_info):\n msg = json.dumps({'type': 'user_join', 'id': node_info['node_id'], 'name': node_info['name']})\n self.send_to_all_clients(msg)",
"def run(self):\n # Enable to kill the node using Ctrl + C\n signal.signal(signal.SIGINT, self.__signal_handler)\n\n\n while True:\n time.sleep(.01)\n node_request = self.server.listen_info()\n print (\"Request: \" + str(node_request))\n if 'node' in node_request:\n if node_request['node'] in self.nodes_register:\n current_pid = self.nodes_register[node_request['node']]\n if node_request['pid'] == current_pid:\n pass\n else:\n try:\n\n print (\"kill: \" + str(current_pid))\n os.kill(current_pid, signal.SIGTERM)\n time.sleep(1)\n\n\n except:\n pass\n \n self.nodes_register[node_request['node']] = node_request['pid']\n\n topic = str(node_request['topic'])\n current_pid = node_request['pid']\n \n if topic in self.topic_register:\n self.__onRegisteredTopic(topic, node_request)\n else:\n self.__onNewTopic(node_request)\n \n\n # Get avaliable topic list\n elif 'topic_list' in node_request: \n msg = self.topic_register\n self.server.send_info(msg)\n\n elif 'master' in node_request: \n action = node_request[\"master\"]\n if action == \"node_kill\":\n self.stopNode(node_request)\n self.server.send_info({\"node\":\"close_node\", \"status\":\"success\"})\n\n elif action == \"kill_all\":\n pass\n \n \n else:\n self.server.send_info({\"node\":\"action\", \"status\":\"failure\"})\n\n else:\n self.server.send_info({\"node\":\"action\", \"status\":\"failure\"})\n\n\n #action = node_request[\"master\"]\n #if action == \"stop\":\n # print (\"Master stoping ...\")\n # time.sleep(1)\n # for p in self.brokers:\n # p.stop()\n # self.server.send_info({\"node\":\"stop\", \"status\":\"success\"})\n # break\n #elif action == \"clean\":\n # print (\"Clean master\")\n # \n # for p in self.brokers:\n # self.current_port = self.initial_port_number\n # p.stop()\n\n\n # self.__stop()\n # self.topic_register = {}\n\n \n # self.server.send_info({\"node\":\"clean\", \"status\":\"success\"})\n #else:\n # self.server.send_info({\"node\":action, \"status\":\"failure\"})\n \n print (self.topic_register)\n print (self.nodes_register)",
"def test_mutual_reconnect_race(node_factory, executor, bitcoind):\n l1, l2 = node_factory.line_graph(2, opts={'may_reconnect': True,\n 'dev-no-reconnect': None})\n\n def send_many_payments():\n for i in range(20):\n time.sleep(0.5)\n inv = l2.rpc.invoice(100, \"label-\" + str(i), \"desc\")['bolt11']\n try:\n l1.rpc.pay(inv)\n except RpcError:\n pass\n\n # Send a heap of payments, while reconnecting...\n fut = executor.submit(send_many_payments)\n\n for i in range(10):\n try:\n l1.rpc.disconnect(l2.info['id'], force=True)\n except RpcError:\n pass\n time.sleep(1)\n # Aim for both at once!\n executor.submit(l1.rpc.connect, l2.info['id'], 'localhost', l2.port)\n executor.submit(l2.rpc.connect, l1.info['id'], 'localhost', l1.port)\n\n # Wait for things to settle down, then make sure we're actually connected.\n # Naively, you'd think we should be, but in fact, two connects which race\n # can (do!) result in both disconnecting, thinking the other side is more\n # recent.\n time.sleep(1)\n if not only_one(l1.rpc.listpeers(l2.info['id'])['peers'])['connected']:\n l1.rpc.connect(l2.info['id'], 'localhost', l2.port)\n\n # Now payments should finish!\n fut.result(TIMEOUT)\n\n wait_for(lambda: only_one(l1.rpc.listpeers(l2.info['id'])['peers'])['connected'])\n inv = l2.rpc.invoice(100000000, \"invoice4\", \"invoice4\")\n l1.rpc.pay(inv['bolt11'])",
"def test_remote_late(self):\n \n self._no_cmd_tx_evts = self._no_requests\n self._no_queue_mod_evts = self._no_requests\n self._no_telem_evts = 2\n \n self.on_link_up()\n\n gevent.sleep(2)\n\n self._remote_server.stop()\n self._remote_client.stop()\n\n for i in range(self._no_requests):\n cmd = self.make_fake_command(i)\n cmd = self.te_client.enqueue_command(cmd)\n self._requests_sent[cmd.command_id] = cmd\n \n self._done_queue_mod_evts.get(timeout=CFG.endpoint.receive.timeout)\n\n gevent.sleep(3)\n \n self._remote_client.start('localhost', self._this_port)\n self._remote_server.start('*', self._other_port)\n\n self._done_cmd_tx_evts.get(timeout=CFG.endpoint.receive.timeout)\n self._done_evt.get(timeout=CFG.endpoint.receive.timeout)\n \n pending = self.te_client.get_pending()\n self.assertEqual(len(pending), 0)\n\n self.on_link_down()\n\n self._done_telem_evts.get(timeout=CFG.endpoint.receive.timeout)\n\n self.assertItemsEqual(self._requests_sent.keys(),\n self._results_recv.keys())",
"def commissioner_joiner_add(self, nodeid: int, usr: str, pwd: str, timeout=None) -> None:\n timeout_s = f\" {timeout}\" if timeout is not None else \"\"\n self.node_cmd(nodeid, f\"commissioner joiner add {usr} {pwd}{timeout_s}\")",
"def _check_election_responses(self):\n print(\"Election timeout reached, checking results\")\n if self.election_request_denials == 0:\n print(\"Election ended and I am the leader!\")\n self.leader_name = self.name\n self.election_request_denials = 0\n self._send_message('all', {\n \"type\": \"new leader\",\n \"sender\": self.name\n })\n else:\n print(\"Got at least one denial, I lost the election :(\")",
"def churnNetwork(self):\n leaving = []\n joining = []\n for nodeID in self.superNodes:\n if random.random() < self.churnRate:\n leaving.append(nodeID)\n for j in self.pool:\n if random.random() < self.churnRate:\n joining.append(j)\n self.pool.remove(j)\n \n tasks = []\n \n for l in leaving:\n tasks += self.removeNode(l)\n self.reallocateTasks(tasks)\n \n for j in joining:\n # assert(len(self.nodeIDs) == len(set(self.nodeIDs)))\n self.insertWorker(j)\n self.addToPool(len(leaving))",
"def wait_for_nodes(self, nodes):\n all_nodes = list(nodes)\n self._start_time = time.time()\n while self._timeout() and len(all_nodes) > 0:\n for node in all_nodes:\n self._ssh_to_node(node)\n if node.available:\n all_nodes.remove(node)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Load team info, subset to relevant columns, and remap column names
|
def team_info(self):
df_team = pd.read_csv(datadir / 'TEAM.csv.gz')
team_cols = {
'gid': 'game_id',
'tname': 'team',
#'pts': 'tm_pts',
'ry': 'tm_rush_yds',
'ra': 'tm_rush_att',
'py': 'tm_pass_yds',
'pa': 'tm_pass_att',
'pc': 'tm_pass_comp',
'sk': 'tm_sacks',
'sky': 'tm_sack_yds',
'ints': 'tm_ints',
'iry': 'tm_int_yds',
'fum': 'tm_fumbles',
'pu': 'tm_punts',
'gpy': 'tm_punt_yds',
'fgm': 'tm_field_goals',
'fgat': 'tm_field_goal_att',
'pen': 'tm_penalty_yds',
'top': 'tm_possess_time',
'tdp': 'tm_pass_tds',
'tdr': 'tm_rush_tds',
'td': 'tm_tds',
'qba': 'tm_qb_rush_att',
'qby': 'tm_qb_rush_yds'}
df_team = df_team[team_cols.keys()].rename(team_cols, axis=1)
df_team = df_team.merge(self.quarterback_info, on=['game_id', 'team'])
return df_team
|
[
"def _load_teams(self):\n self.teams = list(np.unique(self.input_df[[\"HomeTeam\", \"AwayTeam\"]].values.ravel('F')))\n self.results_df = pd.DataFrame(self.teams, columns=['team'])",
"def _load_team_cities(self, country):\n url = SoccerParser.team_cities_lookup[country]['url']\n table_no = SoccerParser.team_cities_lookup[country]['table_no']\n city_field = SoccerParser.team_cities_lookup[country]['city_field']\n team_field = SoccerParser.team_cities_lookup[country]['team_field']\n c_teams_df = pd.read_html(url)[table_no]\n for team in self.teams:\n city_as_dict = c_teams_df[c_teams_df[team_field].str.contains(team)][city_field]\n if not city_as_dict.empty:\n city = city_as_dict.values[0]\n self.results_df[self.results_df.team == team]['city'] = city\n self.results_df[self.results_df.team == team]['country'] = country",
"def _load_matches(self):\n for team in self.teams:\n self._load_team_matches(team)\n self.match_df['result_int'] = self.match_df.result.apply(winloss_to_int)\n self.match_df['unixtime'] = self.match_df.date.apply(lambda row: row.timestamp())",
"def test_load_soruces_renamed_columns():\n filename = 'tests/test_files/1904_comp_renamed_cols.fits'\n colnames = {'ra_col': 'RAJ2000',\n 'dec_col': 'DEJ2000',\n 'peak_col': 'S',\n 'a_col': 'bmaj',\n 'b_col': 'bmin',\n 'pa_col': 'bpa'}\n cat = ar.load_sources(filename, **colnames)\n if cat is None:\n raise AssertionError(\"load_sources failed with renamed columns\")\n return",
"def test_data_source_postgre_sqls_id_team_get(self):\n pass",
"def read_games(self):\n\n urlmask = 'http://www.football-data.co.uk/mmz4281/{}/{}.csv'\n filemask = 'MatchHistory_{}_{}.csv'\n col_rename = {\n 'Div': 'league',\n 'Date': 'date',\n 'HomeTeam': 'home_team',\n 'AwayTeam': 'away_team',\n }\n\n df_list = []\n current_season_ends = str(date.today().year)[-2:]\n for lkey, skey in itertools.product(self._selected_leagues.values(),\n self.seasons):\n filepath = Path(datadir(), filemask.format(lkey, skey))\n url = urlmask.format(skey, lkey)\n current_season = skey[-2:] >= current_season_ends\n if current_season or (not filepath.exists()):\n self._download_and_save(url, filepath)\n\n df_list.append(\n pd.read_csv(str(filepath),\n parse_dates=['Date'],\n infer_datetime_format=True,\n dayfirst=True,\n encoding='UTF-8',\n )\n .assign(season=skey)\n )\n\n df = (\n pd.concat(df_list)\n .rename(columns=col_rename)\n .pipe(self._translate_league)\n .replace({'home_team': TEAMNAME_REPLACEMENTS,\n 'away_team': TEAMNAME_REPLACEMENTS})\n .dropna(subset=['home_team', 'away_team'])\n )\n\n df['game_id'] = df.apply(self._make_game_id, axis=1)\n df.set_index(['league', 'season', 'game_id'], inplace=True)\n df.sort_index(inplace=True)\n return df",
"def test_select_column_step_must_subset_columns_using_column_names(data):\n step = SelectColumnsStep(columns=['year', 'seasons'])\n baked_df = step.prepare(data).bake(data)\n\n assert len(baked_df.columns) == 2\n assert 'year' in baked_df.columns\n assert 'seasons' in baked_df.columns",
"def process_season_matches(season_matches_df):\n\n def expand_raw_fields(row):\n row_data = dict()\n row_data['awayTeamName'] = row.awayTeam['name']\n row_data['homeTeamName'] = row.homeTeam['name']\n row_data['matchId'] = row.id\n row_data['matchDateTime'] = row.utcDate\n row_data['homeScore'] = row.score['fullTime']['homeTeam']\n row_data['awayScore'] = row.score['fullTime']['awayTeam']\n row_data['matchDay'] = row.matchday\n row_data['season'] = row.season\n row_data['competition'] = row.competitionName\n\n return row_data\n\n def create_table_records(row):\n home_row_data = dict()\n home_row_data['teamName'] = row.homeTeamName\n home_row_data['homeOrAway'] = 'home'\n home_row_data['goalsFor'] = row.homeScore\n home_row_data['goalsAgainst'] = row.awayScore\n home_row_data['matchDay'] = row.matchDay\n home_row_data['matchId'] = row.matchId\n home_row_data['goalDiff'] = row.homeScore - row.awayScore\n home_row_data['played'] = 1\n home_row_data['season'] = row.season\n home_row_data['competition'] = row.competitionName\n\n if home_row_data['goalDiff'] > 0:\n points = 3\n home_row_data['gamesWon'] = 1\n elif home_row_data['goalDiff'] == 0:\n points = 1\n home_row_data['gamesDrawn'] = 1\n else:\n points = 0\n home_row_data['gamesLost'] = 1\n\n home_row_data['points'] = points\n\n # repeat for away team\n away_row_data = dict()\n away_row_data['teamName'] = row.awayTeamName\n away_row_data['homeOrAway'] = 'away'\n away_row_data['goalsFor'] = row.awayScore\n away_row_data['goalsAgainst'] = row.homeScore\n away_row_data['matchDay'] = row.matchDay\n away_row_data['matchId'] = row.matchId\n away_row_data['goalDiff'] = row.awayScore - row.homeScore\n away_row_data['played'] = 1\n away_row_data['season'] = row.season\n away_row_data['competition'] = row.competitionName\n\n if away_row_data['goalDiff'] > 0:\n points = 3\n away_row_data['gamesWon'] = 1\n elif away_row_data['goalDiff'] == 0:\n points = 1\n away_row_data['gamesDrawn'] = 1\n else:\n points = 0\n away_row_data['gamesLost'] = 1\n\n away_row_data['points'] = points\n\n return [home_row_data, away_row_data]\n\n expanded_df_dict = season_matches_df.apply(expand_raw_fields, axis=1)\n expanded_df = pd.DataFrame.from_records(expanded_df_dict)\n expanded_df['matchDateTime'] = pd.to_datetime(expanded_df.matchDateTime)\n\n table_df_deep_list = expanded_df.apply(create_table_records, axis=1)\n table_df_flat_list = [l for sublist in table_df_deep_list for l in sublist]\n table_df = pd.DataFrame.from_records(table_df_flat_list)\n\n grouped_table_df = table_df.groupby(['matchDay', 'teamName']).max().groupby('teamName').cumsum()\n\n return expanded_df, table_df, grouped_table_df",
"def _load_input(self):\n localdf = pd.read_sql(\"SELECT * FROM Matches\", self._con, parse_dates=['Date'])\n self.input_df = localdf[localdf.Season == 2011].copy()",
"def _add_team_stats(df_player_stats: pd.DataFrame, df_team_stats: pd.DataFrame) -> pd.DataFrame:\n logging.info('Enriching player stats with team stats...')\n df_team_stats = df_team_stats.rename(columns={\n column: \"team_\" + column for column in df_team_stats if column not in ('team', 'week', 'year')\n })\n return df_player_stats.merge(df_team_stats, how='left', on=['team', 'week', 'year'])",
"def _translateTeam(self, db, column, optteam):\n \n teamRow = self.sqlContext.sql(\"select \" + db + \" from mlb where \" + column + \"='\" + optteam + \"'\").collect()\n print \"teamRow=\", teamRow\n print \"return teamRow=\", teamRow[0][0]\n return str(teamRow[0][0])",
"def main(input_file, output_file, team_size):\n # Load data\n LOGGER.info('Loading data...')\n data = pd.read_csv(input_file, header=0)\n\n # Randomize participants\n LOGGER.info('Randomizing participants...')\n n_participants = data.shape[0]\n indexes = create_indexes(n_participants)\n nb_teams = n_participants // team_size\n\n # Assign teams\n LOGGER.info('Assigning teams...')\n data['Team'] = pd.Series(np.mod(indexes, nb_teams))\n data = data.sort_values('Team').reset_index(drop=True)\n\n data.to_csv(output_file, index=False)\n LOGGER.info('All done. Output file: {}'.format(output_file))",
"def get_matches(self):\n if not self.all_matches:\n self.all_matches = yaml.load(read_file(\"columns.yaml\"))\n\n try:\n self.matches = self.all_matches[\"columns\"][str(self)]\n except:\n raise Exception(\"Unable to load columns for %s\" % self)",
"def build_team_DataFrames():\n\tteams = load_json('all.json', fdir=default.comp_team_dir)\n\tdata_frames = []\n\tfor tid, team in teams.iteritems():\n\t\tbox_arr = team_boxscore_to_array(team, tid)\n\t\tfname = tid +'_DataFrame.df'\n\t\tbox_arr.to_pickle(os.path.join(default.comp_team_dir, fname))\n\t\tdata_frames.append(box_arr)\n\tall_df = concatenate_team_DataFrames(data_frames=data_frames)\n\tall_df.to_pickle(os.path.join(default.comp_team_dir, 'all.df'))",
"def _adjustData(game_data, columnTitle = None):\n if columnTitle == None:\n columnTitle = ['mostUsedWeapon1', 'mostUsedWeapon2']\n\n for t in columnTitle:\n game_data[t+'Name'] = 'None'\n game_data[t+'Tier'] = 'None'\n game_data[t+'Type'] = 'None'\n #get the unique items in that column\n unique_items = game_data[t].unique()\n unique_items_map = {}\n for i in unique_items:\n logger.info(\"Getting data for weapon {0}\".format(i))\n weapon_map = { i : {\n \"Name\": 'None',\n \"Tier\": \"None\",\n \"Type\": \"None\",\n }\n }\n definition = destiny.getInventoryItemOnline(weapon_map.keys()[0])\n\n if definition is not None and definition['ErrorStatus'] == 'Success':\n logger.info(\"Successfully fetched data for {0}\".format(i))\n weapon_map[i]['Name'] = definition['Response']['data']['inventoryItem']['itemName']\n weapon_map[i]['Tier'] = definition['Response']['data']['inventoryItem']['tierTypeName']\n weapon_map[i]['Type'] = definition['Response']['data']['inventoryItem']['bucketTypeHash']\n unique_items_map.update(weapon_map)\n #update game data with the name, tier and type we just pulled\n for hash,data in unique_items_map.iteritems():\n game_data.ix[game_data[t] == hash, t+'Name'] = data['Name']\n game_data.ix[game_data[t] == hash, t+'Tier'] = data['Tier']\n game_data.ix[game_data[t] == hash, t+'Type'] = data['Type']\n\n game_data.to_csv(\"data_updated.csv\",encoding='utf-8')",
"def _load_goals(self):\n self.results_df['goals'] = self.results_df.team.apply(self.team_total_goals)",
"def update_datasources(self):\n self.match = self.match_selector.value\n self.match_data = self.data[self.match]\n self.teams = self.match_data.blue + self.match_data.red\n start = self.start_time * 10\n end = self.end_time * 10\n for idx in range(6):\n self.datasources[idx]['match'] = self.match_selector.value\n self.datasources[idx]['position'] = STATION_NAMES[idx]\n self.datasources[idx]['team'] = self.teams[idx]\n self.datasources[idx]['path'].data = {\n 'xs': self.match_data.paths[2*idx][start:end],\n 'ys': self.match_data.paths[2*idx+1][start:end]}\n end_idx = -1\n self.datasources[idx]['pos'].data = {\n 'x': [self.match_data.paths[2*idx][start:end][end_idx]],\n 'y': [self.match_data.paths[2*idx+1][start:end][end_idx]]}\n self.datasources[idx]['path_len'] = self.match_data.paths.shape[1]",
"def read_and_clean_yearly_stats(fname, year, veteran_ids, previous_rookie_ids):\n df = parse_bball_ref_common_cols(pd.read_csv(fname))\n df = add_additional_stats(df)\n df['Year'] = int(year) #datetime.datetime(year, 6, 1)\n \n if year < 2019:\n champ = finals_team_data['Champion'][year]\n runnerup = finals_team_data['Runner-Up'][year]\n\n champ_players = df['Team'] == champ\n ru_players = df['Team'] == runnerup \n \n if not champ_players.any():\n print(\"No players on championship team in {}\".format(year))\n if not ru_players.any():\n print(\"No players on runner-up team in {}\".format(year))\n\n champ_leaders = get_leader_stats(df, msk=champ_players)\n ru_leaders = get_leader_stats(df, msk=ru_players)\n \n dpoy = dpoys['PlayerID'][year]\n sixth_man = sixth_man_winners['PlayerID'][year]\n mvpid = mvps['PlayerID'][year]\n finals_mvp = finals_team_data['Finals MVP'][year]\n all_nba_players = all_nba_players_by_year[year]\n else:\n champ = None\n runnerup = None\n \n mvpid = None\n finals_mvp = None\n dpoy = None\n sixth_man = None\n all_nba_players = {'1st':[], '2nd':[], '3rd':[]}\n\n all_stars = all_star_pids[year] \n league_leaders = get_leader_stats(df)\n\n def calculate_regseason_value(row): \n if row['Team'] in [champ, runnerup]:\n ## did you play significant minutes on a team that made it to the finals?\n champ_value = finals_minutes_multiplier * (\n row['MinutesPlayed']/3000 + \n row['GamesStarted']/82 + \n 0.33 * row['GamesPlayed']/82)\n \n ## did you contribute significantly in terms of pts, rbs, etc?\n if row['Team'] == champ:\n multiplier = champ_multiplier\n leader_values = champ_leaders \n else:\n multiplier = ru_multiplier\n leader_values = ru_leaders\n \n champ_value += add_weighted_stat_values(row, leader_values)\n champ_value *= multiplier\n else:\n champ_value = 0\n \n league_value = add_weighted_stat_values(row, league_leaders)\n return champ_value + league_value\n\n def calculate_playoff_value(row):\n ### no credit if you weren't with the team at the end of the season\n if not row['EndOfSeason']:\n return 0\n\n playoff_stats_by_round = playoff_stats_by_year[year]\n pid = row['PlayerID']\n\n total_value = 0\n for playoff_round in range(1, 5):\n # 1 = first round\n # 2 = conference semifinals\n # 3 = east/west finals\n # 4 = nba finals\n playoff_round = str(playoff_round)\n\n multiplier = playoff_multipliers(playoff_round)\n round_stats = playoff_stats_by_year[year][playoff_round]\n loc = round_stats['PlayerID'] == pid\n \n if np.count_nonzero(loc):\n round_leader_stats = get_leader_stats(round_stats)\n player_round_stats = round_stats.loc[loc] \n to_add = add_weighted_stat_values(player_round_stats, round_leader_stats).values[0] * multiplier\n \n if np.isnan(to_add):\n print(\"Going to add a NaN for pid = {}, year = {}, round = {}\".format(pid, year, playoff_round))\n vals = round_leader_stats.values()\n if pd.isnull(vals):\n print('got a NaN in leader stats, year {}, round {}'.format(year, playoff_round))\n print(round_leader_stats)\n if pd.isnull(player_round_stats).any(axis=None):\n print(\"got a NaN in player stats, pid = {}, year = {}, round = {}\".format(pid, year, playoff_round))\n for colname in stat_keys:\n print(colname, player_round_stats[colname])\n# if pd.isnull(player_round_stats[colname]):\n# print(colname, player_round_stats[colname])\n raise TypeError(\"got a nan\")\n total_value += to_add\n return total_value\n \n def calculate_awards_value(row):\n \"\"\"\n how much do we award a player in terms of all stars, mvps, and finals mvps?\n \"\"\"\n \n if not row['EndOfSeason']:\n ## only get credit for awards once\n ## (on the team you end the season with)\n return 0\n \n awards_value = 0\n if row['PlayerID'] in all_stars:\n awards_value += all_star_value\n \n for team in ['1st', '2nd', '3rd']:\n if row['isAllNBA_{}'.format(team)]:\n awards_value += all_nba_values[team]\n \n if row['PlayerID'] == mvpid:\n awards_value += mvp_value\n \n if row['PlayerID'] == dpoy:\n awards_value += dpoy_value\n \n if row['PlayerID'] == sixth_man:\n awards_value += sixth_man_value\n \n if row['isFMVP']:\n awards_value += finals_mvp_value\n \n return awards_value\n \n def set_veteran_status(pid):\n if pid in previous_rookie_ids:\n return 1\n elif pid in veteran_ids:\n return 2\n else:\n return 0\n \n def set_isFMVP(row):\n pname = row['PlayerName']\n team = row['Team']\n name = pname.rsplit(maxsplit=1)\n name = name[0][0] + '. ' + name[1]\n if name == finals_mvp and team == champ:\n return True\n else:\n return False\n \n def set_allNBAteam(pname, team):\n if pname in all_nba_players[team]:\n return True\n else:\n return False\n \n \n ## drop the \"total\" values of players now (not earlier, since we want \n ## to use total stats to normalize our value added above)\n ## will sum-up player values later, \n ## but a player gets value from their contribution to each team\n df = df[df['Team'] != 'TOT']\n \n ## then a player only gets credit for the team they're with at the\n ## end of the season, which is the first one to appear in the list\n with_at_eos = np.zeros(df.shape[0])\n msk = np.logical_not(df.duplicated('PlayerID', keep='first'))\n with_at_eos[msk] = True\n df['EndOfSeason'] = with_at_eos\n \n ## set whether a player was the finals mvp:\n df['isFMVP'] = df.apply(set_isFMVP, axis=1)\n num_fmvp = np.count_nonzero(df['isFMVP'].values)\n if num_fmvp != 1:\n print(\"Wrong number of FMVPs ({}) in year {}\".format(num_fmvp, year))\n \n ## set whether a player made each of the all NBA teams:\n for team in ['1st', '2nd', '3rd']:\n dset_name = 'isAllNBA_{}'.format(team)\n df[dset_name] = df['PlayerName'].apply(set_allNBAteam, args=(team,))\n num_on_team = np.count_nonzero(df[dset_name].values)\n if num_on_team != 5:\n print(\"Wrong number of players ({}) on {} All NBA {} Team\".format(num_on_team, year, team))\n ### note -- these datasets will get used later to calculate awards value\n \n df['YearlyRegularSeasonValue'] = df.apply(calculate_regseason_value, axis=1)\n if year < 2019:\n df['YearlyAwardsValue'] = df.apply(calculate_awards_value, axis=1)\n df['YearlyPlayoffsValue'] = df.apply(calculate_playoff_value, axis=1)\n else:\n df['YearlyAwardsValue'] = np.zeros(df.shape[0])\n df['YearlyPlayoffsValue'] = np.zeros(df.shape[0])\n \n df['VeteranStatus'] = df['PlayerID'].apply(set_veteran_status)\n df['isYoungPlayer'] = df['Age'] <= 23\n \n # everyone who was a rookie last year will be a veteran next year\n next_veteran_ids = np.union1d(veteran_ids, previous_rookie_ids)\n rookie_ids = np.array(df['PlayerID'].loc[df['VeteranStatus']==0].values)\n \n df['TotalValue'] = df['YearlyRegularSeasonValue'] + df['YearlyAwardsValue'] + df['YearlyPlayoffsValue']\n\n ## no longer need to know whether it's the EndOfSeason row\n df.drop(columns=['EndOfSeason'], inplace=True)\n \n ## now handle players that are duplicated (i.e. that were on multiple teams in a given year because of trades)\n ## I'm going to just sum those up basically...\n is_a_duplicate_row = df.duplicated('PlayerID', keep=False)\n \n players_traded = np.unique(df['PlayerID'].loc[is_a_duplicate_row])\n print(\"Now dealing with {} players that were traded and appear more than once...\".format(\n players_traded.size))\n \n df_with_no_dupes = df.drop_duplicates('PlayerID', keep=False, inplace=False)\n ### now add the total values back on to df_with_no_dupes\n to_append = []\n for pid in players_traded:\n rows = df[df['PlayerID']==pid]\n assert rows.shape[0] > 1, \"Got a dupilicate PlayerID but only one row...\"\n new_row = combine_traded_player(rows)\n to_append.append(new_row)\n df_with_no_dupes = df_with_no_dupes.append(to_append, ignore_index=True, sort=False)\n\n return df_with_no_dupes, rookie_ids, next_veteran_ids",
"def test_select_column_step_must_allow_selectors_and_column_names(data):\n step = SelectColumnsStep(columns=[AllMatching('air'), 'seasons'])\n baked_df = step.prepare(data).bake(data)\n\n assert len(baked_df.columns) == 2\n assert 'aired' in baked_df.columns\n assert 'seasons' in baked_df.columns"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Compute expected points added by each QB per play
|
def qb_points(self):
# load required datasets
df_play = pd.read_csv(datadir / 'PLAY.csv.gz')
df_sched = pd.read_csv(datadir / 'SCHEDULE.csv.gz')
df_rush = pd.read_csv(datadir / 'RUSH.csv.gz')
df_drive = pd.read_csv(datadir / 'DRIVE.csv.gz')
# Merge schedule and play data
df_play = df_sched[['date', 'gid', 'v', 'h']].merge(
df_play[['gid', 'pid', 'off', 'def', 'epa', 'eps']], on='gid')
# Merge starting quarterback and rush info
df_play = df_play.merge(
self.quarterback_info,
left_on=['gid', 'off'], right_on=['game_id', 'team']
).merge(df_rush[['pid', 'bc']], on='pid', how='left')
# Drop non-qb rushing plays
non_qb_rusher = ~df_play.bc.isna() & (df_play.qb != df_play.bc)
df_play_filtered = df_play[~non_qb_rusher]
# Aggregate qb expected points added (EPA)
df_qb_epa = df_play_filtered.groupby(
by=['gid', 'date', 'qb', 'off', 'def', 'h', 'v']
).agg({'epa': 'sum'}).reset_index()
# Subtract expected points starting (EPS) yielded to opponent
df_first_play = df_play.merge(
df_drive[['gid', 'fpid']],
left_on=['gid', 'pid'], right_on=['gid', 'fpid'])
# Aggregate each team's expected points starting (EPS)
df_qb_eps = df_first_play.groupby(
by=['gid', 'team']
).agg({'eps': 'sum'}).reset_index()
df_qb_eps['eps'] -= df_qb_eps.eps.mean()
# Merge EPA and EPS values
df_qb = df_qb_epa.merge(
df_qb_eps, left_on=['gid', 'def'], right_on=['gid', 'team'])
# Compute "QB points"
df_qb['tm_qb_pts'] = df_qb.epa #- df_qb.eps
qb_cols = {
'gid': 'game_id',
'off': 'team',
'qb': 'qb',
'tm_qb_pts': 'tm_qb_pts'}
df_qb = df_qb[qb_cols.keys()].rename(qb_cols, axis=1)
return df_qb
|
[
"def q_expected(self):\n total = 0.0\n for a in self.pre:\n if self.atom_state[a] == ATOM_ENABLED:\n total += self.usecount * self.Q[a]\n else:\n for a2 in (a, a.negate()):\n total += self.frequencies[a2] * self.Q[a2]\n \n for a in self.eff:\n if self.atom_state[a] == ATOM_DISABLED:\n total += self.usecount * self.Q[a.negate()]\n else:\n for a2 in (a, a.negate()):\n total += self.frequencies[a2] * self.Q[a2]\n \n return (total/self.usecount) / (len(self.pre)+len(self.eff))",
"def sum_bench_points(league: League, lineup: list) -> float:\n return np.sum([player.points for player in lineup if player.slot_position == \"BE\"])",
"def QvQgrid():\n rnd.seed(513)\n \n N_GAMES = 75000 \n REPS = 5\n Q_init = 0.0\n \n epsilons = [0.1, 0.3, 0.5]\n alphas = [0.1,0.3,0.5,0.7,0.9]\n gammas = [-0.1,-0.3,-0.5,-0.7,-0.9]\n \n setting = [[e,a,g] for e in epsilons for a in alphas for g in gammas] \n \n for s in range(len(setting)):\n params = setting[s]\n epsilon = params[0]\n alpha = params[1]\n gamma = params[2]\n \n print('e:', epsilon, ' a:', alpha, ' g:', gamma)\n \n p1_opt_percs = []\n p1_winlose = []\n p2_opt_percs = []\n p2_winlose = []\n \n for i in range(REPS):\n bd = rnd.randint(0,9,3).tolist()\n if sum(bd) >= 0:\n starting_board_hash = get_hash(rnd.randint(0,9,3).tolist())\n else:\n starting_board_hash = get_hash([4,4,4]) # one in million chance this will be needed\n \n p1 = QAgent('p1', starting_board_hash, Q_init, epsilon, alpha, gamma)\n p2 = QAgent('p2', starting_board_hash, Q_init, epsilon, alpha, gamma)\n \n [p1_stats, p2_stats] = train_agents(N_GAMES, p1, p2, starting_board_hash, 1, -1, False)\n p1_opt_percs.append(p1_stats[0])\n p1_winlose.append(p1_stats[1])\n p2_opt_percs.append(p2_stats[0])\n p2_winlose.append(p2_stats[1]) \n \n file_name = '../final/QvQ/QvQ_optimal_moves' + str(epsilon) + str(alpha) + str(gamma) +'vSelfAll_'\n file_contents = p1_opt_percs + p2_opt_percs\n log_contents(file_name, file_contents)\n \n file_name = '../final/QvQ/QvQ_wins' + str(epsilon) + str(alpha) + str(gamma) +'vSelfAll_'\n file_contents = p1_winlose + p2_winlose\n log_contents(file_name, file_contents)\n\n print('learning complete')",
"def proba_round_reached(self):\n\n\t\treturn [x/self.counterPlayed for x in self.counterRoundReached]",
"def testQMatrix(self):\n # The data we have available is only accurate to the 4th decimal place. This should\n # be sufficient. kx and ky are given in the setup, fixed by our angles theta and phi.\n absoluteTolerance = 0.0001;\n relativeTolerance = 0.001;\n kx = 1.0006;\n ky = 0.4247;\n\n # Zeroth, we actually have data for our gap layer\n er = 1.0 + sq(kx) + sq(ky);\n ur = 1.0;\n Q_actual = complexArray([[0.4250, 1.1804],[-2.0013, -0.4250]]);\n Q_calc = calculateQMatrix(kx, ky, er, ur);\n assertAlmostEqual(Q_actual, Q_calc, absoluteTolerance, relativeTolerance);\n\n # First, we have some data for layer 1\n er = 2.0;\n ur = 1.0;\n Q_actual = complexArray([[0.4250, 0.9987],[-1.8196, -0.4250]]);\n Q_calc = calculateQMatrix(kx, ky, er, ur);\n assertAlmostEqual(Q_actual, Q_calc, absoluteTolerance, relativeTolerance);\n\n # Now, we have some data for layer 2.\n er = 1.0;\n ur = 3.0;\n\n Q_actual = complexArray([[0.1417, 0.6662],[-0.9399, -0.1417]]);\n Q_calc = calculateQMatrix(kx, ky, er, ur);\n assertAlmostEqual(Q_actual, Q_calc, absoluteTolerance, relativeTolerance);",
"def expected_Q(self, sp):\n if self._policy == 'eps_greedy':\n Q_exp = (1.0 - self._eps) * max(self._Q[sp])\n for a in range(self._env.num_actions(sp)):\n Q_exp += (self._eps / self._env.num_actions(sp)) * self._Q[sp][a]\n return Q_exp\n if self._policy == 'equiprobable':\n Q_exp = 0.0\n for a in range(self._env.num_actions(sp)):\n Q_exp += (1.0 / self._env.num_actions(sp)) * self._Q[sp][a]\n return Q_exp\n if self._policy == 'custom':\n Q_exp = 0.0\n for a in range(self._env.num_actions(sp)):\n Q_exp += self._P[sp][a] * self._Q[sp][a]\n return Q_exp",
"def test_processed_points_calculation(self):\n\n assert self.test_shape.processed_points == [\n (49.937460888595446, 2.5, \"circle\"),\n (43.300748759659555, 25.000903120744287, \"circle\"),\n (27.1320420790315, 41.99824154201773, \"straight\"),\n (77.154447582418, 128.6358861991937, \"circle\"),\n (129.90375269002172, 75.00010024693078, \"circle\"),\n (149.97916521970643, 2.5, \"straight\"),\n (49.937460888595446, 2.5, \"circle\"),\n ]",
"def compute_expected(self):\n\n # compute the poisson rate\n self.mu = (\n np.dot(\n self.samples[\"post_sample_means\"][\"spot_factors\"], self.samples[\"post_sample_means\"][\"gene_factors\"].T\n )\n * self.samples[\"post_sample_means\"][\"gene_level\"].T\n + self.samples[\"post_sample_means\"][\"gene_add\"].T\n + self.samples[\"post_sample_means\"][\"spot_add\"]\n )\n self.alpha = 1 / (self.samples[\"post_sample_means\"][\"gene_E\"].T * self.samples[\"post_sample_means\"][\"gene_E\"].T)",
"def test_box_scores_v_simulation(self):\n pass",
"def test_value(self):\n\n # Number of modes\n d = 10\n\n # Number of shots\n shots = 100\n\n # rundom parameters for squeezing gates\n squeezing_params_r = np.random.random(d)\n squeezing_params_phi = np.random.random(d)\n\n # random unitary matrix for perform interferometer\n interferometer_param = unitary_group.rvs(d)\n\n ###################################\n\n # Piquasso python program\n with pq.Program() as pq_program:\n # Apply random squeezings\n for idx in range(d):\n pq.Q(idx) | pq.Squeezing(r=squeezing_params_r[idx], phi=squeezing_params_phi[idx])\n\n # Apply random interferometer\n pq.Q() | pq.Interferometer(interferometer_param)\n\n # Measure all modes with shots shots\n pq.Q() | pq.ThresholdMeasurement()\n\n simulator = pq.GaussianSimulator(d=d)\n\n # Measuring runtime\n startTime = time.time()\n result = simulator.execute(program=pq_program, shots=shots)\n pypq_results = np.array(result.samples)\n endTime = time.time()\n\n piquasso_time = endTime - startTime\n\n ###################################\n\n # Piquasso boost program\n with pq.Program() as pq_program:\n # Apply random squeezings\n for idx in range(d):\n pq.Q(idx) | pq.Squeezing(r=squeezing_params_r[idx], phi=squeezing_params_phi[idx])\n\n # Apply random interferometer\n pq.Q() | pq.Interferometer(interferometer_param)\n\n # Measure all modes with shots shots\n pq.Q() | pq.ThresholdMeasurement()\n\n simulator = pqb.BoostedGaussianSimulator(d=d)\n\n # Measuring runtime\n startTime = time.time()\n result = simulator.execute(program=pq_program, shots=shots)\n cpq_results = np.array(result.samples)\n endTime = time.time()\n\n piquasso_boost_time = endTime - startTime\n\n ###################################\n\n print(' ')\n print('*******************************************')\n print('Number of modes: ', d)\n print('Time elapsed with piquasso : ' + str(piquasso_time))\n print('Time elapsed with piquasso boost: ' + str(piquasso_boost_time))\n print('The result of piquasso python: \\n' , pypq_results)\n print('The result of piquasso C++: \\n' , cpq_results)\n print( \"speedup: \" + str(piquasso_time/piquasso_boost_time) )",
"def QtvQtgrid():\n rnd.seed(2001)\n \n N_GAMES = 75000 \n REPS = 5\n Q_init = 0.0\n \n epsilons = [0.1, 0.5, 0.9]\n alphas = [0.1, 0.3]\n gammas = [-0.5, -0.9]\n etas = [0.001, 0.0001, 0.00001]\n \n setting = [[e,a,g,n] for e in epsilons for a in alphas for g in gammas for n in etas] \n \n for s in range(len(setting)):\n params = setting[s]\n epsilon = params[0]\n alpha = params[1]\n gamma = params[2]\n eta = params[3]\n \n print('e:', epsilon, ' a:', alpha, ' g:', gamma, ' eta:', eta)\n \n p1_opt_percs = []\n p1_winlose = []\n p2_opt_percs = []\n p2_winlose = []\n \n for i in range(REPS):\n bd = rnd.randint(0,9,3).tolist()\n if sum(bd) >= 0:\n starting_board_hash = get_hash(rnd.randint(0,9,3).tolist())\n else:\n starting_board_hash = get_hash([5,5,5]) # one in million chance this will be needed\n \n p1 = QtAgent('p1', starting_board_hash, Q_init, epsilon, alpha, gamma, eta)\n p2 = QtAgent('p2', starting_board_hash, Q_init, epsilon, alpha, gamma, eta)\n \n [p1_stats, p2_stats] = train_agents(N_GAMES, p1, p2, starting_board_hash, 1, -1, False)\n p1_opt_percs.append(p1_stats[0])\n p1_winlose.append(p1_stats[1])\n p2_opt_percs.append(p2_stats[0])\n p2_winlose.append(p2_stats[1]) \n \n file_name = '../final/QtvQt/QtvQt_optimal_moves' + str(epsilon) + str(alpha) + str(gamma) + str(eta) +'vSelfAll_'\n file_contents = p1_opt_percs + p2_opt_percs\n log_contents(file_name, file_contents)\n \n file_name = '../final/QtvQt/QtvQt_wins' + str(epsilon) + str(alpha) + str(gamma) + str(eta) +'vSelfAll_'\n file_contents = p1_winlose + p2_winlose\n log_contents(file_name, file_contents)\n \n print('learning complete')",
"def calculate_points(self):\n pass",
"def test_roc_points(self):\n \n #The set up here is a bit elaborate since I generate the test datasets\n #based on the values we need in the confusion matrix.\n #I test the intermediate results though, so any errors should be due \n #to the actual function, not the test\n \n tn_obs = 0\n tn_exp = 0\n\n fp_obs = 1\n fp_exp = 0\n\n tp_obs = 1\n tp_exp = 1\n\n fn_obs = 0\n fn_exp = 1\n\n #point A\n obs = [tp_obs] * 63 + [fp_obs] *28 + [fn_obs] * 37 + [tn_obs]*72\n exp = [tp_exp] * 63 + [fp_exp] *28 + [fn_exp] * 37 + [tn_exp]*72\n trial_a_results = confusion_matrix_from_data(obs,exp)\n #Check that this is correct\n self.assertEqual(trial_a_results,(63,28,37,72))\n trial_a = (obs,exp)\n \n \n #point B\n obs = [tp_obs] * 77 + [fp_obs] *77 + [fn_obs] * 23 + [tn_obs]*23\n exp = [tp_exp] * 77 + [fp_exp] *77 + [fn_exp] * 23 + [tn_exp]*23\n trial_b_results = confusion_matrix_from_data(obs,exp)\n #Check that this is correct\n self.assertEqual(trial_b_results,(77,77,23,23))\n trial_b = (obs,exp)\n \n #point c\n obs = [tp_obs] * 24 + [fp_obs] *88 + [fn_obs] * 76 + [tn_obs]*12\n exp = [tp_exp] * 24 + [fp_exp] *88 + [fn_exp] * 76 + [tn_exp]*12\n trial_c_results = confusion_matrix_from_data(obs,exp)\n #Check that this is correct\n self.assertEqual(trial_c_results,(24,88,76,12))\n trial_c_results = calculate_accuracy_stats_from_observations(obs,exp)\n #Check that this is correct\n self.assertEqual(trial_c_results[\"false_positive_rate\"],0.88)\n\n trial_c = (obs,exp)\n\n trials = [trial_a, trial_b,trial_c]\n \n \n #Finally the actual test\n\n obs_points = roc_points(trials)\n exp_points = [(0.28,0.63),(0.77,0.77),(0.88,0.24)]\n self.assertFloatEqual(obs_points,exp_points)",
"def run_simulation(self):\n for run in range(self.num_runs):\n for play in range(self.num_plays):\n self.run_and_update(play)\n self.reset()\n average_rewards_per_play = self.rewards_per_play / self.num_runs\n optimal_action_percentage = self.optimal_action_played / self.num_runs\n return average_rewards_per_play, optimal_action_percentage",
"def print_expected_values(self):\n solo_list = task_list(False, [])._do_list\n group_list = task_list(True, [])._do_list\n i = 0\n sum = 0\n for boss, task in solo_list.items():\n sum += task.get_points(0)\n i += 1\n print(\"Expected Value for no options always accepting the first task \"\n \"is:\")\n print(sum/i)\n\n i = 0\n sum = 0\n for boss, task in solo_list.items():\n sum += task.get_points(1)\n i += 1\n print(\"Expected Value for extended tasks always accepting the first \"\n \"task is:\")\n print(sum/i)\n\n i = 0\n sum = 0\n for boss, task in group_list.items():\n sum += task.get_points(2)\n i += 1\n print(\"Expected Value with both options always accepting the first \"\n \"task is:\")\n print(sum/i)",
"def learn_Q_QLearning(env, num_episodes=10000, gamma = 0.99, lr = 0.1, e = 0.2, max_step=6):\n \n Q = np.zeros((env.nS, env.nA))\n ########################################################\n # YOUR CODE HERE #\n ########################################################\n\n decay_rate = 1\n scores = np.zeros(num_episodes, dtype=float)\n for i in range(num_episodes):\n s = env.reset()\n print('episode ' + str(i))\n done = False\n total_score = 0\n updates = []\n t = 0\n while not done and t < max_step:\n best_a = np.argmax(Q[s])\n if random.random() > e:\n a = best_a\n else:\n a = random.randint(0, env.nA-1)\n s_next, r, done, _ = env.step(a)\n updates.append((s, a, r + gamma * max(Q[s_next])))\n s = s_next\n total_score += r\n t += 1\n for s, a, q_samp in updates:\n Q[s][a] = (1 - lr) * Q[s][a] + lr * q_samp\n e = e * decay_rate\n if i == 0:\n scores[0] = total_score\n else:\n scores[i] = scores[i-1] + total_score\n scores /= np.arange(1, num_episodes + 1)\n\n plt.plot(scores)\n plt.ylabel('average score')\n plt.xlabel('episodes')\n plt.savefig('q_learning_avg_scores_lr=3e-1_e=8e-1.png')\n\n ########################################################\n # END YOUR CODE #\n ########################################################\n return Q",
"def expected_results():\n return [\n {\n 'strategy': BuffedCoinStrategy,\n 'values': [\n 1318.21, 1250.13, 1318.79, 1355.47, 1560.75, 1694.85, 1918.27,\n 1866.54, 1888.66, 2039.06, 1967.42, 2184.11, 2326.3, 2461.91,\n 2589.18, 2544.36, 2420.49, 2778.22, 2958.32, 3313.64, 3686.43,\n 3704.98, 4091.39, 4395.39, 4085.4, 4770.42, 3487.72, 3384.36,\n 3546.08, 3664.02, 3820.51, 3976.37\n ],\n },\n {\n 'strategy': BuyHoldStrategy,\n 'values': [\n 1318.21, 1250.13, 1318.79, 1355.47, 1560.75, 1706.55, 1953.71,\n 2004.34, 1936.11, 2145.46, 1971.15, 2230.17, 2384.13, 2429.57,\n 2455.09, 2397.81, 2403.63, 2797.57, 2929.94, 3300.03, 3823.09,\n 3898.91, 4190.82, 4435.93, 3901.56, 4713.82, 3341.65, 3222.06,\n 3393.65, 3539.53, 3789.87, 3801.63,\n ],\n },\n {\n 'strategy': PeakRiderStrategy,\n 'values': [\n 1318.21, 1250.13, 1318.79, 1355.47, 1560.75, 1706.55, 1920.65,\n 1889.18, 1906.54, 2071.08, 1947.65, 2156.81, 2296.88, 2381.47,\n 2439.71, 2317.35, 2315.89, 2593.93, 2707.41, 2988.51, 3172.41,\n 3208.15, 3549.13, 3715.67, 3672.46, 4213.29, 3301.56, 3016.65,\n 3196.71, 3241.07, 3325.59, 3354.02,\n ],\n },\n ]",
"def test_expected_tape(self):\n\n m = qml.RX(0.3, wires=0).matrix\n\n op = QuantumPhaseEstimation(m, target_wires=[0], estimation_wires=[1, 2])\n tape = op.expand()\n\n with qml.tape.QuantumTape() as tape2:\n qml.Hadamard(1),\n qml.ControlledQubitUnitary(m @ m, control_wires=[1], wires=[0]),\n qml.Hadamard(2),\n qml.ControlledQubitUnitary(m, control_wires=[2], wires=[0]),\n qml.QFT(wires=[1, 2]).inv()\n\n assert len(tape2.queue) == len(tape.queue)\n assert all([op1.name == op2.name for op1, op2 in zip(tape.queue, tape2.queue)])\n assert all([op1.wires == op2.wires for op1, op2 in zip(tape.queue, tape2.queue)])\n assert np.allclose(tape.queue[1].matrix, tape2.queue[1].matrix)\n assert np.allclose(tape.queue[3].matrix, tape2.queue[3].matrix)",
"def compute_precision_at_yield( Yield,logger ):\r\n\r\n\tprecision_scores_file = codecs.open( ConfigSectionReader(Config,\"evaluation_app\")['precision_scores_file'], 'a', 'utf-8', errors = 'replace' )\r\n\t#precision_scores_file = open( ConfigSectionReader(Config,\"evaluation_app\")['precision_scores_file'], 'a')\r\n\tprecision_scores_file.write( '#yield, P, yield, P, ...\\n' )\r\n\r\n\tfor yield_value in Yield:\r\n\r\n\t\tyield_value = int(yield_value)\r\n\t\tlogger.info( 'target yield = ' + repr(yield_value) )\r\n\r\n\t\t# get top N scores for this yield\r\n\t\tlistScoreSubset = list_scores[ 0:yield_value ]\r\n\r\n\t\tdict_true_positive = {}\r\n\t\tnFP = 0\r\n\t\tnTP = 0\r\n\t\tset_artifact_in_yield = set([])\r\n\t\tset_artifact_in_yield_ground_truth = set([])\r\n\r\n\t\tfor (tuplePair, nScore) in listScoreSubset :\r\n\r\n\t\t\t(first_artifact, second_artifact) = tuplePair\r\n\r\n\t\t\tset_artifact_in_yield.add( first_artifact )\r\n\t\t\tset_artifact_in_yield.add( second_artifact )\r\n\r\n\t\t\t'''\r\n\t\t\t# ignore pair if both artifacts are not in the ground truth set\r\n\t\t\tif (first_artifact not in dict_artefact_cluster) and (second_artifact not in dict_artefact_cluster) :\r\n\t\t\t\tif (not (first_artifact, second_artifact) in setTN) and (not (second_artifact, first_artifact) in setTN) :\r\n\t\t\t\t\tsetTN.add( (first_artifact, second_artifact) )\r\n\t\t\t\tcontinue\r\n\r\n\t\t\t# keep track of how many ground truth artifacts we have seen in result\r\n\t\t\tif first_artifact in dict_artefact_cluster :\r\n\t\t\t\tset_artifact_in_yield_ground_truth.add( first_artifact )\r\n\t\t\tif second_artifact in dict_artefact_cluster :\r\n\t\t\t\tset_artifact_in_yield_ground_truth.add( second_artifact )\r\n\t\t\t'''\r\n\r\n\t\t\t# its a FP if one of the pair is not in ground truth set\r\n\t\t\tif (first_artifact not in dict_artefact_cluster) :\r\n\t\t\t\tnFP = nFP + 1\r\n\t\t\t\tcontinue\r\n\t\t\tif (second_artifact not in dict_artefact_cluster) :\r\n\t\t\t\tnFP = nFP + 1\r\n\t\t\t\tcontinue\r\n\r\n\t\t\t# all artifacts are in a ground truth cluster, so now check they share a cluster ID (FP if not)\r\n\t\t\t# note: record pair not a simple count to avoid mirror pair counting twice\r\n\t\t\tif len( dict_artefact_cluster[first_artifact].intersection( dict_artefact_cluster[second_artifact] ) ) > 0 :\r\n\t\t\t\tnTP = nTP + 1\r\n\t\t\telse:\r\n\t\t\t\tnFP = nFP + 1\r\n\r\n\t\tif nTP + nFP > 0 :\r\n\t\t\tnPrecision = 1.0 * nTP / ( nTP + nFP )\r\n\t\t\tlogger.info( 'precision = ' + repr( nPrecision ) )\r\n\t\telse :\r\n\t\t\tnPrecision = 0.0\r\n\t\t\tlogger.info( 'precision = 0.0' )\r\n\r\n\t\t#logger.info( 'precision = ' + repr( 1.0*len(dict_true_positive)/len(orderedVector)) )\r\n\t\t#logger.info(orderedVector)\r\n\t\tlogger.info( 'unique artifacts in yield = ' + repr( len(set_artifact_in_yield) ) + ', ground truth artifacts in yield = ' + repr( len(set_artifact_in_yield_ground_truth) ) + ' (' + repr( 1.0*len(set_artifact_in_yield_ground_truth)/len(dict_artefact_cluster) ) + ' %)' )\r\n\r\n\t\tprecision_scores_file.write( str(yield_value)+','+ str(nPrecision)+'\\t' )\r\n\r\n\tprecision_scores_file.write('\\n')\r\n\tprecision_scores_file.close()"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Compute home and away teams days rested
|
def rest_days(self, games):
game_dates = pd.concat([
games[["date", "team_home"]].rename(
columns={"team_home": "team"}),
games[["date", "team_away"]].rename(
columns={"team_away": "team"}),
]).sort_values("date")
game_dates['date_prev'] = game_dates.date
game_dates = pd.merge_asof(
game_dates[['team', 'date']],
game_dates[['team', 'date', 'date_prev']],
on='date', by='team', allow_exact_matches=False)
for team in ["home", "away"]:
game_dates_team = game_dates.rename(
columns={
'date_prev': f'date_{team}_prev',
'team': f'team_{team}'})
games = games.merge(game_dates_team, on=['date', f'team_{team}'])
one_day = pd.Timedelta("1 days")
games["tm_rest_days_home"] = np.clip(
(games.date - games.date_home_prev) / one_day, 3, 16).fillna(7)
games["tm_rest_days_away"] = np.clip(
(games.date - games.date_away_prev) / one_day, 3, 16).fillna(7)
return games
|
[
"def day_night_duration(\n self,\n daybreak: datetime.time = datetime.time(NORMAL_DAY_START_H),\n nightfall: datetime.time = datetime.time(NORMAL_DAY_END_H),\n ) -> Tuple[datetime.timedelta, datetime.timedelta]:\n daytotal = datetime.timedelta()\n nighttotal = datetime.timedelta()\n startdate = self.start.date()\n enddate = self.end.date()\n ndays = (enddate - startdate).days + 1\n for i in range(ndays):\n date = startdate + datetime.timedelta(days=i)\n component = self.component_on_date(date)\n # ... an interval on a single day\n day = Interval.daytime(date, daybreak, nightfall)\n daypart = component.intersection(day)\n if daypart is not None:\n daytotal += daypart.duration()\n nighttotal += component.duration() - daypart.duration()\n else:\n nighttotal += component.duration()\n return daytotal, nighttotal",
"def get_last_game(row, df):\n home_col = \"Venue\"\n away_col = \"Opponent\" if row['Team'] == row['Venue'] else \"Team\"\n home_b2b, away_b2b = 0, 0\n days = []\n\n # Home\n prev_games = df[(df[\"Team\"] == row[home_col]) & (df['Date'] < row['Date']) & (df['Season'] == row['Season'])]\n days.append(5 if prev_games.empty else (row['Date'] - prev_games.iloc[prev_games.shape[0] - 1]['Date']).days)\n if not prev_games.empty and (row['Date'] - prev_games.iloc[prev_games.shape[0] - 1]['Date']).days == 1 and \\\n row['Home_Starter'] in [prev_games.iloc[prev_games.shape[0] - 1]['Home_Starter'],\n prev_games.iloc[prev_games.shape[0] - 1]['Away_Starter']]:\n home_b2b = 1\n\n # Away\n prev_games = df[(df[\"Team\"] == row[away_col]) & (df['Date'] < row['Date']) & (df['Season'] == row['Season'])]\n days.append(5 if prev_games.empty else (row['Date'] - prev_games.iloc[prev_games.shape[0] - 1]['Date']).days)\n if not prev_games.empty and (row['Date'] - prev_games.iloc[prev_games.shape[0] - 1]['Date']).days == 1 and \\\n row['Away_Starter'] in [prev_games.iloc[prev_games.shape[0] - 1]['Home_Starter'],\n prev_games.iloc[prev_games.shape[0] - 1]['Away_Starter']]:\n away_b2b = 1\n\n return days[0], days[1], home_b2b, away_b2b",
"def _extract_days(p_schedule_obj, p_now):\n l_dow = p_schedule_obj.DOW\n l_now_day = p_now.weekday()\n l_day = 2 ** l_now_day\n l_is_in_dow = (l_dow & l_day) != 0\n # print(\"A \", l_dow, l_now_day, l_day, l_is_in_dow)\n if l_is_in_dow:\n return 0\n l_days = 1\n for _l_ix in range(0, 7):\n l_now_day = (l_now_day + 1) % 7\n l_day = 2 ** l_now_day\n l_is_in_dow = (l_dow & l_day) != 0\n # print(\"B \", l_dow, l_now_day, l_day, l_is_in_dow)\n if l_is_in_dow:\n return l_days\n l_days += 1\n return 10",
"def calculate_days_left_in_growing_season(self, yr_days):\n \n self.state.remaining_days = [] \n self.state.growing_days = [] \n self.state.leaf_out_days= [] \n for doy in xrange(1, yr_days+1):\n if doy > self.leaf_off - self.len_groloss and doy <= self.leaf_off:\n self.state.remaining_days.append((doy - 0.5) - \n self.leaf_off + \n self.len_groloss)\n else:\n self.state.remaining_days.append(0.0)\n \n if doy > self.leaf_on and doy <= self.len_groloss+self.leaf_on:\n self.state.growing_days.append(self.len_groloss + \n self.leaf_on - (doy - 0.5)) \n else:\n self.state.growing_days.append(0.0)\n \n if doy > self.leaf_on and doy < self.leaf_off:\n self.state.leaf_out_days.append(1.0) \n else:\n self.state.leaf_out_days.append(0.0)",
"def days_until_launch(current_day, launch_day):\n return (launch_day - current_day) if (launch_day - current_day > 0) else 0",
"def days_until_launch(current_day, launch_day):\n return 0 if (launch_day - current_day) < 0 else (launch_day - current_day)",
"def get_days_passed(self):\n return 367 * self.image_time.year - (7 * (self.image_time.year + ((self.image_time.month + 9) / 12))) / 4 \\\n + (275 * self.image_time.month) / 9 + self.image_time.day - 730530",
"def todays_games():\n\turl_str = \"http://mlb.mlb.com/gdcross/components/game/mlb\" \\\n \t\t\t+ \"/year_\" + fix_digit(date.today().year) \\\n \t\t\t+ \"/month_\" + fix_digit(date.today().month) \\\n \t\t\t+ \"/day_\" + fix_digit(date.today().day) \\\n \t\t\t+ \"/miniscoreboard.json\"\n\n\twith urllib.request.urlopen(url_str) as url:\n\t\tdata = json.loads(url.read().decode())\n\t\tgames = data[\"data\"][\"games\"][\"game\"]\n\t\thome = []\n\t\thome_score = []\n\t\taway = []\n\t\taway_score = []\n\t\tinning = []\n\t\touts = []\n\t\tstatus = []\n\t\tfor game in games:\n\t\t\thome.append(game.get(\"home_team_name\", 0))\n\t\t\thome_score.append(game.get(\"home_team_runs\", 0))\n\t\t\taway.append(game.get(\"away_team_name\", 0))\n\t\t\taway_score.append(game.get(\"away_team_runs\", 0))\n\t\t\tinning.append(game.get(\"inning\", 0))\n\t\t\touts.append(game.get(\"outs\",0))\n\t\t\tstatus.append(game.get(\"status\", 0))\n\t\tout = pd.DataFrame.from_items([(\"Home\", home), \\\n\t\t\t\t\t\t\t(\"Score\", home_score), \\\n\t\t\t\t\t\t\t(\"Away\", away), \\\n\t\t\t\t\t\t\t(\"Score\", away_score), \\\n\t\t\t\t\t\t\t(\"Inning\", inning), \\\n\t\t\t\t\t\t\t(\"Outs\", outs), \\\n\t\t\t\t\t\t\t(\"Status\", status)])\t\n\t\tprint(out)",
"def working_days(self) -> Optional[int]:\n \"\"\" Calculated by adjusting duration by TRAC \"\"\"\n return Project.fte_days_to_working_days(self.duration)* self.fte / 100.0",
"def _compute_day_open(self):\n for lead in self.filtered(lambda l: l.date_open):\n date_create = fields.Datetime.from_string(lead.create_date)\n date_open = fields.Datetime.from_string(lead.date_open)\n if date_create and date_open:\n lead.day_open = abs((date_open - date_create).days)",
"def test_leave_day_count(self):\n user = mommy.make(\"auth.User\", first_name=\"Mosh\", last_name=\"Pitt\")\n staff = mommy.make(\"small_small_hr.StaffProfile\", user=user)\n mommy.make(\n \"small_small_hr.AnnualLeave\",\n staff=staff,\n year=2017,\n leave_type=Leave.REGULAR,\n allowed_days=21,\n )\n mommy.make(\n \"small_small_hr.FreeDay\",\n name=\"RANDOM HOLIDAY\",\n date=date(day=15, month=6, year=2017),\n )\n # 9.5 days of leave ==> Sun not counted, Sat = 0.5 and 15/6/2017 is holiday\n start = datetime(2017, 6, 5, 0, 0, 0, tzinfo=pytz.timezone(settings.TIME_ZONE))\n end = datetime(2017, 6, 16, 0, 0, 0, tzinfo=pytz.timezone(settings.TIME_ZONE))\n leave_obj = mommy.make(\n \"small_small_hr.Leave\",\n staff=staff,\n start=start,\n end=end,\n leave_type=Leave.REGULAR,\n review_status=Leave.APPROVED,\n )\n\n self.assertEqual(9.5, leave_obj.day_count)",
"def remaining_days(self) -> float:\n return self.project_days - self.committed_days",
"def get_projected_scores(self, nba_teams, end_date, league_players, current_scores): \n # Get the rosters for each team and the current matchup score\n self.league_players = league_players\n self.rosters = [self.get_team_roster(self.get_user_team_id(), self.league_players), \n self.get_team_roster(self.get_opponent_id(), self.league_players)]\n self.projected_scores = current_scores\n self.end_date = end_date\n self.nba_teams = nba_teams\n self.players_on_court_limit = self.get_num_players_on_court()\n \n self.current_datetime = datetime.strptime(self.date,\"%Y-%m-%d\")\n self.end_datetime = datetime.strptime(self.end_date, \"%Y-%m-%d\")\n self.days_remaining = 0\n \n while self.current_datetime <= self.end_datetime:\n for roster in range(len(self.rosters)):\n self.players_on_court = 0\n for player in self.rosters[roster]:\n # Check if player has a game on this day based on their team\n self.player_nba_team = player.get_player_nba_team()\n self.player_schedule = self.nba_teams[self.player_nba_team].get_schedule()\n if datetime.strftime(self.current_datetime,\"%Y-%m-%d\") in self.player_schedule:\n # Ensure not too many player scores are counted per day\n self.players_on_court += 1\n if self.players_on_court > self.players_on_court_limit:\n break\n \n # Ensure the player is not injured\n if player.get_injury_status():\n break\n \n # Get the players average stats using the player class\n player_stats = player.get_average_stats()\n for stat in player_stats:\n # Check if the particular stat is counted in the league format\n if stat in self.projected_scores:\n # Check to see if the stat is a counting stat or FG%/FT% \n # as needs to be added differently if so \n if stat == \"FG%\" or stat == \"FT%\":\n self.projected_scores[stat][roster] = (30*self.projected_scores[stat][roster] + float(player_stats[stat]))/31\n else:\n self.projected_scores[stat][roster] += float(player_stats[stat])\n\n self.days_remaining += 1\n self.current_datetime += timedelta(days=1)\n \n return(self.projected_scores, self.days_remaining)",
"def dayoff(self):\n self.is_dayoff = True\n self.checkin_manhour = 0\n self.schedule(0)\n self.overtime = 0",
"def getDaysSatisfaction(emailSatisfactionTally, phoneSatisfactionTally, chatRatings):\n\n emailGood = emailSatisfactionTally.count(\"good\")\n emailBad = emailSatisfactionTally.count(\"bad\")\n\n try:\n emailSatisfaction = round(float(emailGood / (emailGood + emailBad)), 2)\n except ZeroDivisionError:\n emailSatisfaction = \"NA\"\n\n phoneGood = phoneSatisfactionTally.count(\"good\")\n phoneBad = phoneSatisfactionTally.count(\"bad\")\n\n try:\n phoneSatisfaction = round(float(phoneGood / (phoneGood + phoneBad)), 2)\n except ZeroDivisionError:\n phoneSatisfaction = \"NA\"\n\n try:\n chatSatisfaction = round(float(chatRatings[\"good\"] / (chatRatings[\"good\"] + chatRatings[\"bad\"])), 2)\n except ZeroDivisionError:\n chatSatisfaction = \"NA\"\n\n return emailSatisfaction, phoneSatisfaction , chatSatisfaction",
"def calculateDaysInteractions(replyCount, phoneInboundCount, chatCount, emailCount):\n totalInteractions = replyCount + phoneInboundCount + chatCount\n solvedInteractions = emailCount + phoneInboundCount + chatCount\n\n return totalInteractions, solvedInteractions",
"def py2_earth_hours_left(start_date=BITE_CREATED_DT):\n time_left = PY2_DEATH_DT - start_date\n one_hour = timedelta(hours=1) \n return round(time_left / one_hour, 2)",
"def test_available_leave_days(self):\n user = mommy.make(\"auth.User\", first_name=\"Mosh\", last_name=\"Pitt\")\n staff = mommy.make(\"small_small_hr.StaffProfile\", user=user)\n annual_leave = mommy.make(\n \"small_small_hr.AnnualLeave\",\n staff=staff,\n year=2017,\n leave_type=Leave.REGULAR,\n allowed_days=21,\n carried_over_days=0,\n )\n\n months = range(1, 13)\n\n for month in months:\n self.assertEqual(\n month * 1.75, annual_leave.get_available_leave_days(month=month)\n )",
"def get_days_left():\n\t\n\t# Counter to store the number of days (today counts).\n\tdays = 0\n\t# Storing the current date.\n\ttoday = dt.date.today()\n\t\n\t# Looping through the days between today and the end of school.\n\tfor date in date_range(today, last_day):\n\t\t# Making sure it's a school day.\n\t\tif date.weekday() not in [5, 6] and date not in holidays:\n\t\t\t# Incrementing the days counter.\n\t\t\tdays += 1\n\treturn days"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Keep track of previous quarterback for each game and each team.
|
def previous_quarterback(self, games):
game_dates = pd.concat([
games[["date", "team_home", "qb_home"]].rename(
columns={"team_home": "team", "qb_home": "qb"}),
games[["date", "team_away", "qb_away"]].rename(
columns={"team_away": "team", "qb_away": "qb"}),
]).sort_values("date")
game_dates['qb_prev'] = game_dates.qb
game_dates = pd.merge_asof(
game_dates[['team', 'date']],
game_dates[['team', 'date', 'qb_prev']],
on='date', by='team', allow_exact_matches=False)
for team in ["home", "away"]:
game_dates_team = game_dates.rename(
columns={'qb_prev': f'qb_prev_{team}',
'team': f'team_{team}'})
games = games.merge(game_dates_team, on=['date', f'team_{team}'])
return games
|
[
"def test_previous(self):\n with mn.model() as m:\n mn.stock('Foo', 1, 0)\n LastFoo = mn.previous('LastFoo', 'Foo')\n\n self.assertEqual(LastFoo[''], 0)\n m.step()\n self.assertEqual(LastFoo[''], 0)\n m.step()\n self.assertEqual(LastFoo[''], 1)\n m.step()\n self.assertEqual(LastFoo[''], 2)\n m.reset()\n self.assertEqual(LastFoo[''], 0)",
"def previous_player(self):\n self.current_player = (self.current_player - 1) % 3",
"def get_prev_timestep(self):\n self.skip_back_timestep()\n m, data = self.get_next_timestep()\n self.skip_back_timestep()\n\n return m, data",
"def test_previous_small_timestep(self):\n with mn.model(timestep=0.5) as m:\n mn.stock('Foo', 1, 0)\n LastFoo = mn.previous('LastFoo', 'Foo')\n\n self.assertEqual(LastFoo[''], 0)\n m.step()\n self.assertEqual(LastFoo[''], 0)\n m.step()\n self.assertEqual(LastFoo[''], 0.5)\n m.step()\n self.assertEqual(LastFoo[''], 1)\n m.reset()\n self.assertEqual(LastFoo[''], 0)",
"def test_previous_with_initial_value_reversed_order(self):\n with mn.model() as m:\n LastFoo = mn.previous('LastFoo', 'Foo', 0.3)\n mn.stock('Foo', 1, 0)\n\n self.assertEqual(LastFoo[''], 0.3)\n m.step()\n self.assertEqual(LastFoo[''], 0)\n m.step()\n self.assertEqual(LastFoo[''], 1)\n m.step()\n self.assertEqual(LastFoo[''], 2)\n m.reset()\n self.assertEqual(LastFoo[''], 0.3)",
"def backtest(self):\n # Cut off most recent history closing price since it is not complete and would effect the calculations\n #kline_array = self.client.get_historical_klines(symbol=pair, interval=Client.KLINE_INTERVAL_5MINUTE, start_str= '1' + ' month ago UTC')\n kline_array = self.client.get_historical_klines(symbol=self.pair, interval=self.asset_interval, start_str= self.time_look_back)\n self.closing_times = [dt.datetime.utcfromtimestamp(x[6]/1000) for x in kline_array][0:-1]\n self.closing_price_array = [float(x[4]) for x in kline_array][0:-1]\n self.checked_prices = []\n\n gain, loss = 0, 0\n for x in range(0, len(self.closing_price_array)-1):\n change = self.closing_price_array[x+1] - self.closing_price_array[x]\n self.checked_prices.append(self.closing_price_array[x+1])\n self.checked_times.append(self.closing_times[x+1])\n if change > 0:\n gain += change\n elif change < 0:\n loss += abs(change)\n\n #Get first rsi simple moving average\n if x == self.rsi_period:\n self.avg_gain = self.simple_moving_average(gain, self.rsi_period)\n self.avg_loss = self.simple_moving_average(loss, self.rsi_period)\n self.rsi = self.rsi_calc(self.avg_gain, self.avg_loss)\n self.rsi_array.append(self.rsi)\n gain, loss = 0, 0\n\n #Use wilders moving average to continue calculating rsi values\n elif x > self.rsi_period:\n self.avg_gain = self.wilders_moving_average(self.rsi_period, gain, self.avg_gain)\n self.avg_loss = self.wilders_moving_average(self.rsi_period, loss, self.avg_loss)\n self.rsi = self.rsi_calc(self.avg_gain, self.avg_loss)\n self.rsi_array.append(self.rsi)\n gain, loss = 0, 0\n\n # When there are enough rsi values begin to calculate stoch_rsi\n if len(self.rsi_array) >= self.stoch_period:\n k_fast = self.k_fast_stoch(self.rsi_array[len(self.rsi_array) - self.stoch_period:])\n self.k_fast_array['k_fast'].append(k_fast)\n self.k_fast_array['time'].append(self.closing_times[x])\n\n # When there are enough %K_FAST values begin to calculate %K_SLOW values = sma of n %K_FAST values\n if len(self.k_fast_array['k_fast']) >= self.k_slow_period:\n k_slow = self.simple_moving_average(self.k_fast_array['k_fast'][-1*self.k_slow_period:], self.k_slow_period)\n self.k_slow_array['k_slow'].append(k_slow)\n self.k_slow_array['time'].append(self.closing_times[x])\n\n # When there are enough %K_SLOW values begin to calculate %D_SLOW values = sma of n %K_SLOW values\n if len(self.k_slow_array['k_slow']) >= self.d_slow_period:\n d_slow = self.simple_moving_average(self.k_slow_array['k_slow'][-1*self.d_slow_period:], self.d_slow_period)\n self.d_slow_array['d_slow'].append(d_slow)\n self.d_slow_array['time'].append(self.closing_times[x])\n\n self.bollinger_bands(self.checked_prices, self.sma_period, self.deviation, self.checked_times[x])\n\n #Once all values start to be calculated we can determine whether to buy or sell until we hit the last\n self.buy_sell(current_time = self.checked_times[x])\n\n self.plot_orders() #Plot orders on graph",
"def previous_last_quarter_moon(date):\n return _find_moon_phase(date, -twopi, pi + halfpi)",
"def test_previous_with_initial_value(self):\n with mn.model() as m:\n mn.stock('Foo', 1, 0)\n LastFoo = mn.previous('LastFoo', 'Foo', 0.3)\n\n self.assertEqual(LastFoo[''], 0.3)\n m.step()\n self.assertEqual(LastFoo[''], 0)\n m.step()\n self.assertEqual(LastFoo[''], 1)\n m.step()\n self.assertEqual(LastFoo[''], 2)\n m.reset()\n self.assertEqual(LastFoo[''], 0.3)",
"def test_previous_with_namedtuple(self):\n Payer = mn.mn_namedtuple(\n 'Payer', ['Medicare', 'Medicaid', 'Commercial'])\n with mn.model() as m:\n mn.stock('Foo', Payer(1, 2, 3), Payer(0, 0, 0))\n LastFoo = mn.previous('LastFoo', 'Foo')\n\n self.assertEqual(LastFoo[''], Payer(0, 0, 0))\n m.step()\n self.assertEqual(LastFoo[''], Payer(0, 0, 0))\n m.step()\n self.assertEqual(LastFoo[''], Payer(1, 2, 3))\n m.step()\n self.assertEqual(LastFoo[''], Payer(2, 4, 6))\n m.reset()\n self.assertEqual(LastFoo[''], Payer(0, 0, 0))",
"def test_previous(self): \n with mn.model(treatments=['conjecture', 'current', 'possible', 'design']\n ) as m:\n mn.variable('X', 1)\n mn.variable('Y', 22).undefined_in('design')\n S = mn.stock('S',\n \"\"\"Start at 22 and increase by 1\"\"\",\n lambda x: x, ('X',), lambda x: x, ('Y',)\n ).undefined_in('design')\n P = mn.previous('P', 'S').undefined_in('possible', 'design')\n\n self.assertEqual(S['current'], 22)\n self.assertEqual(S['design'], None)\n self.assertEqual(P['conjecture'], 22)\n self.assertEqual(P['design'], None)\n self.assertEqual(P['possible'], None)\n m.step() \n self.assertEqual(S['current'], 23)\n self.assertEqual(S['design'], None)\n self.assertEqual(P['conjecture'], 22)\n self.assertEqual(P['design'], None)\n self.assertEqual(P['possible'], None)\n m.step() \n self.assertEqual(S['current'], 24)\n self.assertEqual(S['design'], None)\n self.assertEqual(P['conjecture'], 23)\n self.assertEqual(P['design'], None)\n self.assertEqual(P['possible'], None)",
"def test_get_previous_versions_two_previous(self):\n study = factories.StudyFactory.create()\n now = timezone.now()\n source_study_version_1 = factories.SourceStudyVersionFactory.create(\n study=study, i_version=1, i_date_added=now - timedelta(hours=2))\n source_study_version_2 = factories.SourceStudyVersionFactory.create(\n study=study, i_version=2, i_date_added=now - timedelta(hours=1))\n source_study_version_3 = factories.SourceStudyVersionFactory.create(\n study=study, i_version=3, i_date_added=now)\n result = source_study_version_3.get_previous_versions()\n self.assertEqual(result.count(), 2)\n self.assertEqual(result[0], source_study_version_2)\n self.assertEqual(result[1], source_study_version_1)",
"def test_self_previous(self):\n with mn.model() as m:\n Foo = mn.previous('Foo', 'Foo', 0)\n\n self.assertEqual(Foo[''], 0)\n m.step()\n self.assertEqual(Foo[''], 0)\n m.step()\n self.assertEqual(Foo[''], 0)\n m.reset()\n self.assertEqual(Foo[''], 0)\n m.step()\n self.assertEqual(Foo[''], 0)",
"def prev_reward(self):\n return [env.prev_reward() for env in self._envs]",
"def quarters(self):\n return self.get_quarterdelta()",
"def backstep(self):\n\n self.timestep -= 1\n self.historyLayer.backstep()",
"def test_get_previous_version_two_previous(self):\n study = factories.StudyFactory.create()\n now = timezone.now()\n source_study_version_1 = factories.SourceStudyVersionFactory.create(\n study=study, i_version=1, i_date_added=now - timedelta(hours=2))\n source_study_version_2 = factories.SourceStudyVersionFactory.create(\n study=study, i_version=2, i_date_added=now - timedelta(hours=1))\n source_study_version_3 = factories.SourceStudyVersionFactory.create(\n study=study, i_version=3, i_date_added=now)\n self.assertEqual(source_study_version_3.get_previous_version(), source_study_version_2)",
"def previous(self):\n raise NotImplementedError()",
"def previous_field(self):\n self.stack[-1].previous()",
"def step_back(self):\n if len(self.history) > 0:\n self.round, self.game_pointer, self.round_counter, self.dealer, self.public_cards, self.players = self.history.pop()\n self.stage = Stage(self.round_counter)\n return True\n return False"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Run notebook, convert, save and return PDF path.
|
def export_notebook_to_pdf(self, nb_path: str, nb_params: Dict) -> str: # type: ignore
report_file = Path(nb_path)
if not report_file.is_file():
raise ValueError("Notebook path does not point to a file.")
nb_params = self._parse_params(nb_params)
report_filename, report_extension = report_file.stem, report_file.suffix
if report_extension != "ipynb":
report_nb = self.base_path / f"{report_filename}.ipynb"
else:
report_nb = report_file
now_timestamp = datetime.today().strftime('%Y-%m-%dT%H-%M-%S')
run_nb = self.base_path / f"{report_filename} {now_timestamp}.ipynb"
pdf_filename = self.base_path / f"{report_filename} {now_timestamp}.pdf"
logger.info("Running %s and converting to %s", run_nb, pdf_filename)
jupytext_notebook = jupytext.read(report_file)
# write to execution nb
jupytext.write(jupytext_notebook, report_nb)
_ = pm.execute_notebook(str(report_nb), str(run_nb), parameters=nb_params,)
pdfexp = PDFExporter(
template_file=resource_filename("soam", "resources/pdf_report.tpl")
)
pdf_data, _ = pdfexp.from_filename(run_nb)
with open(pdf_filename, "wb") as f:
f.write(pdf_data)
logger.info("Succesfully wrote: %s", str(pdf_filename))
return str(pdf_filename)
|
[
"def run(self, nb_path: str, nb_params: Dict) -> str: # type: ignore[override]\n return self.export_notebook_to_pdf(nb_path, nb_params)",
"def test_to_pdf_with_nb_path(self):\n nb = nbformat.v4.new_notebook()\n text = \"\"\"\\\n This is an auto-generated notebook.\"\"\"\n nb['cells'] = [nbformat.v4.new_markdown_cell(text)]\n with open(TEST_FILES_PATH + 'test-nb.ipynb', \"w\") as f:\n nbformat.write(nb, f)\n grader = Notebook(test_dir=TEST_FILES_PATH + \"tests\")\n grader.to_pdf(TEST_FILES_PATH + \"test-nb.ipynb\", filtering=False)\n\n self.assertTrue(os.path.isfile(TEST_FILES_PATH + \"test-nb.pdf\"))\n # cleanup\n os.remove(TEST_FILES_PATH + 'test-nb.ipynb')\n os.remove(TEST_FILES_PATH + \"test-nb.pdf\")",
"def run_ipynb(filepath):\n filename = os.path.basename(filepath)\n cmd = ('jupyter-nbconvert', '--to', 'html', '--execute',\n '--ClearOutputPreprocessor.enabled=True', filepath, '--output',\n filename)\n subprocess.check_call(cmd)",
"def test_notebook(path):\n import nbconvert\n print('Running ' + path + ' ... ', end='')\n sys.stdout.flush()\n\n # Load notebook, convert to python\n e = nbconvert.exporters.PythonExporter()\n code, __ = e.from_filename(path)\n\n # Remove coding statement, if present\n ipylines = ['ipython', 'show(']\n code = '\\n'.join([x for x in code.splitlines() if not 'ipython' in x])\n for x in code.splitlines():\n if not any(s in ipylines for s in x):\n code += '\\n'.join([x])\n # print(code)\n\n # Tell matplotlib not to produce any figures\n env = os.environ.copy()\n env['MPLBACKEND'] = 'Template'\n\n # Run in subprocess\n start = time.time()\n cmd = [sys.executable, '-c', code]\n try:\n p = subprocess.Popen(\n cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env\n )\n stdout, stderr = p.communicate()\n # TODO: Use p.communicate(timeout=3600) if Python3 only\n if p.returncode != 0:\n # Show failing code, output and errors before returning\n print('ERROR')\n # print('-- script ' + '-' * (79 - 10))\n # for i, line in enumerate(code.splitlines()):\n # j = str(1 + i)\n # print(j + ' ' * (5 - len(j)) + line)\n print('-- stdout ' + '-' * (79 - 10))\n print(stdout)\n print('-- stderr ' + '-' * (79 - 10))\n print(stderr)\n print('-' * 79)\n return False\n except KeyboardInterrupt:\n p.terminate()\n stop = time.time()\n print('ABORTED after', round(stop-start,4), \"s\")\n sys.exit(1)\n\n # Successfully run\n stop = time.time()\n print('ok. Run took ', round(stop-start,4), \"s\")\n return True",
"def test_to_pdf_without_nb_path_case1_pass(self, mockInp):\n config = {\n \"notebook\": TEST_FILES_PATH + \"test-nb.ipynb\",\n \"endpoint\": \"http://some.url\", # dont include this when testing service enabled stuff\n \"assignment_id\": \"hw00\",\n \"class_id\": \"some_class\",\n \"auth\": \"google\",\n \"save_environment\": False,\n \"ignore_modules\": [],\n }\n # Make new otter file, put it in directory\n f = open(\"demofile2.otter\", \"w\")\n f.write(json.dumps(config))\n f.close()\n nb = nbformat.v4.new_notebook()\n text = \"\"\"\\\n This is an auto-generated notebook.\"\"\"\n nb['cells'] = [nbformat.v4.new_markdown_cell(text)]\n with open(TEST_FILES_PATH + 'test-nb.ipynb', \"w\") as f:\n nbformat.write(nb, f)\n grader = Notebook(test_dir=TEST_FILES_PATH + \"tests\")\n grader.to_pdf(nb_path = None, filtering=False)\n self.assertTrue(os.path.exists(TEST_FILES_PATH + \"test-nb.pdf\"))\n # cleanup\n os.remove(TEST_FILES_PATH + 'test-nb.ipynb')\n os.remove(TEST_FILES_PATH + \"test-nb.pdf\")\n os.remove(\"demofile2.otter\")",
"def execute_notebook(nb_path):\n command = f'jupyter nbconvert --ExecutePreprocessor.timeout=6000 --execute --inplace {nb_path}'\n os.system(command)",
"def gen_report(directory):\n from subprocess import check_call, CalledProcessError\n from pathlib import Path\n import shutil\n import os\n\n directory = Path(directory).absolute()\n\n try:\n os.chdir(str(directory))\n except FileNotFoundError:\n click.echo('No such directory: {}'.format(directory))\n sys.exit(1)\n except PermissionError:\n click.echo(\"Don't have permission to work in: {}\".format(directory))\n sys.exit(1)\n\n os.environ['PWD'] = str(directory)\n\n nb_convert = shutil.which('jupyter-nbconvert')\n base = Path(__file__).absolute().parent\n nb_path = base/\"nb\"/\"gen-report-figures.ipynb\"\n tp_path = base/\"nb\"/\"nocode.tpl\"\n\n if nb_convert is None:\n click.echo(\"Failed to find `jupyter-nbconvert` need it to run report notebook.\", err=True)\n sys.exit(2)\n\n args = [nb_convert,\n '--execute',\n '--to=html',\n '--NbConvertApp.output_base=report',\n '--output-dir=.',\n '--template={}'.format(tp_path),\n str(nb_path)]\n\n click.echo('Working in: {}'.format(directory))\n\n try:\n check_call(args)\n except FileNotFoundError:\n click.echo(\"Failed to find `jupyter-nbconvert` need it to run report notebook.\", err=True)\n sys.exit(2)\n except CalledProcessError:\n sys.exit(3)",
"def run(self, path_to_ebook):\n\n path_to_mobi = os.path.splitext(path_to_ebook)[0] + '.mobi'\n print subprocess.check_output(['ebook-convert', path_to_ebook, path_to_mobi])\n \n return path_to_mobi",
"def jupyter_to_markdown(path):\n\n args = ['jupyter', 'nbconvert', '--to', 'html', path]\n child = subprocess.call(args)",
"def convert_to_pdf(htmlfolder: str, filenames: List[str], outfolder: str = \"./pdf/\", cmd: str = \"wkhtmltopdf\") -> None:\n def _convert_file_parallel(filename: str):\n infile = htmlfolder + filename.replace(\".Rmd\", \".html\")\n outfile = outfolder + filename.replace(\".Rmd\", \".pdf\")\n # Return if provided file path does not exist (also ignores symlinks)\n if not os.path.exists(infile): return\n os.system(\n \"xvfb-run --auto-servernum --server-args='-screen 0, 1920x1080x24' {} --use-xserver --javascript-delay 4000 ./{} ./{}\"\n .format(cmd, infile, outfile)\n )\n\n def _convert_file(filename: str):\n infile = htmlfolder + filename.replace(\".Rmd\", \".html\")\n outfile = outfolder + filename.replace(\".Rmd\", \".pdf\")\n # Return if provided file path does not exist (also ignores symlinks)\n if not os.path.exists(infile): return\n os.system(\"{} --javascript-delay 4000 ./{} ./{}\".format(cmd, infile, outfile))\n\n pool = ThreadPool(cli_args.jobs)\n Log.info(\"Converting {} files to PDF\", len(filenames))\n\n # Use xvfb-run if installed only on Linux, to convert files concurrently\n if which(\"xvfb-run\") and sys.platform.startswith(\"linux\"):\n Log.info(\"Detected xfvb-run. Using {} threads\", cli_args.jobs)\n try:\n pool.map(_convert_file_parallel, filenames)\n except KeyboardInterrupt:\n Log.error(\"Terminating prematurely\")\n Log.info(\"Finishing pending conversions\")\n # Wait for all conversions to finish\n pool.terminate()\n pool.join()\n sys.exit(1)\n return\n pool.close()\n pool.join()\n else:\n for fn in filenames:\n _convert_file(fn)\n\n Log.success(\"Finished converting files to PDF\")",
"def convert_notebooks():\n\timport utils.convert as c\n\tglobal NOTEBOOK_DIR\n\tprint \"Converting notebooks...\"\n\tc.convert_dir(NOTEBOOK_DIR)\n\tprint \"finished conversions\"",
"def write_pdf(self, submission_path):\n ...",
"def txt_to_pdf(self):\n #path = '%s/%s.pdf' % (os.path.dirname(self.filepath), self.document)\n path = os.path.join(os.path.dirname(self.filepath), self.document) + '.pdf'\n p = Popen('a2ps --quiet --portrait --columns=1 --rows=1 -L 100 --no-header --borders=off -o - %s | ps2pdf -sPAPERSIZE=a4 - %s' % (self.filepath, path), shell=True, stdout=PIPE, stderr=PIPE)\n stdout, stderr = p.communicate()\n content = open(path, 'rb').read()\n p = Popen('rm -rf %s' % path, shell=True,stdout=PIPE, stderr=PIPE)\n return ['application/pdf', content]",
"def save_jupyter_nb():\n display(Javascript('Jupyter.notebook.save_checkpoint();'))",
"def tif_to_pdf(self):\n path = os.path.join(os.path.dirname(self.filepath), self.document) + '.pdf'\n p = Popen('tiff2pdf -o %s %s' % (path, self.filepath), shell=True, stdout=PIPE, stderr=PIPE)\n stdout, stderr = p.communicate()\n content = open(path, 'rb').read()\n p = Popen('rm -rf %s' % path, shell=True,stdout=PIPE, stderr=PIPE)\n return ['application/pdf', content]",
"def test_to_pdf_without_nb_path_case2_fail(self):\n nb1 = nbformat.v4.new_notebook()\n nb2 = nbformat.v4.new_notebook()\n text = \"\"\"\\\n This is an auto-generated notebook.\"\"\"\n nb1['cells'] = [nbformat.v4.new_markdown_cell(text)]\n nb2['cells'] = [nbformat.v4.new_markdown_cell(text)]\n with open('test-nb1.ipynb', \"w\") as f:\n nbformat.write(nb1, f)\n with open('test-nb2.ipynb', \"w\") as f:\n nbformat.write(nb2, f)\n grader = Notebook(test_dir=TEST_FILES_PATH + \"tests\")\n self.assertRaises(AssertionError,\n lambda: grader.to_pdf(nb_path=None, filtering=False))\n os.remove('test-nb1.ipynb')\n os.remove('test-nb2.ipynb')",
"def run(self) -> str:\n self.output_msg(f\"{datetime.datetime.now()} => Starting OBS PDF processing for {self.description}…\\n\")\n\n # Clean up left-over files from any previous runs\n self.cleanup_files()\n\n # Initialize some variables\n today = ''.join(str(datetime.date.today()).rsplit(str('-'))[0:3]) # str(datetime.date.today())\n # self.download_dir = '/tmp/obs-to-pdf/{0}-{1}'.format(self.lang_code, int(time.time()))\n make_dir(self.tmp_download_dirpath)\n\n if self.parameter_type == 'Catalog_lang_code':\n # Get the catalog\n self.output_msg(f\"{datetime.datetime.now()} => Downloading the Door43 Catalog…\\n\")\n catalog = get_catalog()\n\n # Find the language we need\n langs = [l for l in catalog['languages'] if l['identifier'] == self.lang_code] # type: dict\n\n if not langs:\n err_msg = f'Did not find \"{self.lang_code}\" in the catalog.'\n self.output_msg(f\"{datetime.datetime.now()} ERROR: {err_msg}\\n\")\n raise ValueError(err_msg)\n\n if len(langs) > 1:\n err_msg = f'Found more than one entry for \"{self.lang_code}\" in the catalog.'\n self.output_msg(f\"{datetime.datetime.now()} ERROR: {err_msg}\\n\")\n raise ValueError(err_msg)\n\n lang_info = langs[0] # type: dict\n\n # 1. Get the zip file from the API\n resources = [r for r in lang_info['resources'] if r['identifier'] == 'obs'] # type: dict\n\n if not resources:\n err_msg = f'Did not find an entry for \"{self.lang_code}\" OBS in the catalog.'\n self.output_msg(f\"{datetime.datetime.now()} ERROR: {err_msg}\\n\")\n raise ValueError(err_msg)\n\n if len(resources) > 1:\n err_msg = f'Found more than one entry for \"{self.lang_code}\" OBS in the catalog.'\n self.output_msg(f\"{datetime.datetime.now()} ERROR: {err_msg}\\n\")\n raise ValueError(err_msg)\n\n resource = resources[0] # type: dict\n\n found_sources = []\n\n for project in resource['projects']:\n if project['formats']:\n urls = [f['url'] for f in project['formats']\n if 'application/zip' in f['format'] and 'text/markdown' in f['format']]\n\n if len(urls) > 1:\n err_msg = f'Found more than one zipped markdown entry for \"{self.lang_code}\" OBS in the catalog.'\n self.output_msg(f\"{datetime.datetime.now()} ERROR: {err_msg}\\n\")\n raise ValueError(err_msg)\n\n if len(urls) == 1:\n found_sources.append(urls[0])\n\n if not found_sources:\n err_msg = f'Did not find any zipped markdown entries for \"{self.lang_code}\" OBS in the catalog.'\n self.output_msg(f\"{datetime.datetime.now()} ERROR: {err_msg}\\n\")\n raise ValueError(err_msg)\n\n if len(found_sources) > 1:\n err_msg = f'Found more than one zipped markdown entry for \"{self.lang_code}\" OBS in the catalog.'\n self.output_msg(f\"{datetime.datetime.now()} ERROR: {err_msg}\\n\")\n raise ValueError(err_msg)\n\n source_zip_url = found_sources[0]\n tmp_source_dirpath = os.path.join(self.tmp_download_dirpath, f'{self.lang_code.lower()}_obs/')\n\n elif self.parameter_type == 'Door43_repo':\n source_zip_url = f'{DOOR43_SITE_URL}/{self.given_repo_spec}/archive/master.zip'\n tmp_source_dirpath = os.path.join(self.tmp_download_dirpath, self.repo_name.lower())\n\n elif self.parameter_type == 'username_repoName_spec':\n source_zip_url = f'{DOOR43_SITE_URL}/{self.username}/{self.repo_name}/archive/{self.repo_spec}.zip'\n tmp_source_dirpath = os.path.join(self.tmp_download_dirpath, self.repo_name.lower())\n\n\n # 2. Download source zip, then unzip\n self.output_msg(f\"{datetime.datetime.now()} => Downloading '{source_zip_url}'…\\n\")\n downloaded_zip_tmp_filepath = f'{self.tmp_download_dirpath}/obs.zip'\n download_file(source_zip_url, downloaded_zip_tmp_filepath)\n unzip(downloaded_zip_tmp_filepath, self.tmp_download_dirpath)\n\n # 3. Check for valid repository structure\n manifest_filepath = os.path.join(tmp_source_dirpath, 'manifest.yaml')\n if not isfile(manifest_filepath):\n err_msg = f\"Did not find manifest.yaml in the resource container at {manifest_filepath}\"\n self.output_msg(f\"{datetime.datetime.now()} ERROR: {err_msg}\\n\")\n raise FileNotFoundError(err_msg)\n\n content_dirpath = os.path.join(tmp_source_dirpath, 'content/')\n if not isdir(content_dirpath):\n err_msg = \"Did not find the content directory in the resource container\"\n self.output_msg(f\"{datetime.datetime.now()} ERROR: {err_msg}\\n\")\n raise NotADirectoryError(err_msg)\n\n # 4. Read the manifest (status, version, localized name, etc)\n self.output_msg(f\"{datetime.datetime.now()} => Reading the {self.description} manifest…\\n\")\n manifest = load_yaml_object(manifest_filepath)\n\n # 5. Initialize OBS objects\n self.output_msg(f\"{datetime.datetime.now()} => Initializing the OBS object…\\n\")\n obs_obj = OBS()\n obs_obj.date_modified = today\n obs_obj.language_id = manifest['dublin_core']['language']['identifier']\n obs_obj.language_name = manifest['dublin_core']['language']['title']\n obs_obj.language_direction = manifest['dublin_core']['language']['direction']\n obs_obj.version = manifest['dublin_core']['version']\n obs_obj.publisher = manifest['dublin_core']['publisher']\n obs_obj.description, obs_obj.extended_description = self.description, self.extended_description\n\n # 6. Import the chapter data\n self.output_msg(f\"{datetime.datetime.now()} => Reading the {self.description} chapter files…\\n\")\n obs_obj.chapters = self.load_obs_chapters(content_dirpath)\n obs_obj.chapters.sort(key=lambda c: int(c['number']))\n\n self.output_msg(f\"{datetime.datetime.now()} => Verifying the chapter data…\\n\")\n if not obs_obj.verify_all():\n err_msg = \"Quality check did not pass.\"\n self.output_msg(f\"{datetime.datetime.now()} ERROR: {err_msg}\\n\")\n raise OBSError(err_msg)\n\n # 7. Front and back matter\n self.output_msg(f\"{datetime.datetime.now()} => Reading the front and back matter…\\n\")\n title_filepath = os.path.join(content_dirpath, 'front', 'title.md')\n if not isfile(title_filepath):\n err_msg = \"Did not find the title file in the resource container\"\n self.output_msg(f\"{datetime.datetime.now()} ERROR: {err_msg}\\n\")\n raise OBSError(err_msg)\n obs_obj.title = read_file(title_filepath)\n\n front_filepath = os.path.join(content_dirpath, 'front', 'intro.md')\n if not isfile(front_filepath):\n err_msg = \"Did not find the front/intro.md file in the resource container\"\n self.output_msg(f\"{datetime.datetime.now()} ERROR: {err_msg}\\n\")\n raise OBSError(err_msg)\n obs_obj.front_matter = self.remove_trailing_hashes(read_file(front_filepath), 'front-matter')\n\n back_filepath = os.path.join(content_dirpath, 'back', 'intro.md')\n if not isfile(back_filepath):\n err_msg = \"Did not find the back/intro.md file in the resource container\"\n self.output_msg(f\"{datetime.datetime.now()} ERROR: {err_msg}\\n\")\n raise OBSError(err_msg)\n obs_obj.back_matter = self.remove_trailing_hashes(read_file(back_filepath), 'back-matter')\n\n return self.create_and_upload_pdf(obs_obj) # Should return upload URL",
"def _save_notebook(self, path, nb):\n bucket_name, bucket_path = self._parse_path(path)\n bucket = self._get_bucket(bucket_name, throw=True)\n data = nbformat.writes(nb, version=nbformat.NO_CONVERT)\n blob = bucket.blob(bucket_path)\n blob.upload_from_string(data, \"application/x-ipynb+json\")\n return blob",
"def compile(self):\n\n\t\tself.save_images(Settings.tmp_dir)\n\n\t\ttex_file = path.join(Settings.tmp_dir, 'pgf_{0}_{1}.tex'.format(Figure._session, self._idx))\n\t\tpdf_file = path.join(Settings.tmp_dir, 'pgf_{0}_{1}.pdf'.format(Figure._session, self._idx))\n\n\t\tcommand = Settings.pdf_compile.format('-output-directory {0} {1}')\n\t\tcommand = command.format(Settings.tmp_dir, tex_file)\n\n\t\t# write LaTeX file\n\t\twith open(tex_file, 'w') as handle:\n\t\t\thandle.write(self.render())\n\n\t\t# compile\n\t\tif system('cd \"{0}\" && {1}'.format(Settings.tmp_dir, command)):\n\t\t\traise RuntimeError('Compiling TeX source file to PDF failed.')\n\n\t\treturn pdf_file"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Task to export the notebook into a pdf.
|
def run(self, nb_path: str, nb_params: Dict) -> str: # type: ignore[override]
return self.export_notebook_to_pdf(nb_path, nb_params)
|
[
"def write_pdf(self, submission_path):\n ...",
"def test_to_pdf_with_nb_path(self):\n nb = nbformat.v4.new_notebook()\n text = \"\"\"\\\n This is an auto-generated notebook.\"\"\"\n nb['cells'] = [nbformat.v4.new_markdown_cell(text)]\n with open(TEST_FILES_PATH + 'test-nb.ipynb', \"w\") as f:\n nbformat.write(nb, f)\n grader = Notebook(test_dir=TEST_FILES_PATH + \"tests\")\n grader.to_pdf(TEST_FILES_PATH + \"test-nb.ipynb\", filtering=False)\n\n self.assertTrue(os.path.isfile(TEST_FILES_PATH + \"test-nb.pdf\"))\n # cleanup\n os.remove(TEST_FILES_PATH + 'test-nb.ipynb')\n os.remove(TEST_FILES_PATH + \"test-nb.pdf\")",
"def export_notebook_to_pdf(self, nb_path: str, nb_params: Dict) -> str: # type: ignore\n report_file = Path(nb_path)\n\n if not report_file.is_file():\n raise ValueError(\"Notebook path does not point to a file.\")\n\n nb_params = self._parse_params(nb_params)\n\n report_filename, report_extension = report_file.stem, report_file.suffix\n\n if report_extension != \"ipynb\":\n report_nb = self.base_path / f\"{report_filename}.ipynb\"\n else:\n report_nb = report_file\n\n now_timestamp = datetime.today().strftime('%Y-%m-%dT%H-%M-%S')\n\n run_nb = self.base_path / f\"{report_filename} {now_timestamp}.ipynb\"\n pdf_filename = self.base_path / f\"{report_filename} {now_timestamp}.pdf\"\n\n logger.info(\"Running %s and converting to %s\", run_nb, pdf_filename)\n\n jupytext_notebook = jupytext.read(report_file)\n # write to execution nb\n jupytext.write(jupytext_notebook, report_nb)\n\n _ = pm.execute_notebook(str(report_nb), str(run_nb), parameters=nb_params,)\n\n pdfexp = PDFExporter(\n template_file=resource_filename(\"soam\", \"resources/pdf_report.tpl\")\n )\n\n pdf_data, _ = pdfexp.from_filename(run_nb)\n\n with open(pdf_filename, \"wb\") as f:\n f.write(pdf_data)\n\n logger.info(\"Succesfully wrote: %s\", str(pdf_filename))\n\n return str(pdf_filename)",
"def _dump_pdf(self) -> None:\n if shutil.which(\"latexmk\") is None and shutil.which(\"pdflatex\") is None:\n # No LaTeX Compiler is available\n self.doc.generate_tex(os.path.join(self.save_dir, self.report_name))\n suffix = '.tex'\n else:\n # Force a double-compile since some compilers will struggle with TOC generation\n self.doc.generate_pdf(os.path.join(self.save_dir, self.report_name), clean_tex=False, clean=False)\n self.doc.generate_pdf(os.path.join(self.save_dir, self.report_name), clean_tex=False)\n suffix = '.pdf'\n print(\"FastEstimator-TestReport: Report written to {}{}\".format(os.path.join(self.save_dir, self.report_name),\n suffix))",
"def to_pdf(dfa: DFA, filename: str, **kwargs):\n\n tmp_file = filename + \".tmp\"\n with open(tmp_file, \"w\") as file:\n file.write(to_dot(dfa, **kwargs))\n\n call((\"dot -Tpdf \" + tmp_file + \" -o \" + filename).split(\" \"))\n call((\"rm \" + tmp_file).split(\" \"))",
"def generate_label_pdf(self):\n self.initialize_pdf_file()\n self.fill_pdf_pages()\n self.finalize_pdf_file()",
"def txt_to_pdf(self):\n #path = '%s/%s.pdf' % (os.path.dirname(self.filepath), self.document)\n path = os.path.join(os.path.dirname(self.filepath), self.document) + '.pdf'\n p = Popen('a2ps --quiet --portrait --columns=1 --rows=1 -L 100 --no-header --borders=off -o - %s | ps2pdf -sPAPERSIZE=a4 - %s' % (self.filepath, path), shell=True, stdout=PIPE, stderr=PIPE)\n stdout, stderr = p.communicate()\n content = open(path, 'rb').read()\n p = Popen('rm -rf %s' % path, shell=True,stdout=PIPE, stderr=PIPE)\n return ['application/pdf', content]",
"def download_dashboard(\n dashboard: models.Dashboard, style: str, width: int, height: int\n):\n assert dashboard.id\n id = int(dashboard.id)\n task = sdk.create_dashboard_render_task(\n id,\n \"pdf\",\n models.CreateDashboardRenderTask(dashboard_style=style),\n width,\n height,\n )\n\n if not (task and task.id):\n raise exceptions.RenderTaskError(\n f'Could not create a render task for \"{dashboard.title}\"'\n )\n\n # poll the render task until it completes\n elapsed = 0.0\n delay = 0.5 # wait .5 seconds\n while True:\n poll = sdk.render_task(task.id)\n if poll.status == \"failure\":\n print(poll)\n raise exceptions.RenderTaskError(f'Render failed for \"{dashboard.title}\"')\n elif poll.status == \"success\":\n break\n\n time.sleep(delay)\n elapsed += delay\n print(f\"Render task completed in {elapsed} seconds\")\n\n result = sdk.render_task_results(task.id)\n filename = f\"{dashboard.title}.pdf\"\n with open(filename, \"wb\") as f:\n f.write(result)\n print(f'Dashboard pdf saved to \"{filename}\"')",
"def test_pdf():\n\n ds = test_dataset('first')\n\n pdf = mkpdf(ds,sample=True)\n\n response.headers['Content-Type']='application/pdf' \n response.headers['Content-Disposition'] = 'filename=badge.pdf'\n\n return pdf",
"def export_pdf(request):\n card_id = request.GET.get('c')\n if card_id:\n concepts = Concept.objects.filter(pk=card_id)\n else:\n concepts = get_concepts_applying_filters()\n if not concepts:\n concepts = Concept.objects.all()\n\n _, path = tempfile.mkstemp(suffix='.pdf')\n try:\n concepts2pdf(concepts, path)\n except Latex2PdfException as e:\n context = {\n 'error': str(e),\n 'filters': [{'visible_name': f.visible_name, 'value': f.value}\n for f in Filter.objects.filter(active=True)],\n }\n return render(request, 'definitions/pdferror.html', context)\n\n response = HttpResponse(FileWrapper(open(path, 'rb')),\n content_type='application/pdf')\n response['Content-Disposition'] = 'attachment; filename=\"nerdhelp.pdf\"'\n return response",
"def test_to_pdf_without_nb_path_case1_pass(self, mockInp):\n config = {\n \"notebook\": TEST_FILES_PATH + \"test-nb.ipynb\",\n \"endpoint\": \"http://some.url\", # dont include this when testing service enabled stuff\n \"assignment_id\": \"hw00\",\n \"class_id\": \"some_class\",\n \"auth\": \"google\",\n \"save_environment\": False,\n \"ignore_modules\": [],\n }\n # Make new otter file, put it in directory\n f = open(\"demofile2.otter\", \"w\")\n f.write(json.dumps(config))\n f.close()\n nb = nbformat.v4.new_notebook()\n text = \"\"\"\\\n This is an auto-generated notebook.\"\"\"\n nb['cells'] = [nbformat.v4.new_markdown_cell(text)]\n with open(TEST_FILES_PATH + 'test-nb.ipynb', \"w\") as f:\n nbformat.write(nb, f)\n grader = Notebook(test_dir=TEST_FILES_PATH + \"tests\")\n grader.to_pdf(nb_path = None, filtering=False)\n self.assertTrue(os.path.exists(TEST_FILES_PATH + \"test-nb.pdf\"))\n # cleanup\n os.remove(TEST_FILES_PATH + 'test-nb.ipynb')\n os.remove(TEST_FILES_PATH + \"test-nb.pdf\")\n os.remove(\"demofile2.otter\")",
"def save_pdf(pdfname, title=\"Domáca úloha\"):\n tex = \"\\n\\n\".join(out)\n generate_pdf(pdfname,title,tex)",
"def convert_to_pdf(htmlfolder: str, filenames: List[str], outfolder: str = \"./pdf/\", cmd: str = \"wkhtmltopdf\") -> None:\n def _convert_file_parallel(filename: str):\n infile = htmlfolder + filename.replace(\".Rmd\", \".html\")\n outfile = outfolder + filename.replace(\".Rmd\", \".pdf\")\n # Return if provided file path does not exist (also ignores symlinks)\n if not os.path.exists(infile): return\n os.system(\n \"xvfb-run --auto-servernum --server-args='-screen 0, 1920x1080x24' {} --use-xserver --javascript-delay 4000 ./{} ./{}\"\n .format(cmd, infile, outfile)\n )\n\n def _convert_file(filename: str):\n infile = htmlfolder + filename.replace(\".Rmd\", \".html\")\n outfile = outfolder + filename.replace(\".Rmd\", \".pdf\")\n # Return if provided file path does not exist (also ignores symlinks)\n if not os.path.exists(infile): return\n os.system(\"{} --javascript-delay 4000 ./{} ./{}\".format(cmd, infile, outfile))\n\n pool = ThreadPool(cli_args.jobs)\n Log.info(\"Converting {} files to PDF\", len(filenames))\n\n # Use xvfb-run if installed only on Linux, to convert files concurrently\n if which(\"xvfb-run\") and sys.platform.startswith(\"linux\"):\n Log.info(\"Detected xfvb-run. Using {} threads\", cli_args.jobs)\n try:\n pool.map(_convert_file_parallel, filenames)\n except KeyboardInterrupt:\n Log.error(\"Terminating prematurely\")\n Log.info(\"Finishing pending conversions\")\n # Wait for all conversions to finish\n pool.terminate()\n pool.join()\n sys.exit(1)\n return\n pool.close()\n pool.join()\n else:\n for fn in filenames:\n _convert_file(fn)\n\n Log.success(\"Finished converting files to PDF\")",
"def export():\n\tquery = \"SELECT id, book_title, book_author, availability, tenant, datedue FROM bookList\"\n\tcursor.execute(query)\n\tdb_data = cursor.fetchall()\n\texport_docx_pdf.export_to_docx(db_data)\n\tmessagebox.showinfo(\"Note\", \"File exported as: book-list.pdf\")",
"def exportAsPDFToFile_2(self, students , filename=\"../files/students.pdf\"):\n\n doc = SimpleDocTemplate(filename)\n styles = getSampleStyleSheet()\n Story = [Spacer(1, 2 * inch)]\n style = styles[\"Normal\"]\n for student in students:\n bogustext = str(student)\n p = Paragraph(bogustext, style)\n Story.append(p)\n Story.append(Spacer(1, 0.2 * inch))\n doc.build(Story)",
"def make_pdf_link(self):\n return",
"def print_as_pdf(self, filename=DEFAULT_FILENAME_PAGE):\n return self.loop.run_until_complete(self.get_async_keyword_group().print_as_pdf(filename))",
"def pdf_generate(self):\n cachefile = self.pdf_get_cachefile()\n xmlfile = cachefile + '.xhtml'\n\n snip_rendered_body = str(self.render()) # TODO do this in the model ? like the board post body ?\n sctpath = hasattr(settings, 'LIB_PATH') and settings.LIB_PATH or '.'\n static_filepath = settings.MEDIA_ROOT\n snip_rendered_body = snip_rendered_body.replace(\n '<img src=\"%(media_url)s' % {\n 'media_url': settings.STATIC_URL\n },\n '<img src=\"%s/' % static_filepath)\n import codecs\n xmlout = codecs.open(xmlfile, mode='w', encoding='utf-8')\n\n xmlout.write('''\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n <head>\n <title>%(title)s</title>\n </head>\n <body>\n <div id=\"header\" class=\"pdf\">\n <div class=\"label\">%(title)s</div>\n </div>\n <div id=\"footer\" class=\"pdf\">\n Page\n <pdf:pagenumber />\n </div>\n\n ''' % {'title': self.title or self.name})\n xmlout.write(snip_rendered_body)\n xmlout.write('''\n </body>\n</html>\n''')\n\n xmlout.close()\n\n command = get_sph_setting('wiki_pdf_generation_command')\n os.system(command % {'srcfile': xmlfile, 'destfile': cachefile, })\n if not os.path.isfile(cachefile):\n raise Exception('Error while generating PDF.')",
"def save(name, dir=\".\"):\n\twarn(\"networkit.viztasks.save is deprecated, will be removed in future updates.\")\n\tsavefig(os.path.join(dir, \"{0}.pdf\".format(name)), bbox_inches=\"tight\", transparent=True)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Convert a matrix to a pickled form format is ,,rowcountcolumncount e.g., [[True, False, True], [True, True, True]] > "2,3,101111"
|
def to_value(matrix):
h = len(matrix)
w = 0 if h == 0 else len(matrix[0])
return ",".join(
(
str(h),
str(w),
"".join(["".join(["1" if v else "0" for v in row]) for row in matrix]),
)
)
|
[
"def matrix2string(matrix):\n\tlines = ''\n\tfor entry in matrix:\n\t\ts = ''\n\t\tfor j, field in enumerate(entry):\n\t\t\tif j > 0:\n\t\t\t\ts += ','\n\t\t\ts += '\"' + str(field) + '\"'\n\t\tlines += s + '\\n'\n\treturn lines",
"def serialize(puzzle):\n assert(len(puzzle)==9)\n assert(all([len(row)==9 for row in puzzle]))\n\n result = str()\n for row in puzzle:\n result += ''.join([str(s) if len(str(s))==1 else '0' for s in row])\n \n assert(len(result)==81)\n\n return result",
"def _encode_matrix(self, data):\n\n if self.msgformat == 'json':\n return [\"__matrix__\", data.dtype.name, data.shape,\n base64.b64encode(data.tostring()).decode()]\n else:\n return [\"__matrix__\", data.dtype.name, data.shape,\n data.tobytes()]",
"def nparray(self):\n import numpy\n rows = self._rows\n columns = self._columns\n matrix = self._matrix\n array = numpy.ndarray((rows, columns), dtype=bool)\n for i in range(rows):\n buf = matrix[i].unpack(zero=b'\\x00', one=b'\\x01')\n array[i] = numpy.frombuffer(buf, dtype=bool)\n return array",
"def unique_rows(matrix):\n return np.vstack({tuple(row) for row in matrix})",
"def deserialize(arr):\n return pickle.loads(arr.astype(np.uint8).tobytes())",
"def serialize(x):\n if isinstance(x, (bool, int, float, str, frozenset, bytes, complex)) or x is None:\n return x\n elif is_numpy_scalar(x):\n return x\n elif is_torch_tensor(x) or is_numpy_array(x):\n if len(x.shape) == 0:\n return x.item()\n elif len(x.shape) == 1:\n return tuple(x.tolist())\n elif len(x.shape) == 2:\n return tuple(tuple(d1) for d1 in x.tolist())\n elif len(x.shape) == 3:\n return tuple(tuple(tuple(d2) for d2 in d1) for d1 in x.tolist())\n elif len(x.shape) == 4:\n return tuple(tuple(tuple(tuple(d3) for d3 in d2) for d2 in d1) for d1 in x.tolist())\n elif len(x.shape) == 5:\n return tuple(tuple(tuple(tuple(tuple(d4) for d4 in d3) for d3 in d2) for d2 in d1) for d1 in x.tolist())\n else:\n return tuple(serialize(z) for z in x.tolist())\n # elif is_numpy_array(x):\n # return x.tostring()\n elif isinstance(x, (tuple, list)):\n return tuple(serialize(z) for z in x)\n elif isinstance(x, set):\n return tuple(sorted(serialize(z)) for z in x)\n elif isinstance(x, dict):\n return tuple(sorted((k, serialize(z)) for k, z in x.items()))\n else:\n raise ValueError(f\"Does not support input type: {type(x)}\")",
"def _write_matrix_data(self, matrix):\n return matrix.newbyteorder('>').tobytes()",
"def mat_to_dict(filepath):\n matrix=open(filepath,\"r\")\n lists=[]\n for line in matrix:\n line=line.rstrip()\n line=line.split()\n lists.append(line)\n dict={}\n for j in range(1,len(lists)):\n for i in range(len(lists[j])-1):\n dict[lists[j][0]+lists[0][i]]=int(lists[j][i+1])\n for i in range(len(lists[0])):\n for j in range(len(lists[0])):\n if lists[0][i]+lists[0][j] not in dict:\n dict[lists[0][i]+lists[0][j]]=dict[lists[0][j]+lists[0][i]]\n matrix.close()\n return dict",
"def _get_matrix(self):\n for row in self.active_sheet.rows:\n row_container = []\n for cell in row:\n row_container.append(cell.value)\n self.matrix.append(tuple(row_container))",
"def _torch_tensor_to_str(torch_tensor):\n return torch_tensor.detach().cpu().numpy().tolist()",
"def matrix_to_dict(matrix: list):\n dictionary: dict = {}\n for row in matrix:\n dictionary[str(row)] = row\n return dictionary",
"def _encode_sparse_matrix(self, data):\n\n # import scipy here to avoid a global import\n import scipy.sparse\n return [\"__sparse__\", data.shape] + \\\n [self._encode_matrix(d) for d in scipy.sparse.find(data)]",
"def _matrix_(self):\n return self.to_matrix()",
"def _flatten_matrix_data(data):\n results = []\n for name, id_labels, matrix in data:\n if len(id_labels) == 1:\n id = id_labels[0]\n results.append((name, id, id, float(matrix)))\n continue\n\n for i in range(0, len(id_labels)):\n for j in range(i, len(id_labels)):\n value = matrix[i][j]\n id1 = id_labels[i]\n id2 = id_labels[j]\n results.append((name, id1, id2, str(value)))\n return results",
"def matrix_to_relations(matrix):\n relations = []\n for row_id, row in enumerate(matrix):\n for col_id, column in enumerate(row):\n if column == 1:\n relations.append((row_id, col_id))\n return relations",
"def mat_to_list(self, mat):\r\n \tif isinstance(mat, (np.matrix, np.ndarray)):\r\n \t\treturn np.asarray(mat).flatten('F').tolist()\r\n \telse:\r\n \t\treturn mat",
"def save_matrix(self, matrix):\n print(\"dumping \")\n path = self._create_path(self.dataset)\n print(path)\n print(matrix.sum())\n np.save(path, matrix)\n print(\"dumped to %s\" % path)",
"def aslistoflist(self):\n class_names = self._keys()\n n = len(class_names)\n\n idx_map = dict()\n for i,k in enumerate(class_names):\n idx_map[k] = i\n\n m = ListOfListMat(n, n)\n\n for actual_class,detected_classes in self.mat.items():\n for detected_class,count in detected_classes.items():\n m[ idx_map[actual_class] ][ idx_map[detected_class] ] = count\n\n return m"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Node label to use when rendering patterns as graphs using dot.
|
def dot_label(self) -> str:
|
[
"def node_label(node):\n return NODE_LABELS[type(node)]",
"def as_dot(self):\r\n node_labels = ''\r\n for (id, node) in self._node_list(0):\r\n node_labels += '{0}[label=\"{1}\"];\\n'.format(id, node)\r\n\r\n (_, tree) = self._as_dot(0)\r\n\r\n return 'graph ast {{\\n{0}\\n{1}\\n}}'.format(node_labels, tree)",
"def create_node_label(mutation: dict) -> str:\n return mutation['path'].name",
"def label(self, graph, node, valid_name):\n return self.depending_library.link_label(graph, node, valid_name)",
"def _ascii_art_node(self, label):\n if label in self._marked_nodes:\n return self.options('marked_node_str')\n return 'O'",
"def __create_label(self, tree_node):\n graph_node_label = '<'\n\n # Add the node state to the label with highlighting if required\n tree_node_str = str(tree_node).replace('\\n', '<br/>')\n if self.highlight_moves and tree_node.parent:\n parent_node_str = str(tree_node.parent).replace('\\n', '<br/>')\n graph_node_label += self.__highlight_differences(\n tree_node_str, parent_node_str)\n else:\n graph_node_label += tree_node_str\n\n # Add scores to the label if required\n if self.node_scores and tree_node.parent:\n score = '{0:.3f}'.format(round(tree_node.score(), 3))\n if self.verbose_score:\n graph_node_label += '<br/><font point-size=\"10\">Wins: {}' \\\n '<br/>Visits: {}<br/>Score: {}'.format(\n float(tree_node.wins), tree_node.visits, score)\n if (hasattr(tree_node, 'ucb1_score') and\n tree_node.ucb1_score is not None):\n ucb1 = '{0:.3f}'.format(round(tree_node.ucb1_score, 3))\n graph_node_label += '<br/>UCB1: {}'.format(ucb1)\n graph_node_label += '</font>'\n else:\n graph_node_label += '<br/>{}'.format(score)\n\n graph_node_label += '>'\n\n return graph_node_label",
"def label():\n return _make_type(_core.LLVMLabelType(), TYPE_LABEL)",
"def _ascii_art_node(self, label):\n if label in self._marked_nodes:\n if (label == self.special_node()\n and self.options('mark_special_node') in ['printing', 'both']):\n return '#'\n return self.options('marked_node_str')\n return 'O'",
"def Dot():\r\n return Leaf(token.DOT, \".\")",
"def render_edge_with_node_label(self, name, edge, edge_settings):\n props_to_display = self.extract_props(edge.settings)\n\n label = '<'\n label += \"|\".join(self.get_label(prop, value) for prop, value in props_to_display.items()) \n label += '>'\n\n edge_node_name = \"{}-{}\".format(name, edge.to)\n\n self.gv_graph.node(edge_node_name, label=label, shape=\"record\")\n\n self.gv_graph.edge(self.get_path_from_name(name), edge_node_name, arrowhead=\"none\", **edge_settings)\n self.gv_graph.edge(edge_node_name, self.get_path_from_name(edge.to), **edge_settings)",
"def label(self, name):\n self.labels[name] = self.node\n return self",
"def _create_label(self, kg: KG, vertex: Vertex, n: int) -> str:\n if len(self._label_map) == 0:\n self._weisfeiler_lehman(kg)\n\n suffix = \"-\".join(\n sorted(\n set(\n [\n self._label_map[neighbor][n - 1]\n for neighbor in kg.get_neighbors(\n vertex, is_reverse=True\n )\n ]\n )\n )\n )\n return f\"{self._label_map[vertex][n - 1]}-{suffix}\"",
"def getLabelName(self):\n\n if self.type == operation.LABEL:\n return self.labelName",
"def get_safe_label(self):\n\n if self.info.get('label') == '/':\n return 'root'\n\n suffix = re.sub(r\"[/ \\(\\)]+\", \"_\", self.info.get('label')) if self.info.get('label') else \"\"\n if suffix and suffix[0] == '_':\n suffix = suffix[1:]\n if len(suffix) > 2 and suffix[-1] == '_':\n suffix = suffix[:-1]\n return suffix",
"def id_for_label(value):\n return f\"labels->{value}\"",
"def label(self):\n if self.tex is None:\n name_tex = r'{\\rm %s}' % text2tex(self.name)\n else:\n name_tex = self.tex\n\n if self.units == ureg.dimensionless:\n units_tex = ''\n else:\n units_tex = r' \\; \\left( {:~L} \\right)'.format(self.units)\n\n return name_tex + units_tex",
"def __str__(self):\n return self.node_name",
"def visit_Label(self, node): # pylint: disable=invalid-name\n if node.name is not None:\n self.ids.add(node.name)\n return node",
"def draw_nodelabels(self, text=None, color=None):\n if text is None:\n textdict = {key: str(key) for key in self.network.nodes()}\n elif isinstance(text, dict):\n textdict = text\n else:\n raise NotImplementedError\n\n colordict = color_to_colordict(color,\n textdict.keys(),\n default=self.settings['color.nodes'],\n colorformat='rgb',\n normalize=False)\n labels = []\n\n for key, text in iter(textdict.items()):\n labels.append({\n 'pos': self.network.node_coordinates(key),\n 'name': \"{}.nodelabel.{}\".format(self.network.name, key),\n 'color': colordict[key],\n 'text': textdict[key]\n })\n\n return compas_ghpython.draw_labels(labels)",
"def convert_to_dot(self, _with_pruning_ratio=False, show_probabilities=True):\n s = 'digraph DT{\\n'\n s += 'node[fontname=\"Arial\"];\\n'\n s += self.convert_node_to_dot(_with_pruning_ratio=_with_pruning_ratio, show_probabilities=show_probabilities)\n s += '}'\n return s"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Compares two predicates and return true if they are equivalent
|
def is_equivalent(self, other: "NodePredicate") -> bool:
|
[
"def __eq__(self, other):\n if len(self.tensors) != len(other.tensors):\n return False\n fermions = tuple(pos for pos, tensor in enumerate(self.tensors)\n if tensor.statistics == fermion)\n for match in match_tensor_lists(self.tensors, other.tensors):\n candidate = [self.tensors[pos] for pos in match]\n matches, free_indices = match_indices(candidate, other.tensors)\n if matches:\n # If there has been an odd permutation of fermions,\n # equality fails\n fermion_reorder = tuple(fermions.index(pos)\n for pos in match if pos in fermions)\n sign = permutations(len(fermions))[fermion_reorder]\n if sign == -1: return False\n\n # Checking that all free indices are equal\n same_free_indices = True\n for i, index in enumerate(free_indices):\n if i != -1 - index:\n same_free_indices = False\n if same_free_indices:\n return True\n return False",
"def test_equivalent(self):\n op1 = And(BoolVar(), PedestriansCrossingRoad())\n op2 = And(PedestriansCrossingRoad(), BoolVar())\n op3 = And(DriversAwaitingGreenLightVar(), BoolVar())\n\n op1.check_equivalence(op2)\n op2.check_equivalence(op1)\n\n assert_raises(AssertionError, op1.check_equivalence, op3)\n assert_raises(AssertionError, op2.check_equivalence, op3)\n assert_raises(AssertionError, op3.check_equivalence, op1)\n assert_raises(AssertionError, op3.check_equivalence, op2)\n\n ok_(op1 == op2)\n ok_(op2 == op1)\n ok_(op1 != op3)\n ok_(op2 != op3)\n ok_(op3 != op1)\n ok_(op3 != op2)",
"def __eq__(self, other):\n return (isinstance(other, self.__class__)\\\n and (self._lhs == other._lhs) \\\n and (self._rhs == other._rhs) \\\n and (self._phi_c == other._phi_c) )",
"def __eq__(self,cat_action_functor):\r\n\r\n return self.cat_functor==cat_action_functor.cat_functor and \\\r\n self.nat_transform==cat_action_functor.nat_transform",
"def _compare_rdf_triples(t1, t2):\n for attr in ['subject', 'predicate', 'object']:\n if(t1[attr]['type'] != t2[attr]['type'] or\n t1[attr]['value'] != t2[attr]['value']):\n return False\n\n if t1['object'].get('language') != t2['object'].get('language'):\n return False\n if t1['object'].get('datatype') != t2['object'].get('datatype'):\n return False\n\n return True",
"def _comparison_helper(\n a: \"BitVecFunc\",\n b: Union[BitVec, int],\n operation: Callable,\n default_value: bool,\n inputs_equal: bool,\n) -> Bool:\n # Is there some hack for gt/lt comparisons?\n if isinstance(b, int):\n b = BitVec(z3.BitVecVal(b, a.size()))\n union = a.annotations.union(b.annotations)\n\n if not a.symbolic and not b.symbolic:\n return Bool(z3.BoolVal(operation(a.value, b.value)), annotations=union)\n\n if (\n not isinstance(b, BitVecFunc)\n or not a.func_name\n or not a.input_\n or not a.func_name == b.func_name\n ):\n return Bool(z3.BoolVal(default_value), annotations=union)\n\n return And(\n Bool(cast(z3.BoolRef, operation(a.raw, b.raw)), annotations=union),\n a.input_ == b.input_ if inputs_equal else a.input_ != b.input_,\n )\n\n return a.input_ == b.input_",
"def __eq__(self, other):\n return self.question == other.question and self.scoring_function == other.scoring_function",
"def pointwise_equal(self, other):\r\n\r\n if self.proper_property_names != other.proper_property_names:\r\n return False\r\n\r\n if self.label != other.label:\r\n return False\r\n\r\n for prop_name in self.proper_property_names:\r\n prop = self.__dict__[prop_name]\r\n other_prop = other.__dict__[prop_name]\r\n # all props are of type Struc or Int, String, or List (but in case of List it is never a list of Strucs)\r\n if isinstance(prop, Struc):\r\n if prop.pointwise_equal(other_prop):\r\n pass\r\n else:\r\n return False\r\n elif type(prop) == list:\r\n if set(prop) != set(other_prop):\r\n return False\r\n else:\r\n if prop != other_prop:\r\n return False\r\n\r\n return True",
"def test_returns_false_if_encapsulated_predicates_are_false(self):\n self.some_left_predicate.return_value = False\n self.some_right_predicate.return_value = False\n self.assertFalse(self.or_predicate(self.get_response_mock, self.request_mock))",
"def eq(a, b):\n a_is_tpl = is_template(a)\n b_is_tpl = is_template(b)\n\n if a_is_tpl and b_is_tpl: False\n if a_is_tpl: a = expand_template(a, b)\n if b_is_tpl: b = expand_template(b, a)\n\n actual = parse(a)\n expected = parse(b)\n\n return match_host(actual, expected) and \\\n match_schema(actual, expected) and \\\n match_path(actual, expected) and \\\n match_querystring(actual, expected)",
"def __eq__(self, other: Transform) -> bool:\n if len(self.transforms) != len(other.transforms):\n return False\n else:\n return all([a == b for a, b in zip(self.transforms, other.transforms)])",
"def compare_multispace(space1: ZfitSpace, space2: ZfitSpace, comparator: Callable):\n axes_not_none = space1.axes is not None and space2.axes is not None\n obs_not_none = space1.obs is not None and space2.obs is not None\n if not (axes_not_none or obs_not_none): # if both are None\n return False\n\n if obs_not_none:\n if set(space1.obs) != set(space2.obs):\n return False\n elif axes_not_none: # axes only matter if there are no obs\n if set(space1.axes) != set(space2.axes):\n return False\n if not space1.binning == space2.binning:\n return False\n # check limits\n if not space1.limits_are_set:\n if not space2.limits_are_set:\n return True\n else:\n return False\n\n elif space1.limits_are_false:\n if space2.limits_are_false:\n return True\n else:\n return False\n\n return compare_limits_multispace(space1, space2, comparator=comparator)",
"def xor( a, b ):\n return bool( a ) != bool( b )",
"def preserves_predicates(self):\n all_props = set(self.prop_regions)\n\n for region in self.regions:\n # Propositions True in Region\n for prop in region.props:\n preimage = self.prop_regions[prop]\n\n if not region <= preimage:\n return False\n\n # Propositions False in Region\n for prop in all_props.difference(region.props):\n preimage = self.prop_regions[prop]\n\n if region.intersect(preimage).volume > pc.polytope.ABS_TOL:\n return False\n return True",
"def __eq__(self, other):\n # If the length differs then we know they will never\n # be the same. We do this before any string comparison\n if len(self.rhs_list) != len(other.rhs_list):\n return False\n\n if self.lhs != other.lhs:\n return False\n\n # Use index to fetch component\n for rhs1, rhs2 in zip(self.rhs_list, other.rhs_list):\n # If there is none inequality then just return\n if rhs1.__eq__(rhs2) is False:\n return False\n\n return True",
"def all_predicates(\n predicates: Iterable[Callable[[Any], bool]]\n) -> Callable[[Any], bool]:\n return lambda entity: all((p(entity) for p in predicates))",
"def some_predicates(\n predicates: Iterable[Callable[[Any], bool]]\n) -> Callable[[Any], bool]:\n\n return lambda entity: any((p(entity) for p in predicates))",
"def test_evaluation_order(self):\n op1 = BoolVar()\n op2 = BoolVar()\n context = {'bool': False}\n And(op1, op2)(context)\n ok_(op1.evaluated)\n assert_false(op2.evaluated)",
"def set_equals(t1: Tensor, t2: Tensor) -> bool:\n t1 = t1.unique(dim=0)\n t2 = t2.unique(dim=0)\n if t1.shape != t2.shape:\n return False\n equals_sum = (t1.unsqueeze(-2) == t2).all(dim=-1).sum(dim=-1)\n return torch.equal(equals_sum, torch.ones_like(equals_sum))",
"def __eq__(self, other: object) -> bool:\n if isinstance(other, PresentationVerificationResult):\n return (\n self.verified == other.verified\n and self.presentation_result == other.presentation_result\n # check credential results list\n and (\n # both not present\n (not self.credential_results and not other.credential_results)\n # both list and matching\n or (\n isinstance(self.credential_results, list)\n and isinstance(other.credential_results, list)\n and all(\n self_result == other_result\n for (self_result, other_result) in zip(\n self.credential_results, other.credential_results\n )\n )\n )\n )\n # check error list\n and (\n # both not present\n (not self.errors and not other.errors)\n # both list and matching\n or (\n isinstance(self.errors, list)\n and isinstance(other.errors, list)\n and all(\n self_error == other_error\n for (self_error, other_error) in zip(\n self.errors, other.errors\n )\n )\n )\n )\n )\n return False"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Determines whether a NodePredicate matches another Node Predicate
|
def matches_predicate(self, predicate_node: "NodePredicate") -> bool:
|
[
"def containsNode(*args, **kwargs):\n \n pass",
"def __eq__(self, other): # overload the == operator\n return isinstance(other, SearchNode) and self.getPriority() == other.getPriority()",
"def isEqualToNode(self, other):\n is_lower = self.nodeName.lower() == other.nodeName.lower()\n same_name = self.namespace == other.namespace\n same_attrs = self.attributes == other.attributes\n is_equal = Node.isEqualToNode(self, other)\n return all([is_lower, same_name, same_attrs, is_equal])",
"def containsNodeExactly(*args, **kwargs):\n \n pass",
"def nodes_equal(node1, node2):\r\n if type(node1) is not type(node2):\r\n return False\r\n if type(node1) == LocalNameTest:\r\n return node1.name == node2.name\r\n return True",
"def _node_match(self, state, pattern, value, flags):\n if '@id' not in value:\n return False\n node_object = state['subjects'][value['@id']]\n return node_object and self._filter_subject(state, node_object, pattern, flags)",
"def match(self, node):\n node = self._resolve_target_node_from_path(node)\n return node and node[self.prop] in self.values",
"def is_congruent(self, t2, node_dict):\n # comparison against self\n if self == t2:\n return True\n # same function name or same literal name\n if self.term.root == t2.term.root:\n if not pred.is_function(self.term.root):\n return True\n\n if len(self.term.arguments) == len(t2.term.arguments):\n for i in range(0, len(self.term.arguments)):\n if TermClass.find(self.term.arguments[i], node_dict) != TermClass.find(self.term.arguments[i], node_dict):\n return False\n return True\n return False",
"def __eq__(self, other):\n if self.nodes == other.nodes:\n return True\n else:\n return False",
"def __and__(self, other: Selector) -> Selector:\n return self.__class__(lambda col: self.predicate(col) and other.predicate(col))",
"def __nodeMatches(node, matchtype, parmlist, basetypematch=False):\n return True",
"def match_node_to_node(self, node, node_other):\n if isinstance(node.item, Group) and isinstance(node_other.item, Group):\n return (self.match_node_to_structure(node, node_other.item, atoms=node_other.item.get_all_labeled_atoms()) and\n self.match_node_to_structure(node_other, node.item, atoms=node.item.get_all_labeled_atoms()))\n elif isinstance(node.item, LogicOr) and isinstance(node_other.item, LogicOr):\n return node.item.match_logic_or(node_other.item)\n else:\n # Assume nonmatching\n return False",
"def __eq__(self,cat_action_functor):\r\n\r\n return self.cat_functor==cat_action_functor.cat_functor and \\\r\n self.nat_transform==cat_action_functor.nat_transform",
"def isa_or_partof(self, ns1, id1, ns2, id2):\n self._isa_counter += 1\n if self.transitive_closure:\n return (self.label(ns1, id1),\n self.label(ns2, id2)) in self.transitive_closure\n return self.isrel(ns1, id1, ns2, id2, rels={'isa', 'partof'})",
"def next_node(match_fn: Callable[[torch.fx.Node], bool]) -> Callable[[torch.fx.Node], bool]:\n\n def fn(node):\n for next_n in node.users.keys():\n if match_fn(next_n):\n return True\n return False\n\n return fn",
"def _compare_rdf_triples(t1, t2):\n for attr in ['subject', 'predicate', 'object']:\n if(t1[attr]['type'] != t2[attr]['type'] or\n t1[attr]['value'] != t2[attr]['value']):\n return False\n\n if t1['object'].get('language') != t2['object'].get('language'):\n return False\n if t1['object'].get('datatype') != t2['object'].get('datatype'):\n return False\n\n return True",
"def match(self, queryDescriptors, trainDescriptors, mask=...) -> matches:\n ...",
"def some_predicates(\n predicates: Iterable[Callable[[Any], bool]]\n) -> Callable[[Any], bool]:\n\n return lambda entity: any((p(entity) for p in predicates))",
"def isEqualToNode(self, other):\n if len(self.childNodes) != len(other.childNodes):\n return False\n\n for a, b in zip(self.childNodes, other.childNodes):\n if not a.isEqualToNode(b):\n return False\n\n return True",
"def __and__(expr):"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Get a single Artwork by its id
|
def artworks_id_get(id): # noqa: E501
return query_manager.get_resource(id=id,
rdf_type_uri=ARTWORK_TYPE_URI,
rdf_type_name=ARTWORK_TYPE_NAME,
kls=Artwork)
|
[
"def get_artikel_by_id(self, id):\n with ArtikelMapper() as mapper:\n return mapper.find_by_id(id)",
"def detail_view(request, id):\n\n # To get object\n #artwork = ArtWork.objects.filter(id=id).first()\n #print(artwork)\n\n # To get query set\n #artwork = ArtWork.objects.filter(id=id)\n #print(artwork)\n\n try:\n artwork = ArtWork.objects.filter(id=id).first().post.all()\n except Exception as identifier:\n return render(request, 'uploadartwork/404.html') \n \n return render(request, 'uploadartwork/detail_view.html', {'artwork':artwork} )",
"def retrieve_artist_from_id(artist_id):\n logging.info('Retrieving %s', artist_id)\n\n url = BASE_URL_MYAPIFILMS + 'imdb?idName=' + artist_id + '&format=JSON&filmography=0&lang=en-us&bornDied=0&starSign=0&uniqueName=0&actorActress=0&actorTrivia=0&actorPhotos=N&actorVideos=N&salary=0&spouses=0&tradeMark=0&personalQuotes=0&token=307cccfe-d20b-4b69-b976-d6a024538864'\n json_page = get(url).encode('utf-8')\n json_data = json.loads(json_page)\n\n artist = Artist(id=json_data[\"idIMDB\"],\n name=json_data[\"name\"],\n photo=clear_url(json_data[\"urlPhoto\"]) if ('urlPhoto' in json_data and json_data['urlPhoto'] != \"\") else None)\n\n return artist.put()",
"def edit_view(request,id):\n\n artwork = ArtWork.objects.filter(id=id).first()\n if not artwork:\n return render(request, 'uploadartwork/404.html') \n return render(request, 'uploadartwork/edit_view.html', {'artwork':artwork} )",
"def get_example(self, id):\n return self.examples.get(id, None)",
"def get_artist_via_id(self, request, artist_id):\n result = ArtistDetail.call(artist_id=artist_id)\n\n if result.failed:\n return Response(errors=dict(errors=result.error.value), status=status.HTTP_400_BAD_REQUEST)\n\n return Response(data=result.value, status=status.HTTP_200_OK)",
"def __getitem__(self, media_id):\n for media in self:\n if media.id == media_id:\n return media\n\n raise KeyError('No media with id {}'.format(media_id))",
"def getById (id):\r\n if id in thingsById:\r\n return thingsById[id]\r\n else:\r\n return None",
"def get_artist(id_artist: int) -> dict:\n sql_request = sql_request_artist(id_artist)\n sql_data = get_data_from_db(sql_request)\n artist = create_artist(sql_data)\n return artist",
"def artist(self, artist_id):\n\n trid = self._get_id(\"artist\", artist_id)\n return self._get(\"artists/\" + trid)",
"def get_artist(self, artist_id):\n response = self.__get_data(self.url.artists_url().format(id=str(artist_id)))\n return Artist(artist_id=artist_id, name=response['name'], popularity=response['popularity'],\n genres=response['genres'])",
"def getById(self, id):\n for item in self.list: \n if item.getId() == id:\n return item",
"def get_object_by_id(self,id):\n return self.objects[id]",
"def get_movie(id):\n return get_object_or_404(Movie, id=id)",
"def get_sg_artist(artist_id):\n\n params = {'client_id': CLIENT_ID,\n 'client_secret': CLIENT_SECRET,\n 'id': artist_id}\n\n response = requests.get(SG_URL + 'performers', params=params)\n\n return response.json()",
"def get_entry_from_id(self, id: int):\n for e in self.container:\n if e.id == id:\n return e",
"def get_recipe_by_id(recipe_id):\n\n \"\"\"IN USE\"\"\"\n\n return Recipe.query.get(recipe_id)",
"def fetchArtistId(name):\n url = \"https://api.spotify.com/v1/search?q=\"+ name +\"&type=artist\" \n req = grequests.get(url)\n result_list = grequests.map([req])\n if not result_list[0].ok:\n print \"Error\"\n info = result_list[0].json()\n ID = info['artists']['items'][0]['id']\n return(ID)",
"def get_photo_by_id(photo_id):\n photo = Gallery.query. \\\n filter_by(id=photo_id). \\\n first_or_404()\n\n return photo"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Calculate the dark current based off the dark data It takes the filename of Light data and searches for the mathing integration time in the dark data directory, finds the required dark data, subtracts off the offset and smear and computes the dark current
|
def calculate_dark_current(image, temp, i, int_time):
dark_data_dir = r'F:\TEMPO\Data\GroundTest\FPS\FPA_Gain_vs_Temp'
tem_file = temp +r'_PT_Dark\Script_Data\saved_quads'
data_file = os.path.join(dark_data_dir, tem_file)
data_path_name_split = image.split('_')
all_int_files = [each for each in os.listdir(data_file) \
if each.endswith('_'+data_path_name_split[-1])]
#print(all_int_files)
dark_data_file = os.path.join(data_file, all_int_files[0])
IDL_variable = readsav(dark_data_file)
all_full_frame = IDL_variable.q
quad = all_full_frame[:, i, :, :]
active_quad = np.mean(quad[:, 4:1028, 10:1034], axis=0)
tsoc = np.mean(quad[:, 4:1028, 1034:1056], axis=0)
dark_current_quad = perform_bias_subtraction_ave(active_quad, tsoc)
return dark_current_quad
|
[
"def getdarkcurrent(self):\n darkrate = 0.005 # electrons/s\n \n try:\n darkcurrent = self.header['DARKTIME'] * darkrate\n \n except:\n str = \"#############################################\\n\"\n str += \"# #\\n\"\n str += \"# Error: #\\n\"\n str += \"# Cannot find the value for 'DARKTIME' #\\n\"\n str += \"# in the image header. WFPC2 input #\\n\"\n str += \"# images are expected to have this header #\\n\"\n str += \"# keyword. #\\n\"\n str += \"# #\\n\"\n str += \"# Error occured in the WFPC2InputImage class#\\n\"\n str += \"# #\\n\"\n str += \"#############################################\\n\"\n raise ValueError, str\n \n \n return darkcurrent",
"def dark_current(self,im):\n\n dark_current = wfirst.dark_current*wfirst.exptime\n dark_noise = galsim.DeviateNoise(galsim.PoissonDeviate(self.rng, dark_current))\n im.addNoise(dark_noise)\n\n # NOTE: Sky level and dark current might appear like a constant background that can be\n # simply subtracted. However, these contribute to the shot noise and matter for the\n # non-linear effects that follow. Hence, these must be included at this stage of the\n # image generation process. We subtract these backgrounds in the end.\n\n # self.logger.debug('Applied nonlinearity to image')\n return im",
"def get_master_dark(exptime, infiles=None, name_template=\"*Dark[0-9]*\", calib_folder=\"\"):\n test_presence = glob(\"{0:s}master_dark_{1:d}s.fits\".format(calib_folder,int(exptime)))\n if (len(test_presence)>=1.) and (infiles is None):\n with fits.open(test_presence[0]) as f:\n master_dark_data = f[0].data\n else:\n if infiles is None:\n infiles = []\n for file in glob(\"{0:s}{1:s}\".format(calib_folder, name_template)):\n infiles.append(file[len(calib_folder):])\n data_array, headers = proj_fits.get_obs_data(infiles, data_folder=calib_folder, compute_flux=False)\n dark_exp = np.array([header['exptime'] for header in headers])\n mask = (dark_exp == float(exptime))\n if not(float(exptime) in np.unique(dark_exp)):\n master_dark_data = interpolate_dark(exptime, calib_folder=calib_folder)\n else:\n master_dark_data = np.median(data_array[mask],axis=0)\n\n # Save to fits for next time\n master_dark_header = headers[np.argmax(mask)].copy()\n master_dark_header.remove('OBJECT')\n master_dark_header['CCD-TEMP'] = np.mean([hdr['CCD-TEMP'] for hdr in headers])\n master_dark_header['EXPTIME'] = exptime\n master_dark_header['IMAGETYP'] = \"Master Dark\"\n master_dark_header.add_history(\"Cal Master Dark {0:d}s, {1:d} inputs\".format(int(exptime), data_array[mask].shape[0]))\n hdu = fits.PrimaryHDU(data=master_dark_data, header=master_dark_header)\n hdul = fits.HDUList([hdu])\n hdul.writeto(\"{0:s}master_dark_{1:d}s.fits\".format(calib_folder,int(exptime)))\n\n return master_dark_data",
"def is_light():\n # load in data directory to avoid redownloading\n loader = Loader('~/skyfield_data')\n ts = loader.timescale()\n e = loader('de421.bsp')\n\n # set current location (melbourne does not appear in the default list)\n melbourne = api.Topos('37.951910 S', '145.152080 E')\n # get current time in UTC format\n now = datetime.datetime.utcnow()\n now = now.replace(tzinfo=utc)\n # set the interval for now and 24 hours from now\n t0 = ts.utc(now)\n t1 = ts.utc(now + timedelta(hours=24))\n\n # find the times and types of event (sunrise/sunset)\n t, y = almanac.find_discrete(t0, t1, almanac.sunrise_sunset(e, melbourne))\n\n #y[0] = True for sunrise (which means it is currently dark)\n\n light = not y[0]\n\n return light",
"def getdarkcurrent(self,extver):\n darkcurrent=0.\n try:\n darkcurrent = self._image[self.scienceExt,extver].header['MEANDARK']\n except:\n str = \"#############################################\\n\"\n str += \"# #\\n\"\n str += \"# Error: #\\n\"\n str += \"# Cannot find the value for 'MEANDARK' #\\n\"\n str += \"# in the image header. ACS input images #\\n\"\n str += \"# are expected to have this header #\\n\"\n str += \"# keyword. #\\n\"\n str += \"# #\\n\"\n str += \"# Error occured in the ACSInputImage class #\\n\"\n str += \"# #\\n\"\n str += \"#############################################\\n\"\n raise ValueError(str)\n\n return darkcurrent",
"def _calculate_light(self, outside_illumination):\n\n for data in self.inside_sensors.values():\n outside_light = (outside_illumination * self.house_light_factor) \\\n * (1 - self.devices_settings['curtains_lvl'])\n\n inside_light = self.devices_settings['light_lvl'] \\\n * self.max_led_illumination\n\n final_light = (outside_light + inside_light) \\\n / self.max_led_illumination\n\n data['light'] = truncate(final_light)",
"def load_master_dark():\n\n par = common.pc_params()\n\n fname = os.path.join(os.environ[par['meta_env_var']],\n par['master_dark_filename'])\n\n assert(os.path.exists(fname))\n\n print('READING MASTER DARK: ' + fname)\n dark = fits.getdata(fname)\n\n return dark",
"def light_distance(self): #may have different lantern with different light functions for different gameplay\n oil_ratio = float(self.oil_meter[0])/(self.oil_meter[1])\n if oil_ratio <= 0:\n return 0\n distance = int(oil_ratio*self.light_multiplier)\n if self.flicker_index < FLICKER_CONSTANT/2:\n prev_ratio = float(self.oil_meter[0] + 1)/(self.oil_meter[1])\n prev_distance = int(prev_ratio*self.light_multiplier)\n if prev_distance != distance:\n self.flicker_index = FLICKER_CONSTANT/2\n else: \n distance -= 1 \n return distance + 1",
"def load_darks_and_flats(self, _date, _mode, _filt, image_size_x=1024):\n try:\n _path_calib = os.path.join(self.config['path_archive', _date, 'calib'])\n if image_size_x == 256:\n dark_image = os.path.join(_path_calib, 'dark_{:s}4.fits'.format(str(_mode)))\n else:\n dark_image = os.path.join(_path_calib, 'dark_{:s}.fits'.format(str(_mode)))\n flat_image = os.path.join(_path_calib, 'flat_{:s}.fits'.format(_filt))\n\n if not os.path.exists(dark_image) or not os.path.exists(flat_image):\n return None, None\n else:\n with fits.open(dark_image) as dark, fits.open(flat_image) as flat:\n # replace NaNs if necessary\n if image_size_x == 256:\n return np.nan_to_num(dark[0].data), np.nan_to_num(flat[0].data[384:640, 384:640])\n else:\n return np.nan_to_num(dark[0].data), np.nan_to_num(flat[0].data)\n except RuntimeError:\n # Failed? Make sure to mark calib.done in DB as False!\n self.db['coll_aux'].update_one(\n {'_id': _date},\n {\n '$set': {\n 'calib.done': False,\n 'calib.raw.flat': [],\n 'calib.raw.dark': [],\n 'calib.last_modified': utc_now()\n }\n }\n )",
"def interpolate_dark(exptime, infiles=None, name_template=\"*Dark[0-9]*\", calib_folder=\"\"):\n if infiles is None:\n infiles = []\n for file in glob(\"{0:s}{1:s}\".format(calib_folder, name_template)) \\\n + glob(\"{0:s}{1:s}\".format(calib_folder, \"master_dark_[0-9]*\")):\n infiles.append(file[len(calib_folder):])\n data_array, headers = proj_fits.get_obs_data(infiles, data_folder=calib_folder, compute_flux=False)\n\n dark_exp = np.unique(np.array([header['exptime'] for header in headers]))\n dark = np.zeros((len(dark_exp), data_array.shape[1], data_array.shape[2]))\n for i,time in enumerate(dark_exp):\n mask = np.array([head['exptime']==time for head in headers])\n dark[i] = np.median(data_array[mask], axis=0)\n\n master_dark_data = np.zeros(dark.shape[1:])\n for r in range(dark.shape[1]):\n for c in range(dark.shape[2]):\n f = interp1d(dark_exp, dark[:,r,c], kind='cubic', fill_value='extrapolate')\n master_dark_data[r,c] = f(exptime)\n\n return master_dark_data",
"def calc_radiance_ground_diffuse(self):\n\n # Check how many periods have to be considered in negativ direction\n lower_bound = 0\n while True:\n cos_B_x = self.calc_sin_B_i(lower_bound, self.x_g_array)\n cos_D_x = self.calc_sin_D_i(lower_bound - 1, self.x_g_array)\n\n # check if sky is visible for any point between B_x and D_x-1\n if all(cos_B_x < cos_D_x):\n break\n lower_bound = lower_bound - 1\n\n # Check how many periods have to be considered in positive direction\n upper_bond = 0\n while True:\n B0 = self.calc_sin_B_i(upper_bond, self.x_g_array)\n B1 = self.calc_sin_B_i(upper_bond + 1, self.x_g_array)\n D0 = self.calc_sin_D_i(upper_bond, self.x_g_array)\n D1 = self.calc_sin_D_i(upper_bond + 1, self.x_g_array)\n # check if sky is visible between module x and x+1\n if all(np.maximum(B0, D0) > np.minimum(B1, D1)):\n break\n upper_bond = upper_bond + 1\n\n sin_eta_arr = self.calc_sin_B_i(\n np.arange(lower_bound, upper_bond + 1), self.x_g_array\n )\n sin_zeta_arr = self.calc_sin_D_i(\n np.arange(lower_bound, upper_bond + 1), self.x_g_array\n )\n\n arr_eta_zeta = np.stack([sin_eta_arr, sin_zeta_arr])\n # sort such that smallest sin is always first in array\n arr_eta_zeta.sort(axis=0)\n\n # substract lower angle of ith row from higher angle of i+1 'th row\n sky_view_factors = np.roll(arr_eta_zeta[0], -1, axis=0) - arr_eta_zeta[1]\n # set negative sky_view_factors to zero\n sky_view_factors[sky_view_factors < 0] = 0\n # sum over all \"windows\" between module rows\n illum_array = sky_view_factors.sum(axis=0) / 2\n\n irradiance_ground_diffuse_received = illum_array\n\n # division by pi converts irradiance into radiance assuming Lambertian scattering\n self.results[\"radiance_ground_diffuse_emitted\"] = irradiance_ground_diffuse_received / np.pi",
"def get_masterdark(anneal_date, paths, ctecorr, mode):\n\n if mode == 'dev':\n masterdark = glob.glob(os.path.join(paths['masterdark_create_dir'], 'masterdark_*.fits'))[0]\n\n elif mode == 'prod':\n\n # Get list of masterdarks in the masterdarks directory\n if ctecorr:\n masterdarks = glob.glob(os.path.join(paths['masterdark_pool'], 'masterdark_*_ctecorr.fits'))\n else:\n masterdarks = glob.glob(os.path.join(paths['masterdark_pool'], 'masterdark_????-??-??.fits'))\n\n # Insert dummy current masterdark\n if ctecorr:\n current_masterdark = 'masterdark_{}_ctecorr'.format(anneal_date)\n else:\n current_masterdark = 'masterdark_{}'.format(anneal_date)\n current_masterdark = os.path.join(paths['masterdark_pool'], current_masterdark)\n masterdarks.append(current_masterdark)\n\n # Sort the masterdarks\n masterdarks = sorted(masterdarks)\n\n # Get index of current masterdark\n current_masterdark_index = masterdarks.index(current_masterdark)\n\n # Determine previous anneal masterdark\n masterdark = masterdarks[current_masterdark_index - 1]\n\n return masterdark",
"def surface_reflectance(meta_path, toa_folder, dem_path, dew_point, outdir = False, kt = 1.0):\n\n meta_path = os.path.abspath(meta_path)\n toa_folder = os.path.abspath(toa_folder)\n dem_path = os.path.abspath(dem_path)\n output_filelist = []\n\n #define the list of constants for effective narrowband transmissivity for incoming solar radiation\n constants_enbt1 = [[0.987, -0.00071, 0.000036, 0.0880, 0.0789],\n [2.319, -0.00016, 0.000105, 0.0437, -1.2697],\n [0.951, -0.00033, 0.000280, 0.0875, 0.1014],\n [0.375, -0.00048, 0.005018, 0.1355, 0.6621],\n [0.234, -0.00101, 0.004336, 0.0560, 0.7757],\n [0.365, -0.00097, 0.004296, 0.0155, 0.6390]]\n\n #define the list of constants for effective narrowband transmissivity for shortwave radiation\n #reflected from the surface\n constants_enbt2 = [[0.987, -0.00071, 0.000036, 0.0880, 0.0789],\n [2.319, -0.00016, 0.000105, 0.0437, -1.2697],\n [0.951, -0.00033, 0.000280, 0.0875, 0.1014],\n [0.375, -0.00048, 0.005018, 0.1355, 0.6621],\n [0.234, -0.00101, 0.004336, 0.0560, 0.7757],\n [0.365, -0.00097, 0.004296, 0.0155, 0.6390]]\n\n #enforce the list of band numbers, grab metadata from the MTL file, and define the band numbers needed from each sensor\n meta = landsat_metadata(meta_path)\n OLI_bands = ['2','3','4','5','6','7']\n TM_ETM_bands = ['1','2','3','4','5','7']\n\n #define the tile name for the landsat scene based on the metadata file's name\n\n #Open the metadata text file and read to set the scene's tilename\n f = open(meta_path)\n MText = f.read()\n\n if \"PRODUCT_CREATION_TIME\" in MText:\n tilename = getattr(meta, \"BAND1_FILE_NAME\")\n else:\n tilename = getattr(meta, \"LANDSAT_SCENE_ID\")\n\n #construct the list of TOA reflectance band tiffs and populate it based on the above definitions\n toa_list = []\n out_list = []\n n = 0\n for file in os.listdir(toa_folder):\n if (\"TOA_Ref\" in file) and (file[-4:] == \".tif\" or file[-4:] == \".TIF\"):\n if \"LC8\" in meta_path:\n tile = \"{0}_B{1}\".format(tilename, OLI_bands[n])\n if tile in file:\n path = \"{0}\\\\{1}\".format(toa_folder, file)\n out_file = file.replace(\"TOA\", \"Surf\")\n toa_list.append(path)\n out_list.append(out_file)\n n = n + 1\n if n > 5:\n break\n elif (\"LE7\" in file) or (\"LT5\" in file) or (\"LT4\" in file):\n tile = \"{0}_B{1}\".format(tilename, TM_ETM_bands[n])\n if tile in file:\n path = \"{0}\\\\{1}\".format(toa_folder, file)\n out_file = file.replace(\"TOA\", \"Surf\")\n toa_list.append(path)\n out_list.append(out_file)\n n = n + 1\n if n > 5:\n break\n\n #grab the corner lat/lon coordinates to calculate the approximate scene center lat/lon\n ul_lat = getattr(meta, \"CORNER_UL_LAT_PRODUCT\")\n ul_lon = getattr(meta, \"CORNER_UL_LON_PRODUCT\")\n ur_lat = getattr(meta, \"CORNER_UR_LAT_PRODUCT\")\n ur_lon = getattr(meta, \"CORNER_UR_LON_PRODUCT\")\n ll_lat = getattr(meta, \"CORNER_LL_LAT_PRODUCT\")\n ll_lon = getattr(meta, \"CORNER_LL_LON_PRODUCT\")\n lr_lat = getattr(meta, \"CORNER_LR_LAT_PRODUCT\")\n lr_lon = getattr(meta, \"CORNER_LR_LON_PRODUCT\")\n\n u_lon_avg = np.mean([ul_lon, ur_lon])\n l_lon_avg = np.mean([ll_lon, lr_lon])\n l_lat_avg = np.mean([ul_lat, ll_lat])\n r_lat_avg = np.mean([ur_lat, lr_lat])\n\n center_lat = np.mean([l_lat_avg, r_lat_avg])\n center_lon = np.mean([u_lon_avg, l_lon_avg])\n\n #construct the datetime object from the date acquired and scene center time attributes\n date = getattr(meta, \"DATE_ACQUIRED\")\n dl = date.split(\"-\")\n time = getattr(meta, \"SCENE_CENTER_TIME\")\n tl = time.split(\":\")\n\n dt = datetime.datetime(int(dl[0]), int(dl[1]), int(dl[2]), int(tl[0]), int(tl[1]), int(tl[2][0:2]))\n\n #use the dnppy.solar module to calculate the solar characteristics at the scene center at the time of acquisition\n sc = solar.solar(center_lat, center_lon, dt, 0)\n sc.compute_all()\n\n #Cosine of Solar Zenith over horizontal surface\n declination = math.degrees(sc.get_declination())\n hour_angle = math.degrees(sc.get_hour_angle())\n lat = math.degrees(center_lat)\n\n cth = (math.sin(declination) * math.sin(lat)) + (math.cos(declination) * math.cos(center_lat) * math.cos(hour_angle))\n\n #Saturation Vapor Pressure\n svp = 0.6108 * math.exp((17.27 * dew_point) / (dew_point + 237.3))\n\n #Atmospheric Pressure\n DEM = arcpy.sa.Raster(dem_path)\n ap = 101.3 * ((( 293 - (0.0065 * DEM))/ 293) ** 5.26)\n\n #Water in Atmosphere\n wia = (0.14 * svp * ap) + 2.1\n\n #Effective Narrowband Transmittance for incoming solar radiation\n entisr_bands = []\n for i in xrange(6):\n c1 = constants_enbt1[i][0]\n c2 = constants_enbt1[i][1]\n c3 = constants_enbt1[i][2]\n c4 = constants_enbt1[i][3]\n c5 = constants_enbt1[i][4]\n enbt1 = c1 * ((arcpy.sa.Exp((c2 * ap)/(kt * cth))) - (((c3 * wia) + c4)/cth)) + c5\n entisr_bands.append(enbt1)\n\n #Effective Narrowband Transmittance for shortwave radiation reflected from surface\n entsrrs_bands = []\n\n #cos_n always 1 for sensor pointing straight nadir\n cos_n = 1\n\n for i in xrange(6):\n c1 = constants_enbt2[i][0]\n c2 = constants_enbt2[i][1]\n c3 = constants_enbt2[i][2]\n c4 = constants_enbt2[i][3]\n c5 = constants_enbt2[i][4]\n enbt2 = c1 * ((arcpy.sa.Exp((c2 * ap)/(kt * cos_n))) - (((c3 * wia) + c4))) + c5\n entsrrs_bands.append(enbt2)\n\n #Per Band Path Reflectance\n pr_bands = []\n pr_constants = [0.254, 0.149, 0.147, 0.311, 0.103, 0.036]\n for j in xrange(6):\n pr = pr_constants[j] * (1 - entisr_bands[j])\n pr_bands.append(pr)\n\n #Calculate and save At-Surface Reflectance band tiffs\n for k in xrange(6):\n if outdir:\n outdir = os.path.abspath(outdir)\n asr_path = \"{0}\\\\{1}\".format(outdir, out_list[k])\n else:\n asr_path = \"{0}\\\\{1}\".format(toa_folder, out_list[k])\n refl_surf = (toa_list[k] - pr_bands[k])/(entisr_bands[k] * entsrrs_bands[k])\n refl_surf.save(asr_path)\n output_filelist.append(asr_path)\n\n return output_filelist",
"def get_light_curves():\n \n # Make sure the required files are downloaded\n if 'Duration.dat' not in os.listdir('summary'):\n get_summary_files()\n if 'duration_data.dat' not in os.listdir('DataFrames'):\n duration_data_to_df()\n if 'LightCurves' not in os.listdir():\n os.mkdir(\"LightCurves\")\n\n trig_ids = pd.read_pickle(\"DataFrames/duration_data.dat\").loc[:, 'Trig_id']\n downloaded = map(lambda s: s[: -7], os.listdir(\"LightCurves\")) # Ret lige i den her\n\n operations = {'Downloaded' : [], 'Eroor': [], 'Existed':[]}\n \n\n while len(trig_ids) > 0:\n get = trig_ids.pop(0)",
"def read_lidar(path_to_file):\r\n # open file\r\n data = open(path_to_file,'r').readlines()\r\n \r\n # first line is metadata - extract metadata for every timestep\r\n meta_data = data[::32]\r\n lidar_data={}\r\n length=len(data[::32])\r\n \r\n # initiate windvectors\r\n windspeed = np.zeros([length, 90])\r\n winddirection = np.zeros([length, 90])\r\n height = np.zeros([length, 90])\r\n vertical_windspeed = np.zeros([length,90])\r\n \r\n # prepare data for extraction\r\n #the three first characters of every line contain the variable name and thus need to \r\n #be stored as dict variables and removed for further processing\r\n for i in range(1,32):\r\n lidar_data[data[i][0:3]]=data[i::32][:]\r\n for j in range(0,len(lidar_data[data[i][0:3]])):\r\n lidar_data[data[i][0:3]][j]=lidar_data[data[i][0:3]][j][3:]\r\n \r\n #extract windinformation. every value has len=6\r\n for i in range(0,len(lidar_data['H '])):\r\n for j in range(0,90):\r\n try:\r\n windspeed[i,j] = float(str(lidar_data['V '][i])[j*6:j*6+6])\r\n except:\r\n windspeed[i,j] = np.nan\r\n try:\r\n winddirection[i,j] = float(str(lidar_data['D '][i])[j*6:j*6+6])\r\n except:\r\n winddirection[i,j] = np.nan\r\n try:\r\n height[i,j] = float(str(lidar_data['H '][i])[j*6:j*6+6])\r\n except:\r\n height[i,j] = np.nan\r\n try:\r\n vertical_windspeed[i,j] = float(str(lidar_data['VVW'][i])[j*6:j*6+6])\r\n except:\r\n vertical_windspeed[i,j] = np.nan\r\n \r\n # calculate hight\r\n height = height * 18 -9\r\n \r\n #time extraction + correction. time is converted from datetime_obj to float \r\n #with matplotlib.dates.date2num\r\n time=np.zeros(len(meta_data))\r\n for i in range(0,len(meta_data)):\r\n time[i] = np.int(meta_data[i][4:16])\r\n time[i] = date2num(datetime.datetime(int('20'+str(time[i])[0:2]),int(str(time[i])[2:4]),\r\n int(str(time[i])[4:6]),int(str(time[i])[6:8]),int(str(time[i])[8:10]),\r\n int(str(time[i])[10:12])) + datetime.timedelta(hours=2))\r\n \r\n data = [time,height,winddirection,windspeed,vertical_windspeed]\r\n \r\n return data",
"def make_master_dark(self):\n self.status_bar.config(text = \"Making master dark frame, please wait...\")\n \n dark_dir = tkFileDialog.askdirectory(initialdir = self.dir_path, parent = self.parent, mustexist = False, title = \"Open the directory with dark frames, then click OK\")\n if dark_dir == '': \n self.status_bar.config(text = \"Master dark frame making aborted!\")\n return 0\n dark_file = tkFileDialog.asksaveasfilename(initialdir = dark_dir, parent = self.parent, title = \"Choose the master dark file name\", initialfile = \"dark.bmp\", defaultextension = \".bmp\", filetypes = [('BMP files', '.bmp')])\n if dark_file == '': \n self.status_bar.config(text = \"Master dark frame making aborted!\")\n return 0\n dark_dir = dark_dir.replace(\"/\", os.sep)\n dark_file = dark_file.replace(\"/\", os.sep)\n\n if (dark_file != '') and (dark_dir!=''):\n if make_flat_frame(dark_dir, dark_file, col_corrected = False, dark_frame = False) == False:\n tkMessageBox.showerror(\"Master dark frame\", \"The folder is empty!\")\n self.status_bar.config(text = \"Master dark frame failed!\")\n return 0\n else:\n self.status_bar.config(text = \"Files for master dark not chosen!\")\n\n self.status_bar.config(text = \"Master dark frame done!\")\n tkMessageBox.showinfo(\"Master dark frame\", \"Master dark frame done!\")",
"def get_central_batt_tariff(self,date_time):\n \"\"\"Input in UI\"\"\"\n return self.central_battery_importing_ls_energy",
"def open_dark_path(self):\n temp_dark = tkFileDialog.askopenfilename(initialdir = self.dir_path, parent = self.parent, title = \"Choose dark frame file\", initialfile = \"dark.bmp\", defaultextension = \".bmp\", filetypes = [('BMP files', '.bmp')])\n temp_dark = temp_dark.replace('/', os.sep)\n if temp_dark != '':\n self.dark_name.set(temp_dark)",
"def _get_delta(self, itg_image):\n # Initialize delta\n delta = 0\n\n # compute delta\n if self.type == 'type-2-y':\n\n white_sum = ii.integrate(itg_image,\n self.top_left,\n (self.top_left[0] + self.width, int(self.top_left[1] + self.height / 2)))\n\n black_sum = ii.integrate(itg_image,\n (self.top_left[0], int(\n self.top_left[1] + self.height / 2)),\n self.bottom_right)\n\n delta = black_sum - white_sum\n\n elif self.type == 'type-2-x':\n black_sum = ii.integrate(itg_image,\n self.top_left,\n (int(self.top_left[0] + self.width / 2), self.top_left[1] + self.height))\n\n white_sum = ii.integrate(itg_image,\n (int(\n self.top_left[0] + self.width / 2), self.top_left[1]),\n self.bottom_right)\n\n delta = black_sum - white_sum\n\n elif self.type == 'type-3-y':\n black_sum = ii.integrate(itg_image,\n self.top_left,\n (self.bottom_right[0], int(self.top_left[1] + self.height / 3)))\n\n white_sum = ii.integrate(itg_image,\n (self.top_left[0], int(\n self.top_left[1] + self.height / 3)),\n (self.bottom_right[0], int(self.top_left[1] + 2 * self.height / 3))) + ii.integrate(itg_image,\n (self.top_left[0], int(\n self.top_left[1] + 2 * self.height / 3)),\n self.bottom_right)\n\n delta = black_sum - white_sum\n\n elif self.type == 'type-3-x':\n\n black_sum = ii.integrate(itg_image,\n self.top_left,\n (int(self.top_left[0] + self.width / 3), self.top_left[1] + self.height))\n\n white_sum = ii.integrate(itg_image,\n (int(\n self.top_left[0] + self.width / 3), self.top_left[1]),\n (int(self.top_left[0] + 2 * self.width / 3), self.top_left[1] + self.height)) + ii.integrate(itg_image,\n (int(\n self.top_left[0] + 2 * self.width / 3), self.top_left[1]),\n self.bottom_right)\n\n delta = black_sum - white_sum\n\n elif self.type == 'type-4':\n # top left area\n first = ii.integrate(itg_image,\n self.top_left,\n (int(self.top_left[0] + self.width / 2), int(self.top_left[1] + self.height / 2)))\n\n # top right area\n second = ii.integrate(itg_image,\n (int(\n self.top_left[0] + self.width / 2), self.top_left[1]),\n (self.bottom_right[0], int(self.top_left[1] + self.height / 2)))\n\n # bottom left area\n third = ii.integrate(itg_image,\n (self.top_left[0], int(\n self.top_left[1] + self.height / 2)),\n (int(self.top_left[0] + self.width / 2), self.bottom_right[1]))\n\n # bottom right area\n fourth = ii.integrate(itg_image,\n (int(self.top_left[0] + self.width / 2),\n int(self.top_left[1] + self.height / 2)),\n self.bottom_right)\n\n delta = second + third - (first + fourth)\n\n return delta"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
the underlying assumption in smear subtraction is that the dark current in the storage region is really small and hence neglected from the analysis. typically, Csmear = tFT / (ti+ tFT) (AVG[C(w)] DCStor tRO tft = 8ms
|
def perform_smear_subtraction(active_quad, int_time):
frame_transfer = 8.333
smear_factor = (frame_transfer / (int_time+ frame_transfer))* np.mean(active_quad, axis=0)
#print(active_quad.shape)
#print(smear_factor.shape)
smear_subtracted_quad = active_quad - smear_factor[None, :]
return smear_subtracted_quad
|
[
"def calculate_shear(self,B31c = 0):\n logger.debug('Calculating magnetic shear...')\n \n # Shorthand introduced: we also have to ransform to 1/B**2 expansion parameters, taking into account the \n # difference in the definition of the radial coordinate. In the work of Rodriguez et al.,\n # Phys. Plasmas, (2021), epsilon=sqrt(psi) while in the work of Landreman et al.,\n # J. Plasma Physics (2019) it is defined r=\\sqrt(2*psi/B0). Need to transform between the\n # two.\n\n eps_scale = np.sqrt(2/self.B0) \n\n # sign_psi = self.spsi\n # sign_G = self.sG # Sign is taken to be positive for simplicity. To include this, need to track expressions\n d_d_varphi = self.d_d_varphi\n G2 = self.G2*eps_scale**2\n G0 = self.G0\n I2 = self.I2*eps_scale**2\n X1c = self.X1c*eps_scale\n Y1c = self.Y1c*eps_scale\n Y1s = self.Y1s*eps_scale\n X20 = self.X20*eps_scale**2\n X2s = self.X2s*eps_scale**2\n X2c = self.X2c*eps_scale**2\n Y20 = self.Y20*eps_scale**2\n Y2s = self.Y2s*eps_scale**2\n Y2c = self.Y2c*eps_scale**2\n Z20 = self.Z20*eps_scale**2\n Z2s = self.Z2s*eps_scale**2\n Z2c = self.Z2c*eps_scale**2\n torsion = -self.torsion # I use opposite sign for the torsion\n curvature = self.curvature\n iota = self.iotaN\n dldp = self.abs_G0_over_B0\n dXc1v = self.d_X1c_d_varphi*eps_scale\n dY1cdp = self.d_Y1c_d_varphi*eps_scale\n dY1sdp = self.d_Y1s_d_varphi*eps_scale\n dZ20dp = self.d_Z20_d_varphi*eps_scale**2\n dZ2cdp = self.d_Z2c_d_varphi*eps_scale**2\n dZ2sdp = self.d_Z2s_d_varphi*eps_scale**2\n dX20dp = self.d_X20_d_varphi*eps_scale**2\n dX2cdp = self.d_X2c_d_varphi*eps_scale**2\n dX2sdp = self.d_X2s_d_varphi*eps_scale**2\n dY20dp = self.d_Y20_d_varphi*eps_scale**2\n dY2cdp = self.d_Y2c_d_varphi*eps_scale**2\n dY2sdp = self.d_Y2s_d_varphi*eps_scale**2\n # Transformation to 1/B**2 parameters \n B0 = 1/self.B0**2\n Ba0 = G0\n Ba1 = G2 + self.iotaN*I2\n eta = self.etabar*np.sqrt(2)*B0**0.25\n B1c = -2*B0*eta\n B20 = (0.75*self.etabar**2/np.sqrt(B0) - self.B20)*4*B0**2\n B31s = 0 # To preserve stellarator symmetry\n I4 = 0 # Take current variations at this order to be 0\n \n # Compute Z31c and Z31s from Cp2: we assume standard equilibria, meaning that we may\n # pick Bpsi0=0 and Bpsi1=0\n Z31c = -1/3/Ba0/X1c/Y1s*(2*iota*(X1c*X2s - Y2c*Y1s + Y1c*Y2s) - 2*Ba0*X2s*Y1c*Z20 +\n 2*Ba0* X2c*Y1s*Z20 + 2*Ba0*X1c*Y2s*Z20 - 4*Ba0*X2s*Y1c*Z2c - 2*Ba0* X20*Y1s*Z2c +\n 4*Ba0*X1c*Y2s*Z2c - dldp*(torsion*(2*X20*Y1c + X2c*Y1c - 2*X1c*Y20 - X1c*Y2c +\n X2s*Y1s) + I2*(2*X20*Y1c + X2c*Y1c - 2*X1c*Y20 - X1c*Y2c + X2s*Y1s) - \n 2*curvature*X1c*Z20 - curvature*X1c*Z2c) + 2*Ba0*X20*Y1c*Z2s + 4*Ba0*X2c*Y1c*Z2s - \n 2*Ba0*X1c*Y20*Z2s - 4*Ba0*X1c*Y2c*Z2s + 2*X1c*dX20dp + X1c*dX2cdp+2*Y1c*dY20dp +\n Y1c*dY2cdp + Y1s*dY2sdp)\n \n dZ31cdp = np.matmul(d_d_varphi, Z31c)\n \n Z31s = 1/3/Ba0/X1c/Y1s*(2*iota*(X1c*X2c + Y1c*Y2c + Y1s*Y2s) - 2*Ba0*X2c*Y1c*Z20 + \n 2*Ba0*X1c*Y2c*Z20 - 2*Ba0*X2s*Y1s*Z20 + 2*Ba0*X20*Y1c*Z2c - 2*Ba0*X1c*Y20*Z2c +\n 4*Ba0*X2s*Y1s*Z2c + 2*Ba0*X20*Y1s*Z2s - 4*Ba0*X2c*Y1s*Z2s + dldp*(I2*X2s*Y1c + \n 2*I2*X20*Y1s - I2*X2c*Y1s - I2*X1c*Y2s + torsion*(X2s*Y1c + 2*X20*Y1s - X2c*Y1s -\n X1c*Y2s) - curvature*X1c*Z2s) - X1c*dX2sdp - 2*Y1s*dY20dp + Y1s*dY2cdp - Y1c*dY2sdp)\n \n dZ31sdp = np.matmul(d_d_varphi, Z31s)\n\n \n # Equation J3: expression for X31c/s\n X31c = 1/2/dldp**2/curvature*(-2*Ba0*Ba1*B1c - Ba0**2*B31c+2*dldp**2*torsion**2*X1c*X20 +\n 2*iota**2*X1c*X2c + dldp**2*torsion**2*X1c*X2c + dldp**2*curvature**2*X1c*(2*X20 + X2c) + \n 3*dldp*iota*torsion*X2s*Y1c + 2*dldp**2*torsion**2*Y1c*Y20 + 2*iota**2*Y1c*Y2c +\n dldp**2*torsion**2*Y1c*Y2c - 2*dldp*iota*torsion*X20*Y1s - 3*dldp*iota*torsion*X2c*Y1s -\n 3*dldp*iota*torsion*X1c*Y2s + 2*iota**2*Y1s*Y2s + dldp**2*torsion**2*Y1s*Y2s + \n 2*dldp*iota*Z31s + 2*iota*X2s*dXc1v + 2*dldp*torsion*Y20*dXc1v + dldp*torsion*Y2c*dXc1v + \n 2*dldp*torsion*Y1c*dX20dp + 2*dXc1v*dX20dp + dldp*torsion*Y1c*dX2cdp + dXc1v*dX2cdp - \n iota*X1c*dX2sdp + dldp*torsion*Y1s*dX2sdp - 2*dldp*torsion*X20*dY1cdp - dldp*torsion*X2c*dY1cdp +\n 2*iota*Y2s*dY1cdp - 2*dldp*torsion*X1c*dY20dp + 2*iota*Y1s*dY20dp + 2*dY1cdp*dY20dp - \n dldp*torsion*X1c*dY2cdp + iota*Y1s*dY2cdp + dY1cdp*dY2cdp - dldp*torsion*X2s*dY1sdp - \n 2*iota*Y2c*dY1sdp - iota*Y1c*dY2sdp + dY1sdp*dY2sdp + dldp*curvature*(-3*iota*X1c*Z2s + \n dldp*torsion*(Y1c*(2*Z20 + Z2c) + Y1s*Z2s) + 2*Z20*dXc1v + Z2c*dXc1v - 2*X1c*dZ20dp - \n X1c*dZ2cdp) + 2*dldp*dZ31cdp)\n \n X31s = 1/2/dldp**2/curvature*(-Ba0**2*B31s + dldp**2*curvature**2*X1c*X2s + dldp**2*torsion**2*X1c*X2s +\n 2*dldp**2*torsion**2*Y20*Y1s - dldp**2*torsion**2*Y2c*Y1s + dldp**2*torsion**2*Y1c*Y2s +\n 2*iota**2*(X1c*X2s - Y2c*Y1s + Y1c*Y2s) + 2*dldp**2*curvature*torsion*Y1s*Z20 - \n dldp**2*curvature*torsion*Y1s*Z2c + dldp**2*curvature*torsion*Y1c*Z2s + dldp*torsion*Y2s*dXc1v +\n dldp*curvature*Z2s*dXc1v + 2*dldp*torsion*Y1s*dX20dp - dldp*torsion*Y1s*dX2cdp + \n dldp*torsion*Y1c*dX2sdp + dXc1v*dX2sdp - dldp*torsion*X2s*dY1cdp - 2*dldp*torsion*X20*dY1sdp + \n dldp*torsion*X2c*dY1sdp + 2*dY20dp*dY1sdp - dY2cdp*dY1sdp - dldp*torsion*X1c*dY2sdp + dY1cdp*dY2sdp +\n iota*(dldp*torsion*(2*X20*Y1c - 3*X2c*Y1c - 2*X1c*Y20 + 3*X1c*Y2c - 3*X2s*Y1s) + dldp*curvature*X1c*\n (-2*Z20 + 3*Z2c) - 2*dldp*Z31c - 2*X2c*dXc1v - 2*X1c*dX20dp + X1c*dX2cdp - 2*Y2c*dY1cdp -\n 2*Y1c*dY20dp + Y1c*dY2cdp - 2*Y2s*dY1sdp + Y1s*dY2sdp) - dldp*curvature*X1c*dZ2sdp +2*dldp*dZ31sdp)\n\n dX31sdp = np.matmul(d_d_varphi, X31s)\n \n # Equation Cb2\n Y31s = 1/4/Ba0/X1c*(-2*Ba1*X1c*Y1s + 2*iota*I2*X1c*Y1s - dldp*(4*curvature*X20 + torsion*I2*\n (X1c**2 + Y1c**2 + Y1s**2)) + 4*Ba0*(X31s*Y1c + 2*X2s*Y2c - X31c*Y1s - 2*X2c*Y2s) -\n I2*Y1c*dXc1v + I2*X1c*dY1cdp + 4*dZ20dp) \n\n dY31sdp = np.matmul(d_d_varphi, Y31s)\n\n \n # From the equation for Bt to order n=4, and looking at m=0\n LamTilde = 2/Y1s**2*(Ba0*B0*I4 + (Ba1*B0 + Ba0*B20)*I2) + 1/Y1s**2*(-2*iota*(2*X2c**2 + X1c*X31c + \n 2*X2s**2 + 2*Y2c**2 + 2*Y2s**2 + Y1s*Y31s + 2*Z2c**2 + 2*Z2s**2) + 2*dldp*(torsion*(-X31s*Y1c -\n 2*X2s*Y2c + X31c*Y1s + 2*X2c*Y2s + X1c*Y31s) + curvature*(-2*X2s*Z2c + 2*X2c*Z2s + X1c*Z31s)) -\n X31s*dXc1v - 2*X2s*dX2cdp + 2*X2c*dX2sdp + X1c*dX31sdp - Y31s*dY1cdp - 2*Y2s*dY2cdp +\n 2*Y2c*dY2sdp + Y1c*dY31sdp - 2*Z2s*dZ2cdp + 2*Z2c*dZ2sdp)\n\n # Need to compute the integration factor necessary for computing the shear\n DMred = d_d_varphi[1:,1:] # The differentiation matrix has a linearly dependent row, focus on submatrix\n\n # Distinguish between the stellarator symmetric case and the non-symmetric one at order r^1.\n # Distinction leads to the expSig function being periodic (stell. sym.) or not.\n if self.sigma0 == 0 and np.max(np.abs(self.rs)) == 0 and np.max(np.abs(self.zc)) == 0:\n # Case in which sigma is stellarator-symmetric:\n integSig = np.linalg.solve(DMred,self.sigma[1:]) # Invert differentiation matrix: as if first entry a zero, need to add it later\n integSig = np.insert(integSig,0,0) # Add the first entry 0\n expSig = np.exp(2*iota*integSig)\n # d_phi_d_varphi = 1 + np.matmul(d_d_varphi,self.phi-self.varphi)\n self.iota2 = self.B0/2*sum(expSig*LamTilde*self.d_varphi_d_phi)/sum(expSig*(X1c**2 + Y1c**2 + Y1s**2)/Y1s**2*self.d_varphi_d_phi) \n else:\n # Case in which sigma is not stellarator-symmetric:\n # d_phi_d_varphi = 1 + np.matmul(d_d_varphi,self.phi-self.varphi)\n avSig = sum(self.sigma*self.d_varphi_d_phi)/len(self.sigma) # Separate the piece that gives secular part, so all things periodic\n integSigPer = np.linalg.solve(DMred,self.sigma[1:]-avSig) # Invert differentiation matrix: as if first entry a zero, need to add it later\n integSig = integSigPer + avSig*self.varphi[1:] # Include the secular piece\n integSig = np.insert(integSig,0,0) # Add the first entry 0\n expSig_ext = np.append(np.exp(2*iota*integSig),np.exp(2*iota*(avSig*2*np.pi/self.nfp))) # Add endpoint at 2*pi for better integration\n LamTilde_ext = np.append(LamTilde,LamTilde[0])\n fac_denom = (X1c**2 + Y1c**2 + Y1s**2) / Y1s**2\n fac_denom_ext = np.append(fac_denom, fac_denom[0])\n varphi_ext = np.append(self.varphi, 2 * np.pi / self.nfp)\n self.iota2 = self.B0 / 2 \\\n * integ.trapz(expSig_ext * LamTilde_ext, varphi_ext) \\\n / integ.trapz(expSig_ext * fac_denom_ext, varphi_ext)\n \n # Using cumtrapz without exploiting periodicity\n # expSig = np.exp(2*iota*integ.cumtrapz(self.sigma,self.varphi,initial=0))",
"def shear_Reuss(self):\r\n s = self.Sij\r\n return 15 / (4 * (s[0, 0] + s[1, 1] + s[2, 2]) - 4 * (s[0, 1] + s[1, 2] + s[0, 2]) + 3 * (s[3, 3] + s[4, 4] + s[5, 5]))",
"def shear(self):\r\n return (self.shear_Voigt + self.shear_Reuss) / 2",
"def measure_rms(signal):\n return np.sqrt(np.mean(np.absolute(signal)**2))",
"def shear_Voigt(self):\r\n c = self.Cij\r\n return ((c[0, 0] + c[1, 1] + c[2, 2]) - (c[0, 1] + c[1, 2] + c[0, 2]) + 3 * (c[3, 3] + c[4, 4] + c[5, 5])) / 15",
"def gas_meter(self, data):\n\n dtime = data.get('Time')\n\n self.newTime = parser.parse(dtime)\n self.meterID = data.get('Message').get('ID')\n self.currentTime = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')\n\n self.newConsumption = data.get('Message').get('Consumption')\n \n self.meter_type = \"Gas\"\n\n if not self.meterID in config.meters.keys():\n if config.debug:print(\"first time seeing this id: {}\".format(self.meterID))\n config.meters[self.meterID] = {\"Time\": self.newTime, \"ID\":self.meterID, \"Consumption\": self.newConsumption}\n return False\n else:\n\n self.oldConsumption = config.meters[self.meterID].get('Consumption')\n self.oldTime = config.meters[self.meterID].get('Time')\n\n # level shift.\n config.meters[self.meterID]['Consumption'] = self.newConsumption\n config.meters[self.meterID]['Time'] = self.newTime\n\n\n self.timeDiff = self.newTime - self.oldTime\n\n ##### DEbUG TAKE OUT.\n #if self.meterID in config.myMeters:print(data)\n\n if(self.timeDiff.total_seconds() < 0):print(\"Error: Time Diff Negative. Customer: %s. %d - %d = %d\" % (self.meterID, self.newTime, self.oldTime, self.timeDiff))\n\n self.mcfDiff = self.newConsumption - self.oldConsumption\n\n #if(self.wattDiff != 0):\n #if(self.mcfDiff):\n \n if data.get('Message').get('Consumption'):\n #print(data)\n self.mcfPerMin = (self.mcfDiff / (self.timeDiff.total_seconds() / 60)) / 1000 # <-\n\n # if numbers are way out of range throw error\n if self.meterID in config.myMeters:\n print(\"[%s] Customer %s Using %f mcf per minute. (consumption: %d) - (time elapsed: %d s) ### %d\" % (self.currentTime, self.meterID, self.mcfPerMin, self.mcfDiff, self.timeDiff.total_seconds(),self.newConsumption))\n else:\n print(\"[%s] Customer %s Using %f mcf per minute. (consumption: %d) - (time elapsed: %d s)\" % (self.currentTime, self.meterID, self.mcfPerMin, self.mcfDiff, self.timeDiff.total_seconds()))\n\n self.log_data(data,self.mcfDiff,self.mcfPerMin,\"mcf/min\")\n \n else:\n # consumption data hasn't changed. time shift back and wait some more.\n config.meters[self.meterID]['Time'] = self.oldTime\n config.meters[self.meterID]['Consumption'] = self.oldConsumption #redundant?\n \n self.log_data(data,0,0,\"mcf/min\")\n\n return True",
"def secant_meth():\n\n x = 0\n ea = 0\n curr = 1\n prev = 0\n x_old = 0\n x_curr = 0\n\n for val in range(15):\n # secant logic\n x = round(curr-(curv(curr)*(prev-curr)/curv(prev)-curv(curr)), 2)\n x_curr = curr = x\n\n if curr != 0:\n ea = abs(round((x_curr-x_old)/curr, 2))\n\n print(x, 'error estimate'.title(), ea)\n x_old = prev = curr\n\n if ea < 0.56:\n break",
"def mtf_cost_core_main(true_tan, true_sag, sim_tan, sim_sag):\n difference_t = true_tan - sim_tan\n difference_s = true_sag - sim_sag\n return difference_t, difference_s",
"def reaction_mandelstam_t(block):\n assert(block['nin'] == 2)\n p1 = block['incoming']['p'][0]\n p3 = block['outgoing']['p'][0]\n mom_sqr = np.square(p1 - p3)\n return mom_sqr[0] - mom_sqr[1:].sum()",
"def get_sweep_average(self): #tested and documented\n self.send_message(\"AVS?\")\n msg = self.flush_buffer()\n if msg==\"OFF\":\n return 0\n else:\n return int(msg)",
"def rmsd_no_align(frame1, frame2):\n ## find the displacement for each coordinate\n disp = frame1 - frame2\n ##find squared displacement\n numpy.multiply(disp, disp, disp)\n sd = numpy.sum(disp, axis=1) # \"squared displacement\"\n ## mean squared displacement, etc.\n msd = sd.sum() / len(sd)\n rmsd = math.sqrt(msd)\n\n# print msd\n# print rmsd\n return rmsd",
"def _thermal_diffusion(self):\r\n if self.mineral == 'apatite': # Farley et al. (2000)\r\n Do = 50\r\n Ea = 137.522\r\n if self.mineral == 'zircon': # Reiners et al. (2004)\r\n Do = 0.46\r\n Ea = 169.0336\r\n \r\n R = 0.00831447\r\n T = self.T + 273.15\r\n \r\n d = (Do * np.exp(-Ea / (R * T))) * 1e8\r\n d = (d[:-1] + d[1:]) / 2 #average for dt\r\n \r\n self.diffusivities = d",
"def pixel_smear(\n t: np.array, sample: np.array, line: np.array, linerate: float, tdi: int,\n):\n # The output here differs from the C++ output in a very, very minor\n # way. The absolute difference between the line and sample smear\n # is 0.002 pixels. I could not track this down. It may be due to\n # precision differences in the double values that C++ uses, but I'm\n # just not sure.\n\n # The array T has large values. Use a shifted version of it when\n # interpolating to reduce the effect of those values on numerical\n # accuracy.\n shifted_t = t - t[0]\n\n # xi = T(1):linerate:T(end);\n n = math.floor((shifted_t[-1] - shifted_t[0]) / linerate) + 1\n # This is from the original code, but by definition shifted_t[0] is zero.\n # xi = np.linspace(0, n - 1, n) * linerate + shifted_t[0]\n xi = np.linspace(0, n - 1, n) * linerate\n\n # Interpolate the jitter function at intervals equivalent to the linerate\n f_samp = PchipInterpolator(shifted_t, sample, extrapolate=False)\n f_line = PchipInterpolator(shifted_t, line, extrapolate=False)\n yis = f_samp(xi)\n yil = f_line(xi)\n\n np.nan_to_num(yis, copy=False, nan=0)\n np.nan_to_num(yil, copy=False, nan=0)\n\n # Undo the earlier shift\n xi += t[0]\n\n # Calculate the rate of change with respect to the linerate\n # in the sample direction\n dysdx = np.diff(yis) * tdi\n # in the line direction\n dyldx = np.diff(yil) * tdi\n\n # Calculate the magnitude of the smear\n mag_smear = np.sqrt(dysdx ** 2 + dyldx ** 2)\n\n # Find maxSmearS, the largest element by magnitude in dysdx\n msi = np.argmax(np.abs(dysdx))\n max_smear_s = dysdx[msi]\n\n # Find maxSmearL, the largest element by magnitude in dyldx\n msi = np.argmax(np.abs(dyldx))\n max_smear_l = dyldx[msi]\n\n # Find maxSmearMag, the largest element by magnitude in magSmear\n max_smear_mag = np.max(mag_smear)\n\n # Outputs\n return max_smear_s, max_smear_l, max_smear_mag, dysdx, dyldx, xi",
"def test_shear_convergence_unittests(modeling_data):\n helper_physics_functions(theo.compute_tangential_shear)\n helper_physics_functions(theo.compute_convergence)\n helper_physics_functions(theo.compute_reduced_tangential_shear)\n helper_physics_functions(theo.compute_magnification)\n\n reltol = modeling_data['theory_reltol']\n\n # Validation Tests -------------------------\n # NumCosmo makes different choices for constants (Msun). We make this conversion\n # by passing the ratio of SOLAR_MASS in kg from numcosmo and CLMM\n cfg = load_validation_config()\n\n # First compute SigmaCrit to correct cosmology changes\n cosmo = cfg['cosmo']\n sigma_c = theo.compute_critical_surface_density(cosmo, cfg['GAMMA_PARAMS']['z_cluster'],\n cfg['z_source'])\n\n # Compute sigma_c in the new cosmology and get a correction factor\n sigma_c_undo = theo.compute_critical_surface_density(cosmo, cfg['GAMMA_PARAMS']['z_cluster'],\n cfg['z_source'])\n sigmac_corr = (sigma_c_undo/sigma_c)\n\n # Chech error is raised if too small radius\n assert_raises(ValueError, theo.compute_tangential_shear,\n 1.e-12, 1.e15, 4, 0.2, 0.45, cosmo)\n\n # Validate tangential shear\n gammat = theo.compute_tangential_shear(cosmo=cosmo, **cfg['GAMMA_PARAMS'])\n assert_allclose(gammat*sigmac_corr,\n cfg['numcosmo_profiles']['gammat'], reltol)\n\n # Validate convergence\n kappa = theo.compute_convergence(cosmo=cosmo, **cfg['GAMMA_PARAMS'])\n assert_allclose(kappa*sigmac_corr,\n cfg['numcosmo_profiles']['kappa'], reltol)\n\n # Validate reduced tangential shear\n assert_allclose(theo.compute_reduced_tangential_shear(cosmo=cosmo, **cfg['GAMMA_PARAMS']),\n gammat/(1.0-kappa), 1.0e-10)\n assert_allclose(gammat*sigmac_corr/(1.-(kappa*sigmac_corr)),\n cfg['numcosmo_profiles']['gt'], 1.e2*reltol)\n\n # Validate magnification\n assert_allclose(theo.compute_magnification(cosmo=cosmo, **cfg['GAMMA_PARAMS']),\n 1./((1-kappa)**2-abs(gammat)**2), 1.0e-10)\n assert_allclose(1./((1-kappa)**2-abs(gammat)**2),\n cfg['numcosmo_profiles']['mu'], 1.e2*reltol)\n\n # Check that shear, reduced shear and convergence return zero and magnification returns one if\n # source is in front of the cluster\n # First, check for a array of radius and single source z\n radius = np.logspace(-2, 2, 10)\n z_cluster = 0.3\n z_source = 0.2\n\n assert_allclose(\n theo.compute_convergence(\n radius, mdelta=1.e15, cdelta=4., z_cluster=z_cluster, z_source=z_source, cosmo=cosmo),\n np.zeros(len(radius)), 1.0e-10)\n assert_allclose(\n theo.compute_tangential_shear(\n radius, mdelta=1.e15, cdelta=4., z_cluster=z_cluster, z_source=z_source, cosmo=cosmo),\n np.zeros(len(radius)), 1.0e-10)\n assert_allclose(\n theo.compute_reduced_tangential_shear(\n radius, mdelta=1.e15, cdelta=4., z_cluster=z_cluster, z_source=z_source, cosmo=cosmo),\n np.zeros(len(radius)), 1.0e-10)\n assert_allclose(\n theo.compute_magnification(\n radius, mdelta=1.e15, cdelta=4., z_cluster=z_cluster, z_source=z_source, cosmo=cosmo),\n np.ones(len(radius)), 1.0e-10)\n\n # Second, check a single radius and array of source z\n radius = 1.\n z_source = [0.25, 0.1, 0.14, 0.02]\n assert_allclose(\n theo.compute_convergence(\n radius, mdelta=1.e15, cdelta=4., z_cluster=z_cluster, z_source=z_source, cosmo=cosmo),\n np.zeros(len(z_source)), 1.0e-10)\n assert_allclose(\n theo.compute_tangential_shear(\n radius, mdelta=1.e15, cdelta=4., z_cluster=z_cluster, z_source=z_source, cosmo=cosmo),\n np.zeros(len(z_source)), 1.0e-10)\n assert_allclose(\n theo.compute_reduced_tangential_shear(\n radius, mdelta=1.e15, cdelta=4., z_cluster=z_cluster, z_source=z_source, cosmo=cosmo),\n np.zeros(len(z_source)), 1.0e-10)\n assert_allclose(\n theo.compute_magnification(\n radius, mdelta=1.e15, cdelta=4., z_cluster=z_cluster, z_source=z_source, cosmo=cosmo),\n np.ones(len(z_source)), 1.0e-10)\n\n # Object Oriented tests\n mod = theo.Modeling()\n mod.set_cosmo(cosmo)\n mod.set_halo_density_profile(\n halo_profile_model=cfg['GAMMA_PARAMS']['halo_profile_model'])\n mod.set_concentration(cfg['GAMMA_PARAMS']['cdelta'])\n mod.set_mass(cfg['GAMMA_PARAMS']['mdelta'])\n # First compute SigmaCrit to correct cosmology changes\n sigma_c = mod.eval_critical_surface_density(\n cfg['GAMMA_PARAMS']['z_cluster'], cfg['GAMMA_PARAMS']['z_source'])\n\n # Compute sigma_c in the new cosmology and get a correction factor\n sigma_c_undo = mod.eval_critical_surface_density(\n cfg['GAMMA_PARAMS']['z_cluster'], cfg['GAMMA_PARAMS']['z_source'])\n sigmac_corr = (sigma_c_undo/sigma_c)\n\n # Validate tangential shear\n profile_pars = (cfg['GAMMA_PARAMS']['r_proj'], cfg['GAMMA_PARAMS']['z_cluster'],\n cfg['GAMMA_PARAMS']['z_source'])\n gammat = mod.eval_tangential_shear(*profile_pars)\n assert_allclose(gammat*sigmac_corr,\n cfg['numcosmo_profiles']['gammat'], reltol)\n\n # Validate convergence\n kappa = mod.eval_convergence(*profile_pars)\n assert_allclose(kappa*sigmac_corr,\n cfg['numcosmo_profiles']['kappa'], reltol)\n\n # Validate reduced tangential shear\n assert_allclose(mod.eval_reduced_tangential_shear(*profile_pars),\n gammat/(1.0-kappa), 1.0e-10)\n assert_allclose(gammat*sigmac_corr/(1.-(kappa*sigmac_corr)),\n cfg['numcosmo_profiles']['gt'], 1.e2*reltol)\n\n # Validate magnification\n assert_allclose(mod.eval_magnification(*profile_pars),\n 1./((1-kappa)**2-abs(gammat)**2), 1.0e-10)\n assert_allclose(1./((1-kappa)**2-abs(gammat)**2),\n cfg['numcosmo_profiles']['mu'], 1.e2*reltol)\n\n # Check that shear, reduced shear and convergence return zero and magnification returns one if\n # source is in front of the cluster\n # First, check for a array of radius and single source z\n radius = np.logspace(-2, 2, 10)\n z_cluster = 0.3\n z_source = 0.2\n\n assert_allclose(mod.eval_convergence(radius, z_cluster, z_source),\n np.zeros(len(radius)), 1.0e-10)\n assert_allclose(mod.eval_tangential_shear(\n radius, z_cluster, z_source), np.zeros(len(radius)), 1.0e-10)\n assert_allclose(mod.eval_reduced_tangential_shear(\n radius, z_cluster, z_source), np.zeros(len(radius)), 1.0e-10)\n assert_allclose(mod.eval_magnification(\n radius, z_cluster, z_source), np.ones(len(radius)), 1.0e-10)\n\n # Second, check a single radius and array of source z\n radius = 1.\n z_source = [0.25, 0.1, 0.14, 0.02]\n\n assert_allclose(mod.eval_convergence(radius, z_cluster, z_source),\n np.zeros(len(z_source)), 1.0e-10)\n assert_allclose(mod.eval_tangential_shear(\n radius, z_cluster, z_source), np.zeros(len(z_source)), 1.0e-10)\n assert_allclose(mod.eval_reduced_tangential_shear(\n radius, z_cluster, z_source), np.zeros(len(z_source)), 1.0e-10)\n assert_allclose(mod.eval_magnification(radius, z_cluster, z_source),\n np.ones(len(z_source)), 1.0e-10)",
"def sas(mol: SmallMolecule) -> float:\n return _sas(mol)",
"def old_SFR(self):\n self.old_SFR_MsunPyr = self.mstar_old.sum() / 100.0e6",
"def diff_flex(self):\n # Lodestar X2\n #plate_ratio = 4.42/(1.56/2)\n # \n plate_ratio = 3.01/(1.56/2)\n # 2018\n #if (-40 < self.MC.Telescope.Declination\n # and self.MC.Telescope.Declination < +10\n # and self.MC.Telescope.Altitude < 30):\n # # Change from guider pixels per 10s to main camera pixels per s\n # dec_pix_rate = -0.020/10 * plate_ratio\n # # Note Pythonic transpose\n # return self.GuideBoxCommander(np.asarray((dec_pix_rate, 0)))\n # 2019 post 9-position filter wheel. Jupiter only got up to\n # 35 and this was variable near the meridian but never much larger.\n # Thu May 09 10:28:09 2019 EDT jpmorgen@snipe\n # This may be messing up flips for ACP\n #if (-40 < self.MC.Telescope.Declination\n # and self.MC.Telescope.Declination < +10\n # and self.MC.Telescope.Altitude < 35):\n # # Change from guider pixels per 10s to main camera pixels per s\n # dec_pix_rate = -0.005/10 * plate_ratio\n # # Note Pythonic transpose\n # return self.GuideBoxCommander(np.asarray((dec_pix_rate, 0)))\n # 2020 early\n # if (-40 < self.MC.Telescope.Declination\n # and self.MC.Telescope.Declination < +10\n # and self.MC.Telescope.Altitude < 30):\n # # Change from guider pixels per 10s to main camera pixels per s\n # ra_pix_rate = -0.014/10 * plate_ratio\n # dec_pix_rate = -0.020/10 * plate_ratio\n # # Note Pythonic transpose\n # return self.GuideBoxCommander(np.asarray((dec_pix_rate, ra_pix_rate)))\n # 2021 after guider change\n if (-40 < self.MC.Telescope.Declination\n and self.MC.Telescope.Declination < +10\n and self.MC.Telescope.Altitude < 30):\n # Change from guider pixels per 10s to main camera pixels per s\n ra_pix_rate = -0.010/10 * plate_ratio\n # Fri May 14 10:24:04 2021 EDT jpmorgen@snipe\n # This is the formal calculation, but intuition tells me\n # it is too big of a swing to make at once\n #dec_pix_rate = +0.051/10 * plate_ratio\n #dec_pix_rate = +0.030/10 * plate_ratio\n # Indeed, this should probably get pretty close\n dec_pix_rate = +0.037/10 * plate_ratio\n # Note Pythonic transpose\n return self.GuideBoxCommander(np.asarray((dec_pix_rate, ra_pix_rate)))\n\n\n return self.GuideBoxCommander(np.asarray((0, 0)))",
"def _damage(self):\r\n if self.mineral =='apatite': # Flowers et al. (2009)\r\n C0 = 0.39528\r\n C1 = 0.01073\r\n C2 = -65.12969\r\n C3 = -7.91715\r\n alpha = 0.04672\r\n rmr0 = 0.83\r\n kappa = 1.04 - rmr0\r\n elif self.mineral =='zircon': # Guenthner et al. (2013)\r\n C0=6.24534\r\n C1=-0.11977\r\n C2=-314.937\r\n C3=-14.2868\r\n alpha=-0.05721\r\n\r\n dt = (self.t1 - self.t2) * 365.25 * 24 * 60 * 60\r\n dam = np.zeros((len(dt),len(dt)))\r\n\r\n def _d_anneal(dt,T_mean):\r\n \"\"\"Calculate change in track length at each timestep\"\"\"\r\n d = ((C0 + C1 * ((np.log(dt) - C2) /\r\n (np.log(1/T_mean) - C3)))**(1/alpha) + 1)**-1\r\n return d\r\n \r\n def _t_eqv(T_mean,d):\r\n \"\"\"Calculate equivalent time\"\"\"\r\n t_eqv = (np.exp(C2 + (np.log(1 / T_mean) - C3) *\r\n (((1 / d) - 1)**alpha - C0) / C1))\r\n return t_eqv\r\n\r\n #calculate track length for newly generated tracks\r\n new_tracks = np.diag_indices_from(dam)\r\n dam[new_tracks] = _d_anneal(dt,self.T_mean)\r\n \r\n #calculate annealing using 'equivalent time'\r\n for i in range(1,len(self.t)-1):\r\n teqv = _t_eqv(self.T_mean[i],dam[i-1,:i])\r\n teqv = teqv + dt[i]\r\n dam[i,:i] = _d_anneal(teqv,self.T_mean[i])\r\n \r\n #volume conversion\r\n if self.mineral =='apatite':\r\n dam[(dam>=rmr0)] = ((dam[(dam>=rmr0)] - rmr0) / (1 - rmr0))**kappa\r\n dam[(dam>=0.765)] = 1.6 * dam[(dam>=0.765)] - 0.6\r\n\r\n df = ((dam!=0.0) & (dam<0.765))\r\n dam[df] = 9.205 * dam[df] * dam[df] - 9.157 * dam[df] + 2.269\r\n \r\n self.damage = dam\r\n \r\n elif self.mineral =='zircon':\r\n dam = 1.25 * (dam - 0.2)\r\n dam[dam<(0.36 / 1.25 + 0.2)] = 0\r\n \r\n self.damage = dam",
"def rms_qual(sample):\n sample = trim(sample, top_db=36)[0] # trim a little higher\n rms = np.sqrt(np.mean(sample ** 2))\n return 1 - rms # rms = 1 is the \"optimal\" rms (which would be a square wave)",
"def calculate_t():\n Data = pd.read_csv(path_csv) # Read Gaia query results\n \n # Focus on the indices that we are interested in:\n Data1 = Data.loc[ : , ['ra', 'dec', 'pmra', 'pmdec', 'pm', 'dist_arcsec', 'dist_to_host', 'z_pc', 'designation', 'ruwe']]\n \n # location and proper motion information of the host star(Gaia DR3 epoch)\n x0 = Data1.iloc[0, 0] # Right Ascension\n y0 = Data1.iloc[0, 1] # Declination\n cos_DEC0 = np.cos( np.radians( y0 ) ) # Cosine value of the declination\n pmra0 = Data1.iloc[0, 2] # Proper Motion in Right Ascension direction times cosine value of the declination\n pmdec0 = Data1.iloc[0, 3] # Proper Motion in Declination diretion\n z0 = Data1.iloc[0, 7] # the parallax of the host star (unit: pc)\n \n # location and proper motion information of all stars\n DEC = np.array( Data1['dec'] ) # Declination\n cos_DEC = np.cos( np.radians( DEC ) ) # Cosine value of the declination\n RA = np.array( Data1['ra'] ) # Right Ascension\n ID = np.array( Data1['designation'] ) # Gaia ID of all stars\n RUWE = np.array( Data1['ruwe'] ) # the renormalized unit weight error of all stars\n\n # relative Right Ascension and Declination between the host star and all neighboring stars(Gaia DR3 epoch)\n unit_c = 3600 * 1000 # Unit conversion:deg. to mas\n RA_r = ( RA - x0 ) * unit_c # unit: mas\n Dec_r = ( DEC - y0 ) * unit_c # unit: mas\n\n # relative proper motion between the host star and all neighboring stars(Gaia DR3 epoch)\n PMRA_r = np.array( Data1['pmra']/cos_DEC - pmra0/cos_DEC0 ) # relative Proper Motion in Right Ascension direction (unit: mas/yr)\n PMDEC_r = np.array( Data1['pmdec'] - pmdec0 ) # relative Proper Motion in Declination direction (unit: mas/yr)\n \n # calculate the closest approach distance\n # refer to Equation (B10) in paper for a, b, and c\n a = PMDEC_r\n b = - PMRA_r\n c = PMRA_r * Dec_r - PMDEC_r * RA_r\n \n f_mas = abs( c )/( ( a ** 2 + b ** 2 ) ** 0.5 ) # The distance of the closest approach (unit: mas)\n f_deg = f_mas/unit_c # Unit conversion:mas to deg\n d_pc = z0 * np.radians( f_deg ) * au.pc # Unit conversion:deg to pc\n d_au = d_pc.to( au.au ) # unit: au\n \n # Right Ascension of neighboring stars at the closest distance\n alpha = ( - a * c )/( a ** 2 + b ** 2 ) # unit: mas\n \n # the time of the closest encounter\n # refer to Equation (B12) in paper for tt\n t = - ( ( RA_r - alpha )/PMRA_r ) # unit: year\n \n # the radius of protoplanetary disk\n r = float( sys.argv[2] ) * au.AU\n \n Data0 = pd.DataFrame( {'designation':ID,'dd/au':d_au,'t/yr':t,'ra/deg':RA, 'dec/deg':DEC,'RUWE':RUWE} )\n \n # limit the time t within past t_traceback years\n # and limit the distance d within 10 times protoplanetary disk radius\n Data00 = Data0[( t <= 0 )&( t > -t_traceback )&( d_au < 10 * r )]\n \n # the number of stars that meet the constraints\n num = Data00.index.tolist()\n \n #return these values\n # num[0]: the row number in Gaia query result .csv file that meets the constraints\n # t[num[0]]: closest encounter time that meets the constraints\n \n return num[0],t[num[0]]"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Configures streaming execution mode.
|
def as_streaming_execution(self):
self._is_stream = True
return self
|
[
"def __init__(__self__, *,\n stream_mode: 'StreamModeDetailsStreamMode'):\n pulumi.set(__self__, \"stream_mode\", stream_mode)",
"def set_stream_on(self, session, params=None):\n if params is None:\n params = {}\n\n force = params.get('force', False)\n if force:\n self.log.debug(\"force starting stream\")\n\n if not self.is_streaming or force:\n if FlowControl.START not in self.flags:\n self.flags.append(FlowControl.START)\n\n return True, \"Started stream\"",
"def AdjustStreamTemplateLoadMode(self):\n return self._AdjustStreamTemplateLoadMode",
"def mode(self, mode):\n # type: (StreamMode) -> None\n\n if mode is not None:\n if not isinstance(mode, StreamMode):\n raise TypeError(\"Invalid type for `mode`, type has to be `StreamMode`\")\n\n self._mode = mode",
"def stream_mode(self) -> 'StreamModeDetailsStreamMode':\n return pulumi.get(self, \"stream_mode\")",
"def mode(self):\n # type: () -> StreamMode\n return self._mode",
"def SetUseStreamedWriting(self, _arg: 'bool const') -> \"void\":\n return _ITKIOImageBaseBasePython.itkImageIOBase_SetUseStreamedWriting(self, _arg)",
"def SetUseStreamedReading(self, _arg: 'bool const') -> \"void\":\n return _ITKIOImageBaseBasePython.itkImageIOBase_SetUseStreamedReading(self, _arg)",
"def enable_streaming_server(self, testcase=None):\n\n self.log.debug(\"Enabling streaming server ...\")\n result = {'successful': False, 'verified': False}\n\n try:\n # edit system setup to enable streaming server (with default settings)\n result['verified'] = \\\n self.configure_vim_system_settings(settings=SYSCONFIG_DEFAULT_SS_SETTINGS)['verified']\n\n if result['verified']:\n self.log.trace(\"Enabled streaming server.\")\n result['successful'] = True\n except BaseException, e:\n self.handle_exception(e, operation=\"enable streaming server\")\n\n # return\n if testcase is not None: testcase.processing = result['successful']\n return result",
"def stop_stream(self):\n self.streaming = False",
"async def streamset(self, inter: disnake.GuildCommandInteraction, txt : str = commands.Param()):\r\n with self.bot.data.lock:\r\n self.bot.data.save['stream']['content'] = txt.split(';')\r\n self.bot.data.pending = True\r\n await inter.response.send_message(embed=self.bot.util.embed(title=\"Stream Settings\", description=\"Stream text sets to\\n`{}`\".format(txt), color=self.color))",
"def initStream(self):\n self.out.write(\"<stream>\")\n self.stream_initiated = True",
"def device_execution_mode(self, value):\n\n self._device_execution_mode.set(value)",
"def start_streaming(self):\n if (not self.is_connected()):\n self.message_string = 'Board is not connected.'\n return\n\n if (not (self.is_streaming)):\n self.message_string = 'Started streaming'\n self.port.reset_input_buffer()\n self.port.write(START_STREAMING_CMD.encode('utf-8'))\n self.is_streaming = True\n self.read_state = 0\n self.skipped_bytes = 0\n read_thread = threading.Thread(target=self.collect_data)\n read_thread.daemon = True\n read_thread.start()\n self.samples_counter = 0",
"def set_target(self, stream):\n pass",
"def startStreaming(self) :\n # tell the rawhid interface program to start saving out data streams\n self.streaming = True\n fbase = \"streams/\" + timeStamped(comm.port)\n self.stream_fname = fbase + \"stream.bin\"\n comm.DataStreamStartSave(DS_STREAM_HIST, self.stream_fname)\n \n # also save off a copy of the machine at this time (so we know what was going on later)\n mach.machine.save(fbase + 'machine.xml')\n \n # tell the device to start streaming\n comm.Write(\"ss 1\")",
"def several_inputs_outputs_stream_config():\n return load_configuration_from_json_file(file_name='several_inputs_outputs_stream_mode_enabled_configuration.json')",
"def set_stream_level(self, lvl):\n self.ch.setLevel(lvl)",
"def streaming_options():\n _opts = {\n 'i2p.streaming.connectTimeout' : '30000',\n 'i2p.streaming.maxMessageSize' : '1730',\n 'i2p.streaming.maxResends' : '8',\n 'i2p.streaming.initialResendDelay' : '1000',\n 'i2p.streaming.initialRTO' : '9000',\n 'i2p.streaming.initialWindowSize' : '6',\n 'i2p.streaming.maxWindowSize' : '128',\n 'i2p.streaming.maxMessageSize' : '1730',\n 'i2p.streaming.connectDelay' : '1000',\n 'i2p.streaming.inactivityTimeout': '90000',\n }\n return _opts",
"def config_ixia_stream(self, rate_percent, flows):\n\n self.add_tcl_cmd(\"ixGlobalSetDefault\")\n self.add_tcl_cmd(\"stream config -rateMode usePercentRate\")\n self.add_tcl_cmd(\"stream config -percentPacketRate %s\" % rate_percent)\n\n # We define one burst with num_frames packets on it and we also want IXIA\n # to stop once all of them have been sent.\n self.add_tcl_cmd(\"stream config -numBursts 1\")\n self.add_tcl_cmd(\"stream config -numFrames %d\" % self.num_of_frames)\n self.add_tcl_cmd(\"stream config -dma stopStream\")"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Sets the parallelism for all operations.
|
def set_parallelism(self, parallelism):
self._parallelism = parallelism
return self
|
[
"def set_parallelism(self, parallelism):\n self._j_execution_environment.setParallelism(parallelism)",
"def set_parallelism_factor(self, factor):\n self.parallelism_factor = factor",
"def set_thread_count(self, threads):\n self.parallelism = threads\n self.info.parallelism = threads",
"def set_cpus(self, num_cpus):\n if self.batch:\n self.batch_settings.batch_args[\"cpus-per-task\"] = num_cpus\n for db in self:\n db.run_settings.set_cpus_per_task(num_cpus)",
"def set_default_local_parallelism(self, parallelism):\n self._j_execution_environment.setDefaultLocalParallelism(parallelism)",
"def parallel(self, max_workers=3):\n self.add_options('--parallel', '--max-workers=' + str(max_workers))\n return self",
"def set_parallel(self, is_parallel: bool = True) -> Tween:\n if self._started:\n raise RuntimeError(\"Cannot change parallel mode on a started Tween object\")\n self._is_parallel = is_parallel\n return self",
"def set_numa_optimization(self):\n\n self.params += \" -XX:+UseNUMA -XX:+UseParallelGC\"",
"def get_parallelism_factor(self):\n return self.parallelism_factor",
"def parallel(self, task: Union[MitTask, \"TaskGraph\"]):\n raise TypeError(\"MitEx.parallel forbidden.\")",
"def _set_default_processes(self) -> None:\n self.processes = cpu_count()\n if self.processes is None:\n logger.warning(\"The number of cores could not be detected - assuming one.\")\n self.processes = 1\n if self.processes > 1:\n self.processes -= 1",
"def AddParallelismFlag(parser):\n parser.add_argument(\n '--parallelism',\n type=arg_parsers.BoundedInt(lower_bound=0),\n help=(\n 'Number of tasks that may run concurrently. Must be less than or'\n ' equal to the number of tasks. Set to 0 to unset.'\n ),\n )",
"def get_parallelism(self):\n return self._j_execution_environment.getParallelism()",
"def set_num_workers(self, num_workers):\n self.num_workers = num_workers",
"def test_parallel_thread_assignment_priority(self):\n\n # If we set all values to max test output\n # We intentionally set the max shot and experiment threads to\n # twice the max threads to check they are limited correctly\n for custom_max_threads in [0, 1, 2, 4]:\n opts = self.backend_options_parallel()\n opts['max_parallel_threads'] = custom_max_threads\n opts['max_parallel_experiments'] = 2 * custom_max_threads\n opts['max_parallel_shots'] = 2 * custom_max_threads\n\n # Calculate actual max threads from custom max and CPU number\n max_threads = self.available_threads()\n if custom_max_threads > 0:\n max_threads = min(max_threads, custom_max_threads)\n\n # Test single circuit, no noise\n # Parallel experiments and shots should always be 1\n result = execute(self.dummy_circuit(1),\n self.SIMULATOR,\n shots=10*max_threads,\n **opts).result()\n for threads in self.threads_used(result):\n target = {\n 'experiments': 1,\n 'shots': 1,\n 'state_update': max_threads,\n 'total': max_threads\n }\n self.assertEqual(threads, target)\n\n # Test single circuit, with noise\n # Parallel experiments should always be 1\n # parallel shots should be greater than 1\n result = execute(self.dummy_circuit(1),\n self.SIMULATOR,\n shots=10*max_threads,\n noise_model=self.dummy_noise_model(),\n **opts).result()\n for threads in self.threads_used(result):\n target = {\n 'experiments': 1,\n 'shots': max_threads,\n 'state_update': 1,\n 'total': max_threads\n }\n self.assertEqual(threads, target)\n\n # Test single circuit, with measure in middle, no noise\n # Parallel experiments should always be 1\n # parallel shots should be greater than 1\n result = execute(self.measure_in_middle_circuit(1),\n self.SIMULATOR,\n shots=10*max_threads,\n **opts).result()\n for threads in self.threads_used(result):\n target = {\n 'experiments': 1,\n 'shots': max_threads,\n 'state_update': 1,\n 'total': max_threads\n }\n self.assertEqual(threads, target)\n\n # Test multiple circuit, no noise\n # Parallel experiments always be greater than 1\n # parallel shots should always be 1\n result = execute(max_threads*[self.dummy_circuit(1)],\n self.SIMULATOR,\n shots=10*max_threads,\n **opts).result()\n for threads in self.threads_used(result):\n target = {\n 'experiments': max_threads,\n 'shots': 1,\n 'state_update': 1,\n 'total': max_threads\n }\n self.assertEqual(threads, target)\n\n # Test multiple circuits, with noise\n # Parallel experiments always be greater than 1\n # parallel shots should always be 1\n result = execute(max_threads*[self.dummy_circuit(1)],\n self.SIMULATOR,\n shots=10*max_threads,\n noise_model=self.dummy_noise_model(),\n **opts).result()\n for threads in self.threads_used(result):\n target = {\n 'experiments': max_threads,\n 'shots': 1,\n 'state_update': 1,\n 'total': max_threads\n }\n self.assertEqual(threads, target)\n\n # Test multiple circuit, with measure in middle, no noise\n # Parallel experiments always be greater than 1\n # parallel shots should always be 1\n result = execute(max_threads*[self.measure_in_middle_circuit(1)],\n self.SIMULATOR,\n shots=10*max_threads,\n noise_model=self.dummy_noise_model(),\n **opts).result()\n for threads in self.threads_used(result):\n target = {\n 'experiments': max_threads,\n 'shots': 1,\n 'state_update': 1,\n 'total': max_threads\n }\n self.assertEqual(threads, target)",
"def setMultiProcessing(self, flag=True, full_copy=False, max_processes=None):\n self.multiProcessing = (flag, full_copy, max_processes)",
"def set_workers(self, n):\n self.stop_workers()\n self._workers = n\n if n is None:\n while self._updates:\n self._updates.get()\n else:\n self.setup_workers()",
"def test_parallel_experiment_thread_assignment(self):\n\n max_threads = self.available_threads()\n opts = self.backend_options_parallel(exp_threads=max_threads)\n\n # Test single circuit\n # Parallel experiments and shots should always be 1\n result = execute(self.dummy_circuit(1),\n self.SIMULATOR,\n shots=10*max_threads,\n **opts).result()\n for threads in self.threads_used(result):\n target = {\n 'experiments': 1,\n 'shots': 1,\n 'state_update': max_threads,\n 'total': max_threads\n }\n self.assertEqual(threads, target)\n\n # Test multiple circuit, no noise\n # Parallel experiments should take priority\n result = execute(max_threads*[self.dummy_circuit(1)],\n self.SIMULATOR,\n shots=10*max_threads,\n **opts).result()\n for threads in self.threads_used(result):\n target = {\n 'experiments': max_threads,\n 'shots': 1,\n 'state_update': 1,\n 'total': max_threads\n }\n self.assertEqual(threads, target)\n\n # Test multiple circuits, with noise\n # Parallel experiments should take priority\n result = execute(max_threads*[self.dummy_circuit(1)],\n self.SIMULATOR,\n shots=10*max_threads,\n noise_model=self.dummy_noise_model(),\n **opts).result()\n for threads in self.threads_used(result):\n target = {\n 'experiments': max_threads,\n 'shots': 1,\n 'state_update': 1,\n 'total': max_threads\n }\n self.assertEqual(threads, target)\n\n # Test multiple circuit, with measure in middle, no noise\n # Parallel experiments should take priority\n result = execute(max_threads*[self.measure_in_middle_circuit(1)],\n self.SIMULATOR,\n shots=10*max_threads,\n noise_model=self.dummy_noise_model(),\n **opts).result()\n for threads in self.threads_used(result):\n target = {\n 'experiments': max_threads,\n 'shots': 1,\n 'state_update': 1,\n 'total': max_threads\n }\n self.assertEqual(threads, target)\n\n # Test multiple circuits, with memory limitation\n # NOTE: this assumes execution on statevector simulator\n # which required approx 2 MB for 16 qubit circuit.\n opts['max_memory_mb'] = 1\n circuit = QuantumVolume(16, 1, seed=0)\n circuit.measure_all()\n result = execute(2 * [circuit],\n self.SIMULATOR,\n shots=10*max_threads,\n **opts).result()\n for threads in self.threads_used(result):\n target = {\n 'experiments': 1,\n 'shots': 1,\n 'state_update': max_threads,\n 'total': max_threads\n }\n self.assertEqual(threads, target)",
"def set_NumberOfIterations(self,NumberOfIterations):\n self.NumberOfIterations = NumberOfIterations",
"def backend_options_parallel(self,\n total_threads=None,\n state_threads=None,\n shot_threads=None,\n exp_threads=None):\n opts = self.BACKEND_OPTS.copy()\n if total_threads:\n opts['max_parallel_threads'] = total_threads\n else:\n opts['max_parallel_threads'] = 0\n if shot_threads:\n opts['max_parallel_shots'] = shot_threads\n if state_threads:\n opts['max_parallel_state_update'] = state_threads\n if exp_threads:\n opts['max_parallel_experiments'] = exp_threads\n return opts"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Util func to check if the object is a FunctionBuilder
|
def isFunctionBuilder(obj):
if isclass(obj) and not isabstract(obj):
return issubclass(obj, FunctionBuilder)
return False
|
[
"def _isScoringFunction(obj):\n if inspect.isclass(obj):\n if callable(obj):\n sig = inspect.getfullargspec(obj.__call__)\n if len(sig.args) == 2:\n if \"return\" in sig.annotations and 'smiles' in sig.annotations:\n if sig.annotations['return'] == dict and sig.annotations['smiles'] == List[str]:\n return True\n return False",
"def takes_arg(obj, arg: str) -> bool:\n if inspect.isclass(obj):\n signature = inspect.signature(obj.__init__)\n elif inspect.ismethod(obj) or inspect.isfunction(obj):\n signature = inspect.signature(obj)\n else:\n raise ConfigureError(f\"object {obj} is not callable\")\n return arg in signature.parameters",
"def is_callable(obj):\n # __call__\n return hasattr(obj, '__call__')",
"def test_callability():\n the_list = l.function_builder(4)\n for func in the_list:\n assert hasattr(func, '__call__')",
"def is_function(self):\n if self.is_instance() or self.is_class(): return False\n return isinstance(self.callback, (Callable, classmethod))",
"def is_top_level_function(obj: Any) -> bool:\n return callable(obj) and obj.__name__ in sys.modules[obj.__module__].__dict__",
"def check_function(self) -> None:\n if not isinstance(self, FunctionType):\n raise UnexpectedTypeError(FunctionType, self)",
"def is_decorated_with_inject(function: Callable[..., Any]) -> bool:\n return hasattr(function, '__bindings__')",
"def is_callable(obj):\n if not callable(obj):\n # Check is to help distinguish between sopel callables and objects\n # which just happen to have parameter commands or rule.\n return False\n if (hasattr(obj, 'commands') or\n hasattr(obj, 'rule') or\n hasattr(obj, 'interval')):\n return True\n return False",
"def is_function(f):\n return isinstance(f, (types.FunctionType, functools.partial))",
"def IsConstructor(self) -> bool:",
"def is_builtin_object(node: astroid.node_classes.NodeNG) -> bool:\n return node and node.root().name == BUILTINS_NAME",
"def is_obj(o):\n return o[0] == 'object'",
"def is_instance(self):\n ret = False\n val = self.callback\n if self.is_class(): return False\n\n ret = not inspect.isfunction(val) and not inspect.ismethod(val)\n# if is_py2:\n# ret = isinstance(val, types.InstanceType) or hasattr(val, '__dict__') \\\n# and not (hasattr(val, 'func_name') or hasattr(val, 'im_func'))\n# \n# else:\n# ret = not inspect.isfunction(val) and not inspect.ismethod(val)\n\n return ret",
"def _isclass(obj):\r\n if sys.version_info < (2, 7):\r\n return isinstance(obj, (type, types.ClassType))\r\n else:\r\n return inspect.isclass(obj)",
"def _is_method_of(func_name, class_object):\n\tattr = getattr(class_object, func_name, None)\n\tif attr is None:\n\t\treturn False\n\telse:\n\t\treturn inspect.ismethod(attr)",
"def is_object(t):\n return t.get_types() == (object,)",
"def hasarg(func, arg):\n return arg in signature(func).parameters",
"def convertable(obj, func):\n\n try:\n func(obj)\n return True\n except ValueError:\n return False"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Create a dictionary of all functions from a dictionary (or configparser).
|
def create_function_dict(self, conf):
all_funcs = process_args(conf,
factory=self,
str_keys=['type', 'path'])
funcs_dict = {}
for k, v in all_funcs.items():
if isinstance(v, dict):
f_type = v.pop('type')
funcs_dict[k.lower()] = self.create_function(f_type, **v)
else:
funcs_dict[k.lower()] = v
return funcs_dict
|
[
"def import_parser_funcs(self):\n self.business_configs['funcs'] = {}\n for business_function, values in self.business_configs.items():\n try:\n if business_function == 'funcs':\n continue\n modname, funcname = values['parser'].rsplit('.', 1)\n # mod = importlib.import_module(f'..{modname}', package=f'parser_scripts.{modname.split(\".\")[0]}')\n mod = importlib.import_module(modname)\n func = getattr(mod, funcname)\n self.business_configs['funcs'][business_function] = func\n except ModuleNotFoundError as exc:\n basiclogger.error(exc.__repr__())\n except Exception as exc:\n basiclogger.error(exc.__repr__())",
"def convert_functions_in_dict_to_values(dict_to_convert):\n return {key: value() if hasattr(value, '__call__') else value for key, value in dict_to_convert.items()}",
"def func_store_list() -> dict:\n functions_dict = {\n o[0]: o[1] for o in getmembers(knowledge_horizons) if isfunction(o[1])\n }\n return functions_dict",
"def MakeFunctionMap():\r\n\treturn ExtendFunctionMap({})",
"def get_functions_dictionary():\n return {\n 'tfidf': extract_tf_idf,\n 'post_length': extract_post_length,\n 'topics': extract_topics,\n 'screamer': extract_screamer,\n 'words': extract_meaningful_words_existence,\n 'off_dis': extract_distance_from_offensive,\n 'not_off_dis': extract_distance_from_not_offensive,\n 'wmd_off': extract_wmd_offensive,\n 'wmd_not_off': extract_wmd_not_offensive,\n 'dis_avg_vec': extract_distance_from_avg_vector\n }",
"def config_by_dictionary(cfg_data):\n for handler in cfg_data.keys():\n args = cfg_data.get(handler)\n func = xtlog_cfg_function_map.get(handler)\n if func is not None:\n func(**args)",
"def _get_module_funcs(mod) -> Dict[str, Callable]:\n return dict(member for member in getmembers(mod, isfunction))",
"def map( # pylint: disable=redefined-builtin\n fn: Callable[[str, str, InT], OutT],\n structure: Mapping[str, Mapping[str, InT]],\n) -> Mapping[str, Mapping[str, OutT]]:\n out = collections.defaultdict(dict)\n for module_name, name, value in traverse(structure):\n out[module_name][name] = fn(module_name, name, value)\n return data_structures.to_haiku_dict(out)",
"def process_function(func):\n\n ruleset = parse(func.__doc__, fname=func.__name__)\n expanded = expand_optionals(ruleset, format=False)\n\n ret = {}\n i = 0\n for rule in expanded:\n ret['p_%s_%s' % (func.__name__, i)] = create_wrapper(rule, func)\n i += 1\n return ret",
"def modifiyItems(dic, keyFunction, valueFunction):\n return {keyFunction(key, value): valueFunction(key, value) for key, value in dic.items()}",
"def conv():\n conv_map = {}\n for name, code in getmembers(converters):\n if isfunction(code):\n conv_map[name] = code\n return conv_map",
"def parse_anotations():\n \n functions = {}\n function = None\n \n for line in open(__file__, 'rt').readlines():\n # Stop?\n if '='*40 in line:\n break\n \n if line.startswith('def '):\n name = line.split(' ')[1].split('(')[0]\n args = line.split('(')[1].split(')')[0].split(', ')\n args = [arg for arg in args if arg]\n out = line.partition('->')[2].strip()\n function = FunctionAnnotation(name, args, out)\n functions[name] = function\n continue\n elif not function:\n continue\n \n # Add line\n line = line.rstrip()\n indent = len(line) - len(line.strip())\n if line.strip() and indent >=4:\n function.lines.append(line)\n\n return functions",
"def data_info_factory(names, funcs):\n\n def func(dat):\n outs = []\n for name, func in zip(names, funcs):\n try:\n if isinstance(func, str):\n out = getattr(dat, func)()\n else:\n out = func(dat)\n except Exception:\n outs.append(\"--\")\n else:\n try:\n outs.append(f\"{out:g}\")\n except (TypeError, ValueError):\n outs.append(str(out))\n\n return OrderedDict(zip(names, outs))\n\n return func",
"def map_values(function, dictionary):\n return dict((k, function(dictionary[k])) for k in dictionary)",
"def dump_functions(self):\n funcs = {}\n for i in xrange(16):\n funcs[i] = self.dump_function(i)\n return funcs",
"def map(self, func):\n return dict((k, func(n)) for k, n in self.items())",
"def get_function_mapper():\n num_events_to_subscribe_to = random.randint(0, len(events))\n mapper = {}\n random.shuffle(events)\n for x in range(0, num_events_to_subscribe_to):\n mapper.update({events[x]: {\"module\": \"example\", \"method\": events[x]}})\n return mapper",
"def __getstate__(self):\n return {k: self.__dict__[k] if k != \"feature_functions_\" else {} for k in self.__dict__}",
"def module_functions(func_prefix, module=None):\n r = PKDict()\n for n, o in inspect.getmembers(module or caller_module(exclude_first=False)):\n if n.startswith(func_prefix) and inspect.isfunction(o):\n r[n] = o\n return r"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Add KafkaManagerrelated commandline arguments to the given parser.
|
def add_cli_arguments(self, parser):
super(Application, self).add_cli_arguments(parser)
add_kafka_manager_api_cli_arguments(parser)
|
[
"def add_custom_cli_args(self, cli_parser):\n pass",
"def add_cmdline_args(parser):\n group = parser.add_argument_group(\"Model\")\n\n # Model\n group.add_argument(\"--model\", type=str, required=True)\n\n # Config\n group.add_argument(\"--config_path\", type=str, required=True)\n\n # Model related.\n args, _ = parser.parse_known_args()\n if args.model not in MODEL_REGISTRY:\n raise ValueError(f\"Unknown model type: {args.model}\")\n MODEL_REGISTRY[args.model].add_cmdline_args(parser)\n return group",
"def add_arguments(self, parser):\r\n parser.add_argument(\"digcoll_retriever_host\",\r\n help=\"The host of the digcoll_retriever\"),\r\n parser.add_argument(\"project_api\",\r\n help=\"\", type=str)\r\n parser.add_argument(\"import_data_file\",\r\n help=\"An identifier for a particular MVol issue\", type=str)",
"def add_arguments(self, parser):\n parser.add_argument(\n \"--datetime\",\n action=\"store\",\n help=\"ISO datetime used for calculating eligibility. Defaults to now. Currently only used for backdating command runs in tests.\",\n )\n parser.add_argument(\n \"--global_userinfo\",\n action=\"store\",\n help=\"specify Wikipedia global_userinfo data. Defaults to fetching live data. Currently only used for faking command runs in tests.\",\n )",
"def add_args(parser):\n # fmt: off\n parser.add_argument('--varscale-beta', default=0.9, type=float,\n help='betas for LaProp optimizer')\n parser.add_argument('--momentum', default=0.9, type=float, metavar='WD',\n help='weight decay')\n parser.add_argument('--beta-min', default=0.5, type=float, metavar='WD',\n help='weight decay')\n parser.add_argument('--varscale-eps', type=float, default=1e-15, metavar='D',\n help='epsilon for LaProp optimizer')\n parser.add_argument('--weight-decay', '--wd', default=0.0, type=float, metavar='WD',\n help='weight decay')\n parser.add_argument('--use-adam', default=False, action=\"store_true\")\n parser.add_argument('--eps-schedule', default=False, action=\"store_true\")\n parser.add_argument('--nesterov', default=False, action=\"store_true\")\n # fmt: on",
"def _init_args(self):\r\n \r\n self.argparser = ArgumentParser(prog=':%s' % self.name, description = self.__doc__, add_help=False)",
"def add_arguments(self, parser):\n parser.add_argument('start_index', type=int)",
"def register_arguments(parser):\n pass",
"def add_simple_args(self):\n self.ctrl_parser.add_argument(\"-V\", \"--version\", action=\"version\", version='0.1.0',\n help='Provides the version of the tool')\n self.ctrl_parser.add_argument(\"-v\", \"--verbosity\", action=\"count\", help=\"increase output verbosity\")\n self.ctrl_parser.add_argument(\"-i\", action=InteractiveCli, nargs=0, help=\"Start in interactive mode\")\n self.ctrl_parser.add_argument(\"-t\", \"--timeout\", type=float,\n help=\"Provides a timeout for the command\")",
"def add_opts(self, optparser):\n return",
"def run_parser(self, parser: ArgumentParser):",
"def _apply_global_arguments(parser):\n for arg in _global_arguments:\n arg.add_to(parser)",
"def setup_args():\n parser = ParlaiParser(False, False)\n parser_grp = parser.add_argument_group('Browser Chat')\n parser_grp.add_argument(\n '--port', default=35496, type=int, help='Port used by the web socket (run.py)'\n )\n parser_grp.add_argument(\n '--host',\n default='0.0.0.0',\n type=str,\n help='Host from which allow requests, use 0.0.0.0 to allow all IPs',\n )\n parser_grp.add_argument(\n '--serving_port',\n default=8080,\n type=int,\n help='Port used to configure the server',\n )\n\n return parser.parse_args()",
"def add_core_options(parser):\n parser.add_option(\"-d\", \"--directory\", dest=\"directory\",\n default=getcwd(),\n help=\"directory from which to load configuration [default: %default]\")\n\n parser.add_option(\"-e\", \"--environment\", dest=\"environment\",\n default=\"local\",\n help=\"environment to operate on [default: %default]\")\n\n parser.add_option(\"-H\", \"--hosts\", dest=\"hosts\",\n default=\"\",\n help=\"comma-separated list of hosts to operate on\")\n\n parser.add_option(\"-q\", \"--quiet\", dest=\"quiet\",\n action=\"store_true\",\n default=False,\n help=\"minimize output verbosity\")\n\n parser.add_option(\"-R\", \"--roles\", dest=\"roles\",\n default=\"\",\n help=\"comma-separated list of roles to operate on\")\n\n parser.add_option(\"-v\", \"--verbose\", dest=\"verbosity\",\n action=\"count\",\n default=0,\n help=\"control confab verbosity; by default, confab suppresses\"\n \"most output. Additional -v flags increase verbosity.\")",
"def setup_argparser() -> argparse.ArgumentParser:\n argp = argparse.ArgumentParser()\n add_setup_options(argp)\n return argp",
"def setInitialArguments(self):\r\n self.argparse.add_argument(\r\n '-s', '--start-dir', default=None,\r\n help=\"Directory to start discovery ('.' default)\")\r\n self.argparse.add_argument(\r\n '-t', '--top-level-directory', '--project-directory',\r\n help='Top level directory of project (defaults to start dir)')\r\n self.argparse.add_argument(\r\n '--config', '-c', nargs='?', action='append',\r\n default=['unittest.cfg', 'nose2.cfg'],\r\n help=\"Config files to load, if they exist. ('unittest.cfg' \"\r\n \"and 'nose2.cfg' in start directory default)\")\r\n self.argparse.add_argument(\r\n '--no-user-config', action='store_const',\r\n dest='user_config', const=False, default=True,\r\n help=\"Do not load user config files\")\r\n self.argparse.add_argument(\r\n '--no-plugins', action='store_const',\r\n dest='load_plugins', const=False, default=True,\r\n help=\"Do not load any plugins. Warning: nose2 does not \"\r\n \"do anything if no plugins are loaded\")\r\n self.argparse.add_argument(\r\n '--plugin', action='append',\r\n dest='plugins', default=[],\r\n help=\"Load this plugin module.\")\r\n self.argparse.add_argument(\r\n '--exclude-plugin', action='append',\r\n dest='exclude_plugins', default=[],\r\n help=\"Do not load this plugin module\")\r\n self.argparse.add_argument(\r\n '--verbose', '-v', action='count', default=0, help=\"print test case names and statuses\")\r\n self.argparse.add_argument('--quiet', action='store_const',\r\n dest='verbose', const=0)\r\n self.argparse.add_argument(\r\n '--log-level', default=logging.WARN,\r\n help='Set logging level for message logged to console.')",
"def option_manager(self, manager):\n group = manager.parser.add_argument_group('FlakeHell')\n group.add_argument('--baseline', help='path to baseline')\n group.add_argument('--safe', action='store_true', help='suppress exceptions from plugins')\n self._option_manager = manager",
"def _add_standard_args(parser: ArgumentParser) -> None:\r\n parser.add_argument(\r\n '--username',\r\n required=True,\r\n action=EnvDefault,\r\n envvar='ZFR_USERNAME',\r\n help='Username used to login to Zephyr Scale.'\r\n )\r\n parser.add_argument(\r\n '--password',\r\n required=True,\r\n action=EnvDefault,\r\n envvar='ZFR_PASSWORD',\r\n help='Password used to login to Zephyr Scale.'\r\n )\r\n parser.add_argument(\r\n '--url',\r\n required=True,\r\n action=EnvDefault,\r\n envvar='ZFR_URL',\r\n help='Jira url used to interace with the Zephyr API.'\r\n )\r\n parser.set_defaults(cmd=PlanCommand(parser))",
"def setup(cls, subparser):\n # creates the parser for options\n parser = subparser.add_parser(cls.__command__, help=cls.__help__)\n\n # adds the arguments\n cls.args(parser)\n\n # sets the default function to invoke\n parser.set_defaults(func=cls.run)\n cls._parser = parser"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Scrape access request data from the access request page for the specified request status.
|
def get_request_data(self, status: RequestStatus = RequestStatus.ALL) -> List[dict]:
SEE_MORE_BTN_XPATH = "//a[text()='See More']"
# filter page to only include requests of the given status
self._browser.click_element_by_xpath(self._status_btn_xpath(status))
self._browser.wait_until_element_is_clickable_by_xpath(
"//*[@class='table manage-table']/tbody/tr[1]/td[1]")
# load all requests of the given status onto the page
total_requests = sum(map(int, self._browser.get_elements_attribute_by_xpath(
"//div[@class='panel panel-default']//a/span[@class='badge' and text()!='0']", "text")))
pages_to_load = int(math.floor(total_requests / 25))
# account for apparent load limit on Handshake's servers
if pages_to_load > 69:
pages_to_load = 69
for i in range(pages_to_load): # click "See More" btn until all rows loaded
self._browser.wait_until_element_exists_by_xpath(SEE_MORE_BTN_XPATH)
self._browser.click_element_by_xpath(SEE_MORE_BTN_XPATH)
time.sleep(2) # wait for final set of names to finish loading before scraping
# scrape request data from page
request_data = []
student_rows = BeautifulSoup(
self._browser.get_element_attribute_by_xpath("//tbody", "innerHTML"),
'html.parser').find_all('tr')
for row in student_rows:
user = row.find('td', {'class': 'requester_name'}).find('a').text
user_id_link = row.find('td', {'class': 'requester_name'}).find('a')['href']
user_id = re.findall(r'([0-9]+)', user_id_link)[0]
date_str = row.find('td', {'class': 'request_date'}).find('a').text
date_str = re.sub(r'(\d)(st|nd|rd|th)', r'\1', date_str)
data_row = {
'user': user,
'user_id': user_id,
'email': row.find('td', {'class': 'requester_email'}).find('a').text,
'request_date': datetime.strptime(date_str, '%B %d %Y').date(),
'request': row.find('td', {'class': 'request'}).find('a').text,
'status': row.find('td', {'class': 'status'}).find('span').text
}
request_data.append(data_row)
return request_data
|
[
"async def access_details_handler(request: aiohttp.web.Request) -> aiohttp.web.Response:\n access_details = {}\n access_details = await request.app[\"db_conn\"].get_access_container_details(\n request.match_info[\"user\"],\n request.query[\"owner\"],\n request.match_info[\"container\"],\n )\n\n MODULE_LOGGER.log(\n logging.DEBUG, \"Returning following access details: %s\", str(access_details)\n )\n\n return aiohttp.web.json_response(access_details)",
"async def has_access_handler(request: aiohttp.web.Request) -> aiohttp.web.Response:\n access_list = []\n access_list = await request.app[\"db_conn\"].get_access_list(request.match_info[\"user\"])\n\n MODULE_LOGGER.log(\n logging.DEBUG, \"Returning following access list: %s\", str(access_list)\n )\n\n return aiohttp.web.json_response(access_list)",
"def process_request(self, request):\n\n request.access_token = None\n request.whoami_url = ''\n request.view_requests = []\n\n if request.COOKIES.has_key('access_token'):\n # Clean up empty access token.\n if request.COOKIES['access_token'] == '':\n response = HttpResponseRedirect('/')\n response.set_cookie('access_token', '', expires=\"Thu, 01 Jan 1970 00:00:00 GMT\")\n return response\n request.access_token = request.COOKIES['access_token']\n request.whoami_url, params, headers = WhoAmI.build_request(request.get_host(), request.access_token)\n request.view_requests.append(grequests.get(request.whoami_url, params=params, headers=headers))\n newrelic.agent.add_custom_parameter('access_token', request.access_token[:6])\n\n request.site_url, params, headers = Site.build_request(request.get_host())\n request.view_requests.append(grequests.get(request.site_url, params=params, headers=headers))",
"def process_request(self, request):\n\n request.access_token = None\n request.delete_token = False\n request.whoami = None\n request.site = None\n request.create_profile = False\n\n if request.COOKIES.has_key('access_token'):\n request.access_token = request.COOKIES['access_token']\n\n # if a bad access token is provided, flag for deletion\n try:\n request.whoami = WhoAmI.retrieve(request.META['HTTP_HOST'], request.access_token)\n except APIException, e:\n if e.status_code == 401:\n request.delete_token = True\n\n try:\n request.site = Site.retrieve(request.META['HTTP_HOST'])\n except APIException, e:\n logger.error(e.message)\n except RequestException, e:\n logger.error(e.message)\n\n return None",
"def process_cleared_requests(msg):\n \"\"\"\n This is the HTTP response message with \n\n HTTP/1.0 200 OK --- status line [index 0]\n Content-Type:Application/json -- headers [index 1]\n Content-Length:2\n Host:127.0.0.1\n Date:2019-04-21 00:51:56.592347\n User-Agent:Custom HTTP endpoint written for CSE5306 lab [index 5]\n [index 6]\n [[\"get/cleared/requests\"], [\"sss\", \"ccc\", true]] actual data [index 7]\n \"\"\"\n # see above that index 7 is the line we care about\n msg = msg.split(\"\\n\")\n response_body = msg[7]\n import json\n\n clearance_requests = json.loads(response_body)\n # if there's more than one entry, we have some data to process\n if len(clearance_requests) > 1:\n # start from entry 2 as first entry is dummy entry\n clearance_requests = clearance_requests[1:]\n\n for request in clearance_requests:\n if request[2]:\n status = \"Approved\"\n else:\n status = \"Rejected\"\n # show approval status in UI\n add_msg_to_scrollbox(\n \"Student name {} \\nCourse Requested: {} \\nAdvisor Decision: {}\\n\".format(\n request[0], request[1], status\n )\n )\n else:\n add_msg_to_scrollbox(\"No message found\\n\")",
"def parse_overview_page1(self, response):\n\t\tcomm = response.meta['comm'] # the private/commercial indicator\n\t\t#cityid = response.meta['cityid'] # the id of the city of which we look for the ads (as string)\n\t\t# find the number of pages in total and open all other pages from 1,...,last page\n\t\tif len(response.xpath('//li[@class=\"pageno\"]/a[@class=\"nothing\"]/strong')) > 1:\n\t\t\tnumpages = int(response.xpath('//li[@class=\"pageno\"]/a[@class=\"nothing\"]/strong[2]/text()').extract()[0])\n\t\t\tfor pageno in xrange(1,numpages+1):\n\t\t\t\t# we have to re-post our form for the filter settings\n\t\t\t\t#request = FormRequest.from_response(response, formdata={'classtype': 'of', 'comm': str(comm), 'pageno': str(pageno), 'cityid': cityid},\n\t\t\t\t#\t\t\t\t\t\t\t\t\tcallback=self.parse_overview_page2)\n\t\t\t\trequest = FormRequest.from_response(response, formdata={'classtype': 'of', 'comm': str(comm), 'pageno': str(pageno)},\n\t\t\t\t\t\t\t\t\t\t\t\t\tcallback=self.parse_overview_page2)\n\t\t\t\trequest.meta['comm'] = comm\n\t\t\t\tyield request\n\t\t\t\t# find the immoscout ads for this site\n\t\t\t\trequest = scrapy.Request('http://www.quoka.de/qs/qpc/xmlSearch.php?search=&view=quoka&platform=desktop&catid=27_2710&maxresults=20&page=' +str(pageno)+\n\t\t\t\t\t\t\t\t\t\t'&output=json&oe=UTF-8', callback=self.parse_immoscout)\n\t\t\t\trequest.meta['comm'] = comm\n\t\t\t\tyield request\n\t\telse:\n\t\t\t# in this case there is no \"Seite 1 von n\", so we simply scrape this page\n\t\t\trequest = scrapy.Request(response.url, callback=self.parse_overview_page2)\n\t\t\trequest.meta['comm'] = comm\n\t\t\tyield request",
"def at_access(self, result, accessing_obj, access_type, **kwargs):\r\n pass",
"def process_request(self, request):\n\n request.access_token = None\n request.whoami_url = ''\n request.view_requests = []\n request.site = None\n\n if request.COOKIES.has_key('access_token'):\n request.access_token = request.COOKIES['access_token']\n url, params, headers = WhoAmI.build_request(request.get_host(), request.access_token)\n request.view_requests.append(grequests.get(url, params=params, headers=headers))\n request.whoami_url = url\n\n try:\n request.site = Site.retrieve(request.get_host())\n except APIException as e:\n if e.status_code == 400:\n return HttpResponseRedirect('https://microco.sm')\n return None",
"def has_user_requested_access(self, access_requests):\n\n # TODO UPDATE THIS FOR NEW METHOD OF REQUESTING ACCESS...\n # ...\n\n return False",
"def _get_data(self):\n json_data = url_to_json(\"http://10.16.20.100:8080/api/search/?q=%s\" % self.username)\n\n for review in json_data[\"search\"][\"reviews\"]:\n if review[\"ship_it\"] is True:\n self.shipits_given.append(review)\n\n for shipit_received in json_data[\"search\"][\"shipits_received\"]:\n self.shipits_recv.append(shipit_received)\n\n self.response_results = json_data[\"search\"][\"response_results\"]\n self.bug_list = json_data",
"def getAssignmentMethod(request):\n try:\n profileId = ndb.Key(urlsafe=getattr(request, 'profileId'))\n except Exception, E:\n print str(E)\n return GetAssignmentResponse(response=1, description=str(E))\n try:\n assignmentId = ndb.Key(urlsafe=getattr(request, 'assignmentId'))\n except Exception, E:\n print str(E)\n return GetAssignmentResponse(response=1, description=str(E))\n\n # to add the views in crons\n assignmentOpened.add(assignmentId.urlsafe())\n\n # fetching from memcache\n cacheVal = memcache.get(assignmentId.urlsafe())\n memViews = memcache.get('views' + assignmentId.urlsafe())\n if cacheVal is not None:\n # if the current user is author\n if profileId == cacheVal[8]:\n isAuthor = 1\n else:\n isAuthor = 0\n if memViews is None:\n assignment = assignmentId.get()\n if assignment is None:\n print \"Invalid assignmentId\"\n return GetAssignmentResponse(response=1, description=\"Invalid assignmentId\")\n memViews = assignment.assignmentViews\n memcache.add('views' + assignmentId.urlsafe(), memViews, 86400)\n if isAuthor == 0:\n memcache.incr('views' + assignmentId.urlsafe())\n coursePage = memcache.get(cacheVal[9])\n if coursePage is not None:\n if assignmentId.urlsafe() in coursePage[8]:\n idx = coursePage[8].index(assignmentId.urlsafe())\n coursePage[8][idx].views += 1\n memcache.set(cacheVal[9], coursePage)\n views = memcache.get('views' + assignmentId.urlsafe())\n return GetAssignmentResponse(response=0, description=\"OK\",\n isAuthor=isAuthor,\n assignmentTitle=cacheVal[0],\n assignmentDesc=cacheVal[1],\n lastUpdated=cacheVal[2],\n uploaderName=cacheVal[3],\n dueDate=cacheVal[4],\n dueTime=cacheVal[5],\n urlList=cacheVal[6],\n courseName=cacheVal[7],\n views=views)\n assignment = assignmentId.get()\n if assignment is None:\n print \"Invalid assignmentId\"\n return GetAssignmentResponse(response=1, description=\"Invalid assignmentId\")\n if profileId == assignment.uploaderId:\n isAuthor = 1\n else:\n isAuthor = 0\n uploaderName = assignment.uploaderId.get().profileName\n course = assignment.courseId.get()\n assignment.put()\n fields = [assignment.assignmentTitle, assignment.assignmentDesc, assignment.dateUploaded,\n uploaderName, assignment.dueDate, assignment.dueTime, assignment.urlList,\n course.courseName, assignment.uploaderId, assignment.courseId.urlsafe()]\n memcache.add(assignmentId.urlsafe(), fields, 86400)\n if memcache.get('views' + assignmentId.urlsafe()) is None:\n if isAuthor == 0:\n memcache.add('views' + assignmentId.urlsafe(), assignment.assignmentViews + 1, 86400)\n else:\n memcache.add('views' + assignmentId.urlsafe(), assignment.assignmentViews, 86400)\n else:\n if isAuthor == 0:\n memcache.incr('views' + assignmentId.urlsafe())\n views = memcache.get('views' + assignmentId.urlsafe())\n return GetAssignmentResponse(response=0, description=\"OK\",\n isAuthor=isAuthor,\n views=views,\n assignmentTitle=fields[0],\n assignmentDesc=fields[1],\n lastUpdated=fields[2],\n uploaderName=fields[3],\n dueDate=fields[4],\n dueTime=fields[5],\n urlList=fields[6],\n courseName=fields[7])",
"def process_request():\n\n with open('inlist.csv', 'r') as csvfile:\n file_read_lines = csv.reader(csvfile, delimiter=',')\n for row in file_read_lines:\n page = ', '.join(row[:1]) # getting first row from file\n logging.info(f'Take URL: {page}')\n\n try:\n response_desktop = psd.analyse(page, strategy='desktop')\n url = response_desktop.url\n except Exception as err:\n logging.info('Error to get response form google: ' + str(err))\n pass\n \n results = response_desktop.lighthouse_results\n audits_results = response_desktop.lighthouse_results_audits\n categories = response_desktop.categories\n\n # Total time page of load\n lighthouse_total_time_page_load = results.timing['total']\n total_time_page_load.labels(url).set(lighthouse_total_time_page_load)\n\n # Main Performance page score\n lighthouse_total_performance_score = categories.performance['score']\n performance_page_score.labels(url).set(lighthouse_total_performance_score)\n\n # Time to interactive metric\n lighthouse_time_to_interactive_score = audits_results.interactive['score']\n time_to_interactive.labels(url).set(lighthouse_time_to_interactive_score)\n\n try:\n lighthouse_time_to_interactive_display = audits_results.interactive['displayValue']\n display_value = re.match(r\"[0-9]+\\.*\\,*[0-9]*\", lighthouse_time_to_interactive_display)\n time_to_interactive_displayvalue.labels(url).set(float(display_value.group(0)))\n except Exception as err:\n logging.error(f'Time to interactive error: {str(err)}')\n time_to_interactive_displayvalue.labels(url).set(0)\n pass\n\n lighthouse_time_to_interactive_title = audits_results.interactive['title']\n lighthouse_time_to_interactive_description = audits_results.interactive['description']\n\n time_to_interactive_info.info({\n 'title': lighthouse_time_to_interactive_title,\n 'description': lighthouse_time_to_interactive_description,\n 'url': url\n })\n\n # speed index metric\n lighthouse_speed_index_score = audits_results.speed_index['score']\n speed_index.labels(url).set(lighthouse_speed_index_score)\n\n try:\n lighthouse_speed_index_display = audits_results.speed_index['displayValue']\n display_value = float(lighthouse_speed_index_display[:3])\n speed_index_displayvalue.labels(url).set(display_value)\n except Exception as err:\n logging.error(f'speed index error: {str(err)}')\n speed_index_displayvalue.labels(url).set(0)\n pass\n\n lighthouse_speed_index_title = audits_results.speed_index['title']\n lighthouse_speed_index_description = audits_results.speed_index['description']\n\n speed_index_info.info({\n 'title': lighthouse_speed_index_title,\n 'description': lighthouse_speed_index_description,\n 'url': url\n })\n\n # first cpu idle metric\n lighthouse_first_cpu_idle_score = audits_results.first_cpu_idle['score']\n first_cpu_idle_score.labels(url).set(lighthouse_first_cpu_idle_score)\n try:\n lighthouse_first_cpu_idle_display = audits_results.first_cpu_idle['displayValue']\n display_value = float(lighthouse_first_cpu_idle_display[:3])\n first_cpu_idle_score_displayvalue.labels(url).set(display_value)\n except Exception as err:\n logging.error(f'first_cpu_idle error: {str(err)}')\n first_cpu_idle_score_displayvalue.labels(url).set(0)\n pass\n\n lighthouse_first_cpu_idle_title = audits_results.first_cpu_idle['title']\n lighthouse_first_cpu_idle_description = audits_results.first_cpu_idle['description']\n\n first_cpu_idle_score_info.info({\n 'title': lighthouse_first_cpu_idle_title,\n 'description': lighthouse_first_cpu_idle_description,\n 'url': url\n })\n\n # mainthread work breakdown metric\n lighthouse_mainthread_work_breakdown_score = audits_results.mainthread_work_breakdown['score']\n mainthread_work_breakdown.labels(url).set(lighthouse_mainthread_work_breakdown_score)\n\n try:\n lighthouse_mainthread_work_breakdown_display = audits_results.mainthread_work_breakdown['displayValue']\n display_value = float(lighthouse_mainthread_work_breakdown_display[:3])\n mainthread_work_breakdown_displayvalue.labels(url).set(display_value)\n except Exception as err:\n logging.error(f'mainthread_work_breakdown error: {str(err)}')\n mainthread_work_breakdown_displayvalue.labels(url).set(0)\n pass\n\n lighthouse_mainthread_work_breakdown_title = audits_results.mainthread_work_breakdown['title']\n lighthouse_mainthread_work_breakdown_description = audits_results.mainthread_work_breakdown['description']\n\n mainthread_work_breakdown_info.info({\n 'title': lighthouse_mainthread_work_breakdown_title,\n 'description': lighthouse_mainthread_work_breakdown_description,\n 'url': url\n })\n\n # first contentful paint metric\n lighthouse_first_contentful_paint_score = audits_results.first_contentful_paint['score']\n first_contentful_paint.labels(url).set(lighthouse_first_contentful_paint_score)\n\n try:\n lighthouse_first_contentful_paint_display = audits_results.first_contentful_paint['displayValue']\n display_value = float(lighthouse_first_contentful_paint_display[:3])\n first_contentful_paint_displayvalue.labels(url).set(display_value)\n except Exception as err:\n logging.error(f'first_contentful_paint error: {str(err)}')\n first_contentful_paint_displayvalue.labels(url).set(0)\n pass\n\n lighthouse_first_contentful_paint_title = audits_results.first_contentful_paint['title']\n lighthouse_first_contentful_paint_description = audits_results.first_contentful_paint['description']\n\n first_contentful_paint_info.info({\n 'title': lighthouse_first_contentful_paint_title,\n 'description': lighthouse_first_contentful_paint_description,\n 'url': url\n })\n\n # first_meaningful_paint metric\n lighthouse_first_meaningful_paint_score = audits_results.first_meaningful_paint['score']\n first_meaningful_paint.labels(url).set(lighthouse_first_meaningful_paint_score)\n try:\n lighthouse_first_meaningful_paint_display = audits_results.first_meaningful_paint['displayValue']\n display_value = float(lighthouse_first_meaningful_paint_display[:3])\n first_meaningful_paint_displayvalue.labels(url).set(display_value)\n except Exception as err:\n logging.error(f'first_meaningful_paint error: {str(err)}')\n first_meaningful_paint_displayvalue.labels(url).set(0)\n pass\n\n lighthouse_first_meaningful_paint_title = audits_results.first_meaningful_paint['title']\n lighthouse_first_meaningful_paint_description = audits_results.first_meaningful_paint['description']\n\n first_meaningful_paint_info.info({\n 'title': lighthouse_first_meaningful_paint_title,\n 'description': lighthouse_first_meaningful_paint_description,\n 'url': url\n })\n\n # render_blocking_resources metric\n lighthouse_render_blocking_resources_score = audits_results.render_blocking_resources['score']\n render_blocking_resources.labels(url).set(lighthouse_render_blocking_resources_score)\n\n try:\n lighthouse_render_blocking_resources_display = audits_results.render_blocking_resources['displayValue']\n display_value = re.search(r\"[0-9]+\\.*\\,*[0-9]*\", lighthouse_render_blocking_resources_display)\n render_blocking_resources_displayvalue.labels(url).set(float(display_value.group(0)))\n except Exception as err:\n logging.error(f'network_server_latency error: {str(err)}')\n render_blocking_resources_displayvalue.labels(url).set(0)\n pass\n\n lighthouse_render_blocking_resources_overall = audits_results.render_blocking_resources['details']['overallSavingsMs']\n render_blocking_resources_overall.labels(url, 'overall', 'render_blocking_resources').set(lighthouse_render_blocking_resources_overall)\n\n lighthouse_render_blocking_resources_title = audits_results.render_blocking_resources['title']\n lighthouse_render_blocking_resources_description = audits_results.render_blocking_resources['description']\n\n render_blocking_resources_info.info({\n 'title': lighthouse_render_blocking_resources_title,\n 'description': lighthouse_render_blocking_resources_description,\n 'url': url\n })\n\n # uses_text_compression metric\n lighthouse_uses_text_compression_score = audits_results.uses_text_compression['score']\n uses_text_compression.labels(url).set(lighthouse_uses_text_compression_score)\n\n # lighthouse_uses_text_compression_display = audits_results.uses_text_compression['displayValue']\n # display_value = lighthouse_uses_text_compression_display\n # uses_text_compression_displayvalue.labels(url, display_value) # no metric\n\n lighthouse_uses_text_compression_overall = audits_results.uses_text_compression['details']['overallSavingsMs']\n uses_text_compression_overall.labels(url, 'overall', 'uses_text_compression').set(lighthouse_uses_text_compression_overall)\n\n lighthouse_uses_text_compression_title = audits_results.uses_text_compression['title']\n lighthouse_uses_text_compression_description = audits_results.uses_text_compression['description']\n\n uses_text_compression_info.info({\n 'title': lighthouse_uses_text_compression_title,\n 'description': lighthouse_uses_text_compression_description,\n 'url': url\n })\n\n # uses_optimized_images metric\n lighthouse_uses_optimized_images_score = audits_results.uses_optimized_images['score']\n uses_optimized_images.labels(url).set(lighthouse_uses_optimized_images_score)\n\n # lighthouse_uses_text_compression_display = audits_results.uses_text_compression['displayValue']\n # display_value = lighthouse_uses_text_compression_display\n # uses_text_compression_displayvalue.labels(url, display_value) #no metric\n\n lighthouse_uses_optimized_images_overall = audits_results.uses_optimized_images['details']['overallSavingsMs']\n uses_optimized_images_overall.labels(url, 'overall', 'uses_optimized_images').set(lighthouse_uses_optimized_images_overall)\n\n lighthouse_uses_optimized_images_title = audits_results.uses_optimized_images['title']\n lighthouse_uses_optimized_images_description = audits_results.uses_optimized_images['description']\n\n uses_optimized_images_info.info({\n 'title': lighthouse_uses_optimized_images_title,\n 'description': lighthouse_uses_optimized_images_description,\n 'url': url\n })\n\n # uses_long_cache_ttl metric\n lighthouse_uses_long_cache_ttl_score = audits_results.uses_long_cache_ttl['score']\n uses_long_cache_ttl.labels(url).set(lighthouse_uses_long_cache_ttl_score)\n\n try:\n lighthouse_uses_long_cache_ttl_display = audits_results.uses_long_cache_ttl['displayValue']\n display_value = re.match(r\"[0-9]+\\.*\\,*[0-9]*\", lighthouse_uses_long_cache_ttl_display)\n uses_long_cache_ttl_displayvalue.labels(url).set(float(display_value.group(0)))\n except Exception as err:\n logging.error(f'network_server_latency error: {str(err)}')\n uses_long_cache_ttl_displayvalue.labels(url).set(0)\n pass\n\n lighthouse_uses_long_cache_ttl_title = audits_results.uses_long_cache_ttl['title']\n lighthouse_uses_long_cache_ttl_description = audits_results.uses_long_cache_ttl['description']\n\n uses_long_cache_ttl_info.info({\n 'title': lighthouse_uses_long_cache_ttl_title,\n 'description': lighthouse_uses_long_cache_ttl_description,\n 'url': url\n })\n\n # max_potential_fid metric\n lighthouse_max_potential_fid_score = audits_results.max_potential_fid['score']\n max_potential_fid.labels(url).set(lighthouse_max_potential_fid_score)\n try:\n lighthouse_max_potential_fid_display = audits_results.max_potential_fid['displayValue']\n display_value = float(lighthouse_max_potential_fid_display[:3].replace(',','.'))\n max_potential_fid_displayvalue.labels(url).set(display_value)\n except Exception as err:\n logging.error(f'max_potential_fid err: {str(err)}')\n pass\n\n lighthouse_max_potential_fid_title = audits_results.max_potential_fid['title']\n lighthouse_max_potential_fid_description = audits_results.max_potential_fid['description']\n\n max_potential_fid_info.info({\n 'title': lighthouse_max_potential_fid_title,\n 'description': lighthouse_max_potential_fid_description,\n 'url': url\n })\n\n # total_blocking_time metric\n lighthouse_total_blocking_time_score = audits_results.total_blocking_time['score']\n total_blocking_time.labels(url).set(lighthouse_total_blocking_time_score)\n\n try:\n lighthouse_total_blocking_time_display = audits_results.total_blocking_time['displayValue']\n display_value = float(lighthouse_total_blocking_time_display[:3].replace(',','.'))\n total_blocking_time_displayvalue.labels(url).set(display_value)\n except Exception as err:\n logging.error(f'total_blocking_time error: {str(err)}')\n total_blocking_time_displayvalue.labels(url).set(0)\n pass\n\n lighthouse_total_blocking_time_title = audits_results.total_blocking_time['title']\n lighthouse_total_blocking_time_description = audits_results.total_blocking_time['description']\n\n total_blocking_time_info.info({\n 'title': lighthouse_total_blocking_time_title,\n 'description': lighthouse_total_blocking_time_description,\n 'url': url\n })\n\n # estimated_input_latency metric\n lighthouse_estimated_input_latency_score = audits_results.estimated_input_latency['score']\n estimated_input_latency.labels(url).set(lighthouse_estimated_input_latency_score)\n try:\n lighthouse_estimated_input_latency_display = audits_results.estimated_input_latency['displayValue']\n display_value = float(lighthouse_estimated_input_latency_display[:3].replace(',','.'))\n estimated_input_latency_displayvalue.labels(url).set(display_value)\n except Exception as err:\n logging.error(f'estimated_input_latency error: {str(err)}')\n estimated_input_latency_displayvalue.labels(url).set(0)\n pass\n\n lighthouse_estimated_input_latency_title = audits_results.estimated_input_latency['title']\n lighthouse_estimated_input_latency_description = audits_results.estimated_input_latency['description']\n\n estimated_input_latency_info.info({\n 'title': lighthouse_estimated_input_latency_title,\n 'description': lighthouse_estimated_input_latency_description,\n 'url': url\n })\n\n # uses_rel_preconnect metric\n lighthouse_uses_rel_preconnect_score = audits_results.uses_rel_preconnect['score']\n uses_rel_preconnect.labels(url).set(lighthouse_uses_rel_preconnect_score)\n\n # lighthouse_uses_rel_preconnect_display = audits_results.uses_rel_preconnect['displayValue']\n # display_value = lighthouse_uses_rel_preconnect_display\n # uses_rel_preconnect_displayvalue.labels(url, display_value) # no metric\n\n lighthouse_uses_rel_preconnect_overall = audits_results.uses_rel_preconnect['details']['overallSavingsMs']\n uses_rel_preconnect_overall.labels(url, 'overall', 'uses_rel_preconnect').set(lighthouse_uses_rel_preconnect_overall)\n\n lighthouse_uses_rel_preconnect_title = audits_results.uses_rel_preconnect['title']\n lighthouse_uses_rel_preconnect_description = audits_results.uses_rel_preconnect['description']\n\n uses_rel_preconnect_info.info({\n 'title': lighthouse_uses_rel_preconnect_title,\n 'description': lighthouse_uses_rel_preconnect_description,\n 'url': url\n })\n\n # bootup_time metric\n lighthouse_bootup_time_score = audits_results.bootup_time['score']\n bootup_time.labels(url).set(lighthouse_bootup_time_score)\n\n\n try:\n lighthouse_bootup_time_display = audits_results.bootup_time['displayValue']\n display_value = float(lighthouse_bootup_time_display[:3])\n bootup_time_displayvalue.labels(url).set(display_value)\n except Exception as err:\n logging.error(f'bootup_time error: {str(err)}')\n bootup_time_displayvalue.labels(url).set(0)\n pass\n\n lighthouse_bootup_time_wastedms = audits_results.bootup_time['details']['summary']['wastedMs']\n bootup_time_wastedms.labels(url, 'bootup_time').set(lighthouse_bootup_time_wastedms)\n\n lighthouse_bootup_time_title = audits_results.bootup_time['title']\n lighthouse_bootup_time_description = audits_results.bootup_time['description']\n\n bootup_time_info.info({\n 'title': lighthouse_bootup_time_title,\n 'description': lighthouse_bootup_time_description,\n 'url': url\n })\n\n # unminified_css metric\n lighthouse_unminified_css_score = audits_results.unminified_css['score']\n unminified_css.labels(url).set(lighthouse_unminified_css_score)\n\n # lighthouse_unminified_css_display = audits_results.unminified_css['displayValue']\n # display_value = lighthouse_unminified_css_display\n # unminified_css_displayvalue.labels(url, display_value) # no this metric\n\n lighthouse_unminified_css_overall = audits_results.unminified_css['details']['overallSavingsMs']\n unminified_css_overall.labels(url, 'overall', 'unminified_css').set(lighthouse_unminified_css_overall)\n\n lighthouse_unminified_css_title = audits_results.unminified_css['title']\n lighthouse_unminified_css_description = audits_results.unminified_css['description']\n\n unminified_css_info.info({\n 'title': lighthouse_unminified_css_title,\n 'description': lighthouse_unminified_css_description,\n 'url': url\n })\n\n # network_server_latency metric\n # lighthouse_network_server_latency_score = audits_results.network_server_latency['score']\n # network_server_latency.labels(url).set(lighthouse_network_server_latency_score)\n try:\n lighthouse_network_server_latency_display = audits_results.network_server_latency['displayValue']\n display_value = re.match(r\"[0-9]+\\.*\\,*[0-9]*\", lighthouse_network_server_latency_display)\n network_server_latency_displayvalue.labels(url).set(float(display_value.group(0)))\n except Exception as err:\n logging.error(f'network_server_latency error: {str(err)}')\n network_server_latency_displayvalue.labels(url).set(0)\n pass\n\n lighthouse_network_server_latency_title = audits_results.network_server_latency['title']\n lighthouse_network_server_latency_description = audits_results.network_server_latency['description']\n\n network_server_latency_info.info({\n 'title': lighthouse_network_server_latency_title,\n 'description': lighthouse_network_server_latency_description,\n 'url': url\n })\n\n # offscreen_images metric\n lighthouse_offscreen_images_score = audits_results.offscreen_images['score']\n offscreen_images.labels(url).set(lighthouse_offscreen_images_score)\n\n lighthouse_offscreen_images_overall = audits_results.offscreen_images['details']['overallSavingsMs']\n offscreen_images_overall.labels(url, 'overall', 'offscreen_images').set(lighthouse_offscreen_images_overall)\n\n try:\n lighthouse_offscreen_images_display = audits_results.offscreen_images['displayValue']\n display_value = lighthouse_offscreen_images_display\n offscreen_images_displayvalue.labels(url, display_value)\n except Exception as err:\n logging.error(f'Offscreen_images error: {str(err)}')\n offscreen_images_displayvalue.labels(url, '0')\n pass\n\n lighthouse_offscreen_images_title = audits_results.offscreen_images['title']\n lighthouse_offscreen_images_description = audits_results.offscreen_images['description']\n\n offscreen_images_info.info({\n 'title': lighthouse_offscreen_images_title,\n 'description': lighthouse_offscreen_images_description,\n 'url': url\n })\n\n # uses_responsive_images metric\n lighthouse_uses_responsive_images_score = audits_results.uses_responsive_images['score']\n uses_responsive_images.labels(url).set(lighthouse_uses_responsive_images_score)\n\n lighthouse_uses_responsive_images_overall = audits_results.uses_responsive_images['details']['overallSavingsMs']\n uses_responsive_images_overall.labels(url, 'overall', 'uses_responsive_images').set(lighthouse_uses_responsive_images_overall)\n\n # lighthouse_offscreen_images_display = audits_results.offscreen_images['displayValue']\n # display_value = lighthouse_offscreen_images_display\n # offscreen_images_displayvalue.labels(url, display_value) # no metric\n\n lighthouse_uses_responsive_images_title = audits_results.uses_responsive_images['title']\n lighthouse_uses_responsive_images_description = audits_results.uses_responsive_images['description']\n\n uses_responsive_images_info.info({\n 'title': lighthouse_uses_responsive_images_title,\n 'description': lighthouse_uses_responsive_images_description,\n 'url': url\n })\n\n # unused_css_rules metric\n lighthouse_unused_css_rules_score = audits_results.unused_css_rules['score']\n unused_css_rules.labels(url).set(lighthouse_unused_css_rules_score)\n\n lighthouse_unused_css_rules_display = audits_results.unused_css_rules['displayValue']\n display_value = lighthouse_unused_css_rules_display\n unused_css_rules_displayvalue.labels(url, display_value)\n\n lighthouse_unused_css_rules_overall = audits_results.unused_css_rules['details']['overallSavingsMs']\n unused_css_rules_overall.labels(url, 'overall', 'unused_css_rules').set(lighthouse_unused_css_rules_overall)\n\n lighthouse_unused_css_rules_title = audits_results.unused_css_rules['title']\n lighthouse_unused_css_rules_description = audits_results.unused_css_rules['description']\n\n unused_css_rules_info.info({\n 'title': lighthouse_unused_css_rules_title,\n 'description': lighthouse_unused_css_rules_description,\n 'url': url\n })\n\n # Total byte weight metric\n lighthouse_total_byte_weight_score = audits_results.total_byte_weight['score']\n total_byte_weight_score.labels(url).set(lighthouse_total_byte_weight_score)\n\n lighthouse_total_byte_weight_display = audits_results.total_byte_weight['displayValue']\n display_value = lighthouse_total_byte_weight_display\n total_byte_weight_displayvalue.labels(url, display_value)\n\n lighthouse_total_byte_weight_title = audits_results.total_byte_weight['title']\n lighthouse_total_byte_weight_description = audits_results.total_byte_weight['description']\n\n total_byte_weight_info.info({\n 'title': lighthouse_total_byte_weight_title,\n 'description': lighthouse_total_byte_weight_description,\n 'url': url\n })\n\n # Uses webp images metric\n lighthouse_uses_webp_images_score = audits_results.uses_webp_images['score']\n uses_webp_images.labels(url).set(lighthouse_uses_webp_images_score)\n\n # lighthouse_uses_webp_images_display = audits_results.uses_webp_images['displayValue']\n # display_value = float(lighthouse_uses_webp_images_display[:3])\n # uses_webp_images_displayvalue.labels(url).set(display_value)\n\n lighthouse_uses_webp_images_overall = audits_results.uses_webp_images['details']['overallSavingsMs']\n uses_webp_images_overall.labels(url, 'overall', 'uses_webp_images').set(lighthouse_uses_webp_images_overall)\n\n lighthouse_uses_webp_images_title = audits_results.uses_webp_images['title']\n lighthouse_uses_webp_images_description = audits_results.uses_webp_images['description']\n\n uses_webp_images_info.info({\n 'title': lighthouse_uses_webp_images_title,\n 'description': lighthouse_uses_webp_images_description,\n 'url': url\n })\n\n # dom_size metric\n lighthouse_dom_size_score = audits_results.dom_size['score']\n dom_size.labels(url).set(lighthouse_dom_size_score)\n\n try:\n lighthouse_dom_size_display = audits_results.dom_size['displayValue']\n display_value = re.match(r\"[0-9]+\\.*\\,*[0-9]*\", lighthouse_dom_size_display)\n dom_size_displayvalue.labels(url).set(float(display_value.group(0).replace(',','.')))\n except Exception as err:\n logging.error(f'dom_siz error: {str(err)}')\n offscreen_images_displayvalue.labels(url, '0')\n pass\n\n lighthouse_dom_size_title = audits_results.dom_size['title']\n lighthouse_dom_size_description = audits_results.dom_size['description']\n\n dom_size_info.info({\n 'title': lighthouse_dom_size_title,\n 'description': lighthouse_dom_size_description,\n 'url': url\n })\n\n # uses_rel_preload metric\n lighthouse_uses_rel_preload_score = audits_results.uses_rel_preload['score']\n uses_rel_preload.labels(url).set(lighthouse_uses_rel_preload_score)\n\n # lighthouse_uses_rel_preload_display = audits_results.uses_rel_preload['displayValue']\n # display_value = float(lighthouse_uses_rel_preload_display[:3].replace(',', '.'))\n # uses_rel_preload_displayvalue.labels(url).set(display_value)\n\n lighthouse_uses_rel_preload_overall = audits_results.uses_rel_preload['details']['overallSavingsMs']\n uses_rel_preload_overall.labels(url, 'overall', 'uses_rel_preload').set(lighthouse_uses_rel_preload_overall)\n\n lighthouse_uses_rel_preload_title = audits_results.uses_rel_preload['title']\n lighthouse_uses_rel_preload_description = audits_results.uses_rel_preload['description']\n\n uses_rel_preload_info.info({\n 'title': lighthouse_uses_rel_preload_title,\n 'description': lighthouse_uses_rel_preload_description,\n 'url': url\n })\n\n # unminified_javascript metric\n lighthouse_unminified_javascript_score = audits_results.unminified_javascript['score']\n unminified_javascript.labels(url).set(lighthouse_unminified_javascript_score)\n\n\n lighthouse_unminified_javascript_overall = audits_results.unminified_javascript['details']['overallSavingsMs']\n unminified_javascript_overall.labels(url, 'overall', 'unminified_javascript').set(lighthouse_unminified_javascript_overall)\n\n # lighthouse_unminified_javascript_display = audits_results.unminified_javascript['displayValue']\n # display_value = float(lighthouse_unminified_javascript_display[:3].replace(',', '.'))\n # unminified_javascript_displayvalue.labels(url).set(display_value) # no metric\n\n lighthouse_unminified_javascript_title = audits_results.unminified_javascript['title']\n lighthouse_unminified_javascript_description = audits_results.unminified_javascript['description']\n\n unminified_javascript_info.info({\n 'title': lighthouse_unminified_javascript_title,\n 'description': lighthouse_unminified_javascript_description,\n 'url': url\n })\n\n # redirects metric\n lighthouse_redirects_score = audits_results.redirects['score']\n redirects.labels(url).set(lighthouse_redirects_score)\n\n lighthouse_redirects_overall = audits_results.redirects['details']['overallSavingsMs']\n redirects_overall.labels(url, 'overall', 'redirects').set(lighthouse_redirects_overall)\n\n # lighthouse_unminified_javascript_display = audits_results.unminified_javascript['displayValue']\n # display_value = float(lighthouse_unminified_javascript_display[:3].replace(',', '.'))\n # unminified_javascript_displayvalue.labels(url).set(display_value) # no metric\n\n lighthouse_redirects_title = audits_results.redirects['title']\n lighthouse_redirects_description = audits_results.redirects['description']\n\n redirects_info.info({\n 'title': lighthouse_redirects_title,\n 'description': lighthouse_redirects_description,\n 'url': url\n })\n\n logging.info('Done.')",
"def do_request(self, url):\n url += '?access_token={}'.format(self.TOKEN)\n logging.debug('requesting url: {}'.format(url))\n r = requests.get(url)\n return r.json()",
"def get(self, request):\n return Response(services.get_agenda_statuses(request.query_params, request.META['HTTP_JWT']))",
"def get_status(self, batch_request: BatchStatisticalRequestType) -> JsonDict:\n request_id = self._parse_request_id(batch_request)\n endpoint_url = f\"{self._get_processing_url(request_id)}/status\"\n request_info = self.client.get_json_dict(url=endpoint_url, use_session=True)\n return request_info",
"def get_all_requests():",
"def _get_access(self, req):\r\n access = req.params.get('AWSAccessKeyId')\r\n if access is None:\r\n cred_param = req.params.get('X-Amz-Credential')\r\n if cred_param:\r\n access = cred_param.split(\"/\")[0]\r\n\r\n if access is None and 'Authorization' in req.headers:\r\n auth_str = req.headers['Authorization']\r\n cred_str = auth_str.partition(\"Credential=\")[2].split(',')[0]\r\n access = cred_str.split(\"/\")[0]\r\n\r\n return access",
"def fetch_status():\n return json.loads(requests.get('http://omegle.com/status').text)",
"def getExamMethod(request):\n try:\n profileId = ndb.Key(urlsafe=getattr(request, 'profileId'))\n except Exception:\n print \"Invalid profileId\"\n return GetExamResponse(response=1, description=\"Invalid profileId\")\n try:\n examId = ndb.Key(urlsafe=getattr(request, 'examId'))\n except Exception:\n print \"Invalid courseId\"\n return GetExamResponse(response=1, description=\"Invalid examId\")\n\n # to add the views in cron\n examOpened.add(examId.urlsafe())\n\n # fetching from memcache\n cacheVal = memcache.get(examId.urlsafe())\n memViews = memcache.get('views' + examId.urlsafe())\n if cacheVal is not None:\n if profileId == cacheVal[8]:\n isAuthor = 1\n else:\n isAuthor = 0\n if memViews is None:\n exam = examId.get()\n if exam is None:\n print \"Invalid examId\"\n return GetExamResponse(response=1, description=\"Invalid examId\")\n memViews = exam.examViews\n memcache.add('views' + examId.urlsafe(), memViews, 86400)\n if isAuthor == 0:\n memcache.incr('views' + examId.urlsafe())\n coursePage = memcache.get(cacheVal[9])\n if coursePage is not None:\n if assignmentId.urlsafe() in coursePage[8]:\n idx = coursePage[8].index(examId.urlsafe())\n coursePage[8][idx].views += 1\n memcache.set(cacheVal[9], coursePage)\n views = memcache.get('views' + examId.urlsafe())\n return GetExamResponse(response=0, description=\"OK\",\n isAuthor=isAuthor, examTitle=cacheVal[0],\n examDesc=cacheVal[1], lastUpdated=cacheVal[2],\n uploaderName=cacheVal[3], dueDate=cacheVal[4],\n dueTime=cacheVal[5], urlList=cacheVal[6],\n courseName=cacheVal[7], views=views)\n exam = examId.get()\n if exam is None:\n print \"Invalid examId\"\n return GetExamResponse(response=1, description=\"Invalid examId\")\n if profileId == exam.uploaderId:\n isAuthor = 1\n else:\n isAuthor = 0\n uploaderName = exam.uploaderId.get().profileName\n exam.put()\n course = exam.courseId.get()\n fields = [exam.examTitle, exam.examDesc, exam.dateUploaded, uploaderName,\n exam.dueDate, exam.dueTime, exam.urlList, course.courseName,\n exam.uploaderId]\n\n if memcache.get('views' + examId.urlsafe()) is None:\n if isAuthor == 0:\n memcache.add('views' + examId.urlsafe(), exam.examViews + 1, 86400)\n else:\n memcache.add('views' + examId.urlsafe(), exam.examViews, 86400)\n else:\n if isAuthor == 0:\n memcache.incr('views' + examId.urlsafe())\n memcache.add(examId.urlsafe(), fields, 86400)\n views = memcache.get('views' + examId.urlsafe())\n return GetExamResponse(response=0, description=\"OK\",\n isAuthor=isAuthor, views=views,\n examTitle=fields[0], examDesc=fields[1],\n lastUpdated=fields[2],\n uploaderName=fields[3], dueDate=fields[4],\n dueTime=fields[5], urlList=fields[6],\n courseName=fields[7])"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Ensure that the given URL is a valid URL. Since the URL is not entered by the user, it is always valid.
|
def _validate_url(self, url):
return
|
[
"def validateURL(url):",
"def validate_url(url):\n\n if not url:\n raise SystemError(\"validate_url() was given an empty URL\")\n\n protocol = \"http://\"\n protocol_error_message = ValueError(\"A URL beginning with \" \\\n \"'http://' is required\")\n\n if len(url) < len(protocol):\n raise protocol_error_message\n\n if url[:len(protocol)] != protocol:\n raise protocol_error_message",
"def validate_url(url):\n schemeSeparatorIndex = url.find(\"://\");\n if (schemeSeparatorIndex < 3):\n # Adding default missing scheme for user.\n url = \"http://\" + url;\n \n if (not validators.url(url)):\n return None;\n \n return url;",
"def validate(cls, url: str) -> typing.Optional[\"URL\"]:\n pass",
"def validate_http_url(url):\r\n if not url.startswith(('http://', 'https://', )):\r\n raise ValidationError(u'Only HTTP and HTTPS protocols are allowed')",
"def validate_url(input_url: str, scheme: typing.Union[str, typing.Tuple[str], None]) -> str:\n\t# Remove leading and trailing whitespaces before parsing\n\turl = urllib.parse.urlparse(input_url.strip())\n\n\tif url.path.endswith(\"/\"):\n\t\turl = url._replace(path=url.path[:-1])\n\n\tif scheme is None: # Scheme doesn't get checked\n\t\treturn url.geturl()\n\telif isinstance(scheme, tuple): # Supports tuple\n\t\tif url.scheme in scheme:\n\t\t\treturn url.geturl()\n\telif scheme == url.scheme:\n\t\treturn url.geturl()\n\telse:\n\t\tif url.scheme:\n\t\t\traise ValueError(\"'{}' has an invalid scheme: '{}'\".format(url.geturl(), url.scheme))\n\t\telif not url.scheme:\n\t\t\traise ValueError(\"'{}' does not have a scheme\".format(url.geturl()))\n\t\telse:\n\t\t\traise ValueError(\"'{}' has an invalid scheme\".format(url.geturl()))\n\treturn url.geturl()",
"def valid_url(x: str) -> bool:\n if isinstance(x, str) and re.match(URL_PATTERN, x):\n return True\n else:\n return False",
"def validate_storefront_url(url):\n try:\n parsed_url = urlparse(url)\n domain, _ = split_domain_port(parsed_url.netloc)\n if not parsed_url.netloc:\n raise ValidationError(\n \"Invalid URL. Please check if URL is in RFC 1808 format.\"\n )\n except ValueError as error:\n raise ValidationError(error)\n if not validate_host(domain, settings.ALLOWED_CLIENT_HOSTS):\n error_message = (\n f\"{domain or url} is not allowed. Please check \"\n \"`ALLOWED_CLIENT_HOSTS` configuration.\"\n )\n raise ValidationError(error_message)",
"def test_url_is_valid_validation(self):\n # when url is unset, False should be returned.\n self.item.url = ''\n self.assertFalse(self.item.url_is_valid())\n # when an invalid url is passed, False should be returned\n self.item.url = 'test.com'\n self.assertFalse(self.item.url_is_valid())\n self.item.url = '/test.com'\n self.assertFalse(self.item.url_is_valid())\n self.item.url = 'http://'\n self.assertFalse(self.item.url_is_valid())\n # when a valid url is passed, True should be returned\n self.item.url = 'http://test.com/test'\n self.assertTrue(self.item.url_is_valid())",
"def validate_url(self, url):\n if url.startswith(\"http://\") or url.startswith(\"https://\") or url.startswith(\"ftp://\"):\n return True\n self.logger.info(f\"GetURL: Unsupported URL prefix: {url}\")\n raise PluginException(\n preset=PluginException.Preset.UNKNOWN,\n assistance=f\"GetURL: Unsupported URL prefix: {url}\",\n )",
"def test_url_parsing_pass():\n\n assert True == url.validate(\"http://example.com\")\n assert True == url.validate(\"http://example.com/\")\n assert True == url.validate(\"http://www.example.com\")\n assert True == url.validate(\"http://www.example.com/\")",
"def validate_uri(self, uri):\n logging.debug(\"Validating URL %s\" % uri)\n\n # Return None in error case. This is 'null' in final output.\n try:\n if not validators.url(uri):\n uri = None\n except validators.utils.ValidationFailure:\n logging.error(\"Invalid URL %s\" % uri)\n uri = None\n return uri",
"def validate_url(self, url):\n return re.match(r\"^https:\\/\\/hitomi\\.la\\/reader\\/[\\d]+\\.html#[\\d]+$\", url) or re.match(r\"^https:\\/\\/hitomi\\.la\\/galleries\\/[\\d]+\\.html$\", url)",
"def validate_url(self, value):\n if value:\n if GoogleDriveSource.parse_address(value):\n return value\n else:\n raise exceptions.ValidationError(\"Invalid Google Drive URL.\")",
"def es_url_valida(url_):\n url_parseado = urlparse.urlparse(url_)\n return all([url_parseado.scheme, url_parseado.netloc])",
"def is_valid_url(url):\n data = dp.route_album_or_playlist(url)\n if \"error\" not in data:\n io.generate_printout(data)\n return data",
"def _validate_url(self):\n real_url = \"{}://www.rightmove.co.uk/{}/\"\n #breakpoint()\n protocols = [\"http\", \"https\"]\n types = [\"house-prices\"]\n urls = [real_url.format(p, t) for p in protocols for t in types]\n conditions = [self.url.startswith(u) for u in urls]\n conditions.append(self._status_code == 200)\n if not any(conditions):\n raise ValueError(f\"Invalid rightmove search URL:\\n\\n\\t{self.url}\")",
"def validate_url(self, value: str) -> str: # pylint: disable=no-self-use\n try:\n return models_utils.validate_netloc_url(value)\n except ValueError as exc:\n raise serializers.ValidationError(\"Invalid URL\") from exc\n\n return value",
"def valid_input(url_to_check: str) -> bool:\r\n if url_to_check == 'q':\r\n sys.exit()\r\n\r\n else:\r\n result = urlparse(url_to_check)\r\n\r\n if ('youtube.com' not in result.netloc) and ('youtube.com' not in result.path):\r\n return False\r\n\r\n if not ('list' in parse_qs(result.query).keys()):\r\n return False\r\n\r\n return True",
"def _is_valid_remote_url(value):\n url = isinstance(value, basestring) and urlparse(value)\n return url and url.scheme and url.netloc and url.path"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Get the xpath for the button to load request data for the given status
|
def _status_btn_xpath(status: RequestStatus):
return f'//div[@id="notifications-affix"]//a[./span[text()="{status.value}"]]'
|
[
"def get_status(self):\n status_elem = self.tds[self.STATUS_COL]\n status_icon = status_elem.find_element_by_tag(\"mat-icon\")\n if status_icon is None:\n # Check for spinner\n if status_elem.find_element_by_tag(\"mat-spinner\") is None:\n raise ValueError(\"Status should be a spinner\")\n\n return STATE_WAITING\n\n return icon_to_status(status_icon)",
"def get_request_data(self, status: RequestStatus = RequestStatus.ALL) -> List[dict]:\n SEE_MORE_BTN_XPATH = \"//a[text()='See More']\"\n\n # filter page to only include requests of the given status\n self._browser.click_element_by_xpath(self._status_btn_xpath(status))\n self._browser.wait_until_element_is_clickable_by_xpath(\n \"//*[@class='table manage-table']/tbody/tr[1]/td[1]\")\n\n # load all requests of the given status onto the page\n total_requests = sum(map(int, self._browser.get_elements_attribute_by_xpath(\n \"//div[@class='panel panel-default']//a/span[@class='badge' and text()!='0']\", \"text\")))\n\n pages_to_load = int(math.floor(total_requests / 25))\n # account for apparent load limit on Handshake's servers\n if pages_to_load > 69:\n pages_to_load = 69\n for i in range(pages_to_load): # click \"See More\" btn until all rows loaded\n self._browser.wait_until_element_exists_by_xpath(SEE_MORE_BTN_XPATH)\n self._browser.click_element_by_xpath(SEE_MORE_BTN_XPATH)\n\n time.sleep(2) # wait for final set of names to finish loading before scraping\n\n # scrape request data from page\n request_data = []\n student_rows = BeautifulSoup(\n self._browser.get_element_attribute_by_xpath(\"//tbody\", \"innerHTML\"),\n 'html.parser').find_all('tr')\n for row in student_rows:\n user = row.find('td', {'class': 'requester_name'}).find('a').text\n user_id_link = row.find('td', {'class': 'requester_name'}).find('a')['href']\n user_id = re.findall(r'([0-9]+)', user_id_link)[0]\n date_str = row.find('td', {'class': 'request_date'}).find('a').text\n date_str = re.sub(r'(\\d)(st|nd|rd|th)', r'\\1', date_str)\n data_row = {\n 'user': user,\n 'user_id': user_id,\n 'email': row.find('td', {'class': 'requester_email'}).find('a').text,\n 'request_date': datetime.strptime(date_str, '%B %d %Y').date(),\n 'request': row.find('td', {'class': 'request'}).find('a').text,\n 'status': row.find('td', {'class': 'status'}).find('span').text\n }\n request_data.append(data_row)\n return request_data",
"def _button_link(self):\n try:\n details_buttons = WebDriverWait(self.driver, 5).until(\n EC.presence_of_all_elements_located((By.CLASS_NAME, \"ab_button\")))\n\n for item in details_buttons:\n if item.text == \"Strona\":\n return item.get_attribute(\"href\")\n except:\n return None\n\n return None",
"def select_request_from_trainer(self):\n self.click_on_element_by_css(adpl.TEST_REQUEST_CHECKBOX)",
"def i8k_buttons_status(self):\n self.writeCommand('i8k_buttons_status')\n return self",
"def findButton(self) -> object:\r\n WebDriverWait(self._webdriver, 25).until(expected_conditions.presence_of_element_located((\r\n By.XPATH, r'//*[@id=\"page_competition_1_block_competition_matches_summary_5_previous\"]')))\r\n return self._webdriver.find_element_by_xpath(r'//*[@id=\"page_competition_1_block_competition_matches_summary_5_previous\"]')",
"def _retrieve_batch_page(self, batch_status, page=1):\n br = self.browser\n params = dict(MANAGE_PARAMS, status=batch_status, page=page)\n url = '%s?%s' % (MANAGE_URL, urlencode(params))\n \n if DEBUG:\n print >>sys.stderr, '*** _retrieve_batch_page(%s, %s)' % (batch_status, page)\n \n response = br.open(url)\n soup = BeautifulSoup(response.read())\n pagination = soup.find(attrs={'class': 'pagination'})\n page_links = set( int(a.string) for a in pagination.find_all('a') if a.string.isdigit() ) \\\n if pagination is not None else set()\n \n next_page = page+1 if (page+1) in page_links else None\n \n DIV_ID_PREFIX = 'batch_capsule_'\n batches = []\n for batch_capsule in soup.find_all(id=lambda x: x and x.startswith(DIV_ID_PREFIX)):\n batch_id = int(batch_capsule.attrs['id'][len(DIV_ID_PREFIX):])\n batch_link_tag = batch_capsule.find('a', id='batch_status_%s' % batch_id)\n batch_name = batch_link_tag.string\n tbl = batch_capsule.find(id=\"batch_%s\" % batch_id)\n metadata = [line for line in tbl.text.splitlines() if line.strip()]\n \n batches.append( Batch(batch_id, batch_name, metadata) )\n \n return batches, next_page",
"def test_status_request(self):\n pass",
"def get_xpath(self):\n return self.node.path()",
"def simulate_loading_any_page(l):\n l.client.get(USER_ENDPOINT)\n l.client.get(STATUS_ENDPOINT)",
"def _click_start_button(driver, result):\n driver.find_element_by_id('websocketButton').click()\n\n start_button = driver.find_elements_by_xpath(\n \"//*[contains(text(), 'Start Test')]\")[0]\n start_button.click()\n result.start_time = datetime.datetime.now(pytz.utc)",
"def fetch_status():\n return json.loads(requests.get('http://omegle.com/status').text)",
"def parse_os_product_id_url_path(response, platform):\r\n soup = BeautifulSoup(response.text, features=\"html.parser\")\r\n data_platform = {\"data-platform\": platform}\r\n button_class = {\"class\": \"btn btn-default download\"}\r\n platform_div = soup.find(\"div\", data_platform)\r\n platform_url = platform_div.find(\"button\", button_class).get(\"data-url\")\r\n return platform_url",
"def status(ctx: click.Context) -> None:\n info = get(\"status\", lambda: status_call(ctx.obj[\"session\"]))\n click.echo(json_pretty(info))",
"def click_status_and_search():\n try_click_image(IMG_STATUS)\n pyautogui.scroll(-7000)\n try_click_image(IMG_SZUKAJ)",
"def update_status(self):\n route = \"/admin/status\"\n self.status = self.get(route)",
"def get_product_status(self, product):\n self.wait_until_dashboard_displayed()\n status_locators = {}\n if product == Products.SPEND:\n status_locators[ProductApplicationStatus.IN_PROGRESS] = \\\n BaseElement(self.driver, locators.CONTINUE_SPEND_SAVE_APPLICATION_BUTTON)\n status_locators[ProductApplicationStatus.COMPLETED] = \\\n BaseElement(self.driver, locators.VIEW_SPEND_ACCOUNT_BUTTON)\n status_locators[ProductApplicationStatus.PENDING] = \\\n BaseElement(self.driver, locators.SPEND_SAVE_TELL_YOUR_FRIENDS_BUTTON)\n elif product == Products.SAVE:\n status_locators[ProductApplicationStatus.IN_PROGRESS] = \\\n BaseElement(self.driver, locators.CONTINUE_SAVE_APPLICATION_BUTTON)\n status_locators[ProductApplicationStatus.COMPLETED] = \\\n BaseElement(self.driver, locators.VIEW_SAVE_ACCOUNT_BUTTON)\n status_locators[ProductApplicationStatus.PENDING] = \\\n BaseElement(self.driver, locators.SAVE_TELL_YOUR_FRIENDS_BUTTON)\n elif product == Products.REDWOOD:\n status_locators[ProductApplicationStatus.IN_PROGRESS] = \\\n BaseElement(self.driver, locators.CONTINUE_REDWOOD_APPLICATION_BUTTON)\n status_locators[ProductApplicationStatus.COMPLETED] = \\\n BaseElement(self.driver, locators.VIEW_REDWOOD_ACCOUNT_BUTTON)\n status_locators[ProductApplicationStatus.PENDING] = \\\n BaseElement(self.driver, locators.REDWOOD_TELL_YOUR_FRIENDS_BUTTON)\n elif product == Products.FLAGSHIP:\n status_locators[ProductApplicationStatus.IN_PROGRESS] = \\\n BaseElement(self.driver, locators.CONTINUE_FLAGSHIP_APPLICATION_BUTTON)\n status_locators[ProductApplicationStatus.COMPLETED] = \\\n BaseElement(self.driver, locators.VIEW_FLAGSHIP_ACCOUNT_BUTTON)\n status_locators[ProductApplicationStatus.PENDING] = \\\n BaseElement(self.driver, locators.FLAGSHIP_TELL_YOUR_FRIENDS_BUTTON)\n else:\n return ProductApplicationStatus.DOES_NOT_EXIST\n\n # Based on product given check which, if any, status that product has\n if status_locators[ProductApplicationStatus.IN_PROGRESS].displayed():\n return ProductApplicationStatus.IN_PROGRESS\n elif status_locators[ProductApplicationStatus.PENDING].displayed():\n return ProductApplicationStatus.PENDING\n elif status_locators[ProductApplicationStatus.COMPLETED].displayed():\n return ProductApplicationStatus.COMPLETED\n else:\n return ProductApplicationStatus.DOES_NOT_EXIST",
"def extract_url(self, tree):\n href = tree.xpath(self._item.get(\"xpath_button_to_click\"))\n if not href:\n raise IndexError\n url = dict(href[0].items()).get('href')\n\n return urljoin(url_start, url)",
"def load_new_data(self):\n r = requests.get(self.STATUS_URL)\n raw_data = self._received_data_processor(r.text)\n soup = BeautifulSoup(raw_data, 'lxml')\n self.status_data = soup.find(\"service\").find(\"subway\").findAll(\"line\")"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Load the bolometric light curves from lbolfile.
|
def load(name, path='.', tcol='time', cols=('L_ubvri', 'L_bol'), is_lum=False):
fname = os.path.join(path, f'{name}.lbol')
# print(f"Loading {fname}")
d, header = read_obs_table_header(fname)
# print(header)
time = np.array(d[tcol])
cut = time > 0
t = time[cut]
res = SetLightCurve(f'L_bol {name}')
for col in cols: # header.items():
b = band.BandUni(name=f"{col}")
lum = np.array(d[col])[cut]
if not is_lum: # convert to magnitudes
lum = Lum2MagBol(10. ** lum)
lc = LightCurve(b, t, lum)
res.add(lc)
return res
|
[
"def load_LSRK(file,lstype='2S',has_emb=False):\n from numpy import sum\n #Read in coefficients\n f=open(file,'r')\n coeff=[]\n for line in f:\n coeff.append(float(line))\n f.close()\n if has_emb:\n f=open(file+'.bhat','r')\n bhat=[]\n for line in f:\n bhat.append(float(line))\n bhat = np.array(bhat)\n\n # Determine number of stages\n if lstype=='2S' or lstype=='2S*': m=int(len(coeff)/3+1)\n elif lstype=='2S_pair': m=int((len(coeff)+1)/3)\n elif lstype=='3S*': m=int((len(coeff)+6.)/4.)\n elif lstype=='3S*_pair': m=int((len(coeff)+3.)/4.)\n\n # Fill in low-storage coefficient arrays\n beta=[0.]\n for i in range(m): beta.append(coeff[2*m-3+i])\n gamma=[[0.],[0.,1.]+coeff[0:m-1]]\n if lstype.startswith('3S*'): gamma.append([0,0,0,0]+coeff[3*m-3:4*m-6])\n if lstype=='2S' or lstype=='3S*': delta=[1.]+coeff[m-1:2*m-3]+[0.]\n elif lstype=='2S*': delta=[1.]+[0.]*len(list(range(m-1,2*m-3)))+[0.]\n elif lstype=='2S_pair': delta=[1.]+coeff[m-1:2*m-3] +[coeff[-2],coeff[-1]]\n elif lstype=='3S*_pair': delta=[1.]+coeff[m-1:2*m-3] +[coeff[-3],coeff[-2],coeff[-1]]\n if lstype=='2S' or lstype=='2S*':\n for i in range(1,m+1): gamma[0].append(1.-gamma[1][i]*sum(delta[0:i]))\n if has_emb:\n meth = TwoSRungeKuttaPair(beta,gamma,delta,lstype,bhat=bhat)\n else:\n meth = TwoSRungeKuttaMethod(beta,gamma,delta,lstype)\n elif lstype=='2S_pair':\n for i in range(1,m+1): gamma[0].append(1.-gamma[1][i]*sum(delta[0:i]))\n meth = TwoSRungeKuttaPair(beta,gamma,delta,lstype)\n elif lstype.startswith('3S*'):\n for i in range(1,m+1): gamma[0].append(1.-gamma[2][i]\n -gamma[1][i]*sum(delta[0:i]))\n if lstype=='3S*':\n if has_emb:\n meth = TwoSRungeKuttaPair(beta,gamma,delta,lstype,bhat=bhat)\n else:\n meth = TwoSRungeKuttaMethod(beta,gamma,delta,lstype)\n\n elif lstype=='3S*_pair':\n meth = TwoSRungeKuttaPair(beta,gamma,delta,lstype)\n ord=meth.order()\n if lstype=='2S_pair':\n emb_ord=meth.embedded_order()\n eostr=str(emb_ord)\n else: eostr=''\n m=len(meth)\n lstypename=lstype\n if lstypename=='2S_pair': lstypename='2S'\n meth.name='RK'+str(ord)+'('+eostr+')'+str(m)+'['+lstypename+']'\n return meth",
"def load_lum_file(self):\n self.lum = burst_tools.load_lum(run=self.run, batch=self.batch,\n source=self.source, basename=self.basename,\n save=self.options['save_lum'],\n reload=self.options['reload'],\n check_monotonic=self.options['check_lumfile_monotonic'])\n\n if self.lum is None:\n self.flags['lum_does_not_exist'] = True\n self.n_bursts = 0\n return\n\n self.lumf = interpolate.interp1d(self.lum[:, 0], self.lum[:, 1])\n self.flags['lum_loaded'] = True",
"def L_B(self, Lbol):\n #Coefficients from Table 1 for the UV luminosity.\n c1, k1, c2, k2 = 6.25, -0.37, 9.00, -0.012\n #Implementation of equation (5).\n x = Lbol/(1e10*L_sun)\n bc = c1*x**k1 + c2*x**k2\n return Lbol/bc",
"def loadLC(folderName, downloadDir, errorIfNot2Min=True, dumpHeader=False, delimiter=\"|\", fluxType=\"PDCSAP\", normalised=True):\n\n lc = None\n if \"|\" in folderName:\n folderNames = folderName.split(delimiter)\n else:\n folderNames = [folderName]\n \n for folderName in folderNames:\n imgFname = \"{}_lc.fits\".format(folderName)\n imgFname = os.path.join(downloadDir, folderName, imgFname)\n head = fits.getheader(imgFname)\n sector = head[\"sector\"]\n if dumpHeader:\n print(repr(head))\n lightCurveData = Table.read(imgFname)\n cadeances = np.nanmedian((lightCurveData[\"TIME\"][1:] - lightCurveData[\"TIME\"][:-1])*24*60)\n if np.abs(cadeances-2.) < 0.5:\n logger.info(\"Cadence is 2 min for {}\".format(imgFname))\n else:\n if errorIfNot2Min:\n raise RuntimeError(\"Cadence is {:1.1f} min for {}\".format(cadeances, imgFname))\n else:\n logger.warning(\"Cadence is {:1.1f} min for {}\".format(cadeances, imgFname))\n \n lightCurveData[\"TIME\"].unit = u.day\n time = lightCurveData[\"TIME\"]\n flux = lightCurveData[\"{}_FLUX\".format(fluxType)] \n fluxErr = lightCurveData[\"{}_FLUX_ERR\".format(fluxType)]\n\n meta = {\n \"TIME\": lightCurveData[\"TIME\"],\n \"MOM_CENTR1\": lightCurveData[\"MOM_CENTR1\"],\n \"MOM_CENTR2\": lightCurveData[\"MOM_CENTR2\"],\n \"MOM_CENTR1_ERR\": lightCurveData[\"MOM_CENTR1_ERR\"],\n \"MOM_CENTR2_ERR\": lightCurveData[\"MOM_CENTR2_ERR\"],\n \"POS_CORR1\": lightCurveData[\"POS_CORR1\"],\n \"POS_CORR2\": lightCurveData[\"POS_CORR2\"],\n }\n\n lcTemp = LightCurve(time=time, flux=flux, flux_err=fluxErr, meta=meta)\n lcTemp = lcTemp.remove_nans()\n if normalised:\n lcTemp = lcTemp.normalize()\n \n if lc is None:\n lc = lcTemp\n sectors = sector\n else:\n lc = lc.append(lcTemp)\n sectors = \"{},{}\".format(sectors, sector)\n \n ids = np.argsort(lc.time)\n lc = lc[ids]\n \n return lc, sectors",
"def load_beam(self, filepath: str) -> Iterable[Brick]:",
"def read_lightning_all(fname,\n labels=['hydro [-]', 'KDPc [deg/Km]', 'dBZc [dBZ]',\n 'RhoHVc [-]', 'TEMP [deg C]', 'ZDRc [dB]']):\n try:\n with open(fname, 'r', newline='') as csvfile:\n # first count the lines\n reader = csv.DictReader(\n row for row in csvfile if not row.startswith('#'))\n nrows = sum(1 for row in reader)\n\n flashnr = np.ma.empty(nrows, dtype=int)\n time_data = np.ma.empty(nrows, dtype=datetime.datetime)\n time_in_flash = np.ma.empty(nrows, dtype=float)\n lat = np.ma.empty(nrows, dtype=float)\n lon = np.ma.empty(nrows, dtype=float)\n alt = np.ma.empty(nrows, dtype=float)\n dBm = np.ma.empty(nrows, dtype=float)\n pol_vals_dict = dict()\n for label in labels:\n pol_vals_dict.update({label: np.ma.empty(nrows, dtype=float)})\n\n # now read the data\n csvfile.seek(0)\n reader = csv.DictReader(\n row for row in csvfile if not row.startswith('#'))\n\n for i, row in enumerate(reader):\n flashnr[i] = int(row['flashnr'])\n time_data[i] = datetime.datetime.strptime(\n row['time_data'], '%Y-%m-%d %H:%M:%S.%f')\n time_in_flash[i] = float(row['time_in_flash'])\n lat[i] = float(row['lat'])\n lon[i] = float(row['lon'])\n alt[i] = float(row['alt'])\n dBm[i] = float(row['dBm'])\n\n for label in labels:\n pol_vals_dict[label][i] = float(row[label])\n\n csvfile.close()\n\n for label in labels:\n pol_vals_dict[label] = np.ma.masked_values(\n pol_vals_dict[label], get_fillvalue())\n\n return flashnr, time_data, time_in_flash, lat, lon, alt, dBm, pol_vals_dict\n except EnvironmentError as ee:\n warn(str(ee))\n warn('Unable to read file ' + fname)\n return None, None, None, None, None, None, None, None",
"def read_fits(self, filename, byte_swap=True, add_tstart=False, time_col='TIME', rate_col='RATE', error_col='ERROR', hdu='RATE', inst=None, bkg=False):\n # shortcut for loading Chandra light curves which helpfully have different HDU and column names!\n if inst == 'chandra':\n time_col = 'TIME'\n rate_col = 'NET_RATE'\n error_col = 'ERR_RATE'\n hdu = 'LIGHTCURVE'\n\n try:\n printmsg(1, \"Reading light curve from \" + filename)\n fitsfile = pyfits.open(filename)\n tabdata = fitsfile[hdu].data\n\n self.time = np.array(tabdata[time_col])\n self.rate = np.array(tabdata[rate_col])\n self.error = np.array(tabdata[error_col])\n\n if byte_swap:\n self._byteswap()\n\n if add_tstart:\n try:\n tstart = fitsfile[0].header['TSTART']\n self.time += tstart\n except:\n raise AssertionError(\"pyLag LightCurve ERROR: Could not read TSTART from FITS header\")\n\n if bkg:\n self.bkg_rate = np.array(tabdata['BACKV'])\n self.bkg_error = np.array(tabdata['BACKE'])\n\n fitsfile.close()\n\n except:\n raise AssertionError(\"pyLag LightCurve ERROR: Could not read light curve from FITS file\")",
"def stage1_lox_loading(self, stage1_lox_loading):\n\n\n self._stage1_lox_loading = stage1_lox_loading",
"def get_light_curves():\n \n # Make sure the required files are downloaded\n if 'Duration.dat' not in os.listdir('summary'):\n get_summary_files()\n if 'duration_data.dat' not in os.listdir('DataFrames'):\n duration_data_to_df()\n if 'LightCurves' not in os.listdir():\n os.mkdir(\"LightCurves\")\n\n trig_ids = pd.read_pickle(\"DataFrames/duration_data.dat\").loc[:, 'Trig_id']\n downloaded = map(lambda s: s[: -7], os.listdir(\"LightCurves\")) # Ret lige i den her\n\n operations = {'Downloaded' : [], 'Eroor': [], 'Existed':[]}\n \n\n while len(trig_ids) > 0:\n get = trig_ids.pop(0)",
"def read_lammps_data_file(lammps_data):\n switch = \"none\"\n type_list = {} # number of each CG type \n lattice = np.zeros((3)) # lattice constants\n\n #read data from lammps file\n LIST_IN = open(lammps_data, 'r')\n print \"Starting to read: \", lammps_data\n \n for line in LIST_IN:\n NewRow = (line.strip()).split()\n if len(NewRow)>0: \n NewRow[0] = NewRow[0].lower() # enable case-insensitive string compares. \n if NewRow[0] == \"bonds\":\n switch = \"bonds\"\n if switch == \"atoms\":\n if len(NewRow)>6:\n #print NewRow[2], NewRow[0]\n grow_dict_array(type_list, NewRow[2], NewRow[0])\n if NewRow[0] == \"atoms\":\n switch = \"atoms\"\n if len(NewRow)>2:\n if NewRow[2] == \"xlo\":\n lattice[0] = float(NewRow[1]) - float(NewRow[0])\n if NewRow[2] == \"ylo\":\n lattice[1] = float(NewRow[1]) - float(NewRow[0])\n if NewRow[2] == \"zlo\":\n lattice[2] = float(NewRow[1]) - float(NewRow[0])\n\n LIST_IN.close()\n return lattice, type_list",
"def read_using_l1b_io(args):\n l1b = L1BioRAD(args.input_file)\n print(l1b)\n print(l1b.get_processor_version())\n print(l1b.get_creation_time())\n print(l1b.get_coverage_time())\n orbit = l1b.get_orbit()\n\n l1b.select()\n for key in l1b:\n print('{}: {!r}'.format(key, l1b.__getattribute__(key)))\n geo = l1b.get_geo_data(icid=args.icid, geo_dset='solar_zenith_angle')\n print('geodata: ', geo.dtype.names, geo.shape,\n np.mean(geo['solar_zenith_angle'], axis=1).shape)\n indx = np.where(np.mean(geo['solar_zenith_angle'], axis=1) <= 85)[0]\n res = l1b.get_msm_data('radiance', icid=args.icid, fill_as_nan=True)\n res_b7 = res[indx, ...]\n l1b.close()\n\n l1b = L1BioRAD(args.input_file.replace('_BD7_', '_BD8_'))\n print(l1b)\n l1b.select()\n res = l1b.get_msm_data('radiance', icid=args.icid, fill_as_nan=True)\n res_b8 = res[indx, ...]\n l1b.close()\n res = np.dstack((res_b7, res_b8))\n print('radiance', res.shape)\n\n plot = S5Pplot('test_plot_l1b_io.pdf')\n plot.draw_signal(biweight(res, axis=0),\n sub_title='orbit={}, ICID={}'.format(orbit, args.icid))\n\n plot.draw_trend2d(biweight(res, axis=2), time_axis=0,\n sub_title='orbit={}, ICID={}'.format(orbit, args.icid))\n\n plot.draw_trend2d(biweight(res, axis=1), time_axis=1,\n sub_title='orbit={}, ICID={}'.format(orbit, args.icid))\n plot.close()",
"def lro(self, file_list, output='LRO_avg.dat', template=None):\n\n\ttemplate = template or self.templates['lro']\n\tif type(file_list) != list:\n\t file_list = fullrange(file_list)[1:]\n\n\tself.__lro_file_list = file_list\n\n\tfiles = [ self.path + template % x for x in file_list ]\n\tprint \"Loading files: \" + str(files)\n\tself.LRO_avg, self.LRO_raw = average_waves(files, output=self.path + output, usecols=(0,3,4))\n\tself.LROvar_avg, self.LROvar_raw = average_waves(files, output=self.path+output.replace('LRO','LROvar'), usecols=(0,1,2))",
"def load_lattice(filename):\n lattice = np.load(filename)\n print (\"SOM lattice loaded from %s\" %filename)\n return lattice",
"def load_snpcc_lc(self, path_to_data: str):\n\n # set the designation of the data set\n self.dataset_name = 'SNPCC'\n\n # set filters\n self.filters = ['g', 'r', 'i', 'z']\n\n # set SN types\n snii = ['2', '3', '4', '12', '15', '17', '19', '20', '21', '24', '25',\n '26', '27', '30', '31', '32', '33', '34', '35', '36', '37',\n '38', '39', '40', '41', '42', '43', '44']\n\n snibc = ['1', '5', '6', '7', '8', '9', '10', '11', '13', '14', '16',\n '18', '22', '23', '29', '45', '28']\n\n # read light curve data\n op = open(path_to_data, 'r')\n lin = op.readlines()\n op.close()\n\n # separate elements\n data_all = np.array([elem.split() for elem in lin])\n\n # flag useful lines\n flag_lines = np.array([True if len(line) > 1 else False for line in data_all])\n\n # get only informative lines\n data = data_all[flag_lines]\n\n photometry_raw = [] # store photometry\n header = [] # store parameter header\n\n # get header information\n for line in data:\n if line[0] == 'SNID:':\n self.id = int(line[1])\n self.id_name = 'SNID'\n elif line[0] == 'SNTYPE:':\n if line[1] == '-9':\n self.sample = 'test'\n else:\n self.sample = 'train'\n elif line[0] == 'SIM_REDSHIFT:':\n self.redshift = float(line[1])\n elif line[0] == 'SIM_NON1a:':\n self.sncode = line[1]\n if line[1] in snibc:\n self.sntype = 'Ibc'\n elif line[1] in snii:\n self.sntype = 'II'\n elif line[1] == '0':\n self.sntype = 'Ia'\n else:\n raise ValueError('Unknown supernova type!')\n elif line[0] == 'VARLIST:':\n header: list = line[1:]\n elif line[0] == 'OBS:':\n photometry_raw.append(np.array(line[1:]))\n elif line[0] == 'SIM_PEAKMAG:':\n self.sim_peakmag = np.array([float(item) for item in line[1:5]])\n\n # transform photometry into array\n photometry_raw = np.array(photometry_raw)\n\n # put photometry into data frame\n self.photometry['mjd'] = np.array([float(item) for item in photometry_raw[:, header.index('MJD')]])\n self.photometry['band'] = np.array(photometry_raw[:, header.index('FLT')])\n self.photometry['flux'] = np.array([float(item) for item in photometry_raw[:, header.index('FLUXCAL')]])\n self.photometry['fluxerr'] = np.array([float(item) for item in photometry_raw[:, header.index('FLUXCALERR')]])\n self.photometry['SNR'] = np.array([float(item) for item in photometry_raw[:, header.index('SNR')]])\n self.photometry['MAG'] = np.array([float(item) for item in photometry_raw[:, header.index('MAG')]])\n self.photometry['MAGERR'] = np.array([float(item) for item in photometry_raw[:, header.index('MAGERR')]])",
"def stage2_lox_loading(self, stage2_lox_loading):\n\n\n self._stage2_lox_loading = stage2_lox_loading",
"def get_binLF(self,Lbin=0.3,zbin=None,plot_fig=False):\n \n if self.data_loaded is False:\n self.load_sample() \n if zbin is None:\n z1=KdeLF.z1\n z2=KdeLF.z2\n else:\n if type(zbin)==list and len(zbin)==2:\n z1,z2=zbin\n else:\n print(\"'zbin' input error, 'zbin' should be a list of two real numbers, e.g., [0.1,0.5]\")\n return\n \n Lmin=KdeLF.Lmin \n Lmax=KdeLF.Lmax \n nLbin=int((Lmax-Lmin)/Lbin) \n Ls=np.empty(nLbin)\n lgphi=np.empty(nLbin)\n nums=np.empty(nLbin)\n zz1=max(1e-6,z1)\n L0=max(Lmin,self.f_lim(zz1))\n f_lim_z2=self.f_lim(z2)\n #print('L0',L0)\n L1=L0\n L2=L1+Lbin \n k=0\n for i in range(nLbin):\n num=0\n for j in range(KdeLF.ndata): \n if KdeLF.red[j]>=z1 and KdeLF.red[j]<z2 and KdeLF.lum[j]>=L1 and KdeLF.lum[j]<L2:\n #if KdeLF.lum[j]>=L1 and KdeLF.lum[j]<L2:\n num=num+1\n #print('L1,L2,num',L1,L2,num)\n Lo=self.f_lim((z1+z2)/2)\n Lc=L1+Lbin/2\n if num>0: #and Lc>=Lo:\n if L2<f_lim_z2:\n x0=optimize.brentq(self.f,zz1,z2,args=(L2))\n #print('x0',x0)\n else:\n x0=z2\n area = dblquad(self.rho, z1, x0, lambda z: max(self.f_lim(z),L1), lambda z: L2)\n #print('area',area)\n phi=num/area[0]\n Ls[k]=Lc\n lgphi[k]=phi #np.log10(phi)\n nums[k]=num\n #print(k,L[k],lgphi[k])\n k=k+1\n L1=L1+Lbin\n L2=L2+Lbin\n if L1>=Lmax:\n break \n #result=np.empty((2,k)) \n #result[0]=L[0:k];result[1]=lgphi[0:k] #$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ \n Ls=Ls[0:k]\n lgphi=lgphi[0:k] \n nums=nums[0:k] \n \n # Calculate errorbars on our binned LF. These have been estimated\n # using Equations 1 and 2 of Gehrels 1986 (ApJ 303 336), as\n # implemented in astropy.stats.poisson_conf_interval. The\n # interval='frequentist-confidence' option to that astropy function is\n # exactly equal to the Gehrels formulas. (also see Kulkarni et al. 2019, MNRAS, 488, 1035) \n \n nlims = pci(nums,interval='frequentist-confidence')\n nlims *= lgphi/nums\n lgphi=np.log10(lgphi) \n uperr = np.log10(nlims[1]) - lgphi \n downerr = lgphi - np.log10(nlims[0])\n left=Ls*0+Lbin/2\n right=Ls*0+Lbin/2 \n \n if plot_fig is True: \n plt.figure(figsize=(8,6)) \n ax=plt.axes([0.13,0.1, 0.82, 0.85])\n ax.tick_params(direction='in', top=True, right=True, labelsize=12) \n plt.plot(Ls,lgphi,'o',mfc='white',mec='black',ms=9,mew=1.0,alpha=0.7,label=r'$\\hat{\\phi}_{\\mathrm{bin}}$') # plot_bin\n ax.errorbar(Ls, lgphi, ecolor='k', capsize=0, xerr=np.vstack((left, right)), \n yerr=np.vstack((uperr, downerr)),fmt='None', zorder=4, alpha=0.5)\n\n if self.absolute_magnitude is True:\n #tx=lmax-(lmax-KdeLF.Lmin)*0.618\n #ty=y1+(y2-y1)*0.88\n #ax.text(tx,ty,'z='+'%.3f' %z,fontsize=13,bbox=dict(boxstyle='square,pad=0.3', fc='yellow', ec='k',lw=0.5 ,alpha=0.4)) \n plt.ylabel(r'$\\log_{10}( \\phi(z,M) ~/~ {\\rm Mpc}^{-3} ~ \\mathrm{mag}^{-1} )$',fontsize=18)\n plt.xlabel(r'$M$',fontsize=18) \n else: \n plt.ylabel(r'$\\log_{10}( \\phi(z,L) ~/~ {\\rm Mpc}^{-3} ~ \\Delta L^{-1} )$',fontsize=18)\n plt.xlabel(r'$\\log_{10} ~ L$',fontsize=18)\n plt.legend(loc='best', fontsize=12)\n plt.savefig('binLF.png')\n plt.show() \n \n return Ls,left,right,lgphi,uperr,downerr",
"def _load_btl_data(btl_file, cols=None):\n btl_data = dataToNDarray(btl_file,float,True,',',0)\n btl_data = pd.DataFrame.from_records(btl_data)\n if cols != None:\n btl_data = btl_data[cols]\n btl_data[\"SSSCC\"] = Path(btl_file).stem.split(\"_\")[0]\n\n return btl_data",
"def load_landlab_components(paths=None):\n return load_components(BmiBase, paths=paths)",
"def load_light_color(self):\n if hasattr(self, \"lightcolor\"):\n return self.lightcolor\n try:\n lightcolor = list(self.load_image(\"light_normal.png\").getdata())\n except Exception:\n logging.warning(\"Light color image could not be found.\")\n lightcolor = None\n self.lightcolor = lightcolor\n return lightcolor"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Prepare proxied file for HTTP
|
def __prepareFileForHTTP( self, lfn, key ):
global HTTP_PATH
res = self.__prepareSecurityDetails()
if not res['OK']:
return res
# Clear the local cache
getFileDir = "%s/%s" % ( HTTP_PATH, key )
os.makedirs(getFileDir)
# Get the file to the cache
from DIRAC.DataManagementSystem.Client.DataManager import DataManager
dataMgr = DataManager()
result = dataMgr.getFile( lfn, destinationDir = getFileDir )
result['CachePath'] = getFileDir
return result
|
[
"def __setHTTPProxy():\n\n global proxyHandler\n\n if not conf.proxy: \n if conf.hostname in ('localhost', '127.0.0.1') or conf.ignoreProxy:\n proxyHandler = urllib2.ProxyHandler({})\n return\n\n debugMsg = \"setting the HTTP proxy to pass by all HTTP requests\"\n logger.debug(debugMsg)\n\n __proxySplit = urlparse.urlsplit(conf.proxy)\n __hostnamePort = __proxySplit[1].split(\":\")\n\n __scheme = __proxySplit[0]\n __hostname = __hostnamePort[0]\n __port = None\n\n if len(__hostnamePort) == 2:\n try:\n __port = int(__hostnamePort[1])\n except:\n pass #drops into the next check block\n\n if not __scheme or not __hostname or not __port:\n errMsg = \"proxy value must be in format 'http://url:port'\"\n raise sqlmapSyntaxException, errMsg\n\n __proxyString = \"%s:%d\" % (__hostname, __port)\n\n # Workaround for http://bugs.python.org/issue1424152 (urllib/urllib2:\n # HTTPS over (Squid) Proxy fails) as long as HTTP over SSL requests\n # can't be tunneled over an HTTP proxy natively by Python (<= 2.5)\n # urllib2 standard library\n if conf.scheme == \"https\":\n proxyHandler = ProxyHTTPSHandler(__proxyString)\n else:\n proxyHandler = urllib2.ProxyHandler({\"http\": __proxyString})",
"def _forward_request(self):\n headers = self._get_headers_as_dict()\n if 'Host' not in headers:\n self._send_generic_failure()\n return\n else:\n host = headers['Host'].split(':')[0]\n print(\"Proxying request for: {}\".format(host))\n\n if host not in HOSTS:\n self._send_generic_failure()\n return\n proxied_host = HOSTS[host]\n headers.pop('Host')\n\n ibody = self.rfile.read(self._get_content_length(headers))\n proxy_connection = HTTPConnection(proxied_host)\n\n try:\n proxy_connection.request(self.command, self.path, body=ibody, headers=headers)\n except Exception as e:\n print(\"Error occured: \" + str(e)) # This one is worth logging.\n self._send_generic_failure()\n return\n response = proxy_connection.getresponse()\n body = response.read()\n response.close()\n self.send_response(response.status)\n for header, value in response.getheaders():\n if header not in SUPPLANTED_HEADERS:\n self.send_header(header, value)\n self.end_headers()\n self.wfile.write(body)",
"def _setup_http_proxy(self):\r\n headers = {}\r\n\r\n if self.proxy_username and self.proxy_password:\r\n # Include authentication header\r\n user_pass = '%s:%s' % (self.proxy_username, self.proxy_password)\r\n encoded = base64.encodestring(b(urlunquote(user_pass))).strip()\r\n auth_header = 'Basic %s' % (encoded.decode('utf-8'))\r\n headers['Proxy-Authorization'] = auth_header\r\n\r\n if hasattr(self, 'set_tunnel'):\r\n # Python 2.7 and higher\r\n # pylint: disable=no-member\r\n self.set_tunnel(host=self.host, port=self.port, headers=headers)\r\n elif hasattr(self, '_set_tunnel'):\r\n # Python 2.6\r\n # pylint: disable=no-member\r\n self._set_tunnel(host=self.host, port=self.port, headers=headers)\r\n else:\r\n raise ValueError('Unsupported Python version')\r\n\r\n self._set_hostport(host=self.proxy_host, port=self.proxy_port)",
"def __setRequestFromFile():\n\n if not conf.requestFile:\n return\n \n conf.requestFile = os.path.expanduser(conf.requestFile)\n \n infoMsg = \"parsing HTTP request from '%s'\" % conf.requestFile\n logger.info(infoMsg)\n\n if not os.path.isfile(conf.requestFile):\n errMsg = \"the specified HTTP request file \"\n errMsg += \"'%s' does not exist\" % conf.requestFile\n raise sqlmapFilePathException, errMsg\n \n fp = open(conf.requestFile, \"r\")\n fread = fp.read()\n fread = fread.replace(\"\\r\", \"\")\n fp.close()\n \n lines = fread.split(\"\\n\")\n \n if len(lines) == 0:\n errMsg = \"the specified HTTP request file \"\n errMsg += \"'%s' has no content\" % conf.requestFile\n raise sqlmapFilePathException, errMsg\n \n if not (lines[0].upper().startswith(\"GET \") or lines[0].upper().startswith(\"POST \")):\n errMsg = \"the specified HTTP request file \"\n errMsg += \"doesn't start with GET or POST keyword\"\n raise sqlmapFilePathException, errMsg\n\n \n if lines[0].upper().startswith(\"GET \"):\n index = 4\n else:\n index = 5\n\n if lines[0].upper().find(\" HTTP/\") == -1:\n errMsg = \"the specified HTTP request file \" \n errMsg += \"has a syntax error at line: 1\"\n raise sqlmapFilePathException, errMsg\n \n host = None\n headers = \"\"\n page = lines[0][index:lines[0].index(\" HTTP/\")]\n \n if conf.method:\n warnMsg = \"HTTP method previously set. overriding it with \"\n warnMsg += \"the value supplied from the HTTP request file\"\n logger.warn(warnMsg)\n conf.method = lines[0][:index-1]\n\n for index in xrange(1, len(lines) - 1):\n line = lines[index]\n valid = True\n \n if len(line) == 0:\n break\n \n headers += line + \"\\n\"\n \n items = line.split(': ')\n if len(items) != 2:\n valid = False\n else:\n if items[0].upper() == \"HOST\":\n host = items[1]\n \n if not valid:\n errMsg = \"the specified HTTP request file\" \n errMsg += \"has a syntax error at line: %d\" % (index + 1)\n raise sqlmapFilePathException, errMsg\n \n if conf.headers and headers:\n warnMsg = \"HTTP headers previously set. overriding it with \"\n warnMsg += \"the value(s) supplied from the HTTP request file\"\n logger.warn(warnMsg)\n conf.headers = headers.strip(\"\\n\")\n \n if fread.find(\"\\n\\n\") != -1:\n if conf.data:\n warnMsg = \"HTTP POST data previously set. overriding it with \"\n warnMsg += \"the value supplied from the HTTP request file\"\n logger.warn(warnMsg)\n conf.data = fread[fread.index('\\n\\n')+2:].strip(\"\\n\")\n \n if conf.url:\n warnMsg = \"target url previously set. overriding it with \"\n warnMsg += \"the value supplied from the HTTP request file\"\n logger.warn(warnMsg)\n \n if host:\n conf.url = \"%s%s\" % (host, page)\n else:\n errMsg = \"mandatory HTTP header HOST is missing in \"\n errMsg += \"the HTTP request file\"\n raise sqlmapFilePathException, errMsg",
"def prepare_url(self, app, path):\n\n # the base url we will use for the connection\n self._base_url = self.setup['http'] + self.setup['hostname'] + ':' + \\\n self.setup['port'] + self.setup['path']\n\n # the specific path we are building\n self.url = self._base_url + app + '/' + self.setup['container'] + path",
"def create_proxy_from_file(issuer_cred_file, public_key, lifetime_hours=1):\n with open(issuer_cred_file) as f:\n issuer_cred = f.read()\n return create_proxy(issuer_cred, public_key, lifetime_hours)",
"def write_proxy(self, proxy):\n with open(proxyfile, 'a') as ofile:\n ofile.write(proxy + '\\n')\n return",
"def __load_proxies_from_file(self):\n proxies_from_file = set()\n try:\n with open(\"http_handler/proxy_data.csv\", 'r', encoding='utf-8') as fd:\n for line in fd:\n line = line.split(' ')\n proxies_from_file.add(line[:-1][0])\n except BaseException as e:\n logs.save_log(\"Exception: failed to load proxies at __load_proxies_from_file method, Error: {}\".format(e))\n print(str(e))\n return\n finally:\n self._address_pool |= proxies_from_file\n self.__update_cycle()",
"def __init__(self, proxies=None):\n self._address_pool = set() if proxies is None else set(proxies)\n self._address_pool_cycle = cycle(self._address_pool)\n self.__load_proxies_from_file()",
"def process(self):\n self.requestHeaders.setRawHeaders(b\"host\",\n [self.factory.host.encode('ascii')])\n clientFactory = self.proxyClientFactoryClass(\n self.method, self.uri, self.clientproto, self.getAllHeaders(),\n self.content.read(), self)\n self.reactor.connectTCP(self.factory.host, self.factory.port,\n clientFactory)",
"def proxify_request(self, f):\n self.proxy_req_handlers.append(f)",
"def __init__(self, host, port):\n self.base_url = \"http://{}:{:d}{}\".format(host, port, self.ENDPOINT)\n self.root = Proxy(self, \"\")\n self.session = requests.Session()",
"def get_proxy(proxy_total):\n\n config = cfg.get_config()\n conn = db.connect()\n\n xml_path = config[\"paths\"][\"xml_path\"]\n proxy_path = config[\"paths\"][\"proxy_path\"]\n tmp_checkin = config[\"paths\"][\"tmp\"]\n root_path = config[\"paths\"][\"root_path\"]\n\n rows = db.fetchall_proxy(\"assets\")\n\n proxy_count = 0\n\n for row in rows:\n rowid = row[0]\n guid = str(row[1])\n proxy_copied = row[22]\n guid_x = guid.replace(\"-\", \"\")\n guid_r = guid_x[24:]\n proxy_fn = guid + \".mov\"\n\n \"\"\"\n Use the parts GUID to generate a list that will be used to build the path to the proxy.\n \"\"\"\n n = 2\n glist = [guid_r[i : i + n] for i in range(0, len(guid_r), n)]\n\n proxy_fpath = os.path.join(proxy_path, glist[2], glist[3], guid, proxy_fn)\n\n if (\n proxy_count < int(proxy_total)\n and proxy_copied == 0\n and os.path.exists(proxy_fpath) is True\n ):\n\n try:\n pcopy = file_copy(proxy_fpath, tmp_checkin)\n\n if len(pcopy) == 0:\n row = db.fetchone_proxy(guid)\n db.update_column(\"assets\", \"proxy_copied\", 1, rowid)\n proxy_cp_msg = f\"{proxy_fn} was copied to the dalet tmp.\"\n logger.info(proxy_cp_msg)\n proxy_count += 1\n else:\n pass\n proxy_err_cp_msg = (\n f\"{proxy_fn} encountered an error on the copy to the dalet tmp.\"\n )\n logger.info(proxy_err_cp_msg)\n\n except Exception as e:\n proxy_excp_msg = f\"\\n\\\n Exception raised on the Proxy copy.\\n\\\n Error Message: {str(e)} \\n\\\n \"\n logger.exception(proxy_excp_msg)\n break\n else:\n if os.path.exists(proxy_fpath) is not True:\n proxy_err_msg = f\"Proxy path does not exist. \\n\\\n {proxy_fpath}\"\n logger.error(proxy_err_msg)\n db.update_column(\"assets\", \"proxy_copied\", 2, rowid)\n continue\n\n os.chdir(root_path)\n proxy_complete_msg = f\"PROXY COPY COMPLETE. \\n\\\n {proxy_count} proxies copied \\n\"\n\n logger.info(proxy_complete_msg)\n\n return",
"def test_get_proxy_information_with_proxy_over_http(self):\n self.configure_response(\n proxy_manager={'http://': 'http://local.proxy:3939'},\n )\n self.configure_request(\n url='http://example.com',\n method='GET',\n )\n\n assert dump._get_proxy_information(self.response) == {\n 'request_path': 'http://example.com'\n }",
"def uploadProxy( self, proxy = False, useDNAsUserName = False ):\n retVal = FileSec.multiProxyArgument( proxy )\n if not retVal[ 'OK' ]:\n return retVal\n proxyDict = retVal[ 'Value' ]\n chain = proxyDict[ 'chain' ]\n proxyLocation = proxyDict[ 'file' ]\n\n #timeLeft = int( chain.getRemainingSecs()[ 'Value' ] / 3600 )\n\n cmdArgs = [ '-n' ]\n cmdArgs.append( '-s \"%s\"' % self._secServer )\n #cmdArgs.append( '-c \"%s\"' % ( timeLeft - 1 ) )\n #cmdArgs.append( '-t \"%s\"' % self._secMaxProxyHours )\n cmdArgs.append( '-C \"%s\"' % proxyLocation )\n cmdArgs.append( '-y \"%s\"' % proxyLocation )\n cmdArgs.append( ' -n -R wms-enmr.cerm.unifi.it ')\n #cmdArgs.append( ' -n -R prod-wms-01.pd.infn.it ')\n if useDNAsUserName:\n cmdArgs.append( '-d' )\n else:\n retVal = self._getUsername( chain )\n if not retVal[ 'OK' ]:\n FileSec.deleteMultiProxy( proxyDict )\n return retVal\n mpUsername = retVal[ 'Value' ]\n cmdArgs.append( '-l \"%s\"' % mpUsername )\n\n mpEnv = self._getExternalCmdEnvironment()\n #Hack to upload properly\n mpEnv[ 'GT_PROXY_MODE' ] = 'old'\n \n os.environ['PATH'] = '/opt/globus/bin/'\n cmd = \"/opt/globus/bin/myproxy-init %s\" % \" \".join( cmdArgs )\n result = shellCall( self._secCmdTimeout, cmd, env = mpEnv )\n\n FileSec.deleteMultiProxy( proxyDict )\n\n if not result['OK']:\n errMsg = \"Call to myproxy-init failed: %s\" % retVal[ 'Message' ]\n return S_ERROR( errMsg )\n\n status, output, error = result['Value']\n\n # Clean-up files\n if status:\n errMsg = \"Call to myproxy-init failed\"\n extErrMsg = 'Command: %s; StdOut: %s; StdErr: %s' % ( cmd, result, error )\n return S_ERROR( \"%s %s\" % ( errMsg, extErrMsg ) )\n\n return S_OK( output )",
"def proxy(request):\n full_url = request.get_full_path()\n http = urllib3.PoolManager()\n url = settings.PROXY_BASE_URL + full_url.replace(\"/elasticsearch/\", \"\")\n content_type = {'Content-Type':request.META.get('CONTENT_TYPE')}\n response = http.request(request.method, url, headers=content_type, body=request.body)\n r_type = response.getheader('content-type')\n r_data = response.data\n r_status = response.status\n return HttpResponse(content=r_data, content_type=r_type, status=r_status)",
"def create_url_adapter(self, request):\n if request is not None:\n\n Website = Pool().get('nereid.website')\n\n website = Website.get_from_host(request.host)\n rv = website.get_url_adapter(self).bind_to_environ(\n request.environ,\n server_name=self.config['SERVER_NAME']\n )\n return rv",
"def make_cached_file(url, fname):\n response = fetch_url(url)\n lfile = open(fname, \"w\")\n lfile.write(json.dumps(response, indent=2))\n lfile.close()",
"def generate_handler():\n class Handler(server.BaseHTTPRequestHandler):\n \"\"\"\n The base http request header\n \"\"\"\n def do_GET(self):\n \"\"\"\n sets the information for the GET request\n \"\"\"\n\n url = urllib.parse.urlparse(self.path)\n url_queries = url.query.split('&')\n\n valid_path = '/subnet?' + url_queries[0] + '&' + url_queries[1]\n if ((len(url_queries) == MAX_URL_QUERIES) and (self.path == valid_path)):\n self.send_response(200)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n ip_address = url_queries[0]\n subnet_mask = url_queries[1]\n html = set_ip_html_information(ip_address, subnet_mask)\n self.wfile.write(html.encode())\n elif not self.path.startswith('/subnet?'):\n self.send_response(404)\n else:\n self.send_error(400)\n return Handler"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Method to send files to clients. fileID is the local file name in the SE. token is used for access rights confirmation.
|
def transfer_toClient( self, fileID, token, fileHelper ):
file_path = "%s/%s" % ( BASE_PATH, fileID )
result = fileHelper.getFileDescriptor( file_path, 'r' )
if not result['OK']:
result = fileHelper.sendEOF()
# check if the file does not really exist
if not os.path.exists(file_path):
return S_ERROR('File %s does not exist' % os.path.basename(file_path))
else:
return S_ERROR('Failed to get file descriptor')
fileDescriptor = result['Value']
result = fileHelper.FDToNetwork(fileDescriptor)
if not result['OK']:
return S_ERROR('Failed to get file %s' % fileID )
if os.path.exists(file_path):
os.remove( file_path )
return result
|
[
"def fileTransferToClient(id, filename, client):\r\n path = (r\"C:\\Cyber\\SafeBoxOnlline\\\\\" + id + r\"\\\\\" + filename)\r\n size = os.path.getsize(path)\r\n if size == 0:\r\n client.send(b\"empty file\")\r\n else:\r\n with open(path, \"rb\") as f:\r\n file_data = f.read(1024)\r\n while (file_data):\r\n client.send(file_data)\r\n file_data = f.read(1024)\r\n client.send(b'endofthefile')",
"def send_file(self, file, to):\n SendFile.file = file\n SendFile.to = to\n SendFile.client = self\n SendFile().start()",
"def fileTransferToServer(id, filename, client):\r\n path = (r\"C:\\Cyber\\SafeBoxOnlline\\\\\" + id + r\"\\\\\" + filename)\r\n files_and_directories = os.listdir(r\"C:\\Cyber\\SafeBoxOnlline\\\\\" + id)\r\n if len(files_and_directories) == 9:\r\n client.send(b'there 9 files in the folder, delete some files')\r\n else:\r\n client.send(b'upload successfully')\r\n with open(path, \"wb\") as f:\r\n while True:\r\n data = (client.recv(1024))\r\n if data[-12:] == b'endofthefile':\r\n f.write(data[:-12])\r\n break\r\n else:\r\n f.write(data)\r\n\r\n print(\"file upload secssfuly\")\r\n\r\n if (get_size(r\"C:\\Cyber\\SafeBoxOnlline\\\\\" + id)>500000000 ):\r\n os.remove(r\"C:\\Cyber\\SafeBoxOnlline\\\\\" + id + r\"\\\\\" + filename)\r\n client.send(b' overLengh')\r\n else:\r\n client.send(b' end upload')",
"def transfer_fromClient( self, fileID, token, fileSize, fileHelper ):\n if not self.__checkForDiskSpace( BASE_PATH, fileSize ):\n return S_ERROR('Not enough disk space')\n\n file_path = \"%s/%s\" % ( BASE_PATH, fileID )\n if not os.path.exists( os.path.dirname( file_path ) ):\n os.makedirs( os.path.dirname( file_path ) )\n result = fileHelper.getFileDescriptor( file_path, 'w' )\n if not result['OK']:\n return S_ERROR('Failed to get file descriptor')\n\n fileDescriptor = result['Value']\n result = fileHelper.networkToFD(fileDescriptor)\n if not result['OK']:\n return S_ERROR('Failed to put file %s' % fileID )\n return result",
"def send_file(self): \n file_name = input(colored(\"Enter file name: \", SYS_COLOR))\n try:\n open(file_name, 'rb')\n except Exception as e:\n sysprint(\"[ERROR] : {}\".format(e))\n self.send(CODE['error'])\n return\n file_size = os.path.getsize(file_name)\n self.send(\"{}{}{}\".format(file_name, SEPERATOR, file_size))\n command = self.get()\n if command != CODE['ready']:\n sysprint(\"Error at server side\")\n return\n \n with open(file_name, 'rb') as file:\n while True:\n bytes_read = file.read(BUFFER)\n if not bytes_read:\n break\n self.server_socket.send(bytes_read)\n \n self.send(CODE['all_sent'])\n sysprint(\"Sent to server!\")",
"def send_file(filepath):\n status = itchat.send('@fil@{}'.format(filepath), toUserName='filehelper')\n return status",
"def send_file(self,\n http_send: 'HttpServer.send',\n conn: 'socket.socket',\n filename: str,\n headers: Union[dict, None] = None\n ):",
"def do_send_file_to_device(self, lab_session_id, content, file_info):\n if self.debug:\n print \"[Aquarium*] do_send_file_to_device called\"\n return \"ok\"",
"def send_file_to_SIMP(file_name):\r\n false, true = False, True\r\n upload_url = \"https://eu.core.resolver.com/creation/import\"\r\n data = open(file_name, 'rb')\r\n fields = {'file': (file_name, data, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')}\r\n m = MultipartEncoder(fields=fields, boundary='----WebKitFormBoundary'+''.join(random.sample(string.ascii_letters+string.digits, 16)))\r\n token = authentication()\r\n headers = {\"Connection\": \"keep-alive\", \"Content-Type\": m.content_type,\r\n \"Authorization\": f\"bearer {token}\"}\r\n payload = {\"dryRun\": false, \"usingExternalRefIds\": true,\r\n \"deferPostProcessing\": false}\r\n uploading = requests.post(upload_url, headers=headers, params=payload, data=m)\r\n return uploading.json()['jobId']",
"def upload_file_to_trello_card(self, key, token, card_id, file_path):\r\n\t\tparams = {'key': self.resource_owner_key, 'token': token}\r\n\t\tfiles = {'file': open(file_path, 'rb')}\r\n\t\turl = ATTACHMENTS_URL % card_id\r\n\t\treturn requests.post(url, params=params, files=files)",
"def send_file(self, file):\n file.seek(0, 2) # Seek end of file\n length = file.tell()\n print(length)\n self.client_socket.send(str(length).encode())\n if length > 0:\n time.sleep(0.5)\n file.seek(0, 0)\n content = file.read()\n print(content)\n self.client_socket.send(str(content).encode())",
"def __send_file(self, file: BinaryIO, filename: str):\n self.__send_string(filename)\n\n # get file size\n file.seek(0, io.SEEK_END)\n file_len = file.tell()\n file.seek(0)\n\n self.__send_int(file_len)\n self.socket.sendfile(file)",
"def send_file(self, client_addr, ephem_port, filename):\n if self.is_valid_file(filename):\n data = open(filename, 'rb').read()\n else:\n data = 'NXFILE'.encode()\n ephem_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n ephem_sock.connect((client_addr, ephem_port))\n protocol.send_msg(ephem_sock, data)\n ephem_sock.close()\n return\n\n # Create ephemeral socket\n ephem_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n ephem_sock.connect((client_addr, ephem_port))\n\n # Send file data to client\n print('Sending {} to {}'.format(filename, client_addr))\n try:\n protocol.send_msg(ephem_sock, filename.encode())\n protocol.send_msg(ephem_sock, data)\n\n md5_send = hashlib.md5(data).hexdigest()\n protocol.send_msg(ephem_sock, md5_send.encode()) # send md5 hash\n except Exception as e:\n print('Error: {}'.format(e))\n print('Unsuccessful transfer of {}'.format(filename))\n ephem_sock.close() \n return\n print('Transfer complete.')\n ephem_sock.close()",
"def upload_request(self, message):\n path_to_file = message[1]\n file_size = message[2]\n # Updates user filesystem\n filename = database.add_user_filesystem(self.username, path_to_file, file_size)\n self.recieve_file(filename, int(file_size))",
"def wc_send_file(self, name, file_path):\r\n\r\n\t\twindow = win32gui.FindWindow('ChatWnd', name) # get window handle\r\n\t\twin32gui.ShowWindow(window, win32con.SW_MAXIMIZE)\r\n\t\twindow = win32gui.FindWindow('ChatWnd', name)\r\n\r\n\t\t# prepare material to send\r\n\t\tapp = QtWidgets.QApplication([])\r\n\t\tdata = QtCore.QMimeData()\r\n\t\turl = QtCore.QUrl.fromLocalFile(file_path)\r\n\t\tdata.setUrls([url])\r\n\t\tapp.clipboard().setMimeData(data)\r\n\r\n\t\t# get control, paste and send file\r\n\t\twin32gui.SetForegroundWindow(window)\r\n\t\tself.__paste_file()\r\n\t\tself.__wc_send()",
"def downloadFile(self, file_id, mimetype, filename):\r\n self.checkToken()\r\n with open(self.drive_token_file, 'r') as token_f:\r\n token = token_f.read()\r\n parameters = {\r\n 'access_token' : token,\r\n 'mimeType': mimetype\r\n } \r\n #Exporting the data from the GDrive file\r\n response = requests.get(self.drive_base_url + self.list_url + '/' + file_id + '/export/', params = parameters) \r\n if response.status_code == 401 or response.status_code == 400:\r\n #Re-authenticating\r\n new_access_token = self.refreshToken()\r\n self.drive_access_token = new_access_token\r\n parameters['access_token'] = self.drive_access_token\r\n response = requests.get(self.drive_base_url + self.list_url + '/' + file_id + '/export/', params = parameters) \r\n try:\r\n data = response.text\r\n except:\r\n e = sys.exc_info()[0]\r\n print(\"Unexpected error: \" + e)\r\n return \r\n #Writing data into a CSV\r\n reader = csv.reader(data.splitlines())\r\n with open(filename,'w', newline='') as outfile:\r\n writer = csv.writer(outfile)\r\n print(\"Writing file %s to current folder\" %filename)\r\n writer.writerows(reader)\r\n return",
"def sendRemoteFiles(self, file_urls, message=None, thread_id=None, thread_type=ThreadType.USER):\n return Sender.s_send_remote_files(self.Sender, self, file_urls, message, thread_id, thread_type)",
"def file_upload(self):\r\n # INIT DATA\r\n data = {}\r\n\r\n # VESSEL ID\r\n vessel_id = request.args.get('vessel_id')\r\n\r\n # # GET DATA\r\n token = request.headers.get('token')\r\n userid = request.headers.get('userid')\r\n\r\n # CHECK TOKEN\r\n token_validation = self.validate_token(token, userid)\r\n\r\n if not token_validation:\r\n data[\"alert\"] = \"Invalid Token\"\r\n data['status'] = 'Failed'\r\n\r\n # RETURN ALERT\r\n return self.return_data(data)\r\n\r\n # RH_<VesselIMO>_<ImageID>\r\n parameters = self.couch_query.get_complete_values(\r\n vessel_id,\r\n \"PARAMETERS\"\r\n )\r\n\r\n # VESSEL IMO\r\n vessel_imo = parameters['PARAMETERS']['INFO']['IMO']\r\n\r\n file_upload = []\r\n filenames = request.files.getlist('upfile')\r\n for filename in filenames:\r\n\r\n try:\r\n\r\n file_name = filename.filename\r\n # ext = file_name.split(\".\")[-1]\r\n\r\n # if not self.allowed_file_type(file_name):\r\n\r\n # data[\"alert\"] = \"File Type Not Allowed!\"\r\n # data['status'] = 'Failed'\r\n # return self.return_data(data)\r\n\r\n except ImportError:\r\n\r\n data[\"alert\"] = \"No image!\"\r\n data['status'] = 'Failed'\r\n\r\n # RETURN ALERT\r\n return self.return_data(data)\r\n\r\n file_name = self.rename_file(vessel_id, file_name)\r\n\r\n vimg_data = {}\r\n vimg_data['vessel_id'] = vessel_id\r\n vimg_data['vessel_imo'] = vessel_imo\r\n vimg_data['file_name'] = file_name\r\n vimg_data['status'] = \"active\"\r\n vimg_data['created_on'] = time.time()\r\n\r\n # ADD FILE TO VESSEL FILE TABLE\r\n self.postgres.insert('vessel_file', vimg_data, 'vessel_file_id')\r\n\r\n # FILE NAME\r\n # file_name_upload = str(vessel_file_id) + \".\" + ext\r\n # upload_file = 'VesselFiles/' + \"RH_\" + vessel_imo + \"_\" + file_name_upload\r\n upload_file = 'VesselFiles/' + vessel_imo +\"/\" + file_name\r\n body = request.files['upfile']\r\n\r\n # SAVE TO S3\r\n url = \"\"\r\n if self.aws3.save_file(upload_file, body):\r\n url = self.aws3.get_url(upload_file)\r\n\r\n file_upload.append({\r\n \"filename\": file_name,\r\n \"url\": url\r\n })\r\n\r\n data[\"status\"] = \"ok\"\r\n data[\"data\"] = file_upload\r\n\r\n # RETURN\r\n return self.return_data(data)",
"def sendDocument(self, peer_id, path, random_id):\n\n document = self.uploadDocument(peer_id, path)\n url_send = 'https://api.vk.com/method/messages.send?attachment={0}&peer_id={1}&access_token={2}&random_id={3}&v=5.103'.format(document, peer_id, self.token, random_id)\n response_send = requests.get(url_send).json()"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Method to receive file from clients. fileID is the local file name in the SE. fileSize can be Xbytes or 1 if unknown. token is used for access rights confirmation.
|
def transfer_fromClient( self, fileID, token, fileSize, fileHelper ):
if not self.__checkForDiskSpace( BASE_PATH, fileSize ):
return S_ERROR('Not enough disk space')
file_path = "%s/%s" % ( BASE_PATH, fileID )
if not os.path.exists( os.path.dirname( file_path ) ):
os.makedirs( os.path.dirname( file_path ) )
result = fileHelper.getFileDescriptor( file_path, 'w' )
if not result['OK']:
return S_ERROR('Failed to get file descriptor')
fileDescriptor = result['Value']
result = fileHelper.networkToFD(fileDescriptor)
if not result['OK']:
return S_ERROR('Failed to put file %s' % fileID )
return result
|
[
"def receive_file_from_socket(self):\n pass",
"def fileTransferToClient(id, filename, client):\r\n path = (r\"C:\\Cyber\\SafeBoxOnlline\\\\\" + id + r\"\\\\\" + filename)\r\n size = os.path.getsize(path)\r\n if size == 0:\r\n client.send(b\"empty file\")\r\n else:\r\n with open(path, \"rb\") as f:\r\n file_data = f.read(1024)\r\n while (file_data):\r\n client.send(file_data)\r\n file_data = f.read(1024)\r\n client.send(b'endofthefile')",
"def transfer_toClient( self, fileID, token, fileHelper ):\n file_path = \"%s/%s\" % ( BASE_PATH, fileID )\n result = fileHelper.getFileDescriptor( file_path, 'r' )\n if not result['OK']:\n result = fileHelper.sendEOF()\n # check if the file does not really exist\n if not os.path.exists(file_path):\n return S_ERROR('File %s does not exist' % os.path.basename(file_path))\n else:\n return S_ERROR('Failed to get file descriptor')\n\n fileDescriptor = result['Value']\n result = fileHelper.FDToNetwork(fileDescriptor)\n if not result['OK']:\n return S_ERROR('Failed to get file %s' % fileID )\n \n if os.path.exists(file_path):\n os.remove( file_path )\n \n return result",
"def get_file(self, user: User): \n self.send(user, CODE['fileTransferS'])\n message = self.get(user)\n if message == CODE['error']:\n return\n self.send(user, CODE['ready'])\n file_name, file_size = message.split(SEPERATOR)\n file_name = os.path.basename(file_name)\n file_size = int(file_size)\n\n with open(file_name, \"wb\") as file:\n gotten = 0\n while gotten < file_size:\n bytes_read = user.client_socket.recv(BUFFER)\n file.write(bytes_read)\n gotten += len(bytes_read)\n \n command = self.get(user)\n if(command == CODE['all_sent']):\n print(\"Recieved!\")\n \n self.send_file(user, file_name, str(file_size))",
"def recv_file(self, client_sock):\n # Create ephemeral socket\n ephem_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n ephem_sock.bind(('', 0)) # 0 = first available port\n ephem_sock.listen(1)\n\n # Send the ephemeral port number to client\n ephem_name = ephem_sock.getsockname()\n protocol.send_msg(client_sock, str(ephem_name[1]).encode())\n\n # Accept any incoming connections on the ephemeral socket\n conn, addr = ephem_sock.accept()\n\n # Receive the file and store in cwd.\n try:\n filename = protocol.recv_msg(conn).decode()\n print('Receiving {} from {}'.format(\n filename, client_sock.getsockname()[0]))\n filedata = protocol.recv_msg(conn).decode()\n\n # Check file integrity\n md5_recv = protocol.recv_msg(conn).decode()\n md5_local = hashlib.md5(filedata.encode()).hexdigest()\n if md5_recv != md5_local:\n print('Corrupt file data during transfer.')\n return\n except Exception as e:\n print(e)\n print('Error receiving file {}'.format(filename))\n print('Unsuccessful transfer.')\n return\n\n with open(filename, 'w') as outfile: # write data file to file\n outfile.write(filedata)\n print('Transfer complete.')\n\n # Close the ephemeral socket.\n conn.close()\n ephem_sock.close()",
"def send_file(self): \n file_name = input(colored(\"Enter file name: \", SYS_COLOR))\n try:\n open(file_name, 'rb')\n except Exception as e:\n sysprint(\"[ERROR] : {}\".format(e))\n self.send(CODE['error'])\n return\n file_size = os.path.getsize(file_name)\n self.send(\"{}{}{}\".format(file_name, SEPERATOR, file_size))\n command = self.get()\n if command != CODE['ready']:\n sysprint(\"Error at server side\")\n return\n \n with open(file_name, 'rb') as file:\n while True:\n bytes_read = file.read(BUFFER)\n if not bytes_read:\n break\n self.server_socket.send(bytes_read)\n \n self.send(CODE['all_sent'])\n sysprint(\"Sent to server!\")",
"def send_file_info(filepath):\r\n total_file_size = os.path.getsize(filepath)\r\n send_response_to_client(PREPARE_FOR_FILE_MSG)\r\n send_response_to_client(total_file_size)",
"def fileTransferToServer(id, filename, client):\r\n path = (r\"C:\\Cyber\\SafeBoxOnlline\\\\\" + id + r\"\\\\\" + filename)\r\n files_and_directories = os.listdir(r\"C:\\Cyber\\SafeBoxOnlline\\\\\" + id)\r\n if len(files_and_directories) == 9:\r\n client.send(b'there 9 files in the folder, delete some files')\r\n else:\r\n client.send(b'upload successfully')\r\n with open(path, \"wb\") as f:\r\n while True:\r\n data = (client.recv(1024))\r\n if data[-12:] == b'endofthefile':\r\n f.write(data[:-12])\r\n break\r\n else:\r\n f.write(data)\r\n\r\n print(\"file upload secssfuly\")\r\n\r\n if (get_size(r\"C:\\Cyber\\SafeBoxOnlline\\\\\" + id)>500000000 ):\r\n os.remove(r\"C:\\Cyber\\SafeBoxOnlline\\\\\" + id + r\"\\\\\" + filename)\r\n client.send(b' overLengh')\r\n else:\r\n client.send(b' end upload')",
"def fetch_file(server, file_config):\n print(\"Fetching file: %s\" % file_config['zone_file'])\n \n # Prevents connecting to Verisign if the file is already in the directory\n if os.path.exists(file_config['zone_file']): return\n \n with FTP(server, ftp_user, ftp_pass) as ftp:\n ftp.retrbinary(\"RETR \" + file_config['zone_file'], open(file_config['zone_file'], 'wb').write)",
"def download_request(self, message):\n file_requested = message[1]\n user_files = database.get_user_filesystem(self.username)\n if file_requested not in user_files:\n self.send_text('File not found')\n return\n file_size = user_files[file_requested]['size']\n self.send_text('File exists,{}'.format(file_size))\n time.sleep(0.1)\n server_filename = user_files[file_requested]['location']\n self.send_file(server_filename, file_size)\n time.sleep(0.1)",
"def contact_server(socket_fd, file_name):\n try:\n check_file_exists(file_name)\n file_len_bytes = len(file_name).to_bytes(2, 'big')\n file_request = bytearray() + 0x497E.to_bytes(2, 'big') + 0x01.to_bytes(1, 'big') + file_len_bytes\n file_request += file_name.encode('utf-8')\n\n except:\n print(\"Error while creating a file_request\\n\")\n sys.exit(1)\n\n s = try_create_socket()\n s.settimeout(1)\n total_bytes_received = 0\n try:\n try_connect(s, socket_fd)\n\n try_send(s, file_request)\n\n header = try_receive(s, 8)\n total_bytes_received += 8\n\n check_magic_no(header)\n\n check_packet_type(header)\n\n status_code = check_status_code(header)\n\n if status_code == 1:\n new_file = open(file_name, 'wb+')\n try:\n while True:\n infile = s.recv(4096)\n if len(infile) < 4096:\n total_bytes_received += len(infile)\n new_file.write(infile)\n break\n total_bytes_received += len(infile)\n new_file.write(infile)\n\n new_file.close()\n\n data_size_from_server = int.from_bytes(header[4:], 'big')\n\n file_that_client_received = open(file_name, 'rb')\n\n content_of_file = file_that_client_received.read()\n\n check_file_length(data_size_from_server, len(content_of_file))\n\n file_that_client_received.close()\n\n print('File has been successfully downloaded!\\n')\n\n print('total bytes received from server is {} bytes\\n'.format(total_bytes_received))\n\n\n except Exception as e:\n print('Problem occurred while processing the file {}\\n'.format(e))\n new_file.close()\n\n except socket.timeout:\n print(\"client socket timed out\\n\")\n\n finally:\n print('client socket closed\\n')\n s.close()\n sys.exit()",
"def request_data_file_stream(file_path,\n buffer_size=DEFAULT_BUFFER_SIZE,\n progress_callback=None,\n client=None):\n if client and client.has_kerberos() and not client.has_auth_header():\n # kerberos currently does not support chunks\n with open(file_path, 'rb') as f:\n data = f.read()\n if progress_callback:\n progress_callback(1, 1)\n else:\n # upload it in chunks\n data = request_data_file_stream_gen(\n file_path,\n buffer_size=buffer_size,\n progress_callback=progress_callback)\n return data",
"def downloadFile(self, file_id, mimetype, filename):\r\n self.checkToken()\r\n with open(self.drive_token_file, 'r') as token_f:\r\n token = token_f.read()\r\n parameters = {\r\n 'access_token' : token,\r\n 'mimeType': mimetype\r\n } \r\n #Exporting the data from the GDrive file\r\n response = requests.get(self.drive_base_url + self.list_url + '/' + file_id + '/export/', params = parameters) \r\n if response.status_code == 401 or response.status_code == 400:\r\n #Re-authenticating\r\n new_access_token = self.refreshToken()\r\n self.drive_access_token = new_access_token\r\n parameters['access_token'] = self.drive_access_token\r\n response = requests.get(self.drive_base_url + self.list_url + '/' + file_id + '/export/', params = parameters) \r\n try:\r\n data = response.text\r\n except:\r\n e = sys.exc_info()[0]\r\n print(\"Unexpected error: \" + e)\r\n return \r\n #Writing data into a CSV\r\n reader = csv.reader(data.splitlines())\r\n with open(filename,'w', newline='') as outfile:\r\n writer = csv.writer(outfile)\r\n print(\"Writing file %s to current folder\" %filename)\r\n writer.writerows(reader)\r\n return",
"def get_file(file_id: str) -> dict:\n endpoint_url = '/real-time-response/entities/put-files/v1'\n params = {\n 'ids': file_id\n }\n response = http_request('GET', endpoint_url, params=params)\n return response",
"def download_box_file(file_name, file_id, client, destination_file_name=None):\n\n local_path = os.path.normpath(f'{os.getcwd()}/{destination_file_name}')\n\n with open(local_path, 'wb') as new_blob:\n client.file(file_id).download_to(new_blob)\n\n print(f'{file_name} successfully downloaded to {local_path}')\n\n return",
"def retrieveFile(_filename):\n print(\"Contacting server...\")\n url = \"http://cycada.ml/game/\" + _filename + \".txt\"\n _data = req.get(url)\n if _data.status_code == 200:\n print(\"File found!\")\n return _data.content.decode('utf-8') #convert to string from binary object\n else:\n print(\"Wrong ID, try relaunching.\")\n time.sleep(2)\n return False",
"def send_file(self, file):\n file.seek(0, 2) # Seek end of file\n length = file.tell()\n print(length)\n self.client_socket.send(str(length).encode())\n if length > 0:\n time.sleep(0.5)\n file.seek(0, 0)\n content = file.read()\n print(content)\n self.client_socket.send(str(content).encode())",
"def view_file(user_id, token):\n validation_res = validate_user(db, user_id, token, admin_requested=True)\n if not validation_res['valid']:\n # Return the error status code:\n abort(validation_res['status'])\n\n # Valid admin user. Load the file and return it:\n file_path = request.form.get('src')\n try:\n logging.info(f\"Reading file from {file_path}...\")\n with open(file_path, 'r') as fp:\n res = fp.read().encode('utf8')\n return res\n except Exception as e:\n # Failed - the path is not there\n print(e)\n abort(404)",
"def _response_file(self, directory: str, file_name: str, mimetype=None):\n if mimetype is None:\n mimetype = self._mime_type(file_name)\n return flask.send_from_directory(\n directory, file_name, mimetype=mimetype)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Check if the directory dpath can accomodate 'size' volume of data
|
def __checkForDiskSpace( dpath, size ):
dsize = (getDiskSpace(dpath)-1)*1024*1024
maxStorageSizeBytes = 1024*1024*1024
return ( min(dsize, maxStorageSizeBytes) > size )
|
[
"def check_disk_usage():\n du = shutil.disk_usage(\"/\")\n free = du.free / du.total * 100\n return free < 20",
"def check_free_space_in_dir(path, size):\n from ..utils.console import human_file_size\n\n space = get_free_space_in_dir(path)\n if space < size:\n raise IOError(\n \"Not enough free space in '{0}' \"\n \"to download a {1} file\".format(\n path, human_file_size(size)))",
"def check_size(archive_dir):\n overhead_bytes = 1024 ** 3 # extra GB for staging directory\n # Size of the cloned iso is directly proportional to the\n # installed package repository (note that patches are a part of\n # the system archive size below).\n # 1G overhead size added (above) will accomodate the temporary\n # workspace (updating system archive etc) needed to create the iso.\n feed_dir = os.path.join('/www', 'pages', 'feed',\n 'rel-' + tsconfig.SW_VERSION)\n overhead_bytes += backup_restore.backup_std_dir_size(feed_dir)\n\n clone_size = (\n overhead_bytes +\n backup_restore.backup_etc_size() +\n backup_restore.backup_config_size(tsconfig.CONFIG_PATH) +\n backup_restore.backup_puppet_data_size(constants.HIERADATA_PERMDIR) +\n backup_restore.backup_keyring_size(backup_restore.keyring_permdir) +\n backup_restore.backup_ldap_size() +\n backup_restore.backup_postgres_size() +\n backup_restore.backup_std_dir_size(backup_restore.home_permdir) +\n backup_restore.backup_std_dir_size(backup_restore.patching_permdir) +\n backup_restore.backup_std_dir_size(\n backup_restore.patching_repo_permdir) +\n backup_restore.backup_std_dir_size(backup_restore.extension_permdir) +\n backup_restore.backup_std_dir_size(\n backup_restore.patch_vault_permdir) +\n backup_restore.backup_armada_manifest_size(\n constants.ARMADA_PERMDIR) +\n backup_restore.backup_std_dir_size(\n constants.HELM_CHARTS_PERMDIR) +\n backup_restore.backup_mariadb_size())\n\n archive_dir_free_space = \\\n utils.filesystem_get_free_space(archive_dir)\n\n if clone_size > archive_dir_free_space:\n print(\"\\nArchive directory (%s) does not have enough free \"\n \"space (%s), estimated size to create image is %s.\" %\n (archive_dir,\n utils.print_bytes(archive_dir_free_space),\n utils.print_bytes(clone_size)))\n raise CloneFail(\"Not enough free space.\\n\")",
"def check_disk_space(self): # this is obsolete as it's done in a separate thread globally\n\n disk_space = shutil.disk_usage(self.the_path)\n if disk_space[2]//1048576 < 200:\n print('NOT ENOUGH SPACE ON DISK (<200MB)! SAVING PICTURES HAS STOPPED!')\n self.cam_opt['disk_full'] = 1\n self.cam_opt['tl_exit'] = 1\n return",
"def _ck_file_size(self,pdf,ckhs=False,min_size=1):\n key_list = [\"size\",\"config\"]\n if ckhs:\n key_list.append(\"hs_file\")\n \n for fsize in key_list:\n if pdf.get(fsize) < min_size:\n return False\n return True",
"def enough_space(self, size, path='/'):\n\n free_space = self._free_available_space(path=path)\n return free_space - size > SPACE_THRESHOLD",
"def check_parameter_file_sizes(wild_card_path):\n zero_sized = 0\n for parameter_file in glob.glob(wild_card_path):\n size = os.stat(parameter_file).st_size\n if size == 0:\n zero_sized += 1\n return zero_sized",
"def is_valid_file(path:Path, thresh=5):\n path = Path(path)\n if path.exists() and path.lstat().st_size > thresh:\n return True\n else: return False",
"def verify(info, directory_path):\n base_path = os.path.join(directory_path, info['name'])\n if 'length' in info:\n if os.stat(base_path).st_size != info['length']:\n return False\n getfile = lambda: open(base_path, 'rb')\n else:\n assert 'files' in info, 'invalid torrent file'\n for f in info['files']:\n p = os.path.join(base_path, *f['path'])\n if os.stat(p).st_size != f['length']:\n return False\n getfile = lambda: ConcatenatedFile(base_path, info['files'])\n with getfile() as f:\n return compare_checksum(info, f)",
"def admissible_seed_size(self, seed):\n seed_size_in_bytes = Path(seed).stat().st_size\n if seed_size_in_bytes >= self.args.file_size_limit:\n return False\n return True",
"def check_dataset_size(self, minimum_dataset_size):\n pass",
"def __len__(self):\n return len(self.data_path)",
"def check():\n path = os.path.abspath(os.path.dirname(__file__))\n fold = os.path.join(path, \"temp_difflibjs\")\n r = os.path.exists(fold)\n if not r:\n return r\n f = os.path.join(fold, \"jsdifflib.zip\")\n r = os.path.exists(f)\n if not r:\n return r\n size = os.stat(f).st_size\n return size > 0",
"def check_storage_config(self):\n\n if get_root_disk_size() < constants.MINIMUM_ROOT_DISK_SIZE:\n print(textwrap.fill(\n \"Warning: Root Disk %s size is less than %d GiB. \"\n \"Please consult the Software Installation Guide \"\n \"for details.\" %\n (self.rootfs_node, constants.MINIMUM_ROOT_DISK_SIZE), 80))\n print('')",
"def has_space(self, data):\n return len(data) <= self.available_storage()",
"def test_as_gigabytes(self):\n self.assertEqual(1, FileSize(1000 * 1000 * 1000).as_gigabytes)",
"def _add_directory_size(self):\n index = reversed(self.df.loc[self.df['TYPE']=='directory', :].index)\n for i in index: \n full_path = str(self.df.loc[i, 'path'])\n directory_size = self.df.loc[self.df['parent_directory'] == full_path, 'size'].sum()\n# print(directory_size)\n self.df.loc[i, 'size'] = directory_size",
"def seed_too_large(self) -> bool:\n return os.stat(self.full_path).st_size > MAXIMUM_SEED_SIZE",
"def validate_data_files_exists(size, data_path):\n\n # If any file is missing the test will be skipped.\n for i in range(1, size + 1):\n validate_patient_file_exist(filename=CMS_PATIENT, years=YEARS, sample_id=i, data_path=data_path)\n validate_cms_file_exist(filename=CMS_INPATIENT, sample_id=i, data_path=data_path)\n validate_cms_file_exist(filename=CMS_OUTPATIENT, sample_id=i, data_path=data_path)\n validate_claims_file_exist(filename=CMS_CARRIER_CLAIMS, claim_ids=CLAIMS, data_path=data_path)\n validate_cms_file_exist(filename=CMS_DRUG, sample_id=i, data_path=data_path)\n return True"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
r""" formatter(...) formatter( fname, fout = None, space_count = 2, kargs, special = 0, EXCEPTION = True ) Given a correct filename fname, this program autoformats the program file. This function formats source code, in a similar fashion to Python, in which "proper" matching spacing is applied for each line between an opening and closing brace. fname is the ONLY required argument. If fout is not defined, the output will have the same name as the input file except now with "_edit.txt" appended to it.
|
def formatter( fname, fout = None, space_count = 2,
*kargs, special = 0, EXCEPTION = True, DEBUG = False ):
import sys
if special == None:
special = 0
# Prevent user from accessing 16
if special & 16:
special ^= 16
shift = 0
shift_delay = 0 #For 4
cond_shift = 0 #For 16
cond_delay = 0 #For 16
mline_shift = 0 #Future Use
brace_start = '{'
brace_end = '}'
stack = [] #For 1
space_char = ' ' #For 2
#Files
source_code = open(fname)
fout = (fname + "_edit.txt") if (fout == None) else fout
dest_code = open(fout, "w" )
###err_code = open(fname + "_err.txt", "w" )
print("%s starting with %s. \nOutput is %s." %
(sys._getframe(0).f_code.co_name , fname, fout) )
#SPECIAL
if special & 2 :
space_char = '\t'
for (count,line) in enumerate(source_code) :
###err_code.write( '%03d | %s' % (len(line.strip()), line))
#Empty Line are Empty
empty_line = 1 if line.strip() else 0
line = ( ( empty_line * ( shift + cond_shift + mline_shift )*
space_count * space_char )
+ line.strip() )
#Insert Extra Formatting here
if special > 0:
if special & 4 :
if r'/*' in line:
shift_delay +=1
if r'*/' in line:
shift_delay -=1
if special & 8 :
if (line.lstrip()).startswith('//'):
if (line[0] == ' ' or line[0] == '\t' ): #CHECK ME
line = line[1:]
if special & 16:
if ( 'if' in line or 'else' in line
or 'for' in line or 'while' in line ) and brace_start not in line:
cond_shift = 1
else:
cond_shift = 0
if special & 1 :
if brace_start in line and brace_end not in line :
temp = line.strip()[:-1]
temp = "".join(temp.split('{').split('}'))
stack.append(temp)
elif brace_start not in line and brace_end in line :
line = "%s%s%s" % (line, " // ", stack.pop())
#Write to File
dest_code.write( "%s%s" % (line, '\n') )
##Calculate Shift for next line
if brace_start in line :
shift += 1
if brace_end in line :
shift -= 1
if shift_delay != 0 :
shift += shift_delay
shift_delay = 0
#Check if negative shift
if EXCEPTION and shift < 0 :
print( "\n File \"%s\", line %i, in %s" %
( fname, count, sys._getframe().f_code.co_name ) )
raise UnbalancedBraces( 0 , "Unbalanced Closing Braces in the file" )
#Check if there is extra shift at end.
if EXCEPTION and shift != 0:
print( "\n File \"%s\" , in %s" %
( fname, sys._getframe().f_code.co_name ) )
raise UnbalancedBraces( 0 , "Unbalanced Opening Braces in the file!" )
print( "%s compeleted!" % sys._getframe(0).f_code.co_name )
|
[
"def format_file(filename, args, standard_out):\n encoding = detect_encoding(filename)\n with open_with_encoding(filename, encoding=encoding) as input_file:\n source = input_file.read()\n formatted_source = format_code(\n source,\n preferred_quote=args.quote)\n\n if source != formatted_source:\n if args.in_place:\n with open_with_encoding(filename, mode='w',\n encoding=encoding) as output_file:\n output_file.write(formatted_source)\n else:\n import difflib\n diff = difflib.unified_diff(\n source.splitlines(),\n formatted_source.splitlines(),\n 'before/' + filename,\n 'after/' + filename,\n lineterm='')\n standard_out.write('\\n'.join(list(diff) + ['']))\n\n return True",
"def run_clang_format(\n filename: str, file_obj: dict, version: str, style: str, lines_changed_only: bool\n) -> None:\n cmds = [\n \"clang-format\" + (\"\" if sys.platform.startswith(\"win32\") else f\"-{version}\"),\n f\"-style={style}\",\n \"--output-replacements-xml\",\n ]\n if lines_changed_only:\n for line_range in file_obj[\"line_filter\"][\"lines\"]:\n cmds.append(f\"--lines={line_range[0]}:{line_range[1]}\")\n cmds.append(filename.replace(\"/\", os.sep))\n logger.info('Running \"%s\"', \" \".join(cmds))\n results = subprocess.run(cmds, capture_output=True)\n with open(\"clang_format_output.xml\", \"wb\") as f_out:\n f_out.write(results.stdout)\n if results.returncode:\n logger.warning(\n \"%s raised the following error(s):\\n%s\", cmds[0], results.stderr.decode()\n )",
"def format(tokens, formatter, outfile=None): # pylint: disable=redefined-builtin\n try:\n if not outfile:\n realoutfile = getattr(formatter, 'encoding', None) and BytesIO() or StringIO()\n formatter.format(tokens, realoutfile)\n return realoutfile.getvalue()\n else:\n formatter.format(tokens, outfile)\n except TypeError:\n # Heuristic to catch a common mistake.\n from pip._vendor.pygments.formatter import Formatter\n if isinstance(formatter, type) and issubclass(formatter, Formatter):\n raise TypeError('format() argument must be a formatter instance, '\n 'not a class')\n raise",
"def apply_to_file(fp, sp, in_place=False):\n rc, encoidng, changed = FormatFile(fp, style_config=sp, verify=True, in_place=in_place)\n return rc",
"async def run_clang_format_on_file(filename, semaphore, verbose=False):\n # -style=file picks up the closest .clang-format, -i formats the files inplace.\n cmd = \"{} -style=file -i {}\".format(CLANG_FORMAT_PATH, filename)\n async with semaphore:\n proc = await asyncio.create_subprocess_shell(cmd)\n _ = await proc.wait()\n if verbose:\n print(\"Formatted {}\".format(filename))",
"def test_log_onefmt(self):\n fpath = self.tmpdir(\"%s.log\" % util.my_name())\n CrawlConfig.log(logpath=fpath, close=True)\n\n # 1 % formatter in first arg\n a1 = \"This has a formatter and one argument: %s\"\n a2 = \"did that work?\"\n exp = (util.my_name() +\n \"(%s:%d): \" % (util.filename(), util.lineno()+2) +\n a1 % a2)\n CrawlConfig.log(a1, a2)\n result = util.contents(fpath)\n self.assertTrue(exp in result,\n \"Expected '%s' in %s\" %\n (exp, util.line_quote(result)))",
"def format_file(file: str, isortconfig: isort.settings.Config) -> None:\n\n isort.api.sort_file(pathlib.Path(file), config=isortconfig)\n\n black.format_file_in_place(\n pathlib.Path(file),\n fast=False,\n mode=black.Mode(),\n write_back=black.WriteBack.YES,\n )\n\n PyFunceble.facility.Logger.info(\"Update format of %r\", file)",
"def run_clang_format(filename: str) -> None:\n subprocess.run(['clang-format', '-assume-filename=fsm.h', '-i', filename])",
"def format_docstring(owner_name, docstring, formatters):\n # Build a dict of parameters to a vanilla format() call by searching for\n # each entry in **formatters and applying any leading whitespace to each\n # line in the desired substitution.\n format_params = {}\n for target, doc_for_target in iteritems(formatters):\n # Search for '{name}', with optional leading whitespace.\n regex = re.compile(r'^(\\s*)' + '({' + target + '})$', re.MULTILINE)\n matches = regex.findall(docstring)\n if not matches:\n raise ValueError(\n \"Couldn't find template for parameter {!r} in docstring \"\n \"for {}.\"\n \"\\nParameter name must be alone on a line surrounded by \"\n \"braces.\".format(target, owner_name),\n )\n elif len(matches) > 1:\n raise ValueError(\n \"Couldn't found multiple templates for parameter {!r}\"\n \"in docstring for {}.\"\n \"\\nParameter should only appear once.\".format(\n target, owner_name\n )\n )\n\n (leading_whitespace, _) = matches[0]\n format_params[target] = pad_lines_after_first(\n leading_whitespace,\n doc_for_target,\n )\n\n return docstring.format(**format_params)",
"def texindent_cli(args: list[str]):\n\n parser = _texindent_parser()\n args = parser.parse_args(args)\n assert all([os.path.isfile(file) for file in args.files])\n\n for filepath in args.files:\n filepath = pathlib.Path(filepath)\n orig = filepath.read_text()\n\n tex = TeX(orig)\n tex.preamble = indent(tex.preamble)\n tex.main = indent(tex.main)\n tex.postamble = indent(tex.postamble)\n formatted = str(tex)\n\n if formatted != orig:\n filepath.write_text(formatted)",
"def highlight(code, lexer, formatter, outfile=None):\n return format(lex(code, lexer), formatter, outfile)",
"def pygmentize():\n if len(sys.argv) < 2:\n _usge_pygmentize()\n sys.exit(1)\n\n filename = sys.argv[1]\n if not filename.endswith('.do.txt'):\n filename += '.do.txt'\n try:\n pygm_style = sys.argv[2]\n except IndexError:\n pygm_style = 'default'\n\n f = open(filename, 'r'); text = f.read(); f.close()\n lexer = DoconceLexer()\n formatter = HtmlFormatter(noclasses=True, style=pygm_style)\n text = highlight(text, lexer, formatter)\n f = open(filename + '.html', 'w'); f.write(text); f.close()",
"def formatFunCommentOldVersion(self, name, args, proto=True, indent=0):\n format_func = self.formatFun(indent, self.oneLineFun(name, args))\n if proto:\n format_func = format_func.replace(\")\", \");\")\n\n line_length = 80\n # If there are arg comments add them...\n if self.commentInArgsPresent(args):\n format_func_list = format_func.split(\"\\n\")\n # Trim the trailing spaces from the function name.\n format_func_name = format_func_list[0].strip(\" (\") + \"( \\n\"\n # Scan arg type_name and comments for maximums.\n comment_max = max([len(x[2]) for x in args])\n type_max = max([len(x.strip()) for x in format_func_list[1:]])\n # Set where to put them.\n comment_list = list(map(self.formComment, [x[2] for x in args]))\n\n # cpos is comment position from left on line\n # apos is argument position from left on line\n cpos = line_length - comment_max\n apos = line_length - (type_max + 1 + comment_max)\n # always indent args 8 or more spaces\n if apos < 8:\n apos = 8\n apad = apos * \" \"\n # always make sure there is a space between args and comment\n if cpos <= apos + type_max + 1:\n cpos = apos + type_max + 1\n\n # place args and comments and put together the string.\n func_arg_list = []\n for i, a in enumerate(format_func_list[1:]):\n pad = (cpos - (apos + len(a.strip()))) * \" \"\n str = (\n apad + a.strip() + pad + comment_list[i] + \"\\n\"\n ) # + pad + comment_list[i]\n func_arg_list.append(str)\n #\n # print 'Last arg: ',func_arg_list[-1].replace(') ',');')\n # TODO: add switch so a ; is inserted - end of last arg after ).\n func_arg_string = \"\"\n format_func = (\n format_func_name + func_arg_string.join(func_arg_list)\n ).strip(\"\\n\")\n return format_func",
"def cfmt(ctx):\n\n fmtCmd = \"clang-format -i -style=file {file}\"\n\n files = glob.glob(\"pkg/ebpf/c/*.[c,h]\")\n\n for file in files:\n ctx.run(fmtCmd.format(file=file))",
"def update_code_format() -> \"ProductionPrep\":\n\n # pylint: disable=import-outside-toplevel, import-error\n import black\n import isort\n\n def format_file(file: str, isortconfig: isort.settings.Config) -> None:\n \"\"\"\n Formats the given file using black.\n\n :param file:\n The file to format.\n :parm isortconfig:\n The configuration to apply while sorting the imports.\n \"\"\"\n\n isort.api.sort_file(pathlib.Path(file), config=isortconfig)\n\n black.format_file_in_place(\n pathlib.Path(file),\n fast=False,\n mode=black.Mode(),\n write_back=black.WriteBack.YES,\n )\n\n PyFunceble.facility.Logger.info(\"Update format of %r\", file)\n\n isort_config = isort.settings.Config(settings_file=\"setup.cfg\")\n\n files = [\n os.path.join(PyFunceble.storage.CONFIG_DIRECTORY, \"setup.py\"),\n ]\n\n for file in files:\n format_file(file, isort_config)\n\n for root, _, files in os.walk(\n os.path.join(\n PyFunceble.storage.CONFIG_DIRECTORY, PyFunceble.storage.PROJECT_NAME\n )\n ):\n if \"__pycache__\" in root:\n continue\n\n for file in files:\n if not file.endswith(\".py\"):\n continue\n\n format_file(os.path.join(root, file), isort_config)\n\n for root, _, files in os.walk(\n os.path.join(PyFunceble.storage.CONFIG_DIRECTORY, \"tests\")\n ):\n if \"__pycache__\" in root:\n continue\n\n for file in files:\n if not file.endswith(\".py\"):\n continue\n\n format_file(os.path.join(root, file), isort_config)",
"def format_prefix(self, data, instrument, filekind, *params, **keys):\n delim = self.args.unique_delimiter # for spreadsheets\n data, instrument, filekind = str(data), str(instrument), str(filekind) # squash 2.7 unicode\n if delim:\n return log.format(delim, instrument.upper(), delim, filekind.upper(), delim, data, delim,\n *params, end=\"\", **keys)\n else:\n return log.format(\"instrument=\"+repr(instrument.upper()), \"type=\"+repr(filekind.upper()), \"data=\"+repr(data), \":: \",\n *params, end=\"\", **keys)",
"def Format(paths: List[pathlib.Path]):\n # In the future I may want to refactor the FormatPaths class so that it can\n # process multiple \"runs\" rather than having to create and dispose of a\n # formatter each time we get a new FS event.\n for event in format_paths.FormatPaths(paths):\n timestamp = datetime.datetime.now().strftime(\"%H:%M:%S\")\n prefix = f\"[format {timestamp}]\"\n if isinstance(event, Exception):\n print(prefix, \"ERROR:\", event)\n else:\n print(prefix, event)",
"def _format_output(text, file, use_unicode=True):\n text = _clean_output(text)\n\n output = \"[Nuke Tools] %s \\n%s\" % (file, text)\n\n if use_unicode:\n # Arrow sign going down\n unicode = u'\\u21B4'\n output = \"[Nuke Tools] %s %s\\n%s\" % (file, unicode, text)\n\n output = insert_time(output)\n\n return output",
"def fn(fnid, fformat, *args):"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
r""" lcount(...) lcount( fname , fout = None, width = 6, kargs, code = "UTF8" ) Writes the line number of each line into the output text file.
|
def lcount( fname , fout = None, width = 5, *kargs, code = "UTF-8" ) :
import sys
#Files
file_in = open(fname, "r", 1, code)
fout = (fname + '_counted.txt') if (fout == None) else fout
file_out = open(fout, "w" , 1, code)
print("%s starting with %s. Output is %s." %
(sys._getframe(0).f_code.co_name , fname, fout) )
width = "%s%d%s" % ("%0", width, "d | %s")
for (count,line) in enumerate(file_in) :
file_out.write( width % (count, line) )
print( "%s Compeleted!" % sys._getframe(0).f_code.co_name )
|
[
"def count_lines(filename):\n pass",
"def mapcount(self):\n f = open(self.__filename, \"r+\")\n buf = mmap.mmap(f.fileno(), 0)\n lines = 0\n readline = buf.readline\n while readline():\n lines += 1\n return lines",
"def linecountinfile(file_or_filename):\n f = open_file_or_filename(file_or_filename)\n numlines = 0\n for line in f:\n numlines += 1\n f.close()\n return numlines",
"def opcount(self):\n with open(self.__filename) as f:\n for i, l in enumerate(f):\n pass\n return i + 1",
"def counter(filelist, exception_col):\n count = 0\n \n for eachfile in filelist:\n fileChecker(eachfile)\n countLabelsLines(eachfile, exception_col)\n count+=getCSVLengthWithoutHeader(eachfile)\n\n if count > 0 and len(filelist) > 1:\n print('Total lines: {}'.format(count))",
"def file_length(fileName):\n with open(f_pass) as f:\n for i, l in enumerate(f):\n pass\n return i + 1",
"def file_count():\n\n corpus = Corpus.from_env()\n click.echo(corpus.file_count)",
"def file_len(fname):\n with open(fname) as f:\n for i, l in enumerate(f):\n pass\n return i + 1",
"def countlines(text,\n\n linecount_table=_linecount_table):\n return len(tag(text, linecount_table)[1])",
"def row_count(filename):\n count = 0\n with open(filename, 'r') as ofp:\n for _ in ofp:\n count = count + 1\n # Remove header row from count\n count = count - 1 if count > 0 else count\n return count",
"def fasta_length_count(in_file, out_file):\r\n SeqCounter = collections.Counter()\r\n for record in FastaParser(in_file):\r\n desc = str(record.description)\r\n seq = str(record.sequence).strip()\r\n seqLength = len(seq)\r\n SeqCounter[seqLength] += 1 \r\n write_count(SeqCounter, out_file)",
"def count_file_code_lines(self):\r\n editorWidget = self.get_current_editor()\r\n if editorWidget:\r\n block_count = editorWidget.blockCount()\r\n blanks = re.findall('(^\\n)|(^(\\s+)?#)|(^( +)?($|\\n))',\r\n editorWidget.get_text(), re.M)\r\n blanks_count = len(blanks)\r\n resume = self.tr(\"Lines code: %s\\n\") % (block_count - blanks_count)\r\n resume += (self.tr(\"Blanks and commented lines: %s\\n\\n\") %\r\n blanks_count)\r\n resume += self.tr(\"Total lines: %s\") % block_count\r\n msgBox = QMessageBox(QMessageBox.Information,\r\n self.tr(\"Summary of lines\"), resume,\r\n QMessageBox.Ok, editorWidget)\r\n msgBox.exec_()",
"def file_word_count(filename, \n skip_inline=True, \n skip_commands=False, \n skip_comments=True,\n **kwargs):\n \n count = 0\n with open(filename) as f:\n for line in f:\n if skip_inline:\n line = skip_inline_equations(line)\n if skip_commands:\n line = remove_tex_commands(line)\n if skip_comments:\n line = remove_tex_comments(line)\n line_count = count_words(line)\n count += line_count\n return count",
"def linevalue_count(filename, n, commentchar):\n nlines, nvalues = _bcs.f90wrap_linevalue_count(filename=filename, n=n, \\\n commentchar=commentchar)\n return nlines, nvalues",
"def count_lines(file):\r\n old_position = file.tell()\r\n file.seek(0)\r\n count = 0\r\n while file.readline() != '':\r\n count += 1\r\n file.seek(old_position)\r\n return count",
"def bufcount(self):\n try:\n f = open(self.__filename) \n except IOError:\n return None\n else:\n with f:\n lines = 0\n ## buffer size is 1 Kb * 1 Kb\n buf_size = 1024 * 1024\n read_f = f.read\n buf = read_f(buf_size)\n while buf:\n lines += buf.count('\\n')\n buf = read_f(buf_size)\n return lines",
"def count_lines(file_path):\n # type: (pathlib.Path) -> int\n\n if file_path.suffixes[-1] == '.gz':\n with gzip.open(str(file_path)) as file_obj:\n count = _count_lines(file_obj)\n else:\n with file_path.open() as file_obj:\n count = _count_lines(file_obj)\n return count",
"async def count_lines_code(self):\n count = 0\n try:\n with open('start.py', 'r') as file:\n for line in file.read().split(\"\\n\"):\n if len(line.strip()) > 2 and line[0] != '#':\n count += 1\n for filename in [f\"plugins/{x.file}.py\" for x in self.bot.cogs.values()]+['checks.py']:\n with open(filename, 'r') as file:\n for line in file.read().split(\"\\n\"):\n if len(line.strip()) > 2 and line[0] != '#':\n count += 1\n except Exception as e:\n await self.bot.get_cog('Errors').on_error(e, None)\n self.codelines = count",
"def count_observation(data_name):\n #filename = str(data_name)\n with open(data_name) as file: \n num_lines = 0\n for line in file: \n num_lines = num_lines + 1\n num_obs = num_lines/3\n return(int(num_obs))"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
r""" rspace_killer(...) rspace_killer ( fname, fout = None ) Removes excess white space on the right
|
def rspace_killer ( fname, fout = None ) :
import sys
fin = open(source,"r")
fout = source + '_wk.txt' if ( fout == None ) else fout
dest = open(fout,"w")
print("%s starting with %s. Output is %s." %
(sys._getframe(0).f_code.co_name , fname, fout) )
for line in fin :
fout.write( line.rstrip() )
print( "%s Compeleted!" % sys._getframe(0).f_code.co_name )
|
[
"def _write_clean(file, outfile, run = False):\r\n\tif run:\r\n\t\tfile = open(f\"../lyrics/{file}.txt\", \"r\").readlines()\r\n\t\twrite_clean_file(file, outfile)",
"def safe_cleanup(file):\n remove_duplicates(file)\n remove_isolated_articles(file)\n lines_altered = clean_article_titles(file)\n while lines_altered > 0:\n remove_isolated_articles(file)\n lines_altered = clean_article_titles(file)\n print(\"Fixed point reached.\")",
"def wipe_bad_chars(filename):\n return multi_replace(filename, {\"(\": \"\", \" \": \"_\", \")\": \"\", \"/\": \"_\"}, True)",
"def cleanup_file(file_name, junk_funcs):\n dirty_file_contents = get_file_contents(file_name)\n clean_file_contents = get_clean_file_contents(dirty_file_contents, junk_funcs)\n clean_file = open(file_name + '.new', 'w+')\n clean_file.writelines(clean_file_contents)\n clean_file.close()",
"def remove_extra_lines_and_tabs():\n\n\tfor filename in os.listdir(DATA_DIR):\n\n\t\tclean_lines = []\n\t\twith open(os.path.join(DATA_DIR, filename), \"r\") as f:\n\t\t lines = f.readlines()\n\t\t clean_lines = [l.strip() for l in lines if l.strip()]\n\n\t\twith open(os.path.join(DATA_DIR, filename), \"w\") as f:\n\t\t f.writelines('\\n'.join(clean_lines))",
"def remove_gap_chars(file_to_clean, output_file_name, gap_chars, file_type):\n\n cleaned_seqs=[]\n output = open(output_file_name, 'w')\n i = 0\n for mySeq in SeqIO.parse(file_to_clean, file_type):\n for gapchar in gap_chars:\n mySeq.seq = mySeq.seq.ungap(gapchar)\n cleaned_seqs.append(mySeq)\n if i % 5000 ==0:\n SeqIO.write(cleaned_seqs, output, file_type)\n cleaned_seqs = []\n i += 1\n SeqIO.write(cleaned_seqs, output, file_type)\n return output_file_name",
"def replace_low_freq_words(self, corpus_file, corpus_file_out):\n for line in corpus_file:\n word = line.split(\" \")\n if self.word_map[word[0]] < 5:\n corpus_file_out.write(\"RARE \" + word[1]) \n else:\n corpus_file_out.write(line)",
"def erase_files(self):\n print('\\n\\n\\n We are erasing files!!! ')\n try:\n writeable_file = open('scrape-html-max/scrape.txt', 'w')\n writeable_file.close()\n print('\\n\\n opened file to erase and closed file.... ')\n writeable_file_2 = open('final-report/report.txt', 'w')\n writeable_file_2.close()\n except:\n print('\\n\\n Could not open file to erase')",
"def clean_nottrimmed_fastqs(filename_regex):\n for f in glob.glob(os.path.join(runs_scratch_dir,'*',filename_regex)):\n os.remove(f)",
"def test_preserve_trailing_spaces_on_lines(self):\n tabfile = TabFile('test',self.fp)\n self.assertEqual(tabfile[0][4],\"A comment\")\n self.assertEqual(tabfile[1][4],\"Comment with a trailing space \")\n self.assertEqual(tabfile[2][4],\".\")",
"def trim(self, dir='./trimmed'):\n self.data = self.__trim_file__(self.data)\n logging.info('File trimmed')\n self.dir = dir\n self.save()",
"def TRAJEC_trim(fname,nskip=0):\n # Get the number of lines from the xyz file\n nlines = int(commands.getoutput('wc -l '+fname).split()[0])\n\n # Get the number of atoms in the system\n f = open(fname,'r')\n natom = int( f.readline().strip() )\n\n # Number of initial lines to skip\n nskiplines = nskip * (natom+2)\n\n # Get the number of lines in the incomplete configuration\n nleftover = int( round( ( float(nlines)/float(natom+2) - nlines/(natom+2) )*(natom+2) ) )\n\n # Calculate the number of lines for the trimmed file\n N = nlines - nleftover\n\n # Replace the original with the trimmed xyz file\n os.system('head -n+'+str(N)+' '+fname+' | tail -'+str(N-nskiplines)+' > '+fname+'.trimmed')\n os.system('mv '+fname+'.trimmed'+' '+fname)",
"def leave_space(self, space):\n pass",
"def fix_spaces():\n mdown = config.markdown.read_text(encoding=\"utf8\")\n mdown = mdown.replace(u'\\xa0', u' ')\n config.markdown.with_name(\"AtomicScala-2.md\").write_text(mdown, encoding=\"utf8\")",
"def editor_remove_trailing_spaces(self):\r\n editorWidget = self.get_current_editor()\r\n if editorWidget:\r\n helpers.remove_trailing_spaces(editorWidget)",
"def removeUnkFromNgramsFile(ngrams_file, output):\n\tf = open(ngrams_file)\n\to = open(output, 'w')\n\tc = 0\n\tfor line in f:\n\t\tc += 1\n\t\tif c % 1000000==0:\n\t\t\tprint(str(c) + ' tokens filtered.')\n\t\tif '<unk>' not in line:\n\t\t\to.write(line)\n\tf.close()\n\to.close()",
"def clean_file(input_dir, output_dir, filename):\n filecontent = process_file(input_dir=input_dir, filename=filename)\n outfile = open(os.path.join(output_dir, filename), 'w', encoding='utf8')\n # outfile = sys.stdout\n\n filecontent = clean_records(filecontent)\n\n print(\"\\n\".join(filecontent), file=outfile)\n outfile.close()",
"def test_remove_spaces(names):\n scanner = Scanner(\n 'test_specfiles/test_scanner/test_remove_spaces.txt', names)\n # Function should advance to next non space character.\n scanner._remove_spaces()\n assert scanner.current_character == 'D'",
"def clean_emptyroom(fpath):\n # keep anything ending in `_meg`\n for fname in os.listdir(fpath):\n name = op.splitext(fname)[0]\n if not name.endswith('_meg'):\n os.remove(op.join(fpath, fname))"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Prepare the inputs for the simulator. The signature follows that given in `elfi.tools.external_operation`. This function appends kwinputs with unique and descriptive filenames and writes an input file for the bdm executable.
|
def prepare_inputs(*inputs, **kwinputs):
alpha, delta, tau, N = inputs
meta = kwinputs['meta']
# Organize the parameters to an array. The broadcasting works nicely with constant
# arguments.
param_array = np.row_stack(np.broadcast(alpha, delta, tau, N))
# Prepare a unique filename for parallel settings
filename = '{model_name}_{batch_index}_{submission_index}.txt'.format(**meta)
np.savetxt(filename, param_array, fmt='%.4f %.4f %.4f %d')
# Add the filenames to kwinputs
kwinputs['filename'] = filename
kwinputs['output_filename'] = filename[:-4] + '_out.txt'
# Return new inputs that the command will receive
return inputs, kwinputs
|
[
"def _populate_inputs(self):\n\n self.inputs = Bunch(outfile=None,\n infile=None)",
"def createNewInput(self,currentInputFiles,oriInputFiles,samplerType,**Kwargs): \n import DecayParser\n import FissionYieldParser\n import QValuesParser\n import MaterialParser\n import PathParser\n \n keyWordDict = {}\n \n directoryFiles = ['path','library_fiss','input_dpl']\n #print (currentInputFiles)\n driverXML = 'test_phisics_code_interface.xml'\n keyWordDict = self.mapFile(driverXML)\n #print (keyWordDict)\n tarName = self.tarFiles(directoryFiles)\n runInfoList = self.getDirInfo(driverXML)\n #print (int(runInfoList[1]))\n N = int(runInfoList[1])\n \n \n #print (Kwargs)\n #print (\"\\n\\n\\n\\n\\n\\n\")\n perturbedVars = Kwargs['SampledVars']\n distributedPerturbedVars = self.distributeVariablesToParsers(perturbedVars)\n #print (distributedPerturbedVars)\n #perturbedVars = {'DECAY|BETA|U235':1.0778}\n #perturbedVars = {'FUEL1|DENSITY|U234':1.2, 'FUEL1|DENSITY|U235':1.08E+02}\n #perturbedVars = {'FY|FAST|PU241|SE78':1.2, 'FY|THERMAL|U238|ZN68':1.08E+02, 'FY|THERMAL|U235|ZN66':5.777}\n #perturbedVars = {'QVALUES|U235':4.5963, 'QVALUES|U238':1.08E+02, 'QVALUES|CF252':7.846}\n #perturbedVars = {'BETADECAY|U235':4.5963, 'BETADECAY|U238':1.08E+02, 'BETADECAY|CF252':7.846}\n \n # NOTE: IF YOU DON'T LIKE OR CAN'T GET THE THE KEYWORDS WIT THE DICTIONARY KEYWORDdICT, I CAN USE GETBASE TO \n # OBRAIN THE KEYWORD CORRESPONDING TO THE PARSER OF INTEREST. EXAMPLE: AAA = currentInputFiles[0].getBase()print (AAA)\n for i in distributedPerturbedVars.iterkeys():\n if i == 'DECAY' : decayParser = DecayParser.DecayParser(currentInputFiles[keyWordDict['decay']].getAbsFile(), **distributedPerturbedVars[i])\n if i == 'DENSITY' : materialParser = MaterialParser.MaterialParser(currentInputFiles[keyWordDict['material']].getAbsFile(), **distributedPerturbedVars[i])\n if i == 'FY' : FissionYieldParser = FissionYieldParser.FissionYieldParser(currentInputFiles[keyWordDict['fissionyield']].getAbsFile(), **distributedPerturbedVars[i])\n if i == 'QVALUES' : QValuesParser = QValuesParser.QValuesParser(currentInputFiles[keyWordDict['fissqvalue']].getAbsFile(), **distributedPerturbedVars[i])\n if i == 'BETADECAY': BetaDecayParser = PathParser.PathParser(currentInputFiles[keyWordDict['betadecay']].getAbsFile(), **distributedPerturbedVars[i])\n \n tarFiles = currentInputFiles[keyWordDict['dirfiles']].getAbsFile()\n workDir = currentInputFiles[0].getPath()\n #print (workDir)\n self.untarFolders(tarFiles, workDir)\n self.copyIntoFolders(workDir)\n \n return currentInputFiles",
"def create_inputs(config):\n return([(\"fastq/{sample}\" + expand(\"{ending}{suffix}\", \\\n ending=R1_file_ending, suffix=suffix)[0]+\"\"),\n (\"fastq/{sample}\" + expand(\"{ending}{suffix}\", \\\n ending=R2_file_ending, suffix=suffix)[0]+\"\")])",
"def create_inputs_file(args):\n validate_args(args)\n\n tumor_bam_paths = find_bams_in_directory(args.tumor_bams_directory)\n simplex_bam_paths = find_bams_in_directory(args.simplex_bams_directory)\n curated_bam_duplex_paths = find_bams_in_directory(args.curated_bams_duplex_directory)\n curated_bam_simplex_paths = find_bams_in_directory(args.curated_bams_simplex_directory)\n\n # Normal bams paths are either from the bams directory, or repeating the default normal\n # Todo: remove! this logic should be based on the args.matched_mode param\n if args.normal_bams_directory:\n normal_bam_paths = find_bams_in_directory(args.normal_bams_directory)\n else:\n normal_bam_paths = [args.default_normal_path] * len(tumor_bam_paths)\n\n fh = open(args.output_file_name, 'w')\n write_yaml_bams(\n fh,\n args,\n tumor_bam_paths,\n normal_bam_paths,\n simplex_bam_paths,\n curated_bam_duplex_paths,\n curated_bam_simplex_paths,\n )\n\n include_yaml_resources(fh, VARIANTS_INPUTS)\n\n if args.standard_bams_directory:\n include_sv_inputs(args, fh)\n\n fh.write('project_name: {}'.format(args.project_name))\n fh.write(INPUTS_FILE_DELIMITER)\n\n try:\n include_yaml_resources(fh, VERSION_PARAM)\n except IOError:\n # that is if version.yaml is absent\n fh.write(INPUTS_FILE_DELIMITER)\n fh.write(\"# Pipeline Run Version:\\n\")\n include_version_info(fh)\n\n fh.close()",
"def generateModelInputData(self):\n data = {}\n # Generate input set data\n indexName = 'investments'\n if indexName not in self.sets.keys():\n raise IOError('Required node ' + indexName + ' is not found in input file, please specify it under node \"Sets\"!')\n else:\n data[indexName] = {None:self.sets[indexName]}\n indexList = ['time_periods','capitals','options','resources']\n for indexName in indexList:\n data[indexName] = self.processInputSets(indexName)\n # Generate input regulatory mandated data\n if self.mandatory is not None:\n data['mandatory'] = {None: self.mandatory}\n\n # set the Parameters with the extended indices\n for paramName, paramInfo in self.paramsAuxInfo.items():\n options = paramInfo['options']\n maxDim = paramInfo['maxDim']\n if paramName not in self.params.keys():\n raise IOError('Required node ' + paramName + ' is not found in input file, please specify it under node \"Parameters\"!')\n else:\n data[paramName] = self.setParameters(paramName, options, maxDim, self.params[paramName])\n\n ## used for DRO model\n if self.uncertainties is not None and 'DRO' in self.name:\n # logger.info('Generate additional model inputs for DRO optimization')\n data['sigma'] = {None:list(self.scenarios['probabilities'].keys())}\n data['prob'] = copy.copy(self.scenarios['probabilities'])\n data['epsilon'] = {None:self.epsilon}\n distData = copy.copy(self.distData[0,:])\n smIndices = list(self.scenarios['probabilities'].keys())\n data['dist'] = dict(zip(smIndices,np.ravel(distData)))\n # used for CVaR model\n if self.uncertainties is not None and 'CVaR' in self.name:\n # logger.info('Generate additional model inputs for CVaR optimization')\n data['_lambda'] = {None: self._lambda}\n data['alpha'] = {None: self.alpha}\n data = {None:data}\n return data",
"def build_input(model, input_file=default_input):\n\n inp = model.new_space(name='Input')\n inp.allow_none = True\n print_time = True\n\n print(\"Started loading data from 'input.xlsm'.\", file=sys.stderr)\n\n if print_time:\n timestamp = _PrintElapsedTime()\n timestamp.set_start('Loading PolicyData...')\n\n policydata = inp.new_space_from_excel(\n book=input_file,\n range_='B7:O307',\n sheet='PolicyData',\n name='PolicyData',\n names_row=0,\n param_cols=[0],\n space_param_order=[0],\n cells_param_order=[])\n\n if print_time:\n timestamp.print_time('Done.')\n timestamp.set_start('Loading MortalityTables...')\n\n mortbl = inp.new_space_from_excel(\n book=input_file,\n range_='E4:Q137',\n sheet='Mortality',\n name='MortalityTables',\n names_row=0,\n param_cols=[0],\n names_col=0,\n param_rows=[1, 2],\n space_param_order=[1],\n cells_param_order=[2, 0])\n\n if print_time:\n timestamp.print_time('Done.')\n timestamp.set_start('Loading ProductSpec...')\n\n prodspec = inp.new_space(name='ProductSpec')\n prodspec.new_cells_from_excel(\n book=input_file,\n range_='B7:V22',\n sheet='ProductSpec',\n names_row=0,\n param_cols=[0, 1, 2],\n param_order=[0, 1, 2])\n\n if print_time:\n timestamp.print_time('Done.')\n timestamp.set_start('Loading OtherParam1...')\n\n inp.new_cells_from_excel(\n book=input_file,\n range_='G6:H9',\n sheet='OtherParams',\n names_row=0,\n param_cols=[0],\n param_order=[0])\n\n if print_time:\n timestamp.print_time('Done.')\n timestamp.set_start('Loading OtherParams2...')\n\n inp.new_cells_from_excel(\n book=input_file,\n range_='V6:W9',\n sheet='OtherParams',\n names_row=0,\n param_cols=[0],\n param_order=[0])\n\n if print_time:\n timestamp.print_time('Done.')\n timestamp.set_start('Loading Assumptions...')\n\n asmp = inp.new_space(name='Assumptions')\n asmp.new_cells_from_excel(\n book=input_file,\n range_='B7:T17',\n sheet='Assumptions',\n names_row=0,\n param_cols=[0, 1, 2],\n param_order=[0, 1, 2])\n\n if print_time:\n timestamp.print_time('Done.')\n timestamp.set_start('Loading AssumptionTables...')\n\n asmptbls = inp.new_space(name='AssumptionTables')\n asmptbls.new_cells_from_excel(\n book=input_file,\n range_='B7:J27',\n sheet='AssumptionTables',\n names_row=0,\n param_cols=[0],\n param_order=[0])\n\n if print_time:\n timestamp.print_time('Done.')\n timestamp.set_start('Loading Scenarios...')\n\n scenarios = inp.new_space_from_excel(\n book=input_file,\n range_='A3:C1513',\n sheet='Scenarios',\n name='Scenarios',\n names_row=0,\n param_cols=[0, 1],\n space_param_order=[0],\n cells_param_order=[1])\n\n if print_time:\n timestamp.print_time('Done.')\n\n print(dedent(\"\"\"\\\n Input space and its sub spaces are saved in 'lifelib.mx'.\n You can load input data from the saved file instead of 'input.xlsx'\n by passing 'load_saved=True' to simplelife.build function.\"\"\"),\n file=sys.stderr)\n\n return inp",
"def cmd_write_inp(self):\n self.ensure_base_path()\n\n self.log.debug(\"Writing inp file\")\n self.write_inp()\n\n self.cmd_write_bloominp()\n self.cmd_write_runid()",
"def _writeInputs(self, inputs):\n try:\n \n dList = [\"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\\n\\n\"\"\"]\n dList.append(\"<inputs>\\n\")\n for input in inputs.keys():\n dList.append(\" <input>%s</input>\\n\" % str(input))\n dList.append(\"</inputs>\\n\\n\")\n data = ''.join(dList)\n fh = tempfile.NamedTemporaryFile(prefix=\"scriptrunner_\", suffix=\".xml\")\n fh.write(data.encode(\"utf-8\"))\n fh.flush()\n except:\n fh = None\n return fh",
"def setup(self):\n\n # Name of the pipeline reduction step\n self.name = 'prepare'\n self.description = 'Prepare Data Arrays'\n\n # Shortcut for pipeline reduction step and identifier for\n # saved file names.\n self.procname = 'pre'\n\n # Clear Parameter list\n self.paramlist = []\n\n # Append parameters\n self.paramlist.append(['detcounts', 'SQ1 Feedback',\n 'Name of the input fits binary table '\n 'column containing the detector flux '\n 'values for R/T arrays'])\n self.paramlist.append(['hwpcounts', 'hwpCounts',\n 'Name of the input fits column containing '\n 'the HWP counts (only used if column '\n '\"HWP Angle\" is not present)'])\n self.paramlist.append(['hwpconv', (360. / 1440.),\n 'Value to convert hwpcounts to HWP '\n 'Angles (only used if column \"HWP Angle\" '\n 'is not present)'])\n self.paramlist.append(['labmode', False,\n 'If TRUE (processing lab data), will '\n 'fill in with zeros a few columns and '\n 'keywords that are important for the DRP'])\n self.paramlist.append(['replacenod', True,\n 'If TRUE will replace Nod Offset by '\n 'calculation based on RA/DEC. If False, '\n 'use original column (has problems)'])\n self.paramlist.append(['chpoffsofiars', True,\n 'If TRUE will calculate Chop Offset '\n 'based on SofiaChopR/S. If False, use '\n 'colrename to specify column to use'])\n self.paramlist.append(['colrename', '',\n 'List of data columns to rename, '\n 'The format is: '\n 'oldname1->newname1|oldname2->newname2|...'])\n self.paramlist.append(['coldelete', [\"hwpA\", \"hwpB\"],\n 'List of data columns to delete. '\n 'The format is: [\"column1\", \"column2\", ...]'])\n self.paramlist.append(['pixscalist', [2.6, 4.0, 4.0, 6.8, 9.0],\n 'List for PIXSCAL values for each band'])\n self.paramlist.append(['traceshift', 0,\n 'Number of samples to shift the data '\n '(default is 0=no shift)'])\n self.paramlist.append(['removedropouts', False,\n 'Remove data dropouts (i.e. data with '\n 'RA==Dec==0 - default is False)'])",
"def _construct_input_spec(self):",
"def _input_data(self, job):\n\n cmd = \"{}/input.sh\".format(\n job.code_dir\n )\n print(\"Will run data submission: \" + cmd)\n try:\n call([\"bash\", cmd])\n except Exception:\n print(\"Failed data input\")",
"def cmd_write_inp(self):\n self.ensure_base_path()\n\n self.log.debug(\"Writing inp file\")\n self.write_inp()\n\n self.cmd_write_bloominp()\n self.cmd_write_runid()\n\n if self.n_bottom_layers and not self.bottom_grid:\n self.write_delwaqg()",
"def writeParAndInputFiles(self):\n pass",
"def inputFiles(self):\n pass",
"def make_input(self, *args, **kwargs):\r\n self.add(input.Input(*args, **kwargs))",
"def get_training_inputs():\n \n ## Create parser and define arguments\n parser = argparse.ArgumentParser()\n \n ## training data directory\n parser.add_argument('--data_dir', type = str, default = '/home/workspace/ImageClassifier/flowers', \n help = 'path to parent directory for training data')\n \n ## save directory\n parser.add_argument('--save_dir', type = str, default = '/home/workspace/ImageClassifier/TrainedModels/temp.pth', \n help = 'path to file you want to save the trained model to')\n \n ## architecture choice\n parser.add_argument('--arch', type = str, default = 'resnet', choices=['resnet', 'vgg', 'densenet'],\n help = 'choice of architecture for the model')\n \n ## learning rate\n parser.add_argument('--learn_rate', type = float, default = 0.001,\n help = 'learning rate (float)')\n \n ## hidden units\n parser.add_argument('--hidden_units', type = int, default = 400,\n help = 'number of units in hidden layer (int)')\n \n ## epochs\n parser.add_argument('--epochs', type = int, default = 10,\n help = 'number of ephochs (int)')\n \n ## train on GPU\n parser.add_argument('--gpu', action = 'store_true', default = False, #argparse.SUPPRESS\n help = 'train on GPU')\n \n return parser.parse_args()",
"def get_multipleInputFiles(self):\n \n # Attach whether we have a dummy input file \n self.multiple_input_files = self.simulation.multiple_input_files\n self.input_files = None\n self.dummy_input_file = None\n \n # If we have a multiple input files, attach the input files to the <path> object \n if self.multiple_input_files==True:\n \n # Get the input files corresponding to a similar simulation with different (kx,ky)\n self.input_files = self.simulation.input_files; self.paths = []\n self.input_files = [i for i in self.input_files if pathlib.Path(str(i).replace(\".in\", \"_kx0.0.in\")) not in self.input_files]\n\n # Create dummy path objects for each input file \n for input_file in self.input_files: \n self.paths.append(create_dummyPathObject(input_file, \"/not/used\"))\n \n # For each input file, remember the modes inside\n for path in self.paths: \n path.dummy_input_file = None\n nakx, naky = read_numberOfModesFromInputFile(path.input_file)\n kx, ky = read_modeFromInputFile(path.input_file)\n path.nakxnaky = nakx*naky\n path.kx = kx \n path.ky = ky\n if path.nakxnaky==1:\n path.dim_kx = 1\n path.dim_ky = 1\n path.vec_kx = [kx]\n path.vec_ky = [ky]\n if path.nakxnaky>1 or \"_dummy.in\" in str(path.input_file):\n with h5py.File(path.dimensions, 'r') as f: \n path.dim_kx = f[\"dim_kx\"][()] \n path.dim_ky = f[\"dim_ky\"][()] \n path.vec_kx = f[\"vec_kx\"][()] \n path.vec_ky = f[\"vec_ky\"][()] \n \n # For each input file, remember if it is part of a dummy input file\n for input_file in self.input_files: \n if \"_dummy.in\" in str(input_file):\n dummy_input_files = read_inputFilesInDummyInputFile(input_file) \n for path in self.paths: \n if path.input_file in dummy_input_files: path.dummy_input_file = input_file \n return",
"def task_input_kwargs(self):\n if self.dtype == \"AIPS\":\n return {\"DataType\": self.dtype,\n \"inName\": self.name,\n \"inClass\": self.aclass,\n \"inSeq\": self.seq,\n \"inDisk\": self.disk}\n elif self.dtype == \"FITS\":\n return {\"DataType\": self.dtype,\n \"inFile\": self.name}\n else:\n _check_disk_type(self.dtype, False)",
"def main_inputs():\n with open(\"../in/b_small.in\") as file:\n\n def get_numbers():\n return [int(v) for v in file.readline().split(\" \")]\n\n M, N = get_numbers()\n p = get_numbers()\n main(M, N, p)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Return the path to the C++ source code.
|
def get_sources_path():
return os.path.join(os.path.dirname(os.path.realpath(__file__)), 'cpp')
|
[
"def source_path(path):\n if path is None:\n return path\n for extension in ['$py.class', '.pyc', '.pyo']:\n if path.endswith(extension):\n return ''.join([path[:-len(extension)], '.py'])\n return path",
"def compile_path(self):\n if not self.precompile:\n return self.filepath\n else:\n if self._compile_path is None:\n segs = self.filepath.split('.')\n segs.pop()\n segs.append(\"F90\")\n self._compile_path = '.'.join(segs)\n\n return self._compile_path",
"def getPythonFileLocation():\n if os.path.dirname(__file__) != \"\":\n return os.path.dirname(__file__)\n elif os.path.dirname(os.path.abspath(__file__)) != \"\":\n return os.path.dirname(os.path.abspath(__file__))\n elif os.path.dirname(os.getcwd()) != \"\":\n return os.path.dirname(os.getcwd())\n else:\n from inspect import getsourcefile\n return os.path.dirname(os.path.abspath(getsourcefile(lambda _:None)))",
"def find_drive() -> Path:\n for source in SOURCES:\n path = Path(source) / \"code.py\"\n if path.exists():\n return path.parent\n raise Exception(\"Could not find a CIRCUITPY drive on your machine\")",
"def menpo_src_dir_path():\n from pathlib import Path # to avoid cluttering the menpo.base namespace\n return Path(os.path.abspath(__file__)).parent",
"def parse_c(source):\n converter = CCodeConverter()\n if os.path.exists(source):\n src = converter.parse(source, flags = [])\n else:\n src = converter.parse_str(source, flags = [])\n return src",
"def menpo3d_src_dir_path():\n return Path(os.path.abspath(__file__)).parent",
"def pc_path(self):\r\n\t\treturn self.__pathstub + \".pc\"",
"def find_corresponding_headerpath(cpp_path):\n (root, filename) = os.path.split(cpp_path)\n (barename, ext) = os.path.splitext(filename)\n (project_path, src) = os.path.split(root)\n (ignore, project_name) = os.path.split(project_path)\n header_path = project_path + \"/inc/Mantid%s/%s.h\" % (project_name, barename)\n return header_path",
"def get_sourcecode(path):\n path = path.replace('*', '/')\n local_path_to_sourcecode = os.path.join(app.config[\"SOURCECODE_DIR\"], path)\n resp = \"No such file...\"\n if os.path.exists(local_path_to_sourcecode):\n with open(local_path_to_sourcecode) as sourcecode_file:\n resp = sourcecode_file.read()\n return resp",
"def get_current_dir():\n return os.path.dirname(os.path.abspath(getsourcefile(lambda: 0)))",
"def GetCodegenFile(self):\n\t\tif os.path.isabs(self.FilePath):\n\t\t\tRelativePath = self.FilePath[3:]\n\t\t\treturn \"%s\\\\%s.codegen.inl\" % (ExportPath, RelativePath)\n\t\telse:\n\t\t\treturn \"%s\\\\%s.codegen.inl\" % (ExportPath, self.FilePath)",
"def _GetSrcRelativePath(path):\n assert path.startswith(_GetToolsParentDir())\n return expand_owners.SRC + path[len(_GetToolsParentDir()) + 1:]",
"def compile_pyc_dir(python_exec_path, src_path):\n py_process = subprocess.Popen(\n [python_exec_path, '-m', 'compileall', '-b', '-f', src_path],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n std_out, std_err = py_process.communicate()\n if VERBOSE:\n print(std_out)\n if std_err:\n raise Exception('Error using Python compileall:\\n{}'.format(std_err))",
"def project_src_path(self):\n project_src_path = os.getenv('PROJECT_SRC_PATH', '/workspace')\n logging.debug('PROJECT_SRC_PATH: %s.', project_src_path)\n return project_src_path",
"def declaration_file(self):\n return os.path.join(self.root, '0=ocfl_1.0')",
"def dll_source_path(self):\n return self._dll_source_path",
"def header_dir():\n return os.path.join(os.path.abspath(os.path.dirname(__file__)), \"include\")",
"def getAbsPath() -> str:\n thisFile:str = os.path.realpath(__file__)\n absPath:str = thisFile.replace(\"/srcTemplates.py\",\"\")\n return absPath"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Return the example model used in Lintusaari et al. 2016. Here we infer alpha using the summary statistic T1. We expect the executable `bdm` be available in the working directory.
|
def get_model(alpha=0.2, delta=0, tau=0.198, N=20, seed_obs=None):
if seed_obs is None and N == 20:
y = np.zeros(N, dtype='int16')
data = np.array([6, 3, 2, 2, 1, 1, 1, 1, 1, 1, 1], dtype='int16')
y[0:len(data)] = data
else:
y = BDM(alpha, delta, tau, N, random_state=np.random.RandomState(seed_obs))
m = elfi.ElfiModel(name='bdm')
elfi.Prior('uniform', .005, 2, model=m, name='alpha')
elfi.Simulator(BDM, m['alpha'], delta, tau, N, observed=y, name='BDM')
elfi.Summary(T1, m['BDM'], name='T1')
elfi.Distance('minkowski', m['T1'], p=1, name='d')
m['BDM'].uses_meta = True
# Warn the user if the executable is not present
if not os.path.isfile('bdm') and not os.path.isfile('bdm.exe'):
cpp_path = get_sources_path()
warnings.warn("This model uses an external simulator `bdm` implemented in C++ "
"that needs to be compiled and copied to your working directory. "
"We could not find it from your current working directory. Please"
"copy the folder `{}` to your working directory "
"and compile the source.".format(cpp_path), RuntimeWarning)
return m
|
[
"def ModelOne(patient):\n\n # import model using pickle de-serializer\n with open('./data/10featint_model400_15b.b', 'rb') as f:\n deployed_model = pickle.load(f)\n\n # import complete dataset\n final_features_raw_wid, final_features_raw, active_all = fns.import_features()\n\n # get normalizing measures\n final_features_raw_array = np.array(final_features_raw_wid.drop(['anon_id'], axis=1))\n final_features_mean = np.mean(final_features_raw_array, axis=0)\n final_features_std = np.std(final_features_raw_array, axis=0)\n\n # get the selected features\n selected_feature_pd = pd.read_csv('./data/10featureimptdf_model400_15b.csv')\n selected_feature_names = list(selected_feature_pd['feature'])\n selected_feature_index = list(selected_feature_pd['index'])\n selected_feature_pd2 = pd.read_csv('./data/10featureimptdf_model400_15b_readable.csv')\n selected_feature_read = list(selected_feature_pd2['feature'])\n\n # get normalized feature set\n final_features_norm = (final_features_raw - final_features_mean) / final_features_std\n\n # merge w. active status\n final_features_raw['status'] = active_all['isactive_interested']\n\n # group by active / drop-off, get means as array\n final_features_group = final_features_raw.groupby(by='status', axis=0)\n final_features_activemean = final_features_group.get_group(1).mean()\n final_features_dropmean = final_features_group.get_group(0).mean()\n final_features_dropmean = final_features_dropmean.drop('status')\n final_features_activemean = final_features_activemean.drop('status')\n activemean_np = np.array(final_features_activemean)\n dropmean_np = np.array(final_features_dropmean)\n\n try:\n # extra safe that check patient is correct format\n patient = int(patient)\n\n # get features for just this patient\n single_patient = final_features_raw_wid[final_features_raw_wid['anon_id'] == patient]\n single_patient_noid = single_patient.drop('anon_id', axis=1)\n test_features = np.array(single_patient_noid)\n # test_feature_norm = (test_features - final_features_mean) / final_features_std\n test_colnames = list(single_patient_noid.columns.values)\n # test_data_norm = pd.DataFrame(test_feature_norm, columns=test_colnames)\n # patientval = np.array(test_feature_norm[0, :])\n\n # get only features included in model\n selected_features = pd.DataFrame()\n selected_dropmean = []\n selected_activemean = []\n for i in selected_feature_names:\n selected_features[i] = single_patient[i]\n selected_patient = np.array(selected_features)\n selected_patient = np.transpose(selected_patient[0, :])\n\n # get means of both groups for features included in model\n for i in selected_feature_index:\n selected_activemean.append(final_features_activemean[i])\n selected_dropmean.append(final_features_dropmean[i])\n selected_activemean_np = np.array(selected_activemean)\n selected_dropmean_np = np.array(selected_dropmean)\n\n # create df to input into function to compare individual to groups\n comparison = pd.DataFrame({'feature': selected_feature_read,\n 'dropoff_mean': selected_dropmean_np.round(2),\n 'patientval': selected_patient.round(2),\n 'active_mean': selected_activemean_np.round(2)})\n\n # compare this patient to the means of both groups\n # dropcloser = 1 if more similar to drop-off group\n comparison['dropcloser'] = comparison.apply(fns.patientdiff_groups, 1)\n\n # select only those features where more similar to drop-off\n compgroup = comparison.groupby(by='dropcloser', axis=0)\n painpoints = compgroup.get_group(1)\n # painpoints = painpoints.sort_values(y='')\n\n # extract status of patient (active/inactive)\n temp = active_all[active_all['anon_id'] == patient]\n temp = temp['isactive_interested']\n temp2 = np.array(temp)\n active_status = temp2[0]\n print(active_status)\n if active_status == 1:\n activity = 'is active'\n else:\n activity = 'is dropped out'\n\n # get probability of drop-off for this patient\n testX = selected_patient\n pred = deployed_model.predict_proba(testX)\n prediction = pred[0][0]\n prediction = prediction.round(3)\n # print(activity)\n\n # determine/report model performance based on actual status\n if activity == 'is dropped out':\n if prediction > .5:\n assessment = 'The model predicted this user correctly'\n elif prediction < .5:\n assessment = 'The model was not correct for this user. No one is perfect!'\n elif prediction == .5:\n assessment = 'This user seems to be on the fence!'\n else:\n assessment = 'Error assessing model accuracy for this user'\n elif activity == 'is active':\n if prediction < .5:\n assessment = 'The model predicted this user correctly'\n elif prediction > .5:\n assessment = 'The model was not correct for this user. No one is perfect!'\n elif prediction == .5:\n assessment = 'This user seems to be on the fence!'\n else:\n assessment = 'Error comparing model prediction and activity status for this patient'\n else:\n assessment = 'Error identifying patient activity status'\n\n prediction = prediction * 100\n prediction = prediction.round(3)\n\n except IndexError:\n prediction = 'not calculable'\n activity = 'is nonexistent'\n assessment = 'please try a different patient id. Hint: try one less than 10187!'\n patient = '-'\n active_status = '-'\n painpoints = pd.DataFrame()\n except ValueError:\n prediction = 'not calculable'\n activity = 'is nonexistent'\n assessment = 'please try a different patient id. Hint: try one less than 10187!'\n patient = '-'\n active_status = '-'\n painpoints = pd.DataFrame()\n\n return prediction, activity, assessment, patient, active_status, painpoints",
"def single_run(model):\n global X_train, X_test, y_train, y_test\n\n model.fit(X_train, y_train)\n Y_hat = model.predict(X_test)\n MAE = np.mean(abs(Y_hat - y_test))\n print('MAE for given model : %.3f' % MAE)",
"def parse_model_file(model_file):\n assert os.path.exists(model_file)\n\n with open(model_file, 'r') as f:\n lines = f.readlines()\n\n bias = None\n alpha = None\n\n for i, line in enumerate(lines):\n line = line.strip()\n if line.startswith('solver_type'):\n assert line.split(' ')[1] in ['L2R_LR_DUAL', 'L2R_L2LOSS_SVC_DUAL']\n elif line.startswith('nr_class'):\n assert line.split(' ')[1] == '2'\n elif line.startswith('label'):\n assert line.split(' ')[1] == '1' and (line.split(' ')[2] == '0' or line.split(' ')[2] == '-1')\n elif line.startswith('nr_feature'):\n nr_feature = int(line.split(' ')[1])\n elif line.startswith('bias'):\n continue\n elif line.startswith('w'):\n w = lines[i + 1: i + nr_feature]\n w = [float(x.strip()) for x in w]\n elif line.startswith('nr_sample'):\n nr_sample = int(line.split(' ')[1])\n elif line.startswith('alpha'):\n alpha = [float(x) for x in lines[i + 1].strip().split(' ')]\n assert len(alpha) == nr_sample\n\n return np.array(alpha)",
"def model_fn(model_dir):\n print(\"Loading model.\")\n\n # Determine the device and construct the model.\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n model = Classifier()\n\n # Load the stored model parameters.\n model_path = os.path.join(model_dir, 'model.pth')\n with open(model_path, 'rb') as f:\n model.load_state_dict(torch.load(f))\n\n # set to eval mode, could use no_grad\n model.to(device).eval()\n\n print(\"Done loading model.\")\n return model",
"def test_tal1_lmo2(self, model):\n\n \"prepare dataloader\"\n data_loader = self.prepare_tal1_lmo2()\n\n \"test model\"\n self.cfg.full_test = True\n self.cfg.compute_pca = False\n self.cfg.get_zero_pred = False\n _, _, _, pred_df, _ = model.test(data_loader)\n\n \"save predictions\"\n pred_df.to_csv(self.cfg.output_directory + \"hiclstm_%s_predictions_chr%s.csv\" % (self.cell, str(self.chr)),\n sep=\"\\t\")\n return pred_df",
"def test_empirical_bnn_prior(self):\n from baobab.bnn_priors import EmpiricalBNNPrior\n cfg = self.test_tdlmc_empirical_config()\n empirical_bnn_prior = EmpiricalBNNPrior(cfg.bnn_omega, cfg.components)\n return empirical_bnn_prior.sample()",
"def build_mt_model(self):\n self.EMA_teacher.trainable = False\n img_in = Input(self.inputshape, name=\"Img_input\")\n out1 = self.student(img_in)\n out2 = self.EMA_teacher(img_in)\n out3 = self.dummy_teacher(img_in)\n out_total = Concatenate()([out1, out2, out3])\n model = Model(inputs=img_in, outputs=out_total)\n # model.summary()\n return model",
"def asl_signal_model(y_est, M0, alpha, lambda_blood, T1blood, T1tissue, pld, tao, scalar_constant):\n \n nt = tf.size(pld)\n \n Ndim = tf.shape(y_est[:,:,:,0])\n \n Nb = Ndim[0]; Nx = Ndim[1]; Ny = Ndim[2]\n \n CBF = expand_vol_1d(y_est[:,:,:,0], [1, 1, 1, nt]) # Cerebral blood flow parameter\n ATT = expand_vol_1d(y_est[:,:,:,1], [1, 1, 1, nt]) # Arterial transit time paremter\n \n PLD = expand_vol_4d(pld, [Nb, Nx, Ny, 1])\n TAO = expand_vol_4d(tao, [Nb, Nx, Ny, 1])\n \n # Estimate the 4D perfusion signal based on the ASL parameters according to the Buxton model\n sig_est = (2*alpha*M0*CBF*T1tissue*tf.exp(-(ATT/T1blood))) * (tf.exp(-tf.maximum(PLD-ATT, 0)/T1tissue) - \\\n tf.exp(-tf.maximum(TAO+PLD-ATT, 0)/T1tissue)) / (scalar_constant*lambda_blood)\n\n return sig_est",
"def test():\n vocabulary = [\n \"bass\", \"pike\", \"deep\", \"tuba\", \"horn\", \"catapult\",\n ]\n beta = np.array([\n [0.4, 0.4, 0.2, 0.0, 0.0, 0.0],\n [0.0, 0.3, 0.1, 0.0, 0.3, 0.3],\n [0.3, 0.0, 0.2, 0.3, 0.2, 0.0]\n ])\n alpha = np.array([0.2, 0.2, 0.2])\n xi = 50\n # np.random.seed(1)\n\n documents = [\n lda_gen(vocabulary, alpha, beta, xi)\n for _ in range(100)\n ]\n\n # Create a corpus from a list of texts\n dictionary = Dictionary(documents)\n corpus = [dictionary.doc2bow(text) for text in documents]\n model = LdaModel(\n corpus,\n id2word=dictionary,\n num_topics=3,\n )\n print(model.alpha)\n print(model.show_topics())",
"def model_with_hdplda(corpus,dictionary,hdplda_file):\n hdplda=None\n if(os.path.isfile(hdplda_file)):\n #load model instead of training\n hdplda=models.LdaModel.load(hdplda_file)\n else:\n # Train HDP model for topic modelling -- using default parameters for now\n hdp=models.hdpmodel.HdpModel(corpus=corpus, id2word=dictionary)\n alpha,beta=hdp.hdp_to_lda() #only gives alpha and beta for LDA\n hdplda=models.LdaModel(id2word=hdp.id2word,num_topics=len(alpha), \n alpha=alpha, eta=hdp.m_eta)\n hdplda.expElogbeta = numpy.array(beta, dtype=numpy.float32)\n hdplda.save(hdplda_file)\n return hdplda, len(alpha)",
"def test_active_inference_SPM_1a(self):\n array_path = os.path.join(os.getcwd(), DATA_PATH + \"vbx_test_1a.mat\")\n mat_contents = loadmat(file_name=array_path)\n\n A = mat_contents[\"A\"][0]\n B = mat_contents[\"B\"][0]\n C = to_arr_of_arr(mat_contents[\"C\"][0][0][:,0])\n obs_matlab = mat_contents[\"obs\"].astype(\"int64\")\n policy = mat_contents[\"policies\"].astype(\"int64\") - 1\n t_horizon = mat_contents[\"t_horizon\"][0, 0].astype(\"int64\")\n actions_matlab = mat_contents[\"actions\"].astype(\"int64\") - 1\n qs_matlab = mat_contents[\"qs\"][0]\n xn_matlab = mat_contents[\"xn\"][0]\n vn_matlab = mat_contents[\"vn\"][0]\n\n likelihoods_matlab = mat_contents[\"likelihoods\"][0]\n\n num_obs, num_states, _, num_factors = get_model_dimensions(A, B)\n obs = convert_observation_array(obs_matlab, num_obs)\n T = len(obs)\n\n agent = Agent(A=A, B=B, C=C, inference_algo=\"MMP\", policy_len=1, \n inference_horizon=t_horizon, use_BMA = False, \n policy_sep_prior = True)\n \n actions_python = np.zeros(T)\n\n for t in range(T):\n o_t = (np.where(obs[t])[0][0],)\n qx, xn_t, vn_t = agent.infer_states_test(o_t)\n q_pi, efe= agent.infer_policies()\n action = agent.sample_action()\n\n actions_python[t] = action\n\n xn_python = build_xn_vn_array(xn_t)\n vn_python = build_xn_vn_array(vn_t)\n\n if t == T-1:\n xn_python = xn_python[:,:,:-1,:]\n vn_python = vn_python[:,:,:-1,:]\n\n start_tstep = max(0, agent.curr_timestep - agent.inference_horizon)\n end_tstep = min(agent.curr_timestep + agent.policy_len, T)\n\n xn_validation = xn_matlab[0][:,:,start_tstep:end_tstep,t,:]\n vn_validation = vn_matlab[0][:,:,start_tstep:end_tstep,t,:]\n\n self.assertTrue(np.isclose(xn_python, xn_validation).all())\n self.assertTrue(np.isclose(vn_python, vn_validation).all())\n \n self.assertTrue(np.isclose(actions_matlab[0,:],actions_python[:-1]).all())",
"def load_bert_model(output_dir,\n bert_config_file='./model/uncased_L-12_H-768_A-12/bert_config.json',\n init_checkpoint='./tuned_model/model.ckpt-2461',\n num_labels=2,\n attn_processor_fn=None):\n bert_config = modeling.BertConfig.from_json_file(bert_config_file)\n tf.logging.info('Setting output dir to {} ...'.format(output_dir))\n # I don't expect to be running this model on a TPU so whatever...\n is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2\n run_config = tf.contrib.tpu.RunConfig(\n cluster=None,\n master=None,\n model_dir=output_dir,\n save_checkpoints_steps=1000,\n tpu_config=tf.contrib.tpu.TPUConfig(\n iterations_per_loop=1000,\n num_shards=8,\n per_host_input_for_training=is_per_host))\n\n model_fn = model_fn_builder(\n bert_config=bert_config,\n num_labels=num_labels,\n init_checkpoint=init_checkpoint,\n learning_rate=1e-3,\n num_train_steps=2,\n num_warmup_steps=1,\n use_tpu=False,\n use_one_hot_embeddings=False)\n\n estimator = tf.contrib.tpu.TPUEstimator(\n use_tpu=False,\n model_fn=model_fn,\n config=run_config,\n train_batch_size=32,\n eval_batch_size=8,\n predict_batch_size=8,\n export_to_tpu=False,\n params={'attn_processor_fn': attn_processor_fn})\n\n return estimator",
"def Model1_B():\n M1_B = Model()\n return M1_B",
"def model():\n return DBC14(dist_jb=10, mag=6, v_s30=600, depth_hyp=10, mechanism='SS')",
"def load_latest_emg_model():\n return _load_latest_model(EMG_MODEL_DIR)",
"def fit(direct):\n path = direct+ \"/msd.txt\"\n #making the dataframe with the msd from the txt file\n df = pd.DataFrame(pd.read_csv(path,sep = \" \"))\n msd = np.mean(df)\n #fit the msd\n popt = an.fit(msd)\n D = popt[0]\n alpha = popt[1]\n\n return D, alpha",
"def getModelDesc():\n\n return \"Example model: A 3D spherical Gaussian blob in a 3D cartesian grid\"",
"def load_model(model_name: str,\n model_dir: Union[str, Path] = './models',\n dataset: Union[str,\n BenchmarkDataset] = BenchmarkDataset.cifar_10,\n threat_model: Union[str, ThreatModel] = ThreatModel.Linf,\n norm: Optional[str] = None) -> nn.Module:\n\n # if model_name in timm.list_models():\n # return timm.create_model(model_name, pretrained=True).eval()\n\n dataset_: BenchmarkDataset = BenchmarkDataset(dataset)\n if norm is None:\n threat_model_: ThreatModel = ThreatModel(threat_model)\n else:\n threat_model_ = ThreatModel(norm)\n warnings.warn(\n \"`norm` has been deprecated and will be removed in a future version.\",\n DeprecationWarning)\n\n model_dir_ = Path(model_dir) / dataset_.value / threat_model_.value\n model_path = model_dir_ / f'{model_name}.pt'\n\n models = all_models[dataset_][threat_model_]\n \n # if models[model_name]['gdrive_id'] is None:\n # raise ValueError(f\"Model `{model_name}` is not a timm model and has no `gdrive_id` specified.\")\n\n if not isinstance(models[model_name]['gdrive_id'], list):\n model = models[model_name]['model']()\n if dataset_ == BenchmarkDataset.imagenet and 'Standard' in model_name:\n return model.eval()\n \n if not os.path.exists(model_dir_):\n os.makedirs(model_dir_)\n if not os.path.isfile(model_path):\n download_gdrive(models[model_name]['gdrive_id'], model_path)\n checkpoint = torch.load(model_path, map_location=torch.device('cpu'))\n\n if 'Kireev2021Effectiveness' in model_name or model_name == 'Andriushchenko2020Understanding':\n checkpoint = checkpoint['last'] # we take the last model (choices: 'last', 'best')\n try:\n # needed for the model of `Carmon2019Unlabeled`\n state_dict = rm_substr_from_state_dict(checkpoint['state_dict'],\n 'module.')\n # needed for the model of `Chen2020Efficient`\n state_dict = rm_substr_from_state_dict(state_dict,\n 'model.')\n except:\n state_dict = rm_substr_from_state_dict(checkpoint, 'module.')\n state_dict = rm_substr_from_state_dict(state_dict, 'model.')\n\n if dataset_ == BenchmarkDataset.imagenet:\n # so far all models need input normalization, which is added as extra layer\n state_dict = add_substr_to_state_dict(state_dict, 'model.')\n \n model = _safe_load_state_dict(model, model_name, state_dict, dataset_)\n\n return model.eval()\n\n # If we have an ensemble of models (e.g., Chen2020Adversarial, Diffenderfer2021Winning_LRR_CARD_Deck)\n else:\n model = models[model_name]['model']()\n if not os.path.exists(model_dir_):\n os.makedirs(model_dir_)\n for i, gid in enumerate(models[model_name]['gdrive_id']):\n if not os.path.isfile('{}_m{}.pt'.format(model_path, i)):\n download_gdrive(gid, '{}_m{}.pt'.format(model_path, i))\n checkpoint = torch.load('{}_m{}.pt'.format(model_path, i),\n map_location=torch.device('cpu'))\n try:\n state_dict = rm_substr_from_state_dict(\n checkpoint['state_dict'], 'module.')\n except KeyError:\n state_dict = rm_substr_from_state_dict(checkpoint, 'module.')\n\n model.models[i] = _safe_load_state_dict(model.models[i],\n model_name, state_dict,\n dataset_)\n model.models[i].eval()\n\n return model.eval()",
"def _get_best_automl_model(self):\n if not self.best_trial:\n self.best_trial = self.searcher.get_best_trial()\n best_model_path = self.best_trial.model_path\n best_config = self.best_trial.config\n best_automl_model = self.model_builder.build(best_config)\n best_automl_model.restore(best_model_path)\n return best_automl_model"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
active and inactive should be lists of usernames
|
def assertUserState(self, active, inactive):
for usernames, is_active in [(active, True), (inactive, False)]:
self.assertItemsEqual(
usernames,
[user.raw_username for user in
CommCareUser.by_domain(self.domain, is_active=is_active)]
)
|
[
"def active_user():\n return [user for user in session['user'] if user['active']][0]",
"def getActiveUsers(self):\n if self.activeUserCount == 0:\n logger.info(\"Empty room %s\" % self.roomName)\n return list()\n \n userList = list()\n for user in self.activeUsers:\n userList.append(user.userName)\n\n return userList",
"def list_service_usernames(args):\n usernames = get_usernames_for_passwords()\n action_set({'usernames': usernames or []})",
"def see_inactive_users(self):\n # table result class merely expects an iterator of iterators\n return [('Mike', 'Dan', 'Gabe')]",
"def indexActiveUsers(self):\n return self.indexUsers()\n return self.indexUsers(where=\"status='a'\")",
"def make_active_users_selectable(self, user=None):\n active_users = HypothesisUtils().get_active_users()\n most_recently_active_user = active_users[0][0]\n select = ''\n for active_user in active_users:\n if user is not None and active_user[0] == user:\n option = '<option selected value=\"%s\">%s (%s)</option>'\n else:\n option = '<option value=\"%s\">%s (%s)</option>'\n option = option % (active_user[0], active_user[0], active_user[1])\n select += option\n select = \"\"\"<select class=\"stream-active-users\" name=\"active_users\" \n onchange=\"javascript:show_user()\">\n <option>choose</option>\n %s\n </select>\"\"\" % (select)\n if user==None:\n return most_recently_active_user, select, active_users\n else:\n return user, select, active_users",
"def clm_ajax_get_table_users(request):\n if request.method == 'GET':\n users = prep_data('admin_clm/user/get_list/', request.session)\n\n for item in users:\n item['is_activeName'] = unicode(user_states[item['is_active']])\n\n return messages_ajax.success(users)",
"def get_active_users():\n\treturn frappe.db.sql(\"\"\"select count(*) from `tabUser`\n\t\twhere enabled = 1 and user_type != 'Website User'\n\t\tand name not in ({})\n\t\tand hour(timediff(now(), last_login)) < 72\"\"\".format(\", \".join([\"%s\"]*len(STANDARD_USERS))), STANDARD_USERS)[0][0]",
"def get_active_users_as_choices(agency_ein):\n active_users = sorted(\n [(user.get_id(), user.name)\n for user in Agencies.query.filter_by(ein=agency_ein).one().active_users],\n key=lambda x: x[1])\n active_users.insert(0, ('', 'All'))\n return active_users",
"def listUsers():\n exec_get_all('SELECT username FROM users')",
"def get_all_usernames():\n return list(map(lambda u: u.username, get_all_users()))",
"def list_newsletterusers_by_active():\n\n return NewsLetterMailing.objects.filter(is_active=True)",
"def check_users_botometer(list_users):\n return dict(BOM.check_accounts_in(list_users))",
"def get_users_on_waitlist(self):\n waitlist = self.waitlistslot_set.all()\n return UserProfile.objects.filter(waitlistslot__in=waitlist)",
"def test_get_run_as_users_list(self):\n pass",
"def getInactiveUsers():\n if request.method == 'GET':\n users = dbSession.query(User).filter(User.active == False).all()\n if len(users) == 0:\n return bad_request(\"No inactive users were found\")\n return jsonify(users)",
"def listActiveUsers(request):\n reverseUrl = 'api-datatables-user-list-active-users'\n ### get URL prefix\n prefix = getPrefix(request)\n ### get aoColumns pre-config\n aoColumns = []\n aoColumns += getAoColumnsDictWithTitles(COL_TITLES[reverseUrl])\n ### get filter fields\n filterFields = getFilterFieldIDs(FILTERS[reverseUrl])\n ### get indices of columns to refer by name in render javascript function\n fieldIndices = {}\n for col in ORDER_COLUMNS[reverseUrl]:\n i = None\n try:\n i = ORDER_COLUMNS[reverseUrl].index(col)\n except:\n pass\n fieldIndices[col] = i\n ### get reverse url of the data view\n dataUrl = reverse(reverseUrl)\n ### set request response data\n data = { \\\n 'prefix': prefix, \\\n 'datasrc': str(dataUrl + \"?format=json\"), \\\n 'columns': json_dumps(aoColumns), \\\n 'tableid': 'listactiveusers', \\\n 'caption': 'users', \\\n 'fieldIndices': json_dumps(fieldIndices), \\\n 'filterFields': filterFields, \\\n }\n data.update(getContextVariables(request))\n return render_to_response('pandajob/users/listusers.html', data, RequestContext(request))",
"def gui_active_users(self):\n list_users = self.database.get_all_active_users()\n active_user_list = QStandardItemModel()\n active_user_list.setHorizontalHeaderLabels([\n 'Имя клиента',\n 'IP-адрес',\n 'Порт',\n 'Время подключения'\n ])\n for row in list_users:\n user, ip, port, time = row\n user = QStandardItem(user)\n user.setEditable(False)\n ip = QStandardItem(ip)\n ip.setEditable(False)\n port = QStandardItem(str(port))\n port.setEditable(False)\n # Убираем миллисекунды.\n time = QStandardItem(str(time.replace(microsecond=0)))\n time.setEditable(False)\n active_user_list.appendRow([user, ip, port, time])\n self.active_clients_table.setModel(active_user_list)\n self.active_clients_table.resizeColumnsToContents()\n self.active_clients_table.resizeRowsToContents()",
"def get_users(self, username):\n active_users = get_user_model()._default_manager.filter(\n username__iexact=username, is_active=True)\n return (u for u in active_users if u.has_usable_password())"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Sample from discrete distribution ps over set xs
|
def inverse_cdf_sample(xs,ps):
r = random.random()
acc = 0
for x,p in zip(xs,ps):
acc += p
if acc > r:
return x
|
[
"def discrete_sample(prob, rng):\n return (np.cumsum(prob) > rng.rand()).argmax()",
"def sample_from_D(self, m):\n xs = np.random.uniform(0, 1, m)\n xs.sort()\n probabilities = numpy.random.random(len(xs))\n A = [(0, 0.2), (0.4, 0.6), (0.8, 1)]\n sample = np.ndarray((m, 2))\n for idx, x in enumerate(xs):\n if any(interval[0] <= x <= interval[1] for interval in A):\n sample[idx] = (x, numpy.random.choice([0, 1], size=1, p=[0.2,0.8]))\n else:\n sample[idx] = (x, numpy.random.choice([0, 1], size=1, p=[0.9,0.1]))\n return sample",
"def target_sampler(seed_f, domain=[-1.0, 1.0], count=1000, noise_dev=0.01):\n \n res = []\n\n for i in xrange(count):\n x = np.random.random()*(domain[1]-domain[0])+domain[0]\n y = seed_f(x) + gauss_distribution(0.0, noise_dev)\n res.append([x,y])\n\n return np.array(res)",
"def validate_discrete_distribution(xs, ps):\n if len(xs) != len(set(xs)) or len(xs[xs<0]) > 0:\n logger.info('Duplicates in empirical distribution and/or negative values, summarizing.')\n temp_df = pd.DataFrame({'x': xs, 'p': ps})\n temp_df.loc[temp_df.x < 0, 'x'] = 0.\n temp_df = temp_df.groupby('x').sum('p')\n xs = np.array(temp_df.index)\n ps = temp_df.p.values\n return xs, ps",
"def sample_distribution(numbers, probabilities, num_samples):\n intervals = []\n intervals.append(probabilities[0])\n new_interval = probabilities[0]\n\n for i in range(1, len(probabilities)):\n new_interval += probabilities[i]\n intervals.append(new_interval)\n\n counter = 0\n new_numbers = []\n while counter <= num_samples:\n for i in range(len(intervals)):\n # Generate a random num between 0 - 1\n # i.e. flip a coin.\n rand_prob = np.random.random_sample((1, ))\n if rand_prob <= [intervals[i]]:\n new_numbers.append(numbers[i])\n counter += 1\n\n return new_numbers",
"def random_distribution(n_items):\r\n return np.random.dirichlet([1.0 for i in range(n_items)])",
"def _sample_proportional(self):\n indices = []\n p_total = self.sum_tree.sum(0, len(self)-1)\n\n segment = p_total / self.batch_size\n\n for i in range(self.batch_size):\n a = segment * i\n b = segment * (i+1)\n upperbound = random.uniform(a, b)\n idx = self.sum_tree.retrieve(upperbound)\n indices.append(idx)\n\n return indices",
"def _sample_from_pdf(x, pdf, n):\n cum_sum = np.cumsum(pdf)\n inverse_density_function = interp1d(cum_sum, x)\n b = np.zeros(n)\n for i in range(len( b )):\n u = random.uniform( min(cum_sum), max(cum_sum) )\n b[i] = inverse_density_function( u )\n return b",
"def createSample(dist,lenSamp):\n return [random.choice(dist) for i in range(lenSamp)]",
"def sample_distribution(\n self,\n probability_distribution: Union[np.ndarray, List[float], None]) -> int:",
"def sample_discrete(cumulative, values):\n assert len(cumulative) == len(values)\n random_number = random()\n for cum_prob, value in zip(cumulative, values):\n if cum_prob >= random_number:\n return value",
"def random_subset(self, perc=0.5):",
"def distribution(rp, param, rep='CE'):\n if type(param) == str:\n i = parameter_position(param, rep)\n else:\n i = param\n xs = []\n for sim in range(1, 100):\n p = get_parameters(rp, sim, rep)\n xs.append(p[i])\n return xs",
"def sample(probs):\n import tensorflow as tf\n return tf.floor(probs + tf.random.uniform(tf.shape(probs), 0, 1))",
"def discreteSamp(happyCat, sadCat, s):\n trials = rv_discrete(name='trials', values=(happyCat, sadCat))\n sample = trials.rvs(size = s)\n x = []\n x.append(sample)\n return x",
"def random_subset(indicator_arr, sample_prob):\n subset_arr = (np.random.random(indicator_arr.shape) < sample_prob) & indicator_arr\n return subset_arr",
"def sample_cdf(cdf_vals, sample_vals, n_samples, rs, cdf, *cdf_args):\n sampled_cdf = cdf(cdf_vals, *cdf_args)\n samples = [sample_vals[inverse_transformation_sample(sampled_cdf, rs)]\n for _ in range(n_samples)]\n return samples",
"def sample(self, amount):\n s = pd.Series(np.random.sample(size=amount))\n snew = s.copy()\n\n for value, cumsum in zip(self._domain, self._cumsum):\n snew[s <= cumsum] = value\n s[s <= cumsum] = 2 # reassign so we don't mess it up.\n\n return snew",
"def discrete_joint_distribution_sampler(features, mapping, distribution, careful=False):\n p = distribution\n for key in mapping:\n value = features.get(key)\n if value is None:\n raise KeyError(f\"Can not find mapping: {key} in sampling features: {features}\")\n\n p = p.get(value)\n if p is None:\n if careful:\n raise KeyError(f\"Can not find feature for {key}: {value} in distribution: {p}\")\n else:\n return False\n\n return random() <= p"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Compute partition function for Gq model by direct enumeration
|
def compute_partition(ks,q):
return sum(falling_fac(q,j)*esp(ks,j) for j in range(q+1))
|
[
"def get_partition_function(self, T):\n cython.declare(Q=cython.double)\n if self.conformer is not None and len(self.conformer.modes) > 0:\n Q = self.conformer.get_partition_function(T)\n else:\n raise SpeciesError('Unable to calculate partition function for transition state {0!r}: '\n 'no statmech data available.'.format(self.label))\n return Q",
"def get_partition_function(self, T):\n cython.declare(Q=cython.double)\n if self.has_statmech():\n Q = self.conformer.get_partition_function(T)\n else:\n raise Exception('Unable to calculate partition function for species {0!r}: '\n 'no statmech data available.'.format(self.label))\n return Q",
"def a_partition(par):\n if par.m_q < 0:\n raise NotImplementedError(\"Q<0 not implemented.\")\n \n _parts = [_partition_gs, _partition_mq, _partition_left]\n for c_pairs in _parts:\n pairs = c_pairs(par)\n if is_valid(pairs, par) and not is_singular(pairs, par): \n return pairs\n\n # never get here\n raise RuntimeError(\"Failed to generate a_partition for %s\" % par)",
"def partitioning_node(input_dataset_name, output_dataset_name) -> Callable:\n return node(\n func=partition_function,\n inputs=dict(\n content=input_dataset_name,\n ),\n outputs=output_dataset_name\n )",
"def init_partition_function(self):\n assert np.allclose(self.weights.as_numpy_array(), 0.)\n return gnp.sum(gnp.log_1_plus_exp(self.vbias)) + gnp.sum(gnp.log_1_plus_exp(self.hbias))",
"def partition_with_iso_checking(G):\n partition_dict_all = partition(G)\n mul_dict = multiplier_dict(partition_dict_all)\n ### init\n keys = dict()\n for k, v in partition_dict_all.items():\n keys['{}_{}'.format(nx.number_of_nodes(v), nx.number_of_edges(v))] = []\n for k, v in partition_dict_all.items():\n keys['{}_{}'.format(nx.number_of_nodes(v), nx.number_of_edges(v))].append(k)\n v_e = set()\n for k, v in keys.items():\n if len(v) > 1:\n v_e.add(k)\n checked = set()\n ### iteration\n while len(v_e) > 0:\n for k in v_e:\n count = 0\n for u, v in combinations(keys[k], 2):\n if nx.is_isomorphic(partition_dict_all[u], partition_dict_all[v]):\n partition_dict_all.pop(v, None)\n mul_dict[u] += mul_dict[v]\n mul_dict.pop(v, None)\n break\n else:\n count += 1\n if count == len(keys[k]) * (len(keys[k]) - 1) / 2: # no isomorphism\n checked.add(k)\n keys = dict()\n for k, v in partition_dict_all.items():\n keys['{}_{}'.format(nx.number_of_nodes(v), nx.number_of_edges(v))] = []\n for k, v in partition_dict_all.items():\n keys['{}_{}'.format(nx.number_of_nodes(v), nx.number_of_edges(v))].append(k)\n v_e = set()\n for k, v in keys.items():\n if len(v) > 1:\n v_e.add(k)\n v_e -= checked\n\n return list(partition_dict_all.values()), list(mul_dict.values())",
"def partition_dataset(x):\n\n N = x.shape[0]\n Nd = x.shape[1]\n\n #all indices list\n all_indices = set([j for j in range(N)])\n\n #Jets number indices (0,1,2 or 3)\n jet_values = list(range(4))\n jet_number_indices = [ii(x[:, 22] == jet_number_value) for jet_number_value in jet_values]\n\n #Undefined values indices lists\n undefined_values_indices = [None]*Nd\n defined_values_indices = [None]*Nd\n undefined_values_indices_list = [None]*Nd\n defined_values_indices_list = [None]*Nd\n\n for j in range(Nd):\n undefined_values_indices[j] = ii(x[:,j] == -999.)\n defined_values_indices[j] = ii(x[:,j] != -999.)\n\n undefined_values_indices_list[j] = list(undefined_values_indices[j])\n defined_values_indices_list[j] = list(defined_values_indices[j])\n\n undefined_values_indices_list[j].sort()\n defined_values_indices_list[j].sort()\n\n # partitionning according to feature 22 value and samples defined or not for the feature 0\n # it happens that 0th feature has undefined value without respect to value of 22th feature\n partitions = [jet_number_indices[i] & defined_values_indices[0] for i in range(len(jet_values))] \\\n + [jet_number_indices[i] & undefined_values_indices[0] for i in range(len(jet_values))]\n\n return partitions, all_indices, defined_values_indices",
"def bisimilarity_partition(aut):\n assert aut.collection.events[\"tau\"] in aut.alphabet\n\n partition_list, state_function = initialize_partition(aut)\n return create_partitions(aut, partition_list, state_function, aut.alphabet)",
"def partition(self, *args, **kwargs):\n return _ms.ms_partition(self, *args, **kwargs)",
"def test_multiple_partitioned_functions():\n\n def before():\n composite_func_name = \"ethos-n_0\"\n inp = relay.var(\"x\", shape=(1, 2, 2, 4), dtype=\"int8\")\n\n # partitioned func 1 (non compute intensive)\n x = relay.reshape(inp, newshape=(1, 2, 2, 4))\n partitioned_func_1 = tei.make_ethosn_partition(x)[composite_func_name]\n gv_1 = relay.GlobalVar(\"ethos-n_0\")\n\n # partitioned func 2 (compute intensive)\n x = relay.nn.max_pool2d(inp, layout=\"NHWC\")\n partitioned_func_2 = tei.make_ethosn_partition(x)[composite_func_name]\n gv_2 = relay.GlobalVar(\"ethos-n_1\")\n\n # partitioned func 3 (non compute intensive)\n x = relay.clip(inp, 0.0, 1.0)\n partitioned_func_3 = tei.make_ethosn_partition(x)[composite_func_name]\n gv_3 = relay.GlobalVar(\"ethos-n_2\")\n\n mod = tvm.IRModule({})\n mod[gv_1] = partitioned_func_1\n mod[gv_2] = partitioned_func_2\n mod[gv_3] = partitioned_func_3\n main_expr = relay.Call(gv_1, [inp])\n main_expr = relay.Call(gv_2, [main_expr])\n main_expr = relay.Call(gv_3, [main_expr])\n mod[\"main\"] = relay.Function([inp], main_expr)\n return relay.transform.InferType()(mod)\n\n def expected():\n composite_func_name = \"ethos-n_0\"\n inp = relay.var(\"x\", shape=(1, 2, 2, 4), dtype=\"int8\")\n\n # partitioned func 2 (compute intensive)\n x = relay.nn.max_pool2d(inp, layout=\"NHWC\")\n partitioned_func_2 = tei.make_ethosn_partition(x)[composite_func_name]\n gv_2 = relay.GlobalVar(\"ethos-n_1\")\n\n mod = tvm.IRModule({})\n mod[gv_2] = partitioned_func_2\n main_expr = relay.reshape(inp, newshape=(1, 2, 2, 4))\n main_expr = relay.Call(gv_2, [main_expr])\n main_expr = relay.clip(main_expr, 0.0, 1.0)\n mod[\"main\"] = relay.Function([inp], main_expr)\n return relay.transform.InferType()(mod)\n\n mod = before()\n mod = InlineNonComputeIntensivePartitions()(mod)\n expected_mod = expected()\n for global_var in mod.get_global_vars():\n _assert_structural_equal(mod[global_var.name_hint], expected_mod[global_var.name_hint])",
"def partition(numPart):\n ierr = c_int()\n lib.gmshModelMeshPartition(\n c_int(numPart),\n byref(ierr))\n if ierr.value != 0:\n raise ValueError(\n \"gmshModelMeshPartition returned non-zero error code: \",\n ierr.value)",
"def partitioned_eval(fn, arg_columns, partition_columns):\n if (partition_columns is None) or (len(partition_columns) <= 0):\n return fn(*arg_columns)\n arity = len(arg_columns)\n res = [None] * len(arg_columns[0])\n index_lists = get_index_lists(partition_columns)\n for indexs in index_lists.values():\n # slice out a level set\n ni = len(indexs)\n fn_cols_i = [\n [arg_columns[j][indexs[i]] for i in range(ni)] for j in range(arity)\n ]\n # call function on slice\n hi = fn(*fn_cols_i)\n # copy back result\n for i in range(ni):\n res[indexs[i]] = hi[i]\n return res",
"def get_partition(self,x,y):\n N = int(np.sqrt(len(self.partitions)))\n\n if x>=self.xmax:\n # check upper limit\n xind = N-1\n else:\n # in case we are < xmin, don't let the index go negative\n xind = np.max([0,np.argmax(x<np.linspace(self.xmin,self.xmax,N+1))-1])\n\n if y>=self.ymax:\n # check upper limit\n yind = N-1\n else:\n # in case we are < xmin, don't let the index go negative\n yind = np.max([0,np.argmax(y<np.linspace(self.ymin,self.ymax,N+1))-1])\n\n ## print xind\n ## print yind\n\n #linear index\n return yind*N+ xind",
"def _get_partition_resume(graph, partition, n_words=4):\n\n partition_df = pd.DataFrame.from_dict(partition, orient=\"index\").rename(columns={0: 'group'})\n n_words = min(n_words, min(partition_df[\"group\"].value_counts().values))\n groups_df = pd.DataFrame(columns=set(partition_df[\"group\"]), index=list(range(1, n_words + 1)))\n for group in set(partition_df[\"group\"]):\n subgraph = graph.subgraph(partition_df[partition_df[\"group\"] == group].index.values)\n groups_df[group] = pd.DataFrame.from_dict([nx.pagerank(G=subgraph, alpha=0.99)]).T.rename(\n columns={0: 'pagerank'}) \\\n .sort_values(\"pagerank\", ascending=False).index.values[:n_words]\n return groups_df",
"def partition(m, n):\n return [ ( m + i - 1 ) // n for i in range(1, n + 1 )]",
"def get_partition(hostname, is_q=False):\n number = int(re.findall('\\d+', hostname)[0])\n if 'cpu' in hostname:\n return 'cpu'\n else:\n if is_q:\n if number == 1: return 'interactive'\n elif 5 <= number <= 7: return 'nlp'\n elif number >= 116: return 'wsgpu'\n else: return 'gpu'\n else: # Vaughan cluester\n if number == 59: return 'interactive'\n elif 4 <= number <= 6: return 'max12hours'\n elif 17 <= number <= 26: return 't4'\n else: return 'p100'",
"def partition(self, curve):\n print ('partitioning')\n # get edges with consistent ordering\n ordered_curve = self.order_edges(curve.faces)\n\n incidence, unique_edges = self.compute_face_incidence()\n\n # filter out the curve edges\n # incidence = incidence[~npi.contains(ordered_curve, unique_edges)]\n incidence = incidence[np.flatnonzero(~npi.in_(unique_edges, ordered_curve))]\n adjecency = incidence.T * incidence\n # find and split connected components\n n_components, labels = scipy.sparse.csgraph.connected_components(adjecency)\n partitions = [self.faces[labels == l] for l in range(n_components)]\n partitions = [Mesh(self.vertices, triangles).squeeze() for triangles in partitions]\n return sorted(partitions, key=lambda m: len(m.vertices))",
"def test_partition1(self):\n\n inputShape = (3, 3, 2)\n inputLayer = NxInputLayer(inputShape)\n flattenLayer = NxFlatten()(inputLayer.input)\n outputLayer = NxDense(10, validatePartitions=True)\n model = NxModel(inputLayer.input, outputLayer(flattenLayer))\n\n model.partition()\n\n model.clearTemp()",
"def test_partitionModel4(self):\n\n inputShape = (15, 15, 3)\n inputLayer = NxInputLayer(inputShape)\n outputLayer = NxConv2D(3, 3, strides=(2, 2), padding='same',\n validatePartitions=True)(inputLayer.input)\n\n model = NxModel(inputLayer.input, outputLayer,\n numCandidatesToCompute=10)\n\n model.partition()\n\n model.clearTemp()"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
given ks, the roots of a polynomial P(x) = a_n x^n+...+a_1x^1+a_0, compute sequence of coefficients a_n...a_0
|
def compute_coefficients_ref(ks):
coeffs = [1]
for k in ks:
coeffs = zipWith(lambda x,y:x+y,coeffs+[0],[0]+[-k*c for c in coeffs])
return coeffs
|
[
"def LagrangePolynomial( k ): # Inputs arrays\r\n assert len(x) == len(f_x) , \" x and f not same size \"\r\n sum_ = 0\r\n for i in range( n ): \r\n product = 1 # Reset the product for each i\r\n for j in range( len(x) ):\r\n if i!=j:\r\n product = product * ( k - x[j] ) / ( x[i] - x[j] ) # Product over j's for a given i\r\n sum_ = sum_ + product * f_x[i] # Sum over i's after product over j done\r\n return sum_",
"def kPar(k):\r\n \r\n k_par=ka*np.sqrt(1+(k/ks)**2)\r\n \r\n return k_par",
"def poly_exp(p: list, k: int) -> list:\n rtn = [1]\n while k > 0:\n # bit on in the binary representation of the exponent\n if k & 1 == 1:\n rtn = poly_mult(rtn, p)\n k >>= 1\n p = poly_mult(p, p)\n return rtn",
"def victor_miller_basis(k, prec=10, cusp_only=False, var='q'):\n k = Integer(k)\n if k%2 == 1 or k==2:\n return Sequence([])\n elif k < 0:\n raise ValueError(\"k must be non-negative\")\n elif k == 0:\n return Sequence([PowerSeriesRing(ZZ,var)(1).add_bigoh(prec)], cr=True)\n e = k.mod(12)\n if e == 2: e += 12\n n = (k-e) // 12\n\n if n == 0 and cusp_only:\n return Sequence([])\n\n # If prec is less than or equal to the dimension of the space of\n # cusp forms, which is just n, then we know the answer, and we\n # simply return it.\n if prec <= n:\n q = PowerSeriesRing(ZZ,var).gen(0)\n err = bigO(q**prec)\n ls = [0] * (n+1)\n if not cusp_only:\n ls[0] = 1 + err\n for i in range(1,prec):\n ls[i] = q**i + err\n for i in range(prec,n+1):\n ls[i] = err\n return Sequence(ls, cr=True)\n\n F6 = eisenstein_series_poly(6,prec)\n\n if e == 0:\n A = Fmpz_poly(1)\n elif e == 4:\n A = eisenstein_series_poly(4,prec)\n elif e == 6:\n A = F6\n elif e == 8:\n A = eisenstein_series_poly(8,prec)\n elif e == 10:\n A = eisenstein_series_poly(10,prec)\n else: # e == 14\n A = eisenstein_series_poly(14,prec)\n\n if A[0] == -1 :\n A = -A\n\n if n == 0:\n return Sequence([PowerSeriesRing(ZZ,var)(A.list()).add_bigoh(prec)],cr=True)\n\n F6_squared = F6**2\n F6_squared._unsafe_mutate_truncate(prec)\n D = _delta_poly(prec)\n Fprod = F6_squared\n Dprod = D\n\n if cusp_only:\n ls = [Fmpz_poly(0)] + [A] * n\n else:\n ls = [A] * (n+1)\n\n for i in range(1,n+1):\n ls[n-i] *= Fprod\n ls[i] *= Dprod\n ls[n-i]._unsafe_mutate_truncate(prec)\n ls[i]._unsafe_mutate_truncate(prec)\n\n Fprod *= F6_squared\n Dprod *= D\n Fprod._unsafe_mutate_truncate(prec)\n Dprod._unsafe_mutate_truncate(prec)\n\n\n P = PowerSeriesRing(ZZ,var)\n if cusp_only :\n for i in range(1,n+1) :\n for j in range(1, i) :\n ls[j] = ls[j] - ls[j][i]*ls[i]\n\n return Sequence([P(l.list()).add_bigoh(prec) for l in ls[1:]],cr=True)\n else :\n for i in range(1,n+1) :\n for j in range(i) :\n ls[j] = ls[j] - ls[j][i]*ls[i]\n\n return Sequence([P(l.list()).add_bigoh(prec) for l in ls], cr=True)",
"def chebyshev_polynomials(adj, k):\n print(\"Calculating Chebyshev polynomials up to order {}...\".format(k))\n\n adj_normalized = sym_normalize_list(adj)\n laplacian = sp.eye(adj.shape[0]) - adj_normalized\n largest_eigval, _ = eigsh(laplacian, 1, which='LM')\n scaled_laplacian = (2. / largest_eigval[0]) * laplacian - sp.eye(adj.shape[0])\n\n t_k = list()\n t_k.append(sp.eye(adj.shape[0]))\n t_k.append(scaled_laplacian)\n\n def chebyshev_recurrence(t_k_minus_one, t_k_minus_two, scaled_lap):\n s_lap = sp.csr_matrix(scaled_lap, copy=True)\n return 2 * s_lap.dot(t_k_minus_one) - t_k_minus_two\n\n for i in range(2, k + 1):\n t_k.append(chebyshev_recurrence(t_k[-1], t_k[-2], scaled_laplacian))\n\n return sparse_to_tuple(t_k)",
"def genK():\n return [frac_bin(p ** (1/3.0)) for p in first_n_primes(64)]",
"def solve(self):\n prev_xk = self.x0\n\n for k in range(self.K):\n xk = self.calc_xk(prev_xk)\n rk = self.A * xk - self.b\n if self.check_rel_prec(rk):\n return Solution(True, k + 1, xk)\n\n prev_xk = xk.copy()\n \n return Solution(False, K, None)",
"def ma_roots(self):\n polynomial = [i for i in self.theta]\n polynomial.append(1)\n return np.roots(polynomial)",
"def CPA_K(self, correctKey=0, leakage='HW'):\n Nk = self.NkDES\n numPT = 2 ** 6\n sboxNum = self.sboxNum\n cv = self.CPA_CV(correctKey = correctKey) # Diagonal of the confusion matrix\n K = np.zeros((Nk, Nk))\n Ks = np.zeros((Nk, Nk)) # K*\n Kss = np.zeros((Nk, Nk)) # K**\n keys = np.arange(64) # List of wrong keys\n keys = np.delete(keys, correctKey)\n\n evkc = [] # E [V | kc]\n for ptBlock in range(numPT):\n sboxOutc = des_block.sbox(sboxNum, ptBlock ^ correctKey)\n evkc.append(self.hw(sboxOutc))\n evkc = np.mean(evkc)\n #print evkc\n\n for i in keys:\n for j in keys:\n # Calculate kcij = E[(V|kc - V|ki) * (V|kc - V|ki)]\n # Calculate kcijss = E[4 * (V|kc - E[V|kc])^2 * (V|kc - V|ki) * (V|kc - V | kj)]\n kcij = []\n kcijs = []\n kcijss = []\n for ptBlock in range(numPT):\n sboxOutc = des_block.sbox(sboxNum, ptBlock ^ correctKey)\n sboxOuti = des_block.sbox(sboxNum, ptBlock ^ i)\n sboxOutj = des_block.sbox(sboxNum, ptBlock ^ j)\n if self.leakage =='HW':\n vkc = self.hw(sboxOutc) # V | kc\n vki = self.hw(sboxOuti) # V | ki\n vkj = self.hw(sboxOutj) # V | kj\n elif self.leakage =='HD':\n vkc = HD(sboxOutc, correctKey^ptBlock) # V | kc\n vki = HD(sboxOuti, i^ptBlock) # V | ki\n vkj = HD(sboxOutj, j^ptBlock) # V | kj\n\n\n kcij.append((vkc - vki) * (vkc -vkj))\n kcijs.append(((vkc-vki)**2) * ((vkc-vkj)**2))\n kcijss.append( 4 * ((vkc - evkc)**2) * (vkc - vki) * (vkc -vkj))\n kcij = np.mean(kcij)\n kcijss = np.mean(kcijss)\n kcijs = np.mean(kcijs)\n\n K[i][j] = kcij\n Ks[i][j] = kcijs\n Kss[i][j] = kcijs\n\n K = np.delete(K, correctKey,0)\n K = np.delete(K, correctKey,1)\n Ks = np.delete(Ks, correctKey,0)\n Ks = np.delete(Ks, correctKey,1)\n Kss = np.delete(Kss, correctKey,0)\n Kss = np.delete(Kss, correctKey,1)\n\n return K, Ks, Kss",
"def general_poly (L):\n k = len(L)-1\n answer = 0\n x = 10\n \n for n in L:\n if n == k:\n answer += L[n] * x**k\n else:\n answer += L[n] * x**(k-1)",
"def learn_koop_learn_pts(self, k):\n approx_pts = [np.array([i, j]) for i in np.linspace(-2,2,k) for j in np.linspace(-2,2,k)]\n en = lambda y: np.linalg.norm(y) ** 2\n g_prime = lambda i, x: sum([2 * (x[j] - self.centers[i][j]) * self.fs[j](x) *\n (logistic(en(x - self.centers[i]), self.alpha) -\n logistic(en(x - self.centers[i]), self.alpha) ** 2) for j in range(self.n)])\n funcs = [lambda x: 0] + self.fs + [partial(g_prime, i) for i in range(self.m)]\n # Build our koopman operator\n K = np.zeros((self.npm + 1, self.npm + 1))\n row = 0\n for f in funcs[1:]:\n row += 1\n to_min = lambda inpt: sum([(inpt[0] + sum([inpt[l+1] * x[l] for l in range(self.n)]) +\n sum([inpt[i+self.n] * logistic(en(x - inpt[self.m+(i+1)*self.n:self.m+(i+2)*self.n]), self.alpha)\n for i in range(self.m)]) - f(x))**2 for x in approx_pts])\n weights = optimize.minimize(to_min, np.random.rand(self.npm + 1 + self.m*self.n),\n method=\"CG\") # , jac=jacobian)#, hess=hessian)\n print(\"Optimizaiton Sucessfull \", weights.success, \"weights\", weights.x[0:12])\n K[row] = weights.x[0:self.m+self.n+1]\n self.koop = K",
"def kstairs(n, k):\n if n == 0:\n return 0\n if n <= k:\n return 2**(n-1)\n return sum([kstairs(n - i, k) for i in range(1, k + 1)])",
"def pDpk(self, x, k):\n k = np.array(k)\n return 2*c*c*k/(self._omega*self._omega)",
"def reconstruct_linP_kms(zs,k_kms,pars_fid,linP_params,z_star,kp_kms):\n # get linear power and background expansion for fiducial cosmology\n results_fid = camb.get_results(pars_fid)\n H_star_fid = results_fid.hubble_parameter(z=z_star)\n k_kms_fid, zs_out, P_kms_fid = get_linP_kms(pars_fid,zs)\n # get parameters describing linear power for input cosmology\n f_star=linP_params['f_star']\n g_star=linP_params['g_star']\n linP_kms=linP_params['linP_kms']\n # get parameters describing fiducial cosmology linear power\n linP_params_fid=parameterize_cosmology_kms(pars_fid,z_star=z_star,\n kp_kms=kp_kms)\n f_star_fid=linP_params_fid['f_star']\n g_star_fid=linP_params_fid['g_star']\n linP_kms_fid=linP_params_fid['linP_kms']\n # get relative parameters\n df_star=f_star-f_star_fid\n dg_star=g_star-g_star_fid\n # will store reconstructed linear power here\n Nz=len(zs)\n Nk=len(k_kms)\n rec_linP_kms=np.empty([Nz,Nk])\n for iz in range(Nz):\n z=zs_out[iz]\n # Hubble parameter in fiducial cosmology\n H_fid = results_fid.hubble_parameter(z=z)\n # evaluate fiducial power at slightly different wavenumber \n x = 1 + 3/2*dg_star*(z-z_star)/(1+z_star)\n P_rec = np.interp(x*k_kms,k_kms_fid[iz],P_kms_fid[iz]) * x**3\n # apply change in shape, taking into account we work in km/s\n y_fid = H_fid/(1+z)/H_star_fid*(1+z_star)\n y=y_fid*x\n lnky=np.log(y*k_kms/kp_kms)\n P_rec *= np.exp(linP_kms(lnky)-linP_kms_fid(lnky))\n # correct linear growth\n P_rec *= (1-df_star*(z-z_star)/(1+z_star))**2\n rec_linP_kms[iz]=P_rec\n return rec_linP_kms",
"def fcc_kps(kmax):\n\n kpds = []\n for k in range(kmax):\n for m in range(1,4,16):\n p = m*(k**3)\n if p <= kmax and p not in kpds:\n kpds.append(p)\n\n return kpds",
"def sc_and_bcc_kps(kmax):\n\n kpds = []\n for k in range(kmax):\n for m in range(1,2,4):\n p = m*(k**3)\n if p <= kmax and p not in kpds:\n kpds.append(p)\n\n return kpds",
"def test_kl_div(self):\r\n import numpy as np\r\n import cvxpy as cp\r\n\r\n kK=50\r\n kSeed=10\r\n\r\n prng=np.random.RandomState(kSeed)\r\n #Generate a random reference distribution\r\n npSPriors=prng.uniform(0.0,1.0,kK)\r\n npSPriors=npSPriors/np.sum(npSPriors)\r\n\r\n #Reference distribution\r\n p_refProb=cp.Parameter(kK,1,sign='positive')\r\n #Distribution to be estimated\r\n v_prob=cp.Variable(kK,1)\r\n objkl=0.0\r\n for k in xrange(kK):\r\n objkl += cp.kl_div(v_prob[k,0],p_refProb[k,0])\r\n\r\n constrs=[__builtins__['sum']([v_prob[k,0] for k in xrange(kK)])==1]\r\n klprob=cp.Problem(cp.Minimize(objkl),constrs)\r\n p_refProb.value=npSPriors\r\n result = klprob.solve(solver=CVXOPT, verbose=True)\r\n self.assertItemsAlmostEqual(v_prob.value, npSPriors)\r\n result = klprob.solve(solver=SCS, verbose=True)\r\n self.assertItemsAlmostEqual(v_prob.value, npSPriors, places=3)",
"def c_root_p(a, p):\n if (a % p) == 0:\n return [0]\n if p == 2 or p == 3 :\n return [a % p]\n if (p % 3) == 2:\n return [pow(a, (((2 * p) - 1) // 3), p)]\n p_div_3, p_mod_3 = divmod((p - 1), 3)\n # Compute e,q\n e = 0\n temp = p_div_3\n tempmod = p_mod_3\n\n while tempmod == 0:\n e += 1\n temp, tempmod = divmod(temp, 3)\n q = (p - 1) // (3 ** e)\n search_range = (p - 1) >> 1\n h = 2\n while pow(h, p_div_3, p) == 1:\n h = random.randrange(2, search_range)\n sym = pow(h, p_div_3, p)\n g = pow(h, q, p)\n # Initialize\n y = g\n r = e\n if q % 3 == 2:\n x = pow(a, (q - 2) // 3, p)\n else:\n x = pow(a, (((2 * q) - 2) // 3), p)\n\n b = (pow(a, 2, p) * pow(x, 3, p)) % p\n x = (a * x) % p\n while (b % p) != 1:\n # Find exponent\n b_pow = pow(b, 3, p)\n m = 1\n while b_pow != 1:\n b_pow = (b_pow ** 3) % p\n m += 1\n if m == r:\n raise ValueError(\"there is no cubic root mod p\")\n # Reduce exponent\n if sym == pow(b, pow(3, m - 1, p), p):\n t = pow(y, 2, p)\n sym = pow(sym, 2, p)\n else:\n t = y\n t = pow(t, pow(3, r - m - 1, p), p)\n y = pow(t, 3, p)\n r = m\n x = (x * t) % p\n b = (b * y) % p\n return [ x, (x * sym) % p, (x * pow(sym, 2, p)) % p ]",
"def polyNest(a, b):\n\taN = len(a)-1 # degree of a\n\tbN = len(b)-1 # degree of b\n\tcN = aN*bN # degree of result\n\tan = [1] # coeffs of successive powers of a\n\tc = [0]*(cN+1) # coeffs for result\n\tc[0] = b[0]\n\tK = 1\n\tfor n in range(1, bN+1):\n\t\tan = polyMul(an, a)\n\t\tK += aN\n\t\tfor k in range(0, K):\n\t\t\tc[k] += b[n] * an[k]\n\treturn c"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Compute log probability of k out N successes at probability p
|
def log_dbinom(k,N,p):
return log(choose(N,k)) + k*log(p) + (N-k)*log(1-p)
|
[
"def log_likelihood(p):\n\tp_full = np.append(p, [1.0 - sum(p)]) # one parameter for the probability of each review score\n\tprobability_list = binom.pmf(review_frequencies, nbr_reviews, p_full)\n\tlog_probability_sum = np.sum(np.log(probability_list))\n\t\n\tif np.isnan(log_probability_sum):\n\t\treturn -np.inf\n\telse:\n\t\treturn log_probability_sum",
"def log_prob(self, ts):\n self.k_inv = np.linalg.inv(self.k)\n self.k_det = np.linalg.det(self.k)\n\n # calculate predictions at each time point\n predictors = self.munge(ts, order=self.order)\n predictions = self.a_full.dot(predictors.T)\n truths = ts[self.order:, :].T\n\n log_probs = self.log_prob_mvn(truths, means=predictions, cov_inv=self.k_inv, cov_det=self.k_det)\n return log_probs.sum()",
"def bench_log_probability( distribution, n=10000000, symbol=5 ):\n\n\ttic = time.time()\n\tfor i in range(n):\n\t\tlogp = distribution.log_probability( symbol )\n\treturn time.time() - tic",
"def getLogFactorial(k):\n return np.sum([log(i) for i in range(1, k+1)])",
"def perform_bernoulli_trials(n, p):\r\n # Initialize number of successes: n_success\r\n n_success = 0\r\n\r\n # Perform trials\r\n for i in range(n):\r\n # Choose random number between zero and one: random_number\r\n random_number= np.random.random()\r\n\r\n # If less than p, it's a success so add one to n_success\r\n if random_number<p:\r\n n_success += 1\r\n\r\n return n_success",
"def perform_bernoulli_trials(n, p):\n # Initialize number of successes: n_success\n n_success = 0\n\n # Perform trials\n for i in range(n):\n # Choose random number between zero and one: random_number\n random_number = np.random.random()\n\n # If less than p, it's a success so add one to n_success\n if random_number < p:\n n_success += 1\n\n return n_success",
"def probabilities(n):\n prob2 = np.array([1., 1.])\n it2 = [1, 2]\n\n if n == 2:\n p = 0.5*np.array(prob2)\n expect = np.dot(p, it2)\n return p, it2, expect\n\n if n > 2:\n prob = prob2\n it = it2\n k = 2\n while k < n:\n prob = np.concatenate([prob, prob / k])\n it = np.concatenate([it, it + np.ones_like(it)])\n k += 1\n # print(k)\n return (1/n) * np.array(prob), it",
"def perform_bernoulli_trials(n, p):\n # Initialize number of successes: n_success\n n_success = 0\n\n # Perform trials\n for i in range(n):\n # Choose random number between zero and one: random_number\n random_number = np.random.random()\n\n # If less than p, it's a success so add one to n_success\n if random_number<p:\n n_success +=1\n\n return n_success",
"def log_prob(list):\n p=0\n for i in list:\n p += math.log10(i)\n return math.exp(p)",
"def log_probability(self, text):\n\t\tdef _access_values(key):\n\t\t\t\"\"\"\n\t\t\t_access_values(key)\n\t\t\tA helper closure to allow for a try except inside a list comp for\n\t\t\tthe total log prob calculation. If the table is a dict, then it \n\t\t\twill throw keyerrors if the key isn't found which for our purposes\n\t\t\tis a 0. \n\n\t\t\tGets: key, a string of length k or k+1\n\t\t\tReturns: an int\n\t\t\t\"\"\"\n\t\t\ttry:\n\t\t\t\treturn self.table[key]\n\t\t\texcept KeyError:\n\t\t\t\treturn 0\n\t\tk_k1_len_substrings = [(text[i-1:i+self.k-1], text[i-1:i+self.k]) for i in range(len(text)) if i+self.k-1 < len(text)][1:]\n\t\tk_k1_len_substrings.append((text[-self.k:], text[-self.k:]+text[0]))\n\t\tif self.k > 1:\n\t\t\tfor char_index, char in enumerate(text[-self.k+1:]):\n\t\t\t\tk_k1_len_substrings.append((text[-self.k +1 + char_index:]+text[:char_index+1], text[-self.k +1 + char_index:]+text[:char_index+2]))\n\t\ttotal_log_prob = sum([log((_access_values(str_tuple[1])+1) / (_access_values(str_tuple[0])+self.alphabet_len)) for str_tuple in k_k1_len_substrings])\n\t\treturn total_log_prob",
"def prob_atleast_k(num_balls, num_bins, k):\n bnded = pigeonhole_bounded( num_balls, num_bins, max_balls_per_bin = k-1)\n tot = pigeonhole( num_balls, num_bins )\n return 1 - bnded / tot",
"def binomial_trial(n: int, p: float) -> int:\n return sum(bernoulli_trial(p) for _ in range(n))",
"def log_probability(value, mean, variance):\n\n # return the log probability (a sum instead of a product)\n return -0.5 *log(2*kPI*variance) - 1/(2*variance)*(value - mean)**2",
"def logfac(n, k=0): # default value of k = 0\n assert type(n)==int, \"error message: here n should be an integer\"\n assert type(k)==int, \"error message: here n should be an integer\"\n assert n >= 0, \"error message: n must be great than or equal to zero\"\n assert k >= 0, \"error message: k must be greater than or equal to zero\"\n\n\n result = 0\n\n for i in range(k,n):\n result += math.log(i+1) # to start with k (or 1 if k = 0)\n return result",
"def sentence_logprob(self, sentence):\n res = 0\n temp = get_ngrams(sentence, 3)\n for item in temp:\n \tp = self.smoothed_trigram_probability(item)\n \tif p > 0:\n \t\tres = res + math.log2(p)\n return res",
"def log_probability(self):\n return tf.reduce_sum(self.log_ps, axis=0)",
"def likelihood(x, n, P):\n if type(n) is not int or n <= 0:\n raise ValueError(\"n must be a positive integer\")\n\n if type(x) is not int or x < 0:\n message = \"x must be an integer that is greater than or equal to 0\"\n raise ValueError(message)\n if x > n:\n raise ValueError(\"x cannot be greater than n\")\n\n if type(P) is not np.ndarray or P.ndim != 1:\n raise TypeError(\"P must be a 1D numpy.ndarray\")\n\n if (P < 0).any() or (P > 1).any():\n raise ValueError(\"All values in P must be in the range [0, 1]\")\n\n denominador = np.math.factorial(x) * np.math.factorial(n - x)\n factorial = np.math.factorial(n) / denominador\n\n prob = factorial * np.power(P, x) * np.power(1 - P, n - x)\n\n return prob",
"def kl_divergence(prob, p_hat):\n ret = tf.reduce_sum(prob*(math.log(prob)-tf.log(p_hat)) +\n (1-prob)*(math.log(1-prob)-tf.log(1-p_hat)))\n return ret",
"def log_prob(self, xs, zs):\n x, y = xs['x'], xs['y']\n log_prior = multivariate_normal.logpdf(\n zs['z'], tf.zeros(self.N), self.kernel(x))\n log_lik = tf.reduce_sum(\n bernoulli.logpmf(y, p=self.inverse_link(y * zs['z'])))\n return log_prior + log_lik"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Return max in window of radius k over circular array of scores
|
def max_in_window_ref(scores,k):
G = len(scores)
max_scores = np.empty(G)
for i in verbose_gen(xrange(G),10000):
m = None
for j in xrange(-k,k+1):
if scores[(i+j) % G] > m:
m = scores[(i+j) % G]
max_scores[i] = m
return max_scores
|
[
"def max_in_window(scores,k):\n max_scores = np.copy(scores)\n for j in verbose_gen(xrange(-k,k+1)):\n max_scores = np.maximum(max_scores,np.roll(scores,j))\n return max_scores",
"def maxScore(self, cardPoints: list[int], k: int) -> int:\n maxLen = len(cardPoints) - k\n minSum = float('inf')\n start = currSum = 0\n for end, p in enumerate(cardPoints):\n currSum += p\n\n if end - start + 1 > maxLen:\n currSum -= cardPoints[start]\n start += 1\n\n if end - start + 1 == maxLen:\n minSum = min(minSum, currSum)\n\n return sum(cardPoints) - minSum",
"def minMaxRiddle(arr):\n # the most brutal brute force can get, i think cubic time:\n # n = len(arr)\n # window_maxs = []\n # for w in range(1, n + 1):\n # window_max = 0\n # for i in range(n - w + 1):\n # window = arr[i : i + w]\n # window_min = min(window)\n # if window_min > window_max:\n # window_max = window_min\n # window_maxs.append(window_max)\n # return window_maxs\n\n # little better, quyadratic time\n n = len(arr)\n mins = [[0 for _ in range(n)] for _ in range(n)]\n mins[0] = arr\n maxes = [max(mins[0])]\n for i in range(1, n):\n curr_max = 0\n for j in range(n - i):\n mins[i][j] = min(mins[i - 1][j], mins[i - 1][j + 1])\n if mins[i][j] > curr_max:\n curr_max = mins[i][j]\n maxes.append(curr_max)\n return maxes",
"def __get_radius_for_clusters(k, clusters, centroids):\n clusters_radii = []\n\n for i in range(k):\n centroid = centroids[i]\n cluster = clusters[i]\n max_val = 0\n\n for j in range(len(cluster)):\n val = np.linalg.norm(centroid-cluster[j])\n if val > max_val:\n max_val = val\n\n clusters_radii.append(max_val)\n\n return clusters_radii",
"def calc_windowscore(score_array):\n\tabsolutes = [fabs(x) for x in score_array]\n\ttotal = sum(absolutes)\n\treturn total/len(score_array)",
"def _roll_orig_max_squared(x, window=2000):\n x_rolled = np.lib.stride_tricks.sliding_window_view(x, window, axis=0)\n # https://stackoverflow.com/questions/61703879/in-numpy-how-to-select-elements-based-on-the-maximum-of-their-absolute-values\n shape = np.array(x_rolled.shape)\n shape[-1] = -1\n return np.take_along_axis(x_rolled, np.square(x_rolled).argmax(-1).reshape(shape), axis=-1)",
"def smart_argmax(vector,w=5):\n mx = vector.max()\n mxmask = vector == mx\n n_mx = mxmask.sum()\n sargmax = np.nan # A bad invalid is returned if somehow it's not assigned.\n center_index = int(np.round(vector.shape[0] / 2))\n if n_mx == 1:\n #print('No need for smart_argmax()')\n return vector.argmax()\n hw = int(w/2)\n \n oords = np.arange(0,vector.shape[0]) \n locs = oords[mxmask]\n # 1. If maxes are touching (adjacent),\n # - If only 2, pick the one closest to center\n # - If > 2, pick the one in the middle\n d = np.diff(locs)\n if (d == 1).sum() != 0: # A difference of 1 implies consecutive integers\n # --- Save non-consecutive peaks for analysis\n singular_peak_locs = []\n if d[0] != 1: singular_peak_locs.append(locs[0])\n for s in range(1,d.shape[0]):\n if ((d[s] > 1) and (d[s-1] != 1)): singular_peak_locs.append(locs[s])\n if d[-1] != 1: singular_peak_locs.append(locs[-1])\n # --- \n if np.unique(d).shape[0] > 1: # Check to make sure all d's != 1.\n ic,nc,bn = delineate_consecutive_binned_vector_values(d,[0,1.1,2]) # bin 1 will be diff of 1\n else: # Entering this block means that this is only 1 consecutive span\n ic = np.array([0])\n nc = np.array([locs.shape[0]-1]) # minus 1 because +1 will be added back [5/22/23]\n bn = np.array([1])\n diff_bin_mask = bn == 1\n if ic is None: pdb.set_trace()\n ic = ic[diff_bin_mask]\n nc = nc[diff_bin_mask] + 1\n middle_points = []\n for j in range(0,ic.shape[0]):\n print(j)\n start_index = locs[ic[j]]\n end_index = start_index + nc[j]\n print(end_index,start_index,end_index-start_index)\n print(vector[start_index:end_index])\n print(oords[start_index:end_index])\n x = oords[start_index:end_index]\n print(x.shape)\n # Now find the middle or suitable point\n if x.shape[0] == 2:\n middle_index = np.abs(x - center_index).argmin()\n middle_index = x[middle_index]\n print('middle index: ',middle_index)\n print('Shape of 2 block')\n else:\n middle_index = int(np.median(x))\n print(middle_index)\n print('---------------------')\n middle_points.append(middle_index)\n locs = np.array( middle_points + singular_peak_locs, dtype=int ) # pared consecutives and singulars back into modified locs variable\n n_mx = locs.shape[0] # New # of maxes, with consecutives cut out\n \n reliefs = np.full(n_mx,999)\n for i,argmax in enumerate(locs):\n reliefs[i] = (mx - vector[argmax-hw:argmax+hw+1]).sum()\n \n # 1. Choose max with least topographic relief\n mn_relief = reliefs.min()\n relief_mask = reliefs == mn_relief\n n_mnrf = relief_mask.sum()\n if n_mnrf == 1:\n i = locs[relief_mask]\n sargmax_val = vector[i]\n sargmax = i\n else: # Should have to be > 1\n # 2. Maxes are tied for topographic relief,\n # choose the one closer to the center.\n imid = np.abs(locs[relief_mask] - center_index).argmin()\n i = locs[relief_mask][imid]\n sargmax_val = vector[i]\n sargmax = i\n #print('Standard argmax',vector.argmax(),vector[vector.argmax()])\n #print('Chosen argmax: ',sargmax,sargmax_val)\n if sargmax_val != vector.max(): pdb.set_trace()\n if sargmax_val != vector[sargmax]: pdb.set_trace()\n return int(sargmax)",
"def find_local_max(arr, kernel_width=15):\n arr_convolved = np.convolve(arr, generate_pulse_kernel(kernel_width=kernel_width), mode=\"same\")\n # find local max using scipy.signal.argrelextrema\n ind_local_max = argrelextrema(arr_convolved, np.greater_equal, order=kernel_width, mode='clip')[0]\n logging.info(f\"{len(ind_local_max)} maxima found\")\n # interpolate for local min\n ind_local_max_delta = np.diff(ind_local_max) / 2\n ind_local_min_derived = np.hstack(\n (\n ind_local_max[:-1] - ind_local_max_delta,\n ind_local_max[-1] - ind_local_max_delta[-1],\n ind_local_max[-1] + ind_local_max_delta[-1],\n )\n ).astype(int)\n # calculate SNR for local max\n ind_two_sides = np.array([\n ind_local_min_derived[:-1],\n ind_local_min_derived[1:]\n ])\n ind_two_sides_mask = np.logical_or(ind_two_sides < 0, ind_two_sides > len(arr) - 1)\n ind_two_sides_valid = np.where(ind_two_sides_mask, 0, ind_two_sides) # do not go out of bounds\n # estimate SNR of local max, clip out-of-bounds values\n interp_val_local_max = np.ma.MaskedArray(\n data=arr_convolved[ind_two_sides_valid],\n mask=ind_two_sides_mask,\n ).mean(axis=0)\n assert interp_val_local_max.mask.sum() == 0\n interp_val_local_max = interp_val_local_max.data\n val_local_max = arr_convolved[ind_local_max]\n snr_local_max = val_local_max / interp_val_local_max\n return LocalMax(\n num=len(ind_local_max),\n max_ind=ind_local_max,\n max_val=val_local_max,\n max_val_interp=interp_val_local_max,\n max_snr=snr_local_max,\n min_ind=ind_local_min_derived,\n side_ind=ind_two_sides,\n side_mask=ind_two_sides_mask,\n )",
"def findMaxValueOfEquation(self, points: list[list[int]], k: int) -> int:\n heap = []\n rslt = float('-inf')\n for x, y in points:\n while heap and heap[0][1] < x - k:\n heappop(heap)\n\n if heap:\n rslt = max(\n rslt,\n x + y - heap[0][0]\n )\n\n heappush(heap, (x - y, x))\n\n return rslt",
"def window_size(radius):\n return 2 * radius + 1",
"def select_each_frame_best_locations(k, radius, predicted_heat_maps):\n T = predicted_heat_maps.shape[0]\n future_positions = []\n for i in range(T):\n best_positions = select_top_k_positions(k, predicted_heat_maps[i, :, :], radius)\n future_positions.append(best_positions)\n return future_positions",
"def depth_scoring(scores):\n minima = set(argrelextrema(numpy.array(scores), numpy.less)[0])\n maxima = set(argrelextrema(numpy.array(scores), numpy.greater)[0])\n last_maxima = 0\n depth_scores = [] # a list of tuples (index_of_minima, depth_score_at_minima)\n for i in xrange(len(scores)):\n if i in maxima:\n last_maxima = i\n\n if i in minima:\n # find the next maxima\n next_maxima = None\n count = 0\n while next_maxima is None:\n count += 1\n if i + count in maxima:\n next_maxima = i + count\n elif i + count == len(scores) - 1:\n next_maxima = i + count\n depth_score = (scores[last_maxima] - scores[i]) + (scores[next_maxima] - scores[i])\n depth_scores.append((i, depth_score))\n\n return depth_scores",
"def cluster(r):\r\n # TODO: finish this\r\n k,m=r.shape\r\n clusters=np.argmax(r,axis=0)\r\n return clusters",
"def maxScoreSightseeingPair(self, values: list[int]) -> int:\n maxScore = values[0]\n prevBestIdx = 0\n prevBestSum = values[prevBestIdx] + prevBestIdx\n for j in range(1, len(values)):\n maxScore = max(\n maxScore, prevBestSum + values[j] - j)\n if values[j] + j > prevBestSum:\n prevBestIdx = j\n prevBestSum = values[j] + j\n\n return maxScore",
"def maxWidthRamp(self, nums):\r\n n = len(nums)\r\n res = 0\r\n \r\n for r in range(n):\r\n for l in range(r):\r\n if nums[r] >= nums[l]:\r\n res = max( res, r-l )\r\n \r\n return res",
"def max_radius():\r\n return 20",
"def max_fold_enrichment (self):\n peaks = self.peaks\n chrs = peaks.keys()\n chrs.sort()\n x = 0\n for chrom in chrs:\n if peaks[chrom]:\n m = max([i[7] for i in peaks[chrom]])\n if m>x:\n x=m\n return x",
"def maxLk_interval(self, z, zs):\n izmax = np.argmax(z)\n zmax = np.max(z)\n\n print \"izmax=\", izmax\n print \"zmax=\", zmax\n\n\n \"\"\"\n ### (31-dec-2015): don't remember logic of this; but it \n ### is causing problems!..\n rb = [k for k in range(len(z)) if np.abs(zmax - z[k]) < 0.025 ]\n print \"rb=\",rb\n\n if len(rb)>1: \n sb = [ zs[k] for k in rb ]\n print \"sb=\",sb\n izmax = np.argmin(sb)\n \"\"\"\n\n print \"final izmax=\", izmax\n return izmax",
"def score_max_depths(graph, max_depths):\n score = []\n for i in max_depths:\n partition_girvan = partition_girvan_newman(graph, i)\n norm = norm_cut(S, T, graph)\n score.append((i, norm_cut))\n return score"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Return max in window of radius k over circular array of scores
|
def max_in_window(scores,k):
max_scores = np.copy(scores)
for j in verbose_gen(xrange(-k,k+1)):
max_scores = np.maximum(max_scores,np.roll(scores,j))
return max_scores
|
[
"def max_in_window_ref(scores,k):\n G = len(scores)\n max_scores = np.empty(G)\n for i in verbose_gen(xrange(G),10000):\n m = None\n for j in xrange(-k,k+1):\n if scores[(i+j) % G] > m:\n m = scores[(i+j) % G]\n max_scores[i] = m\n return max_scores",
"def maxScore(self, cardPoints: list[int], k: int) -> int:\n maxLen = len(cardPoints) - k\n minSum = float('inf')\n start = currSum = 0\n for end, p in enumerate(cardPoints):\n currSum += p\n\n if end - start + 1 > maxLen:\n currSum -= cardPoints[start]\n start += 1\n\n if end - start + 1 == maxLen:\n minSum = min(minSum, currSum)\n\n return sum(cardPoints) - minSum",
"def minMaxRiddle(arr):\n # the most brutal brute force can get, i think cubic time:\n # n = len(arr)\n # window_maxs = []\n # for w in range(1, n + 1):\n # window_max = 0\n # for i in range(n - w + 1):\n # window = arr[i : i + w]\n # window_min = min(window)\n # if window_min > window_max:\n # window_max = window_min\n # window_maxs.append(window_max)\n # return window_maxs\n\n # little better, quyadratic time\n n = len(arr)\n mins = [[0 for _ in range(n)] for _ in range(n)]\n mins[0] = arr\n maxes = [max(mins[0])]\n for i in range(1, n):\n curr_max = 0\n for j in range(n - i):\n mins[i][j] = min(mins[i - 1][j], mins[i - 1][j + 1])\n if mins[i][j] > curr_max:\n curr_max = mins[i][j]\n maxes.append(curr_max)\n return maxes",
"def __get_radius_for_clusters(k, clusters, centroids):\n clusters_radii = []\n\n for i in range(k):\n centroid = centroids[i]\n cluster = clusters[i]\n max_val = 0\n\n for j in range(len(cluster)):\n val = np.linalg.norm(centroid-cluster[j])\n if val > max_val:\n max_val = val\n\n clusters_radii.append(max_val)\n\n return clusters_radii",
"def calc_windowscore(score_array):\n\tabsolutes = [fabs(x) for x in score_array]\n\ttotal = sum(absolutes)\n\treturn total/len(score_array)",
"def _roll_orig_max_squared(x, window=2000):\n x_rolled = np.lib.stride_tricks.sliding_window_view(x, window, axis=0)\n # https://stackoverflow.com/questions/61703879/in-numpy-how-to-select-elements-based-on-the-maximum-of-their-absolute-values\n shape = np.array(x_rolled.shape)\n shape[-1] = -1\n return np.take_along_axis(x_rolled, np.square(x_rolled).argmax(-1).reshape(shape), axis=-1)",
"def smart_argmax(vector,w=5):\n mx = vector.max()\n mxmask = vector == mx\n n_mx = mxmask.sum()\n sargmax = np.nan # A bad invalid is returned if somehow it's not assigned.\n center_index = int(np.round(vector.shape[0] / 2))\n if n_mx == 1:\n #print('No need for smart_argmax()')\n return vector.argmax()\n hw = int(w/2)\n \n oords = np.arange(0,vector.shape[0]) \n locs = oords[mxmask]\n # 1. If maxes are touching (adjacent),\n # - If only 2, pick the one closest to center\n # - If > 2, pick the one in the middle\n d = np.diff(locs)\n if (d == 1).sum() != 0: # A difference of 1 implies consecutive integers\n # --- Save non-consecutive peaks for analysis\n singular_peak_locs = []\n if d[0] != 1: singular_peak_locs.append(locs[0])\n for s in range(1,d.shape[0]):\n if ((d[s] > 1) and (d[s-1] != 1)): singular_peak_locs.append(locs[s])\n if d[-1] != 1: singular_peak_locs.append(locs[-1])\n # --- \n if np.unique(d).shape[0] > 1: # Check to make sure all d's != 1.\n ic,nc,bn = delineate_consecutive_binned_vector_values(d,[0,1.1,2]) # bin 1 will be diff of 1\n else: # Entering this block means that this is only 1 consecutive span\n ic = np.array([0])\n nc = np.array([locs.shape[0]-1]) # minus 1 because +1 will be added back [5/22/23]\n bn = np.array([1])\n diff_bin_mask = bn == 1\n if ic is None: pdb.set_trace()\n ic = ic[diff_bin_mask]\n nc = nc[diff_bin_mask] + 1\n middle_points = []\n for j in range(0,ic.shape[0]):\n print(j)\n start_index = locs[ic[j]]\n end_index = start_index + nc[j]\n print(end_index,start_index,end_index-start_index)\n print(vector[start_index:end_index])\n print(oords[start_index:end_index])\n x = oords[start_index:end_index]\n print(x.shape)\n # Now find the middle or suitable point\n if x.shape[0] == 2:\n middle_index = np.abs(x - center_index).argmin()\n middle_index = x[middle_index]\n print('middle index: ',middle_index)\n print('Shape of 2 block')\n else:\n middle_index = int(np.median(x))\n print(middle_index)\n print('---------------------')\n middle_points.append(middle_index)\n locs = np.array( middle_points + singular_peak_locs, dtype=int ) # pared consecutives and singulars back into modified locs variable\n n_mx = locs.shape[0] # New # of maxes, with consecutives cut out\n \n reliefs = np.full(n_mx,999)\n for i,argmax in enumerate(locs):\n reliefs[i] = (mx - vector[argmax-hw:argmax+hw+1]).sum()\n \n # 1. Choose max with least topographic relief\n mn_relief = reliefs.min()\n relief_mask = reliefs == mn_relief\n n_mnrf = relief_mask.sum()\n if n_mnrf == 1:\n i = locs[relief_mask]\n sargmax_val = vector[i]\n sargmax = i\n else: # Should have to be > 1\n # 2. Maxes are tied for topographic relief,\n # choose the one closer to the center.\n imid = np.abs(locs[relief_mask] - center_index).argmin()\n i = locs[relief_mask][imid]\n sargmax_val = vector[i]\n sargmax = i\n #print('Standard argmax',vector.argmax(),vector[vector.argmax()])\n #print('Chosen argmax: ',sargmax,sargmax_val)\n if sargmax_val != vector.max(): pdb.set_trace()\n if sargmax_val != vector[sargmax]: pdb.set_trace()\n return int(sargmax)",
"def find_local_max(arr, kernel_width=15):\n arr_convolved = np.convolve(arr, generate_pulse_kernel(kernel_width=kernel_width), mode=\"same\")\n # find local max using scipy.signal.argrelextrema\n ind_local_max = argrelextrema(arr_convolved, np.greater_equal, order=kernel_width, mode='clip')[0]\n logging.info(f\"{len(ind_local_max)} maxima found\")\n # interpolate for local min\n ind_local_max_delta = np.diff(ind_local_max) / 2\n ind_local_min_derived = np.hstack(\n (\n ind_local_max[:-1] - ind_local_max_delta,\n ind_local_max[-1] - ind_local_max_delta[-1],\n ind_local_max[-1] + ind_local_max_delta[-1],\n )\n ).astype(int)\n # calculate SNR for local max\n ind_two_sides = np.array([\n ind_local_min_derived[:-1],\n ind_local_min_derived[1:]\n ])\n ind_two_sides_mask = np.logical_or(ind_two_sides < 0, ind_two_sides > len(arr) - 1)\n ind_two_sides_valid = np.where(ind_two_sides_mask, 0, ind_two_sides) # do not go out of bounds\n # estimate SNR of local max, clip out-of-bounds values\n interp_val_local_max = np.ma.MaskedArray(\n data=arr_convolved[ind_two_sides_valid],\n mask=ind_two_sides_mask,\n ).mean(axis=0)\n assert interp_val_local_max.mask.sum() == 0\n interp_val_local_max = interp_val_local_max.data\n val_local_max = arr_convolved[ind_local_max]\n snr_local_max = val_local_max / interp_val_local_max\n return LocalMax(\n num=len(ind_local_max),\n max_ind=ind_local_max,\n max_val=val_local_max,\n max_val_interp=interp_val_local_max,\n max_snr=snr_local_max,\n min_ind=ind_local_min_derived,\n side_ind=ind_two_sides,\n side_mask=ind_two_sides_mask,\n )",
"def findMaxValueOfEquation(self, points: list[list[int]], k: int) -> int:\n heap = []\n rslt = float('-inf')\n for x, y in points:\n while heap and heap[0][1] < x - k:\n heappop(heap)\n\n if heap:\n rslt = max(\n rslt,\n x + y - heap[0][0]\n )\n\n heappush(heap, (x - y, x))\n\n return rslt",
"def window_size(radius):\n return 2 * radius + 1",
"def select_each_frame_best_locations(k, radius, predicted_heat_maps):\n T = predicted_heat_maps.shape[0]\n future_positions = []\n for i in range(T):\n best_positions = select_top_k_positions(k, predicted_heat_maps[i, :, :], radius)\n future_positions.append(best_positions)\n return future_positions",
"def depth_scoring(scores):\n minima = set(argrelextrema(numpy.array(scores), numpy.less)[0])\n maxima = set(argrelextrema(numpy.array(scores), numpy.greater)[0])\n last_maxima = 0\n depth_scores = [] # a list of tuples (index_of_minima, depth_score_at_minima)\n for i in xrange(len(scores)):\n if i in maxima:\n last_maxima = i\n\n if i in minima:\n # find the next maxima\n next_maxima = None\n count = 0\n while next_maxima is None:\n count += 1\n if i + count in maxima:\n next_maxima = i + count\n elif i + count == len(scores) - 1:\n next_maxima = i + count\n depth_score = (scores[last_maxima] - scores[i]) + (scores[next_maxima] - scores[i])\n depth_scores.append((i, depth_score))\n\n return depth_scores",
"def cluster(r):\r\n # TODO: finish this\r\n k,m=r.shape\r\n clusters=np.argmax(r,axis=0)\r\n return clusters",
"def maxScoreSightseeingPair(self, values: list[int]) -> int:\n maxScore = values[0]\n prevBestIdx = 0\n prevBestSum = values[prevBestIdx] + prevBestIdx\n for j in range(1, len(values)):\n maxScore = max(\n maxScore, prevBestSum + values[j] - j)\n if values[j] + j > prevBestSum:\n prevBestIdx = j\n prevBestSum = values[j] + j\n\n return maxScore",
"def maxWidthRamp(self, nums):\r\n n = len(nums)\r\n res = 0\r\n \r\n for r in range(n):\r\n for l in range(r):\r\n if nums[r] >= nums[l]:\r\n res = max( res, r-l )\r\n \r\n return res",
"def max_radius():\r\n return 20",
"def max_fold_enrichment (self):\n peaks = self.peaks\n chrs = peaks.keys()\n chrs.sort()\n x = 0\n for chrom in chrs:\n if peaks[chrom]:\n m = max([i[7] for i in peaks[chrom]])\n if m>x:\n x=m\n return x",
"def maxLk_interval(self, z, zs):\n izmax = np.argmax(z)\n zmax = np.max(z)\n\n print \"izmax=\", izmax\n print \"zmax=\", zmax\n\n\n \"\"\"\n ### (31-dec-2015): don't remember logic of this; but it \n ### is causing problems!..\n rb = [k for k in range(len(z)) if np.abs(zmax - z[k]) < 0.025 ]\n print \"rb=\",rb\n\n if len(rb)>1: \n sb = [ zs[k] for k in rb ]\n print \"sb=\",sb\n izmax = np.argmin(sb)\n \"\"\"\n\n print \"final izmax=\", izmax\n return izmax",
"def score_max_depths(graph, max_depths):\n score = []\n for i in max_depths:\n partition_girvan = partition_girvan_newman(graph, i)\n norm = norm_cut(S, T, graph)\n score.append((i, norm_cut))\n return score"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Construct a CertificateType object.
|
def __init__(self, value=CertificateTypeEnum.X_509):
super(CertificateType, self).__init__(value, Tags.CERTIFICATE_TYPE)
|
[
"def create_certificate(self, name=None, request_type=None, subject_dn=None,\n source_container_ref=None, ca_id=None, profile=None,\n request_data=None):\n name = name or self.generate_random_name()\n order = self._clients.barbican().orders.create_certificate(\n name=name, request_type=request_type, subject_dn=subject_dn,\n source_container_ref=source_container_ref, ca_id=ca_id,\n profile=profile, request_data=request_data)\n order.submit()\n return order",
"def constructor(key_type: str):\n return KeyType._constructors[key_type]",
"def create(self, certTypes=None):\r\n self.certTypes = certTypes\r\n return self",
"def test_creating_cert(self):\n\n certificate = keyper.Certificate(AppleKeychainTests.TEST_CERT_PATH, password=AppleKeychainTests.TEST_CERT_PASSWORD)\n self.assertEqual(certificate.sha1, \"75:22:4C:AD:D6:A0:BD:0C:88:5F:B1:77:85:2F:83:A4:F6:80:69:70\")\n self.assertEqual(certificate.common_name, \"TestCertificate_CodeSign\")\n self.assertEqual(certificate.private_key_name, \"TestCertificate_CodeSign\")",
"def create_certificate_signing_request(*props): # pylint: disable=unused-argument\n pass",
"def test_certificate_create(self):\n body = CertificatePayload()\n response = self.client.open(\n '/api/v1.0/domain/{domainName}/certificate/'.format(domainName='domainName_example'),\n method='POST',\n data=json.dumps(body),\n content_type='application/json')\n self.assert200(response,\n 'Response body is : ' + response.data.decode('utf-8'))",
"def _create_certificate (self, batch, certificate_data):\n with transaction.atomic ():\n certificate = Certificate.objects.create (batch=batch, **certificate_data)\n\n return certificate",
"def makeCertRequest(cn):\n key = KeyPair.generate()\n return key.certificateRequest(DN(CN=cn))",
"def test_create_cloud_certificate(self):\n pass",
"def _generate_cert(cert, course, student, grade_contents, template_pdf):\n course_id = unicode(course.id)\n\n key = make_hashkey(random.random())\n cert.key = key\n contents = {\n 'action': 'create',\n 'username': student.username,\n 'course_id': course_id,\n 'course_name': course.display_name or course_id,\n 'name': cert.name,\n 'grade': grade_contents,\n 'template_pdf': template_pdf,\n }\n cert.status = CertificateStatuses.downloadable\n cert.verify_uuid = uuid4().hex\n\n cert.save()\n\treturn cert",
"def mk_cacert(issuer, request, private_key):\n pkey = request.get_pubkey()\n cert = X509.X509()\n cert.set_serial_number(1)\n cert.set_version(2)\n mk_cert_valid(cert)\n cert.set_issuer(issuer)\n cert.set_subject(cert.get_issuer())\n cert.set_pubkey(pkey)\n cert.add_ext(X509.new_extension('basicConstraints', 'CA:TRUE'))\n cert.add_ext(X509.new_extension('subjectKeyIdentifier', cert.get_fingerprint()))\n cert.sign(private_key, 'sha256')\n return cert, private_key, pkey",
"def createCertRequest(self, pkey, digest=\"md5\", **name):\n req = crypto.X509Req()\n subj = req.get_subject()\n\n for (key, value) in name.items():\n setattr(subj, key, value)\n\n req.set_pubkey(pkey)\n req.sign(pkey, digest)\n return req",
"def new(cls, commonName, certDir):\n\n o = cls.Options(CN = commonName)\n subject, extensions = gencert.name_from_options(o)\n rsa, x509 = gencert.new_cert(o.key_length,\n subject, o.expiry, isCA=False, extensions=extensions,\n timestamp_offset=-86400)\n\n certHash = cls.computeHashFromX509(x509)\n\n certFile = os.path.join(certDir, certHash + '.0')\n keyFile = os.path.join(certDir, certHash + '.0.key')\n\n o.output = certFile\n o.output_key = keyFile\n gencert.writeCert(o, rsa, x509)\n return certFile, keyFile",
"def _create_csr(cert, private_key):\n\n subject_public_key_info = decoder.decode(private_key.public_key().public_bytes(\n encoding=serialization.Encoding.DER,\n format=serialization.PublicFormat.SubjectPublicKeyInfo\n ), asn1Spec=rfc2314.SubjectPublicKeyInfo())[0]\n\n subject = cert[0]['tbsCertificate']['subject']\n\n # Microsoft OID: szOID_RENEWAL_CERTIFICATE\n renewal_certificate_type = rfc2314.AttributeType((1, 3, 6, 1, 4, 1, 311, 13, 1))\n renewal_certificate_value = rfc2314.univ.SetOf().setComponents(cert[0])\n\n renewal_certificate = rfc2314.Attribute()\n renewal_certificate.setComponentByName('type', renewal_certificate_type)\n renewal_certificate.setComponentByName('vals', renewal_certificate_value)\n\n attributes = rfc2314.Attributes().subtype(\n implicitTag=rfc2314.tag.Tag(rfc2314.tag.tagClassContext,\n rfc2314.tag.tagFormatConstructed, 0))\n attributes.setComponents(renewal_certificate)\n\n certification_request_info = rfc2314.CertificationRequestInfo()\n certification_request_info.setComponentByName('version', 0)\n certification_request_info.setComponentByName('subject', subject)\n certification_request_info.setComponentByName('subjectPublicKeyInfo', subject_public_key_info)\n certification_request_info.setComponentByName('attributes', attributes)\n\n raw_signature, signature_algorithm = _sign(private_key,\n encoder.encode(certification_request_info))\n\n signature = rfc2314.univ.BitString(hexValue=binascii.hexlify(raw_signature).decode('ascii'))\n\n certification_request = rfc2314.CertificationRequest()\n certification_request.setComponentByName('certificationRequestInfo', certification_request_info)\n certification_request.setComponentByName('signatureAlgorithm', signature_algorithm)\n certification_request.setComponentByName('signature', signature)\n\n return encoder.encode(certification_request)",
"def test_new_cert():\n data = [\"요리자격증\", \"국가요리원\", date(2021, 1, 1), 1]\n cert = Certification(data[0], data[1], data[2], data[3])\n assert cert.name == data[0]\n assert cert.provider == data[1]\n assert cert.acquired_date == data[2]\n assert cert.user_id == data[3]",
"def create_self_signed_certificate(*props): # pylint: disable=unused-argument\n pass",
"def make(spec: dict, strict: bool = False) -> Type:\n ll_spec = SpecParser.parse(spec, strict)\n return TypeFactory.make(ll_spec)",
"def test_create_certificate_signing_request(self):\n pass",
"def create_ContextObject(self, _type=None, **kwargs):\n return ContextObject(self.graph, rdf_type=_type, **kwargs)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Construct a DigestValue object.
|
def __init__(self, value=b''):
super(DigestValue, self).__init__(value, Tags.DIGEST_VALUE)
|
[
"def test05_digest_value(self):\n d = Digest()\n d.want_digest = 'md5'\n self.assertEqual(d.digest_value(b'hello'), 'md5=XUFAKrxLKna5cZ2REBfFkg==')",
"def load_digest(cls, alg: HashAlgorithm, digest: ByteString) -> MessageDigest:\n return MessageDigest(bytes(digest), cls(alg))",
"def _get_digest_auth(self) -> httpx.DigestAuth:\n username = \"\" if self._username is None else self._username\n return httpx.DigestAuth(username, self._password)",
"def test03_digest(self):\n oo = Object(digest_algorithm='md5')\n self.assertEqual(oo.digest('tests/testdata/files/empty'),\n 'd41d8cd98f00b204e9800998ecf8427e')",
"def __init__(\n self, value, f=64, reg=r'[\\w\\u4e00-\\u9fcc]+', hashfunc=None, log=None\n ):\n\n self.f = f\n self.reg = reg\n self.value = None\n\n if hashfunc is None:\n self.hashfunc = _hashfunc\n else:\n self.hashfunc = hashfunc\n\n if log is None:\n self.log = logging.getLogger(\"simhash\")\n else:\n self.log = log\n\n if isinstance(value, Simhash):\n self.value = value.value\n elif isinstance(value, basestring):\n self.build_by_text(unicode(value))\n elif isinstance(value, collections.Iterable):\n self.build_by_features(value)\n elif isinstance(value, numbers.Integral):\n self.value = value\n else:\n raise Exception('Bad parameter with type {}'.format(type(value)))",
"def sign_dsa(self, digest):\n assert self._check_key_type(), \"'ec' type error\"\n return m2.ecdsa_sign(self.ec, digest)",
"def DigestSize() -> int:",
"def digest(self):\n if not self._hash:\n self._hash = self._calchash(self.content)\n return self._hash",
"def digest_converter(self, digest):\r\n binary = bin(int(digest, 16))[2:].zfill(len(digest * 4))\r\n return binary",
"def compute_digest(self) -> bytes:\n if self.raw_digest is not None:\n return self.raw_digest\n\n md = getattr(hashlib, self.md_algorithm)()\n stream = self.reader.stream\n\n # compute the digest\n # here, we allow arbitrary byte ranges\n # for the coverage check, we'll impose more constraints\n total_len = 0\n for lo, chunk_len in misc.pair_iter(self.byte_range):\n stream.seek(lo)\n chunk = stream.read(chunk_len)\n assert len(chunk) == chunk_len\n md.update(chunk)\n total_len += chunk_len\n\n self.total_len = total_len\n self.raw_digest = digest = md.digest()\n return digest",
"def get_digest(logger, digest_def):\n #session = db.get_session()\n\n # Get or create protease.\n protease = Protease(**digest_def['protease'])\n protease_id = str(digest_def['protease']['id'])\n cur = db.get_psycopg2_cursor()\n cur.execute(\"select * from protease where protease.id=%s;\", (protease_id,))\n results = cur.fetchone()\n\n if results is None:\n logger.info(\n \"No protease exists for the given definition, creating...\")\n protease = Protease(**digest_def['protease'])\n cur.execute(\"insert into protease (id, cleavage_rule) values( %s, %s);\", (str(digest_def['protease']['id']), str(digest_def['protease']['cleavage_rule']),))\n else:\n protease = Protease(id=results[0], cleavage_rule=results[1])\n db.psycopg2_connection.commit()\n\n # Get or create digest object.\n cur = db.get_psycopg2_cursor()\n\n #not all possible digestion parameters will have a value so build the query to account for this\n query_params = [protease.id]\n digest_query = \"select * from digest where digest.protease_id = %s\";\n if digest_def.get('max_missed_cleavages') is not None:\n digest_query = digest_query + \" and digest.max_missed_cleavages = %s \"\n query_params.append(digest_def.get('max_missed_cleavages'))\n if digest_def.get('min_acids') is not None:\n digest_query = digest_query + \" and digest.min_acids = %s \"\n query_params.append(digest_def.get('min_acids'))\n if digest_def.get('max_acids') is not None:\n digest_query = digest_query + \" and digest.max_acids = %s \"\n query_params.append(digest_def.get('max_acids'))\n\n cur.execute(digest_query, (query_params))\n results = cur.fetchone()\n db.psycopg2_connection.commit\n if results is None:\n #if not digest:\n logger.info(\n \"No digest exists for the given definition, creating...\")\n digest_kwargs = {}\n digest_kwargs.update(digest_def)\n digest_kwargs['protease'] = protease\n digest = Digest(**digest_kwargs)\n cur = db.get_psycopg2_cursor()\n\n\n cur.execute(\"select * from digest_insert( %s, %s, %s, %s);\", (protease.id, digest.max_missed_cleavages, digest.min_acids, digest.max_acids,))\n digest_result = cur.fetchone()\n\n if digest_result:\n digest = Digest(id=digest_result[0], protease = protease, max_missed_cleavages=digest_result[2], min_acids = digest_result[3], max_acids = digest_result[4])\n else:\n digest = Digest(id=results[0], protease = protease, max_missed_cleavages=results[2], min_acids = results[3], max_acids = results[4])\n db.psycopg2_connection.commit()\n return digest",
"def build_value_construct_expr(self, type_decl, value):\n\n def build_value_expr(type_name, value):\n \"\"\" Special treatment for bstring and hstring values,\n which use different construction depending on target type.\n \"\"\"\n if isinstance(value, BinaryStringValue):\n if type_name == 'OCTET STRING':\n return 'binValue=\\'%s\\'' % value.value\n else:\n return '\"\\'%s\\'B\"' % value.value\n elif isinstance(value, HexStringValue):\n if type_name == 'OCTET STRING':\n return 'hexValue=\\'%s\\'' % value.value\n else:\n return '\"\\'%s\\'H\"' % value.value\n else:\n return self.translate_value(value)\n\n if isinstance(value, ObjectIdentifierValue):\n return self.build_object_identifier_value(value)\n else:\n value_type = _translate_type(type_decl.type_name)\n root_type = self.sema_module.resolve_type_decl(type_decl, self.referenced_modules)\n return '%s(%s)' % (value_type, build_value_expr(root_type.type_name, value))",
"def __init__(self, hashname=\"sha1\", sequence_class=None):\n self.hashname = hashname\n self.sequence_class = sequence_class\n self.__hash = hashlib.new(hashname)\n self.is_dict = True # The root is always a dict.",
"def from_bytes(cls: type['HexBytes'], value: bytes) -> 'HexBytes':\n return super().__new__(cls, value)",
"def generate_hash(value, hash='sha1'):\n sha_obj = getattr(hashlib, hash)(value)\n return sha_obj.hexdigest()",
"def __init__(self, hash_algorithm):\n\n self.hash_algorithm = hash_algorithm.upper().replace(\"_\", \"-\")\n hashlib_name = self.hash_algorithm\n\n # DIF names deviate from python's hashlib names\n deviating_names = [(\"MD5\", \"md5\"),\n (\"SHA-1\", \"sha1\"),\n (\"SHA-224\", \"sha224\"),\n (\"SHA-256\", \"sha256\"),\n (\"SHA-384\", \"sha384\"),\n (\"SHA-512\", \"sha512\"),\n (\"SHA3-224\", \"sha3_224\"),\n (\"SHA3-256\", \"sha3_256\"),\n (\"SHA3-384\", \"sha3_384\"),\n (\"SHA3-512\", \"sha3_512\")]\n for dif_name, lib_name in deviating_names:\n if self.hash_algorithm == dif_name or\\\n self.hash_algorithm == lib_name.upper():\n self.hash_algorithm = dif_name\n hashlib_name = lib_name\n break\n\n if self.hash_algorithm not in self.SUPPORTED_ALGORITHMS:\n raise ValueError(\"{0} is not a supported hash algorithm.\".format(\n self.hash_algorithm))\n\n self._hasher = hashlib.new(hashlib_name)",
"def digest(self):\n return b''.join(struct.pack('>I', h) for h in self.finalize(self.buffer))",
"def new(self) -> HashFunction:\n return self.hashfunc(self.algorithm)",
"def GetDigestOfFile(digest_algorithm, file_to_digest):\n messages = cloudkms_base.GetMessagesModule()\n algorithm = _DIGEST_ALGORITHMS.get(digest_algorithm)\n if not algorithm:\n raise exceptions.InvalidArgumentException('digest',\n 'digest_algorithm is invalid.')\n digest = algorithm()\n for chunk in _ChunkReader(file_to_digest):\n digest.update(chunk)\n kwargs = {digest_algorithm: digest.digest()}\n return messages.Digest(**kwargs)",
"def __init__(self, data=None, tag: Tag=None, length: Length=None, value: Value=None):\n if data is None:\n # building data with Tag + Length + Value\n assert tag is not None, 'TLV tag should not be empty'\n data = tag\n if length is not None:\n data = data.concat(length)\n if value is not None:\n data = data.concat(value)\n elif isinstance(data, TagLengthValue):\n # get Tag + Value from another TLV object\n tag = data.tag\n value = data.value\n super().__init__(data=data)\n self.__tag = tag\n self.__value = value"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Construct a Digest object.
|
def __init__(self,
hashing_algorithm=None,
digest_value=None,
key_format_type=None):
super(Digest, self).__init__(Tags.DIGEST)
if hashing_algorithm is None:
self.hashing_algorithm = HashingAlgorithm()
else:
self.hashing_algorithm = hashing_algorithm
if digest_value is None:
self.digest_value = DigestValue()
else:
self.digest_value = digest_value
if key_format_type is None:
self.key_format_type = KeyFormatType()
else:
self.key_format_type = key_format_type
self.validate()
|
[
"def load_digest(cls, alg: HashAlgorithm, digest: ByteString) -> MessageDigest:\n return MessageDigest(bytes(digest), cls(alg))",
"def _get_digest_auth(self) -> httpx.DigestAuth:\n username = \"\" if self._username is None else self._username\n return httpx.DigestAuth(username, self._password)",
"def test05_digest_value(self):\n d = Digest()\n d.want_digest = 'md5'\n self.assertEqual(d.digest_value(b'hello'), 'md5=XUFAKrxLKna5cZ2REBfFkg==')",
"def test03_digest(self):\n oo = Object(digest_algorithm='md5')\n self.assertEqual(oo.digest('tests/testdata/files/empty'),\n 'd41d8cd98f00b204e9800998ecf8427e')",
"def DigestSize() -> int:",
"def __init__(self, hash_algorithm):\n\n self.hash_algorithm = hash_algorithm.upper().replace(\"_\", \"-\")\n hashlib_name = self.hash_algorithm\n\n # DIF names deviate from python's hashlib names\n deviating_names = [(\"MD5\", \"md5\"),\n (\"SHA-1\", \"sha1\"),\n (\"SHA-224\", \"sha224\"),\n (\"SHA-256\", \"sha256\"),\n (\"SHA-384\", \"sha384\"),\n (\"SHA-512\", \"sha512\"),\n (\"SHA3-224\", \"sha3_224\"),\n (\"SHA3-256\", \"sha3_256\"),\n (\"SHA3-384\", \"sha3_384\"),\n (\"SHA3-512\", \"sha3_512\")]\n for dif_name, lib_name in deviating_names:\n if self.hash_algorithm == dif_name or\\\n self.hash_algorithm == lib_name.upper():\n self.hash_algorithm = dif_name\n hashlib_name = lib_name\n break\n\n if self.hash_algorithm not in self.SUPPORTED_ALGORITHMS:\n raise ValueError(\"{0} is not a supported hash algorithm.\".format(\n self.hash_algorithm))\n\n self._hasher = hashlib.new(hashlib_name)",
"def __init__(self, hashname=\"sha1\", sequence_class=None):\n self.hashname = hashname\n self.sequence_class = sequence_class\n self.__hash = hashlib.new(hashname)\n self.is_dict = True # The root is always a dict.",
"def compute_digest(self) -> bytes:\n if self.raw_digest is not None:\n return self.raw_digest\n\n md = getattr(hashlib, self.md_algorithm)()\n stream = self.reader.stream\n\n # compute the digest\n # here, we allow arbitrary byte ranges\n # for the coverage check, we'll impose more constraints\n total_len = 0\n for lo, chunk_len in misc.pair_iter(self.byte_range):\n stream.seek(lo)\n chunk = stream.read(chunk_len)\n assert len(chunk) == chunk_len\n md.update(chunk)\n total_len += chunk_len\n\n self.total_len = total_len\n self.raw_digest = digest = md.digest()\n return digest",
"def digest(self):\n return b''.join(struct.pack('>I', h) for h in self.finalize(self.buffer))",
"def get_digest(logger, digest_def):\n #session = db.get_session()\n\n # Get or create protease.\n protease = Protease(**digest_def['protease'])\n protease_id = str(digest_def['protease']['id'])\n cur = db.get_psycopg2_cursor()\n cur.execute(\"select * from protease where protease.id=%s;\", (protease_id,))\n results = cur.fetchone()\n\n if results is None:\n logger.info(\n \"No protease exists for the given definition, creating...\")\n protease = Protease(**digest_def['protease'])\n cur.execute(\"insert into protease (id, cleavage_rule) values( %s, %s);\", (str(digest_def['protease']['id']), str(digest_def['protease']['cleavage_rule']),))\n else:\n protease = Protease(id=results[0], cleavage_rule=results[1])\n db.psycopg2_connection.commit()\n\n # Get or create digest object.\n cur = db.get_psycopg2_cursor()\n\n #not all possible digestion parameters will have a value so build the query to account for this\n query_params = [protease.id]\n digest_query = \"select * from digest where digest.protease_id = %s\";\n if digest_def.get('max_missed_cleavages') is not None:\n digest_query = digest_query + \" and digest.max_missed_cleavages = %s \"\n query_params.append(digest_def.get('max_missed_cleavages'))\n if digest_def.get('min_acids') is not None:\n digest_query = digest_query + \" and digest.min_acids = %s \"\n query_params.append(digest_def.get('min_acids'))\n if digest_def.get('max_acids') is not None:\n digest_query = digest_query + \" and digest.max_acids = %s \"\n query_params.append(digest_def.get('max_acids'))\n\n cur.execute(digest_query, (query_params))\n results = cur.fetchone()\n db.psycopg2_connection.commit\n if results is None:\n #if not digest:\n logger.info(\n \"No digest exists for the given definition, creating...\")\n digest_kwargs = {}\n digest_kwargs.update(digest_def)\n digest_kwargs['protease'] = protease\n digest = Digest(**digest_kwargs)\n cur = db.get_psycopg2_cursor()\n\n\n cur.execute(\"select * from digest_insert( %s, %s, %s, %s);\", (protease.id, digest.max_missed_cleavages, digest.min_acids, digest.max_acids,))\n digest_result = cur.fetchone()\n\n if digest_result:\n digest = Digest(id=digest_result[0], protease = protease, max_missed_cleavages=digest_result[2], min_acids = digest_result[3], max_acids = digest_result[4])\n else:\n digest = Digest(id=results[0], protease = protease, max_missed_cleavages=results[2], min_acids = results[3], max_acids = results[4])\n db.psycopg2_connection.commit()\n return digest",
"def digest(self):\n if not self._hash:\n self._hash = self._calchash(self.content)\n return self._hash",
"def sign_dsa(self, digest):\n assert self._check_key_type(), \"'ec' type error\"\n return m2.ecdsa_sign(self.ec, digest)",
"def GetDigestOfFile(digest_algorithm, file_to_digest):\n messages = cloudkms_base.GetMessagesModule()\n algorithm = _DIGEST_ALGORITHMS.get(digest_algorithm)\n if not algorithm:\n raise exceptions.InvalidArgumentException('digest',\n 'digest_algorithm is invalid.')\n digest = algorithm()\n for chunk in _ChunkReader(file_to_digest):\n digest.update(chunk)\n kwargs = {digest_algorithm: digest.digest()}\n return messages.Digest(**kwargs)",
"def finalize(self) -> MessageDigest:\n if self._digest is None:\n self._digest = MessageDigest(self._finalize(), self)\n return self._digest",
"def __init__(self):\n _snap.TStrHashF_Md5_swiginit(self,_snap.new_TStrHashF_Md5())",
"def get_digest(clue):\n return clue.info['digest']",
"def executeDigest(uri, digest):\n r = requests.post(uri, data=digest, headers=HEADERS)\n if 400 == r.status_code:\n print r\n failure = ET.fromstring(r.text)\n debug_print(ET.tostring(failure))\n if None == failure:\n raise FatalError('Bad Request', 1, r.text)\n messageElement = failure.find('message')\n if None == messageElement:\n raise FatalError(None, 1, r.text)\n raise FatalError(messageElement.text, 1, r.text)\n elif 404 == r.status_code:\n raise FatalError('The operation could not be found', 1, r.text)\n elif 409 == r.status_code:\n raise FatalError('Another process has already acted some parts of this request, so this attempt will halt', r.status_code, r.text)\n# elif 201 == r.status_code:\n# return\n elif 200 != r.status_code:\n raise FatalError('Unexpected status (' + str(r.status_code) + ') returned from \"' + uri + '\"', r.status_code, r.text)\n created = ET.fromstring(r.text)\n debug_print(ET.tostring(created))\n return created",
"def GetDigest(digest_algorithm, filename):\n with files.BinaryFileReader(filename) as f:\n return GetDigestOfFile(digest_algorithm, f)",
"def __init__(self):\n super(SHA1Hasher, self).__init__()\n self._sha1_context = hashlib.sha1()",
"def digest(self):\n target = self.serialize(for_id=True)\n d = hashlib.sha256(target).digest()\n self.transaction_id = d[:self.id_length]\n return d"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Read the data encoding the Digest object and decode it into its constituent parts.
|
def read(self, istream):
super(Digest, self).read(istream)
tstream = BytearrayStream(istream.read(self.length))
self.hashing_algorithm.read(tstream)
self.digest_value.read(tstream)
self.key_format_type.read(tstream)
self.is_oversized(tstream)
self.validate()
|
[
"def readData(self, det):\n f = open(self.file, \"rb\")\n fortran.skip(f) # Skip header\n for _ in range(2 * det):\n fortran.skip(f) # Detector Header & Data\n fortran.skip(f) # Detector Header\n data = fortran.read(f)\n f.close()\n return data",
"def load_digest(cls, alg: HashAlgorithm, digest: ByteString) -> MessageDigest:\n return MessageDigest(bytes(digest), cls(alg))",
"def _readStruct(self, unpack):\n length = struct.calcsize(unpack)\n ba = self.object_stream.read(length)\n\n if len(ba) != length:\n raise RuntimeError(\n \"Stream has been ended unexpectedly while unmarshaling.\"\n )\n\n return struct.unpack(unpack, ba)",
"def compute_digest(self) -> bytes:\n if self.raw_digest is not None:\n return self.raw_digest\n\n md = getattr(hashlib, self.md_algorithm)()\n stream = self.reader.stream\n\n # compute the digest\n # here, we allow arbitrary byte ranges\n # for the coverage check, we'll impose more constraints\n total_len = 0\n for lo, chunk_len in misc.pair_iter(self.byte_range):\n stream.seek(lo)\n chunk = stream.read(chunk_len)\n assert len(chunk) == chunk_len\n md.update(chunk)\n total_len += chunk_len\n\n self.total_len = total_len\n self.raw_digest = digest = md.digest()\n return digest",
"def GetDigest(digest_algorithm, filename):\n with files.BinaryFileReader(filename) as f:\n return GetDigestOfFile(digest_algorithm, f)",
"def decode_read(data):\n data, _, crc = data.partition(b\" \")\n data = base64.b64decode(data)\n crc = int(crc.decode('ascii'))\n\n if binascii.crc32(data) == crc:\n return data\n else:\n raise Exception(\"CRC mismatch on received data\")",
"def get_digest(clue):\n return clue.info['digest']",
"def digest(self):\n return b''.join(struct.pack('>I', h) for h in self.finalize(self.buffer))",
"def decode(self, data):\n\t\traise NotImplementedError()",
"def _read_eigc(self, data: bytes, n: int) -> int:\n op2 = self.op2\n if 0:\n ntotal = 60\n nentries = (len(data) - n) // ntotal\n op2.increase_card_count('EIGB', nentries)\n struct1 = Struct(op2._endian + b'i 4s 4s 2i f 2i')\n #struct2 = Struct(op2._endian + b'5f2i')\n for i in range(nentries):\n edata = data[n:n+ntotal]\n #op2.show_data(edata[44:])\n # int, 8s, 2f, 3i, i, 8s, 4i\n out = struct1.unpack(edata)\n sid, method, L1, L2, nep, ndp, ndn, dunno, norm, g, c, dunno_a, dunno_b = out\n if op2.is_debug_file:\n op2.binary_debug.write('EIGC=%s\\n' % str(out))\n #print('out = %s' % str(out))\n method = method.strip().decode('latin1')\n norm = norm.strip().decode('latin1')\n eigb = EIGB(sid, method, L1, L2, nep, ndp, ndn, norm, g, c)\n op2._add_methods._add_method_object(eigb)\n n += ntotal\n #return n\n\n #-------------------------------------------------\n ndata = len(data)\n nfields = (ndata - n) // self.size\n datan = data[n:]\n if self.size == 4:\n ints = unpack(op2._endian + b'%ii' % nfields, datan)\n floats = unpack(op2._endian + b'%if' % nfields, datan)\n strings = unpack(op2._endian + b'4s'* nfields, datan)\n else:\n ints = unpack(op2._endian + b'%iq' % nfields, datan)\n floats = unpack(op2._endian + b'%id' % nfields, datan)\n strings = unpack(op2._endian + b'8s'* nfields, datan)\n\n i = 0\n nentries = 0\n while i < nfields:\n sid = ints[i+0]\n method = (strings[i+1] + strings[i+2]).strip().decode('latin1')\n norm = (strings[i+3] + strings[i+4]).strip().decode('latin1')\n grid = ints[i+5]\n component = ints[i+6]\n epsilon = floats[i+7]\n neigenvalues = ints[i+8]\n control_flag = ints[i+9]\n\n #print('sid=%s method=%r norm=%r grid=%s component=%s epsilon=%g, '\n #'neigenvalues=%s ctlflag=%s' % (\n #sid, method, norm, grid, component, epsilon, neigenvalues, control_flag))\n\n alphaAjs = []\n omegaAjs = []\n alphaBjs = []\n omegaBjs = []\n LJs = []\n NEJs = []\n NDJs = []\n\n # dummy\n mblkszs = []\n iblkszs = []\n ksteps = []\n NJIs = []\n if control_flag == -1:\n datai = [sid, method, norm, grid, component, epsilon, neigenvalues, -1]\n i += 10\n elif control_flag == 0:\n intsi = ints[i+10:i+17]\n assert len(intsi) == 7, 'len=%s intsi=%s' % (len(intsi), intsi)\n datai = [sid, method, norm, grid, component, epsilon, neigenvalues, 0]\n while intsi != (-1, -1, -1, -1, -1, -1, -1):\n aaj, waj, abj, wbj, lj = floats[i+10:i+15]\n #print('aaj=%s waj=%s abj=%s wbj=%s lj=%s' % (\n #aaj, waj, abj, wbj, lj))\n nej, ndj = ints[i+15:i+17]\n datai.extend([(aaj, waj, abj, wbj, lj, nej)])\n\n alphaAjs.append(aaj)\n omegaAjs.append(waj)\n alphaBjs.append(abj)\n omegaBjs.append(wbj)\n if norm == 'MAX':\n # faked\n mblkszs.append(0.)\n iblkszs.append(0)\n ksteps.append(0)\n NJIs.append(0)\n\n LJs.append(lj)\n NEJs.append(nej)\n NDJs.append(ndj)\n #print('aaj=%s waj=%s abj=%s wbj=%s lj=%s nej=%s ndj=%s' % (\n #aaj, waj, abj, wbj, lj, nej, ndj\n #))\n i += 7\n intsi = ints[i+10:i+17]\n #print('intsi = ', intsi)\n assert len(intsi) == 7, 'len=%s intsi=%s' % (len(intsi), intsi)\n #print(\"intsi = \", intsi)\n #print()\n #11 AAJ RS Location of A on real axis\n #12 WAJ RS Location of A on imaginary axis\n #13 ABJ RS Location of B on real axis\n #14 WBJ RS Location of B on imaginary axis\n #15 LJ RS Width of search region\n #16 NEJ I Number of estimated roots\n #17 NDJ I Number of desired eigenvectors\n assert len(intsi) == 7, intsi\n #print('intsi = ', intsi)\n #raise NotImplementedError('EIGC control_flag=%s' % control_flag)\n\n # +10 is for the prefix; +7 is for the -1s\n i += 10 + 7 # 3 + 4 from (-1,-1,-1) and (sid,grid,comp,coeff)\n else:\n raise NotImplementedError('EIGC control_flag=%s' % control_flag)\n datai.extend([-1, -1, -1, -1, -1, -1, -1]) # creates a +7\n\n if op2.is_debug_file:\n op2.binary_debug.write(' EIGC=%s\\n' % str(datai))\n\n if grid == 0:\n grid = None\n assert component == 0, component\n component = None\n\n eigc = op2.add_eigc(sid, method, grid, component, epsilon, neigenvalues, norm=norm,\n mblkszs=mblkszs, iblkszs=iblkszs, ksteps=ksteps, NJIs=NJIs,\n alphaAjs=alphaAjs, omegaAjs=omegaAjs,\n alphaBjs=alphaBjs, omegaBjs=omegaBjs,\n LJs=LJs, NEJs=NEJs, NDJs=NDJs,\n shift_r1=None, shift_i1=None, isrr_flag=None,\n nd1=None, comment='')\n eigc.validate()\n\n #while intsi != (-1, -1, -1):\n #gridi, compi, coeffi = ints[i+4], ints[i+5], floats[i+6]\n #mpc_data.extend([gridi, compi, coeffi])\n #nodes.append(gridi)\n #components.append(compi)\n #coefficients.append(coeffi)\n #i += 3\n\n nentries += 1\n #print('--------------')\n op2.increase_card_count('EIGC', nentries)\n return len(data)",
"def decrypt_and_decode(self, data, **kwargs):\n return",
"def umd_field_decode(fp,pos):\n fp.seek(pos)\n field_type_list={2:'title',3:'author',4:'year',5:'month',6:'day',7:'gender',8:'publisher',9:'vendor'}\n dtype=struct.unpack('=H',fp.read(2))\n if dtype[0]<>11:\n field_type=field_type_list[dtype[0]]\n field_value=u''\n i=pos+3\n fp.seek(i,0)\n field_len=int(ord(fp.read(1)))\n field_len=field_len-5\n i+=1\n fp.seek(i,0)\n m=i\n while m<i+field_len:\n onechar=unichr(struct.unpack('=H',fp.read(2))[0])\n field_value+=onechar\n m+=2\n fp.seek(m)\n else:\n field_type='content'\n pos+=4\n fp.seek(pos,0)\n field_len=struct.unpack('=I',fp.read(4))[0]\n pos+=5\n fp.seek(pos,0)\n## print field_len\n chapter_type=struct.unpack('=H',fp.read(2))[0]\n## print hex(chapter_type)\n\n pos+=4\n fp.seek(pos,0)\n r1=struct.unpack('=I',fp.read(4))[0]\n## print \"random-1 is \"+str(hex(r1))\n\n pos+=5\n fp.seek(pos,0)\n r2=struct.unpack('=I',fp.read(4))[0]\n## print \"random-2 is \"+str(hex(r2))\n\n pos+=4\n fp.seek(pos,0)\n offset_len=struct.unpack('=I',fp.read(4))[0]-9\n## print \"offset_len is \"+str(offset_len)\n\n i=0\n pos+=4\n fp.seek(pos,0)\n chapter_offset=[]\n while i<offset_len:\n chapter_offset.append(struct.unpack('=I',fp.read(4))[0])\n## print chapter_offset\n i+=4\n fp.seek(pos+i,0)\n## print \"chapter offsets are:\"\n## print chapter_offset\n\n pos+=offset_len+1\n fp.seek(pos,0)\n ch_t_type=struct.unpack('=H',fp.read(2))[0]\n## print \"ch_title_type is \"+str(hex(ch_t_type))\n\n pos+=4\n fp.seek(pos,0)\n r3=struct.unpack('=I',fp.read(4))[0]\n## print \"random-3 is \"+str(hex(r3))\n\n pos+=5\n fp.seek(pos,0)\n r4=struct.unpack('=I',fp.read(4))[0]\n## print \"random-4 is \"+str(hex(r4))\n\n pos+=4\n fp.seek(pos,0)\n ch_title_len=struct.unpack('=I',fp.read(4))[0]-9\n m=0\n pos+=4\n fp.seek(pos,0)\n while m<ch_title_len:\n t_len=ord(struct.unpack('=c',fp.read(1))[0])\n pos+=1\n fp.seek(pos,0)\n n=pos\n t_val=u''\n while n<pos+t_len:\n onechar=unichr(struct.unpack('=H',fp.read(2))[0])\n t_val+=onechar\n n+=2\n fp.seek(n)\n## print t_val.encode('gbk',\"replace\")\n m+=1+t_len\n pos+=t_len\n fp.seek(pos,0)\n## print \"chapter title len is \"+str(ch_title_len)\n\n fp.seek(pos,0)\n t_tag=fp.read(1)\n content=u''\n while t_tag=='$':\n pos+=5\n fp.seek(pos,0)\n content_len=struct.unpack(GetPint(),fp.read(4))[0]-9\n## print \"content_len is:\"+str(content_len)\n #content_len=192450\n\n pos+=4\n fp.seek(pos,0)\n x=content_len/65535\n y=content_len%65535\n n=0\n zstr=''\n while n<x:\n xx=fp.read(65535)\n zstr+=xx\n pos+=65535\n fp.seek(pos,0)\n n+=1\n zstr+=fp.read(y)\n pos+=y\n z_len=zstr.__len__()\n## print \"z_len is \"+str(z_len)\n ystr=zlib.decompress(zstr)\n y_len=ystr.__len__()\n## print \"y_len is \"+str(y_len)\n ystr=ystr.replace('\\x29\\x20','\\n\\x00')\n content+=ystr.decode('utf-16','ignore')\n## sys.exit()\n## n=0\n## while n<y_len:\n## onechar=unichr(struct.unpack('H',ystr[n:n+2])[0])\n## if onechar==u'\\u2029':\n## onechar=u'\\n'\n## content+=onechar\n## n+=2\n #print content.encode('GBK','replace')\n fp.seek(pos,0)\n t_tag=fp.read(1)\n## print t_tag\n #print content.encode('GBK','ignore')\n\n fp.seek(pos,0)\n if fp.read(1)=='#':\n pos+=1\n fp.seek(pos,0)\n m_tag=struct.unpack('=H',fp.read(2))[0]\n else:\n m_tag=0\n\n while m_tag<>0xc:\n if m_tag==0xf1:\n pos+=20\n else:\n if m_tag==0xa:\n pos+=4\n fp.seek(pos,0)\n R1=struct.unpack('=I',fp.read(4))[0]\n## print \"Random-1 is \"+str(hex(R1))\n pos+=4\n else:\n if m_tag==0x81:\n pos+=8\n fp.seek(pos,0)\n## print fp.read(1)\n pos+=5\n fp.seek(pos,0)\n page_count=struct.unpack('=I',fp.read(4))[0]-9\n pos+=page_count+4\n\n else:\n if m_tag==0x87:\n pos+=15\n fp.seek(pos,0)\n offset_len=struct.unpack('=I',fp.read(4))[0]-9\n## print \"offset_len is \"+str(offset_len)\n## i=0\n pos+=4+offset_len\n## fp.seek(pos,0)\n## chapter_offset=[]\n## while i<offset_len:\n## chapter_offset.append(struct.unpack('I',fp.read(4))[0])\n## i+=4\n## fp.seek(pos+i,0)\n## print \"chapter offsets are:\"\n## print chapter_offset\n\n else:\n if m_tag==0x82:\n pos+=14\n fp.seek(pos,0)\n cover_len=struct.unpack(GetPint(),fp.read(4))[0]-9\n pos+=cover_len+4\n else:\n if m_tag==0xb:\n pos+=8\n else:\n fp.seek(pos,0)\n t_tag=fp.read(1)\n while t_tag=='$':\n pos+=5\n fp.seek(pos,0)\n content_len=struct.unpack(GetPint(),fp.read(4))[0]-9\n ## print \"content_len is:\"+str(content_len)\n pos+=4\n fp.seek(pos,0)\n x=content_len/65535\n y=content_len%65535\n n=0\n zstr=''\n while n<x:\n xx=fp.read(65535)\n zstr+=xx\n pos+=65535\n fp.seek(pos,0)\n n+=1\n zstr+=fp.read(y)\n pos+=y\n z_len=zstr.__len__()\n ## print \"z_len is \"+str(z_len)\n ystr=zlib.decompress(zstr)\n y_len=ystr.__len__()\n ## print \"y_len is \"+str(y_len)\n ystr=ystr.replace('\\x29\\x20','\\n\\x00')\n content+=ystr.decode('utf-16','ignore')\n fp.seek(pos,0)\n t_tag=fp.read(1)\n ## print t_tag\n\n #print content.encode('GBK','ignore')\n fp.seek(pos,0)\n xxx=fp.read(1)\n if xxx=='#':\n pos+=1\n fp.seek(pos,0)\n m_tag=struct.unpack('=H',fp.read(2))[0]\n else:\n m_tag=0\n## print type(content)\n return ('Content',content,pos,True)\n\n return (field_type,field_value,m,False)",
"def unpack(self, stream):\n raise NotImplementedError()",
"def git_decode_object(data):\n decompressed = zlib.decompress(data)\n header, contents = decompressed.split(b'\\0', 1)\n kind = header.split()[0]\n p = subprocess.Popen(['git', 'hash-object', '-w', '--stdin', '-t', kind],\n stdin=subprocess.PIPE, stdout=subprocess.PIPE,\n stderr=DEVNULL)\n sha = p.communicate(contents)[0].decode('utf8').strip()\n return sha",
"def read(self, stream):\n logger = logging.getLogger(\"pyffi.bsa.data\")\n\n # inspect\n self.inspect_quick(stream)\n\n # read file\n logger.debug(\"Reading header at 0x%08X.\" % stream.tell())\n BsaFormat._Header.read(self, stream, data=self)\n if self.version == 0:\n # morrowind\n logger.debug(\"Reading file records at 0x%08X.\" % stream.tell())\n self.old_files.read(stream, data=self)\n logger.debug(\n \"Reading file name offsets at 0x%08X.\" % stream.tell())\n for old_file in self.old_files:\n old_file._name_offset_value_.read(stream, data=self)\n logger.debug(\"Reading file names at 0x%08X.\" % stream.tell())\n for old_file in self.old_files:\n old_file._name_value_.read(stream, data=self)\n logger.debug(\"Reading file hashes at 0x%08X.\" % stream.tell())\n for old_file in self.old_files:\n old_file._name_hash_value_.read(stream, data=self)\n # \"read\" the files\n logger.debug(\n \"Seeking end of raw file data at 0x%08X.\" % stream.tell())\n total_num_bytes = 0\n for old_file in self.old_files:\n total_num_bytes += old_file.data_size\n stream.seek(total_num_bytes, os.SEEK_CUR)\n else:\n # oblivion and up\n logger.debug(\n \"Reading folder records at 0x%08X.\" % stream.tell())\n self.folders.read(stream, data=self)\n logger.debug(\n \"Reading folder names and file records at 0x%08X.\"\n % stream.tell())\n for folder in self.folders:\n folder._name_value_.read(stream, data=self)\n folder._files_value_.read(stream, data=self)\n logger.debug(\"Reading file names at 0x%08X.\" % stream.tell())\n for folder in self.folders:\n for file_ in folder.files:\n file_._name_value_.read(stream, data=self)\n # \"read\" the files\n logger.debug(\n \"Seeking end of raw file data at 0x%08X.\" % stream.tell())\n total_num_bytes = 0\n for folder in self.folders:\n for file_ in folder.files:\n total_num_bytes += file_.file_size.num_bytes\n stream.seek(total_num_bytes, os.SEEK_CUR)\n\n # check if we are at the end of the file\n if stream.read(1):\n raise ValueError(\n 'end of file not reached: corrupt bsa file?')",
"def readData(self, n):\n f = open(self.file, \"rb\")\n fortran.skip(f)\n for i in range(n):\n fortran.skip(f) # Detector Header\n if self.detector[i].lowneu:\n fortran.skip(f) # Detector low energy neutron groups\n fortran.skip(f) # Detector data\n\n fortran.skip(f) # Detector Header\n if self.detector[n].lowneu:\n fortran.skip(f) # Detector low energy neutron groups\n data = fortran.read(f) # Detector data\n f.close()\n return data",
"def read(self, n=None):\n data = super().read(n)\n self.hash.update(data)\n return data",
"def read(self, stream, **kwargs):\n game = kwargs['data'].game\n gamesig = self._str(game)\n signat = stream.read(8)\n if not signat.startswith(gamesig):\n raise ValueError(\n \"invalid CGF signature: expected %s but got %s\"\n %(gamesig, signat))",
"def _get_raw_data(self, start, nibbles):\n ignore_first_nibble, ignore_last_nibble = False, False\n # if the data field terminates at the middle of a byte,\n # create a flag to ignore the last nibble of data\n if (start + nibbles / 2.0) % 1 != 0:\n ignore_last_nibble = True\n # if the data begins at the middle of a byte,\n # create a flag to ignore the first nibble\n if start % 1 != 0:\n ignore_first_nibble = True\n # move the starting byte index to the beginning of the byte\n start = int(start - 0.5)\n # determine the number of bytes to read\n if nibbles % 2 == 1:\n n_bytes = (nibbles + 1) / 2\n else:\n n_bytes = nibbles / 2\n self.segdfile.seek(self.cursor_position + start - 1)\n data = self.segdfile.read(n_bytes)\n return data, ignore_first_nibble, ignore_last_nibble, n_bytes"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Write the data encoding the Digest object to a stream.
|
def write(self, ostream):
tstream = BytearrayStream()
self.hashing_algorithm.write(tstream)
self.digest_value.write(tstream)
self.key_format_type.write(tstream)
self.length = tstream.length()
super(Digest, self).write(ostream)
ostream.write(tstream.buffer)
|
[
"def send_message(stream, message, digest, pickle_dep=pickle):\n if hasattr(stream, 'getsockname'):\n stream = FileLikeSocket(stream)\n\n if not callable(digest):\n raise ValueError('digest must be callable')\n\n serialized = pickle_dep.dumps(message, pickle_dep.HIGHEST_PROTOCOL)\n data_digest = digest(serialized)\n header = '%s %s\\n' % (data_digest, len(serialized))\n\n with stdout_lock:\n logger.debug('Stream %s is locked' % stream)\n stream.write(header)\n stream.write(serialized)\n stream.flush()\n\n logger.debug('Stream %s is unlocked' % stream)\n logger.debug('Message sent with header: %s' % header)",
"def _encode_to_stream(self, output_stream, data, options=None, **kwargs):\n output_stream.write(self._encode(data, options=options, **kwargs))",
"def digest(self):\n return b''.join(struct.pack('>I', h) for h in self.finalize(self.buffer))",
"def writable(stream):",
"def write(self, data):\r\n if self.stream is False:\r\n return\r\n if isinstance(data, Exception):\r\n data = unicode(SafeString(data, self.encoding,\r\n self.encoding_errors, self.decoding_errors))\r\n try:\r\n self.stream.write(data)\r\n except UnicodeEncodeError:\r\n self.stream.write(data.encode(self.encoding, self.encoding_errors))\r\n except TypeError: # in Python 3, stderr expects unicode\r\n if self.stream in (sys.stderr, sys.stdout):\r\n self.stream.buffer.write(data) # write bytes to raw stream\r\n else:\r\n self.stream.write(unicode(data, self.encoding,\r\n self.decoding_errors))",
"def send_data(self, stream, length):\n\t\tsha = hashlib.sha256()\n\t\ttotalsent = 0\n\t\twhile totalsent < length:\n\t\t\tchunk = stream.read(self.BUFFERSIZE)\n\t\t\tsha.update(chunk)\n\n\t\t\tchunksent = 0\n\t\t\twhile chunksent < len(chunk):\n\t\t\t\tsent = self.sock.send(chunk)\n\t\t\t\tif not sent:\n\t\t\t\t\traise RuntimeError('connection broken')\n\t\t\t\tchunksent += sent\n\t\t\ttotalsent += chunksent\n\t\treturn sha.digest()",
"def recv_data(self, stream, size):\n\t\tsha = hashlib.sha256()\n\t\tbytesread = 0\n\t\twhile bytesread < size:\n\t\t\tchunk = self.sock.recv(self.BUFFERSIZE)\n\t\t\tif not chunk:\n\t\t\t\traise RuntimeError('connection broken')\n\t\t\tstream.write(chunk)\n\t\t\tsha.update(chunk)\n\t\t\tbytesread += len(chunk)\n\t\treturn sha.digest()",
"def write(self,data):\r\n if not self.has_started:\r\n self.write_headers()\r\n self.has_started = True\r\n if self.is_chunked:\r\n self._write(hex(len(data))[2:])\r\n self._write(\"\\r\\n\")\r\n self._write(data)\r\n self._write(\"\\r\\n\")\r\n else:\r\n self._write(data)",
"def write_bytes(stream, bytes):\n return stream.write(bytes)",
"def encode_stream(cls, stream):\n stream.seek(0)\n return cls.encode_string(stream.read())",
"def pack(self, obj, stream):\n raise NotImplementedError()",
"def write_bytes(self, datum):\n self.write_long(len(datum))\n self.write(struct.pack('%ds' % len(datum), datum))",
"def write_bytes(self, data):\n # type-check for the buffer interface before truncating the file\n view = memoryview(data)\n with self.open(mode='wb') as f:\n return f.write(view)",
"def send(self, data):\n ret = libvirtmod.virStreamSend(self._o, data)\n if ret == -1: raise libvirtError ('virStreamSend() failed')\n return ret",
"def read(self, istream):\n super(Digest, self).read(istream)\n tstream = BytearrayStream(istream.read(self.length))\n\n self.hashing_algorithm.read(tstream)\n self.digest_value.read(tstream)\n self.key_format_type.read(tstream)\n\n self.is_oversized(tstream)\n self.validate()",
"def write(self, fd):\n raise ESGError, \"Method not implemented\"",
"def write(self, ostream):\n tstream = BytearrayStream()\n\n self.application_namespace.write(tstream)\n self.application_data.write(tstream)\n\n self.length = tstream.length()\n super(ApplicationSpecificInformation, self).write(ostream)\n ostream.write(tstream.buffer)",
"def write(self, data):\r\n if not self.opened:\r\n self.open()\r\n if ('b' not in self.mode and sys.version_info < (3,0)\r\n or check_encoding(self.destination, self.encoding) is False\r\n ):\r\n if sys.version_info >= (3,0) and os.linesep != '\\n':\r\n data = data.replace('\\n', os.linesep) # fix endings\r\n data = self.encode(data)\r\n\r\n try: # In Python < 2.5, try...except has to be nested in try...finally.\r\n try:\r\n self.destination.write(data)\r\n except TypeError as e:\r\n if sys.version_info >= (3,0) and isinstance(data, bytes):\r\n try:\r\n self.destination.buffer.write(data)\r\n except AttributeError:\r\n if check_encoding(self.destination, \r\n self.encoding) is False:\r\n raise ValueError('Encoding of %s (%s) differs \\n'\r\n ' from specified encoding (%s)' %\r\n (self.destination_path or 'destination',\r\n self.destination.encoding, self.encoding))\r\n else:\r\n raise e\r\n except (UnicodeError, LookupError) as err:\r\n raise UnicodeError(\r\n 'Unable to encode output data. output-encoding is: '\r\n '%s.\\n(%s)' % (self.encoding, ErrorString(err)))\r\n finally:\r\n if self.autoclose:\r\n self.close()\r\n return data",
"def write(self, data):\r\n if not self.opened:\r\n self.open()\r\n if ('b' not in self.mode and sys.version_info < (3,0)\r\n or check_encoding(self.destination, self.encoding) is False\r\n ):\r\n if sys.version_info >= (3,0) and os.linesep != '\\n':\r\n data = data.replace('\\n', os.linesep) # fix endings\r\n data = self.encode(data)\r\n\r\n try: # In Python < 2.5, try...except has to be nested in try...finally.\r\n try:\r\n self.destination.write(data)\r\n except TypeError, e:\r\n if sys.version_info >= (3,0) and isinstance(data, bytes):\r\n try:\r\n self.destination.buffer.write(data)\r\n except AttributeError:\r\n if check_encoding(self.destination, \r\n self.encoding) is False:\r\n raise ValueError('Encoding of %s (%s) differs \\n'\r\n ' from specified encoding (%s)' %\r\n (self.destination_path or 'destination',\r\n self.destination.encoding, self.encoding))\r\n else:\r\n raise e\r\n except (UnicodeError, LookupError), err:\r\n raise UnicodeError(\r\n 'Unable to encode output data. output-encoding is: '\r\n '%s.\\n(%s)' % (self.encoding, ErrorString(err)))\r\n finally:\r\n if self.autoclose:\r\n self.close()\r\n return data"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Construct a Digest object from provided digest values.
|
def create(cls,
hashing_algorithm=HashingAlgorithmEnum.SHA_256,
digest_value=b'',
key_format_type=KeyFormatTypeEnum.RAW):
algorithm = HashingAlgorithm(hashing_algorithm)
value = DigestValue(bytearray(digest_value))
format_type = KeyFormatType(key_format_type)
return Digest(hashing_algorithm=algorithm,
digest_value=value,
key_format_type=format_type)
|
[
"def load_digest(cls, alg: HashAlgorithm, digest: ByteString) -> MessageDigest:\n return MessageDigest(bytes(digest), cls(alg))",
"def parse_digests(digests):\n def _atom(orig):\n s = orig\n if s.startswith(\"hash://\"):\n s = os.path.split(s[len(\"hash://\"):])[1]\n if ':' in s:\n # e.g. \"md5:asdaddas\"\n s = s.split(':')[-1]\n if '_' in s:\n # e.g. \"sha1_asdsads\"\n s = s.split('_')[-1]\n s = s.lower()\n res = {32: ('md5', s),\n 40: ('sha1', s),\n 64: ('sha256', s),\n 128: ('sha512', s)}.get(len(s), None)\n if not res:\n raise ValueError(\"invalid digest string: %s\" % (orig,))\n return res\n\n if isinstance(digests, (dict,)):\n return dict([_atom(v) for v in digests.values()])\n if not isinstance(digests, (tuple, list)):\n digests = (digests,)\n return dict([_atom(digest) for digest in digests])",
"def test05_digest_value(self):\n d = Digest()\n d.want_digest = 'md5'\n self.assertEqual(d.digest_value(b'hello'), 'md5=XUFAKrxLKna5cZ2REBfFkg==')",
"def get_digest(logger, digest_def):\n #session = db.get_session()\n\n # Get or create protease.\n protease = Protease(**digest_def['protease'])\n protease_id = str(digest_def['protease']['id'])\n cur = db.get_psycopg2_cursor()\n cur.execute(\"select * from protease where protease.id=%s;\", (protease_id,))\n results = cur.fetchone()\n\n if results is None:\n logger.info(\n \"No protease exists for the given definition, creating...\")\n protease = Protease(**digest_def['protease'])\n cur.execute(\"insert into protease (id, cleavage_rule) values( %s, %s);\", (str(digest_def['protease']['id']), str(digest_def['protease']['cleavage_rule']),))\n else:\n protease = Protease(id=results[0], cleavage_rule=results[1])\n db.psycopg2_connection.commit()\n\n # Get or create digest object.\n cur = db.get_psycopg2_cursor()\n\n #not all possible digestion parameters will have a value so build the query to account for this\n query_params = [protease.id]\n digest_query = \"select * from digest where digest.protease_id = %s\";\n if digest_def.get('max_missed_cleavages') is not None:\n digest_query = digest_query + \" and digest.max_missed_cleavages = %s \"\n query_params.append(digest_def.get('max_missed_cleavages'))\n if digest_def.get('min_acids') is not None:\n digest_query = digest_query + \" and digest.min_acids = %s \"\n query_params.append(digest_def.get('min_acids'))\n if digest_def.get('max_acids') is not None:\n digest_query = digest_query + \" and digest.max_acids = %s \"\n query_params.append(digest_def.get('max_acids'))\n\n cur.execute(digest_query, (query_params))\n results = cur.fetchone()\n db.psycopg2_connection.commit\n if results is None:\n #if not digest:\n logger.info(\n \"No digest exists for the given definition, creating...\")\n digest_kwargs = {}\n digest_kwargs.update(digest_def)\n digest_kwargs['protease'] = protease\n digest = Digest(**digest_kwargs)\n cur = db.get_psycopg2_cursor()\n\n\n cur.execute(\"select * from digest_insert( %s, %s, %s, %s);\", (protease.id, digest.max_missed_cleavages, digest.min_acids, digest.max_acids,))\n digest_result = cur.fetchone()\n\n if digest_result:\n digest = Digest(id=digest_result[0], protease = protease, max_missed_cleavages=digest_result[2], min_acids = digest_result[3], max_acids = digest_result[4])\n else:\n digest = Digest(id=results[0], protease = protease, max_missed_cleavages=results[2], min_acids = results[3], max_acids = results[4])\n db.psycopg2_connection.commit()\n return digest",
"def _get_digest_auth(self) -> httpx.DigestAuth:\n username = \"\" if self._username is None else self._username\n return httpx.DigestAuth(username, self._password)",
"def digest_converter(self, digest):\r\n binary = bin(int(digest, 16))[2:].zfill(len(digest * 4))\r\n return binary",
"def executeDigest(uri, digest):\n r = requests.post(uri, data=digest, headers=HEADERS)\n if 400 == r.status_code:\n print r\n failure = ET.fromstring(r.text)\n debug_print(ET.tostring(failure))\n if None == failure:\n raise FatalError('Bad Request', 1, r.text)\n messageElement = failure.find('message')\n if None == messageElement:\n raise FatalError(None, 1, r.text)\n raise FatalError(messageElement.text, 1, r.text)\n elif 404 == r.status_code:\n raise FatalError('The operation could not be found', 1, r.text)\n elif 409 == r.status_code:\n raise FatalError('Another process has already acted some parts of this request, so this attempt will halt', r.status_code, r.text)\n# elif 201 == r.status_code:\n# return\n elif 200 != r.status_code:\n raise FatalError('Unexpected status (' + str(r.status_code) + ') returned from \"' + uri + '\"', r.status_code, r.text)\n created = ET.fromstring(r.text)\n debug_print(ET.tostring(created))\n return created",
"def from_dict(cls, _dict: Dict) -> 'ImageFileChecksums':\n args = {}\n if 'sha256' in _dict:\n args['sha256'] = _dict.get('sha256')\n return cls(**args)",
"def test03_digest(self):\n oo = Object(digest_algorithm='md5')\n self.assertEqual(oo.digest('tests/testdata/files/empty'),\n 'd41d8cd98f00b204e9800998ecf8427e')",
"def digest(self):\n return b''.join(struct.pack('>I', h) for h in self.finalize(self.buffer))",
"def createDigests(self, store_to_db=True, mark=None):\r\n if self.FromDate is None or self.ToDate is None:\r\n if mark is None:\r\n logging.error(\"Cannot proceed since there's no time range to get the digests for!\")\r\n return False\r\n else:\r\n # Set the date range to yesterday\r\n # TODO: This really should be a lot more configurable!\r\n td = datetime.date(mark)\r\n fd = td + relativedelta(days=-1)\r\n self.FromDate = str(fd)\r\n self.ToDate = str(td)\r\n logging.info('Getting digests for date range: %s to %s' % (fd, td))\r\n\r\n resp = self.getDataToCreateDigest()\r\n base_url = self.Config.get('default_host')\r\n member_profile_url = \"%suseraccount/\" % base_url\r\n digests = {}\r\n for projId in resp.keys():\r\n # Ignore all empty projects, and projects that have no recipients\r\n if ((resp[projId].get('members') is None or len(resp[projId].get('members')) == 0) and\\\r\n (resp[projId].get('messages') is None or len(resp[projId].get('messages')) == 0)) or\\\r\n resp[projId].get('recipients') is None or len(resp[projId].get('recipients')) == 0:\r\n continue\r\n \r\n # Initialize the digest data structure\r\n if digests.get(projId) is None:\r\n digests[projId] = {'members':[], 'messages':[], 'recipients': \"\"}\r\n\r\n digests[projId]['recipients'] = resp[projId].get('recipients')\r\n digests[projId]['title'] = resp[projId].get('title')\r\n digests[projId]['project_id'] = projId\r\n digests[projId]['num_members'] = resp[projId].get('num_members')\r\n digests[projId]['link'] = \"<a href='%sproject/%s'>%s</a>\" % (self.Config.get('default_host'), projId, resp[projId].get('title'))\r\n\r\n if resp[projId].get('members') is not None and len(resp[projId].get('members')) > 0:\r\n digests[projId]['members'] = resp[projId].get('members')\r\n \r\n if resp[projId].get('messages') is not None and len(resp[projId].get('messages')) > 0:\r\n digests[projId]['messages'] = resp[projId].get('messages')\r\n\r\n # Store the formatted body\r\n for digest in digests:\r\n currentDigest = digests.get(digest)\r\n currentDigest['subject'] = \"%s%s\\n\\n\" % (self.Config.get('email').get('digest').get('digest_subject_prefix'), currentDigest.get('title'))\r\n currentDigest['body'] = Emailer.render('email/digest', \r\n {'digest':currentDigest,\r\n 'baseUrl':base_url,\r\n 'contactEmail':self.Config.get('email').get('from_email')})\r\n\r\n # Store it for later consumption\r\n logging.info('Created digests (in DB) for %s projects' % len(digests.keys()))\r\n self.Digests = digests\r\n return True",
"def __init__(self, hash_algorithm):\n\n self.hash_algorithm = hash_algorithm.upper().replace(\"_\", \"-\")\n hashlib_name = self.hash_algorithm\n\n # DIF names deviate from python's hashlib names\n deviating_names = [(\"MD5\", \"md5\"),\n (\"SHA-1\", \"sha1\"),\n (\"SHA-224\", \"sha224\"),\n (\"SHA-256\", \"sha256\"),\n (\"SHA-384\", \"sha384\"),\n (\"SHA-512\", \"sha512\"),\n (\"SHA3-224\", \"sha3_224\"),\n (\"SHA3-256\", \"sha3_256\"),\n (\"SHA3-384\", \"sha3_384\"),\n (\"SHA3-512\", \"sha3_512\")]\n for dif_name, lib_name in deviating_names:\n if self.hash_algorithm == dif_name or\\\n self.hash_algorithm == lib_name.upper():\n self.hash_algorithm = dif_name\n hashlib_name = lib_name\n break\n\n if self.hash_algorithm not in self.SUPPORTED_ALGORITHMS:\n raise ValueError(\"{0} is not a supported hash algorithm.\".format(\n self.hash_algorithm))\n\n self._hasher = hashlib.new(hashlib_name)",
"def sign_dsa(self, digest):\n assert self._check_key_type(), \"'ec' type error\"\n return m2.ecdsa_sign(self.ec, digest)",
"def GetDigestOfFile(digest_algorithm, file_to_digest):\n messages = cloudkms_base.GetMessagesModule()\n algorithm = _DIGEST_ALGORITHMS.get(digest_algorithm)\n if not algorithm:\n raise exceptions.InvalidArgumentException('digest',\n 'digest_algorithm is invalid.')\n digest = algorithm()\n for chunk in _ChunkReader(file_to_digest):\n digest.update(chunk)\n kwargs = {digest_algorithm: digest.digest()}\n return messages.Digest(**kwargs)",
"def __init__(self, vals):\n\n self.__vals = vals\n self.__dct = {}\n for (name, val, _) in vals:\n self.__dct[name] = val",
"def get_digester(digest):\n # type: (str) -> Optional[HASH]\n\n algo = get_digest_algorithm(digest)\n func = get_digest_hash(algo) if algo else None\n\n if not func:\n logger.warning(\"No valid hash algorithm found for digest %r\", digest)\n\n return func",
"def compute_digest(self) -> bytes:\n if self.raw_digest is not None:\n return self.raw_digest\n\n md = getattr(hashlib, self.md_algorithm)()\n stream = self.reader.stream\n\n # compute the digest\n # here, we allow arbitrary byte ranges\n # for the coverage check, we'll impose more constraints\n total_len = 0\n for lo, chunk_len in misc.pair_iter(self.byte_range):\n stream.seek(lo)\n chunk = stream.read(chunk_len)\n assert len(chunk) == chunk_len\n md.update(chunk)\n total_len += chunk_len\n\n self.total_len = total_len\n self.raw_digest = digest = md.digest()\n return digest",
"def from_contents(cls, contents: str, name='sha256') -> 'FileHash':\n data = contents.encode('utf-8')\n checksum = hashlib.new(name, data).hexdigest()\n return cls(name=name, checksum=checksum)",
"def get_digest(clue):\n return clue.info['digest']",
"def DigestSize() -> int:"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Construct an ApplicationNamespace object.
|
def __init__(self, value=None):
super(ApplicationNamespace, self).__init__(
value, Tags.APPLICATION_NAMESPACE)
|
[
"def CreateAbsentNamespace (cls):\n rv = Namespace(None)\n rv.__absentNamespaceID = cls.__absentNamespaceID\n cls.__absentNamespaceID += 1\n\n return rv",
"def create_namespace(self):\n name = 'namespace-{random_string}'.format(random_string=random_str(5))\n\n namespace = client.V1Namespace(metadata=client.V1ObjectMeta(name=name))\n\n self.core_api.create_namespace(namespace)\n\n logger.info(\"Creating namespace: %s\", name)\n\n # save all namespaces created with this backend\n self.managed_namespaces.append(name)\n\n # wait for namespace to be ready\n Probe(timeout=30, pause=5, expected_retval=True,\n fnc=self._namespace_ready, namespace=name).run()\n\n return name",
"def create_namespace(self):\n ns = self.project.create_namespace()\n ns['task'] = self\n return ns",
"def create_sns_application(self, args):\n new_region_args = create_args_for_multi_region(args, ALL_REGIONS)\n return self.create_pool(self._create_platform_application_from_meta,\n new_region_args)",
"def create(cls, application_namespace, application_data):\n namespace = ApplicationNamespace(application_namespace)\n data = ApplicationData(application_data)\n return ApplicationSpecificInformation(\n application_namespace=namespace, application_data=data)",
"def namespaces(self):\n return NamespacesDict(self._build_namespaces())",
"def namespace_create(self, name, size=None, password=None, public=True):\n self.state.check('status', 'running', 'ok')\n if self._namespace_exists_update_delete(name):\n raise ValueError('Namespace {} already exists'.format(name))\n self.data['namespaces'].append({'name': name, 'size': size, 'password': password, 'public': public})\n self._zerodb_sal.deploy()",
"def __init__(self, name=None, id=None, creator=None, pid=None, url=None, aemapp=None, \n\t\t\tterms=True, newinstance=False, hide=False):\n\t\tif len([i for i in [name, id, creator, pid, url, aemapp] if i]) > 1:\n\t\t\traise TypeError('app() received more than one of the following arguments: name, id, creator, pid, url, aemapp')\n\t\tif name:\n\t\t\tconstructor, identifier = 'path', aem.findapp.byname(name)\n\t\telif id:\n\t\t\tconstructor, identifier = 'path', aem.findapp.byid(id)\n\t\telif creator:\n\t\t\tconstructor, identifier = 'path', aem.findapp.bycreator(creator)\n\t\telif pid:\n\t\t\tconstructor, identifier = 'pid', pid\n\t\telif url:\n\t\t\tconstructor, identifier = 'url', url\n\t\telif aemapp:\n\t\t\tconstructor, identifier = 'aemapp', aemapp\n\t\telse:\n\t\t\tconstructor, identifier = 'current', None\n\t\t# Defer initialisation of AppData until it's needed. This allows user to call launch() on a non-running application without the application being launched by aem.Application, which automatically launches local applications in order to construct an AEAddressDesc of typeProcessSerialNumber.\n\t\t# launch()'s usefulness is somewhat limited, since constructing a real app-based reference will also launch the application normally in order to get its terminology. So to actually launch an application, you have to use launch() before constructing any real references to its objects; i.e.:\n\t\t# te = app('TextEdit'); te.launch(); d = app.documents\n\t\t# will launch TE without it creating any new documents (i.e. app receives 'ascrnoop' as its first event), but:\n\t\t# te = app('TextEdit'); d = app.documents; te.launch()\n\t\t# will launch TE normally (i.e. app receives 'aevtoapp' as its first event), causing it to open a new, empty window.\n\t\tReference.__init__(self, \n\t\t\t\tAppData(self._Application, constructor, identifier, terms, {'newinstance': newinstance, 'hide': hide}), \n\t\t\t\taem.app)",
"def create_application(fv_tenant, application, **args):\n args = args['optional_args'] if 'optional_args' in args.keys() else args\n\n fv_ap = Ap(fv_tenant, application,\n prio=get_value(args, 'prio', DEFAULT_QOS).lower())\n return fv_ap",
"def create_app(self):\n app.config.from_object('app.config.Production')\n return app",
"def _getAppConfig(self, aAppName):\n app_module = importlib.import_module(\".\" + aAppName, \"applications\")\n app_cfg = ApplicationConfig(aAppName, app_module)\n return app_cfg",
"def __new__ (cls, *args, **kw):\n (uri,) = args\n if isinstance(uri, tuple):\n # Special handling to reconstruct absent namespaces.\n (variant, uid) = uri\n if cls.__SerializedVariantAbsent == variant:\n ns = cls.__AbsentNamespaceRegistry.get(uid)\n if ns is None:\n raise pyxb.UsageError('Unable to reconstruct instance of absent namespace')\n return ns\n raise pyxb.LogicError('Unrecognized serialized namespace variant %s uid %s' % (variant, uid))\n elif not (uri in cls.__Registry):\n instance = object.__new__(cls)\n # Do this one step of __init__ so we can do checks during unpickling\n instance.__uri = uri\n instance._reset()\n # Absent namespaces are not stored in the registry.\n if uri is None:\n cls.__AbsentNamespaces.add(instance)\n return instance\n cls.__Registry[uri] = instance\n return cls.__Registry[uri]",
"def _create_application(self):\n key = datetime.datetime.now().strftime('%Y%m%d%H%M%S')\n\n if not self.interactive:\n name = 'tortuga-{}'.format(key)\n else:\n name = ''\n while not name:\n name = input(self.format('Application name: '))\n name = name.strip()\n\n if not self.interactive:\n url = 'https://univa.com/tortuga/{}'.format(key)\n else:\n url = ''\n while not url_valid(url):\n url = input(self.format('Application URL (a unique URI): '))\n\n password = secrets.token_urlsafe()\n\n print('Creating application...')\n\n try:\n application = self._run_az([\n 'ad', 'app', 'create',\n '--display-name', name,\n '--native-app', 'false',\n '--identifier-uris', url,\n '--key-type', 'Password',\n '--password', password\n ])\n #\n # Attach password to the application object so we can refer to\n # it later.\n #\n application['password'] = password\n self._az_applications.append(application)\n\n except APIError as e:\n print(self.format_error(str(e)))\n return self._create_application()\n\n #\n # Create the Service Principal\n #\n print('Creating service principal...')\n\n self._run_az([\n 'ad', 'sp', 'create',\n '--id', application['appId']\n\n ])\n\n print(self.format('The following application API password was '\n 'generated: {}', password))\n\n return application",
"def app():\n\n application = create_app()\n application.test_client_class = JSON_Client\n application.response_class = Load_JSON_Response\n return application",
"def getApplication():",
"def addNamespace(*args, **kwargs):\n \n pass",
"def create_app():\n app = Flask(__name__, instance_relative_config=True)\n app.config.from_object(config[SELECTED_CONFIG])\n db.init_app(app)\n app.register_blueprint(recipes)\n\n ma.init_app(app)\n Bootstrap(app)\n\n app.before_request(create_before_request(app))\n return app",
"def __init__ (self, uri,\n description=None,\n builtin_namespace=None,\n builtin_module_path=None,\n is_undeclared_namespace=False,\n is_loaded_namespace=False,\n bound_prefix=None,\n default_namespace=None,\n in_scope_namespaces=None):\n\n # New-style superclass invocation\n super(Namespace, self).__init__()\n\n self.__contextDefaultNamespace = default_namespace\n self.__contextInScopeNamespaces = in_scope_namespaces\n\n # Make sure that we're not trying to do something restricted to\n # built-in namespaces\n is_builtin_namespace = not (builtin_namespace is None)\n if not is_builtin_namespace:\n if bound_prefix is not None:\n raise pyxb.LogicError('Only permanent Namespaces may have bound prefixes')\n\n # We actually set the uri when this instance was allocated;\n # see __new__().\n assert self.__uri == uri\n self.__boundPrefix = bound_prefix\n self.__description = description\n self.__isBuiltinNamespace = is_builtin_namespace\n self.__builtinNamespaceVariable = builtin_namespace\n self.__builtinModulePath = builtin_module_path\n self.__isUndeclaredNamespace = is_undeclared_namespace\n self.__isLoadedNamespace = is_loaded_namespace\n\n self._reset()\n\n assert (self.__uri is None) or (self.__Registry[self.__uri] == self)",
"def _build_namespace_tree(self) -> None:\n # initialize empty node with empty string name\n root_node = Node(name='')\n\n # populate queue prior to tree building\n queue = copy.deepcopy(self.obj['avsc'])\n\n while queue:\n\n # get first item in queue\n item = queue.pop(0)\n\n # impute namespace and name\n item['namespace'] = _get_namespace(item)\n item['name'] = _get_name(item)\n\n # traverse to namespace starting from root_node\n current_node = self._traverse_tree(\n root_node=root_node, namespace=item['namespace']\n )\n\n # initialize empty file obj for mutation\n file = File(\n name=item['name'],\n avrotype=item['type'],\n namespace=item['namespace'],\n schema=item,\n fields={},\n imports=[],\n enum_sumbols=[]\n )\n\n # handle record type\n if file.avrotype == 'record':\n _record_file(file, item, queue)\n\n # handle enum type file\n elif file.avrotype == 'enum':\n _enum_file(file, item)\n else:\n raise ValueError(\n f\"{file['type']} is currently not supported.\"\n )\n\n current_node.files[item['name']] = file\n\n self.file_tree = root_node"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Construct an ApplicationData object.
|
def __init__(self, value=None):
super(ApplicationData, self).__init__(value, Tags.APPLICATION_DATA)
|
[
"def create(cls, application_namespace, application_data):\n namespace = ApplicationNamespace(application_namespace)\n data = ApplicationData(application_data)\n return ApplicationSpecificInformation(\n application_namespace=namespace, application_data=data)",
"def app_data():\n bootcamp_run = BootcampRunFactory.create()\n installment = InstallmentFactory.create(bootcamp_run=bootcamp_run, amount=0)\n run_steps = BootcampRunApplicationStepFactory.create_batch(\n 2, bootcamp_run=bootcamp_run\n )\n application = BootcampApplicationFactory(bootcamp_run=bootcamp_run)\n application.resume_file = SimpleUploadedFile(\n \"resume.txt\", b\"these are the file contents!\"\n )\n application.save()\n return SimpleNamespace(\n application=application, installment=installment, run_steps=run_steps\n )",
"def _get_app_data(self):\n return self._get_base_app_data()",
"async def startup_data(app: App):\n\n app[\"data\"] = create_data_layer(\n get_authorization_client_from_app(app),\n app[\"db\"],\n app[\"pg\"],\n get_config_from_app(app),\n get_http_session_from_app(app),\n app[\"redis\"],\n )",
"def __init__(self, application_namespace=None, application_data=None):\n super(ApplicationSpecificInformation, self).__init__(\n Tags.APPLICATION_SPECIFIC_INFORMATION)\n\n if application_namespace is None:\n self.application_namespace = ApplicationNamespace()\n else:\n self.application_namespace = application_namespace\n\n if application_data is None:\n self.application_data = ApplicationData()\n else:\n self.application_data = application_data\n\n self.validate()",
"def app_data(self):\n return self._app_data",
"def __init__(self, app_id: str):\n # Absolute path of the data directory\n self._data_path = None\n\n # Managers\n self._settings = None\n self._files = None\n\n # This assigns the manager variables and may raise KeyValidationError\n self.app_id = app_id",
"def _create_application(\n self,\n name,\n client_type=None,\n grant_type=None,\n capability=None,\n user=None,\n data_access_type=None,\n end_date=None,\n **kwargs\n ):\n client_type = client_type or Application.CLIENT_PUBLIC\n grant_type = grant_type or Application.GRANT_PASSWORD\n # This is the user to whom the application is bound.\n dev_user = user or User.objects.create_user(\"dev\", password=\"123456\")\n application = Application.objects.create(\n name=name,\n user=dev_user,\n client_type=client_type,\n authorization_grant_type=grant_type,\n **kwargs\n )\n\n if data_access_type:\n application.data_access_type = data_access_type\n\n if end_date:\n application.end_date = end_date\n\n if data_access_type or end_date:\n application.save()\n\n # add capability\n if capability:\n application.scope.add(capability)\n return application",
"def __init__(self, name=None, id=None, creator=None, pid=None, url=None, aemapp=None, \n\t\t\tterms=True, newinstance=False, hide=False):\n\t\tif len([i for i in [name, id, creator, pid, url, aemapp] if i]) > 1:\n\t\t\traise TypeError('app() received more than one of the following arguments: name, id, creator, pid, url, aemapp')\n\t\tif name:\n\t\t\tconstructor, identifier = 'path', aem.findapp.byname(name)\n\t\telif id:\n\t\t\tconstructor, identifier = 'path', aem.findapp.byid(id)\n\t\telif creator:\n\t\t\tconstructor, identifier = 'path', aem.findapp.bycreator(creator)\n\t\telif pid:\n\t\t\tconstructor, identifier = 'pid', pid\n\t\telif url:\n\t\t\tconstructor, identifier = 'url', url\n\t\telif aemapp:\n\t\t\tconstructor, identifier = 'aemapp', aemapp\n\t\telse:\n\t\t\tconstructor, identifier = 'current', None\n\t\t# Defer initialisation of AppData until it's needed. This allows user to call launch() on a non-running application without the application being launched by aem.Application, which automatically launches local applications in order to construct an AEAddressDesc of typeProcessSerialNumber.\n\t\t# launch()'s usefulness is somewhat limited, since constructing a real app-based reference will also launch the application normally in order to get its terminology. So to actually launch an application, you have to use launch() before constructing any real references to its objects; i.e.:\n\t\t# te = app('TextEdit'); te.launch(); d = app.documents\n\t\t# will launch TE without it creating any new documents (i.e. app receives 'ascrnoop' as its first event), but:\n\t\t# te = app('TextEdit'); d = app.documents; te.launch()\n\t\t# will launch TE normally (i.e. app receives 'aevtoapp' as its first event), causing it to open a new, empty window.\n\t\tReference.__init__(self, \n\t\t\t\tAppData(self._Application, constructor, identifier, terms, {'newinstance': newinstance, 'hide': hide}), \n\t\t\t\taem.app)",
"def make_object(self, data):\n return Deployment(**data)",
"def create_app(self):\n app.config.from_object('app.config.Production')\n return app",
"def _get_base_app_data(self):\n app_data = super()._get_base_app_data()\n app_data.update(\n {\n \"modelName\": self.model.RESOURCE_NAME,\n \"state\": APP_DATA_STATE_SUCCESS,\n \"player\": settings.VIDEO_PLAYER,\n \"uploadPollInterval\": settings.FRONT_UPLOAD_POLL_INTERVAL,\n # front is expecting duration in milliseconds\n \"attendanceDelay\": settings.ATTENDANCE_PUSH_DELAY * 1000,\n # In certain context, such as embedding the resource in content,\n # we want to collapse the dashboard.\n \"dashboardCollapsed\": \"custom_embedded_resource\" in self.request.POST,\n }\n )\n\n if self.request.resolver_match.app_name:\n app_data.update(\n {\n \"appName\": self.request.resolver_match.app_name,\n }\n )\n\n return app_data",
"def app_data(self, app_data):\n if self.local_vars_configuration.client_side_validation and app_data is None: # noqa: E501\n raise ValueError(\"Invalid value for `app_data`, must not be `None`\") # noqa: E501\n\n self._app_data = app_data",
"def app_data(self, value):\n self._app_data = value",
"def create_app(self):\n app.config.from_object('app.config.Development')\n return app",
"def create_app():\n app = Flask(__name__, instance_relative_config=True)\n app.config.from_object(config[SELECTED_CONFIG])\n db.init_app(app)\n app.register_blueprint(recipes)\n\n ma.init_app(app)\n Bootstrap(app)\n\n app.before_request(create_before_request(app))\n return app",
"def app():\n\n application = create_app()\n application.test_client_class = JSON_Client\n application.response_class = Load_JSON_Response\n return application",
"def create_application(**kwargs):\n app = Flask(__name__)\n\n app.config.from_object('pybel_tools.web.config.Config')\n\n if 'PYBEL_WEB_CONFIG' in os.environ:\n log.info('importing config from %s', os.environ['PYBEL_WEB_CONFIG'])\n app.config.from_json(os.path.expanduser(os.environ['PYBEL_WEB_CONFIG']))\n\n app.config.update(kwargs)\n\n # Initialize extensions\n bootstrap_extension.init_app(app)\n pybel_extension.init_app(app)\n\n app.register_blueprint(async_blueprint)\n\n return app",
"def init_db():\n\n with app.app_context():\n data = json.loads(urllib2.urlopen(DATA_URL).read())\n ds = DataSource(data['data'], data['meta']['view']['columns'])\n headers = ds.get_headers(\n set([\n 'Applicant', \n 'Address', \n 'FoodItems', \n 'Latitude', \n 'Longitude'\n ]),\n 'name'\n )\n db = get_db()\n db.init_database()\n for item in ds.gen_items(headers):\n try:\n db.add_row(\n item['Applicant'], \n item['Address'], \n item['FoodItems'], \n item['Latitude'], \n item['Longitude']\n )\n except psycopg2.IntegrityError:\n pass"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Construct an ApplicationSpecificInformation object.
|
def __init__(self, application_namespace=None, application_data=None):
super(ApplicationSpecificInformation, self).__init__(
Tags.APPLICATION_SPECIFIC_INFORMATION)
if application_namespace is None:
self.application_namespace = ApplicationNamespace()
else:
self.application_namespace = application_namespace
if application_data is None:
self.application_data = ApplicationData()
else:
self.application_data = application_data
self.validate()
|
[
"def create(cls, application_namespace, application_data):\n namespace = ApplicationNamespace(application_namespace)\n data = ApplicationData(application_data)\n return ApplicationSpecificInformation(\n application_namespace=namespace, application_data=data)",
"def __init__(self, value=None):\n super(ApplicationData, self).__init__(value, Tags.APPLICATION_DATA)",
"def _create_application_request(app_metadata, template):\n app_metadata.validate([\"author\", \"description\", \"name\"])\n request = {\n \"Author\": app_metadata.author,\n \"Description\": app_metadata.description,\n \"HomePageUrl\": app_metadata.home_page_url,\n \"Labels\": app_metadata.labels,\n \"LicenseBody\": app_metadata.license_body,\n \"LicenseUrl\": app_metadata.license_url,\n \"Name\": app_metadata.name,\n \"ReadmeBody\": app_metadata.readme_body,\n \"ReadmeUrl\": app_metadata.readme_url,\n \"SemanticVersion\": app_metadata.semantic_version,\n \"SourceCodeUrl\": app_metadata.source_code_url,\n \"SpdxLicenseId\": app_metadata.spdx_license_id,\n \"TemplateBody\": template,\n }\n # Remove None values\n return {k: v for k, v in request.items() if v}",
"def add_app_info(_, __, event_dict: dict) -> dict:\n event_dict[\"logGitHubRepoName\"] = LogEntryProcessor._BI.repo_name\n event_dict[\"logServiceType\"] = LogEntryProcessor._BI.service_type\n event_dict[\"logServiceName\"] = LogEntryProcessor._BI.service_name\n event_dict[\"logServiceVersion\"] = LogEntryProcessor._BI.version\n event_dict[\"logServiceInstance\"] = LogEntryProcessor._HOST\n event_dict[\"logThreadId\"] = threading.current_thread().getName()\n if LogEntryProcessor.get_request_id():\n # We are also used by the gunicorn logger so this may not be set\n event_dict[\"logRequestId\"] = LogEntryProcessor.get_request_id()\n return event_dict",
"def __init__(self, runtime_info: Dict[str, Any]) -> None:\n\n super().__init__(runtime_info, SimulatorControlType.RUNTIME)\n self.raw_info = runtime_info\n self.availability = runtime_info.get(\"availability\")\n self.build_version = runtime_info[\"buildversion\"]\n self.bundle_path = runtime_info[\"bundlePath\"].replace(\"\\\\/\", \"/\")\n self.identifier = runtime_info[\"identifier\"]\n self.is_available = runtime_info[\"isAvailable\"]\n self.name = runtime_info[\"name\"]\n self.version = runtime_info[\"version\"]",
"def test_appinfo_get(self):\n pass",
"def get_iphone_system_information(self):\n information = {\n 'build_version': self.get_iphone_build_version(),\n 'device_name': self.get_iphone_device_name(),\n 'display_name': self.get_iphone_display_name(),\n 'GUID': self.get_iphone_GUID(),\n 'ICCID': self.get_iphone_ICCID(),\n 'IMEI': self.get_iphone_IMEI(),\n 'last_backup_date': self.get_iphone_last_backup_date(),\n 'MEID': self.get_iphone_MEID(),\n 'phone_number': self.get_iphone_phone_number(),\n 'product_type': self.get_iphone_product_type(),\n 'product_version': self.get_iphone_product_version(),\n 'serial_number': self.get_iphone_serial_number(),\n 'target_identifier': self.get_iphone_target_identifier(),\n 'target_type': self.get_iphone_target_type(),\n 'unique_identifier': self.get_iphone_unique_identifier()\n }\n\n self.storage_master['iphone_system_information'] = information\n return information",
"def info(self):\n assr_info = {}\n\n assr_info['ID'] = self.get('ID')\n assr_info['label'] = self.get('label')\n assr_info['assessor_id'] = assr_info['ID']\n assr_info['assessor_label'] = assr_info['label']\n assr_info['project_id'] = self.get('project')\n assr_info['project_label'] = assr_info['project_id']\n assr_info['subject_id'] = self.parent().get('xnat:subject_ID')\n assr_info['subject_label'] = self.parent().subject\n assr_info['session_id'] = self.parent().get('ID')\n assr_info['session_label'] = self.parent().get('label')\n xmltype = '{http://www.w3.org/2001/XMLSchema-instance}type'\n assr_info['xsiType'] = self.get(xmltype).lower()\n\n if assr_info['xsiType'].lower() == DEFAULT_FS_DATATYPE.lower():\n # FreeSurfer\n assr_info['procstatus'] = self.get('fs:procstatus')\n assr_info['qcstatus'] = self.get('xnat:validation/status')\n assr_info['version'] = self.get('fs:procversion')\n assr_info['jobid'] = self.get('fs:jobid')\n assr_info['jobstartdate'] = self.get('fs:jobstartdate')\n assr_info['memused'] = self.get('fs:memused')\n assr_info['walltimeused'] = self.get('fs:walltimeused')\n assr_info['jobnode'] = self.get('fs:jobnode')\n assr_info['proctype'] = 'FreeSurfer'\n\n elif assr_info['xsiType'].lower() == DEFAULT_DATATYPE.lower():\n # genProcData\n assr_info['procstatus'] = self.get('proc:procstatus')\n assr_info['proctype'] = self.get('proc:proctype')\n assr_info['qcstatus'] = self.get('xnat:validation/status')\n assr_info['version'] = self.get('proc:procversion')\n assr_info['jobid'] = self.get('proc:jobid')\n assr_info['jobstartdate'] = self.get('proc:jobstartdate')\n assr_info['memused'] = self.get('proc:memused')\n assr_info['walltimeused'] = self.get('proc:walltimeused')\n assr_info['jobnode'] = self.get('proc:jobnode')\n else:\n msg = 'Warning:unknown xsitype for assessor: %s'\n print(msg % assr_info['xsiType'])\n\n return assr_info",
"def get_application(name=''):\n obj = spinnaker_client.get(endpoint=f'/applications/{name}')\n attr = obj.pop('attributes')\n obj.update(attr)\n obj.pop('clusters', None)\n return obj",
"def getApplication():",
"def current_app_info(self):\n\n app_info = {}\n app_activity = self.mob_conn.current_activity\n app_package = self.mob_conn.current_package\n app_info['current_activity'] = app_activity\n app_info['current_package'] = app_package\n return app_info",
"def create_application(fv_tenant, application, **args):\n args = args['optional_args'] if 'optional_args' in args.keys() else args\n\n fv_ap = Ap(fv_tenant, application,\n prio=get_value(args, 'prio', DEFAULT_QOS).lower())\n return fv_ap",
"def __init__(self, name=None, id=None, creator=None, pid=None, url=None, aemapp=None, \n\t\t\tterms=True, newinstance=False, hide=False):\n\t\tif len([i for i in [name, id, creator, pid, url, aemapp] if i]) > 1:\n\t\t\traise TypeError('app() received more than one of the following arguments: name, id, creator, pid, url, aemapp')\n\t\tif name:\n\t\t\tconstructor, identifier = 'path', aem.findapp.byname(name)\n\t\telif id:\n\t\t\tconstructor, identifier = 'path', aem.findapp.byid(id)\n\t\telif creator:\n\t\t\tconstructor, identifier = 'path', aem.findapp.bycreator(creator)\n\t\telif pid:\n\t\t\tconstructor, identifier = 'pid', pid\n\t\telif url:\n\t\t\tconstructor, identifier = 'url', url\n\t\telif aemapp:\n\t\t\tconstructor, identifier = 'aemapp', aemapp\n\t\telse:\n\t\t\tconstructor, identifier = 'current', None\n\t\t# Defer initialisation of AppData until it's needed. This allows user to call launch() on a non-running application without the application being launched by aem.Application, which automatically launches local applications in order to construct an AEAddressDesc of typeProcessSerialNumber.\n\t\t# launch()'s usefulness is somewhat limited, since constructing a real app-based reference will also launch the application normally in order to get its terminology. So to actually launch an application, you have to use launch() before constructing any real references to its objects; i.e.:\n\t\t# te = app('TextEdit'); te.launch(); d = app.documents\n\t\t# will launch TE without it creating any new documents (i.e. app receives 'ascrnoop' as its first event), but:\n\t\t# te = app('TextEdit'); d = app.documents; te.launch()\n\t\t# will launch TE normally (i.e. app receives 'aevtoapp' as its first event), causing it to open a new, empty window.\n\t\tReference.__init__(self, \n\t\t\t\tAppData(self._Application, constructor, identifier, terms, {'newinstance': newinstance, 'hide': hide}), \n\t\t\t\taem.app)",
"def make_cid_system_info_object():\n return IndirectPdfDict(\n Registry=PdfString('(Adobe)'),\n Ordering=PdfString('(UCS)'),\n Supplement=0\n )",
"def _get_base_app_data(self):\n app_data = super()._get_base_app_data()\n app_data.update(\n {\n \"modelName\": self.model.RESOURCE_NAME,\n \"state\": APP_DATA_STATE_SUCCESS,\n \"player\": settings.VIDEO_PLAYER,\n \"uploadPollInterval\": settings.FRONT_UPLOAD_POLL_INTERVAL,\n # front is expecting duration in milliseconds\n \"attendanceDelay\": settings.ATTENDANCE_PUSH_DELAY * 1000,\n # In certain context, such as embedding the resource in content,\n # we want to collapse the dashboard.\n \"dashboardCollapsed\": \"custom_embedded_resource\" in self.request.POST,\n }\n )\n\n if self.request.resolver_match.app_name:\n app_data.update(\n {\n \"appName\": self.request.resolver_match.app_name,\n }\n )\n\n return app_data",
"def get_ap_info(self, ue, ap_id):\n # Get UE_AP_STATE\n ue_ap_state = self.env.get_ue_ap_state(ue, ap_id)\n\n # Create a new AP_INFO and fill in the details.\n return AP_INFO(\n ap_id=ap_id,\n ue_ap_state=ue_ap_state)",
"def _parse_app_info(self, app_info):\n # The app name is the first part of the app information\n app_name = app_info[0]\n # The secret key is the second part of the app information\n secret_key = app_info[1]\n\n return (app_name, secret_key)",
"def new_info(self, ean, serial, **attrs):\r\n info = DeviceInfo()\r\n info.ean = ean\r\n info.serial = serial\r\n info.update(attrs)\r\n self.add(info)\r\n return info",
"def construct_app(\n self,\n process_class: Type[TProcessApplication],\n infrastructure_class: Optional[\n Type[ApplicationWithConcreteInfrastructure]\n ] = None,\n **kwargs: Any,\n ) -> TProcessApplication:\n\n # If process class isn't already an infrastructure class, then\n # subclass the process class with concrete infrastructure.\n if not issubclass(process_class, ApplicationWithConcreteInfrastructure):\n\n # Default to PopoApplication infrastructure.\n if infrastructure_class is None:\n infrastructure_class = self.infrastructure_class or PopoApplication\n\n # Assert that we now have an application with concrete infrastructure.\n if not issubclass(\n infrastructure_class, ApplicationWithConcreteInfrastructure\n ):\n raise ProgrammingError(\n \"Given infrastructure_class {} is not subclass of {}\"\n \"\".format(\n infrastructure_class, ApplicationWithConcreteInfrastructure\n )\n )\n\n # Subclass the process application class with the infrastructure class.\n process_class = process_class.mixin(infrastructure_class)\n\n assert issubclass(process_class, ApplicationWithConcreteInfrastructure)\n\n # Set 'session' and 'setup_table' in kwargs.\n kwargs = dict(kwargs)\n if \"session\" not in kwargs and process_class.is_constructed_with_session:\n kwargs[\"session\"] = self.session or self.shared_session\n if \"setup_tables\" not in kwargs and self.setup_tables:\n kwargs[\"setup_table\"] = self.setup_tables\n\n # Construct the process application.\n app = process_class(**kwargs)\n\n # Catch the session, so it can be shared.\n if self.session is None and self.shared_session is None:\n if process_class.is_constructed_with_session and self.is_session_shared:\n if self.shared_session is None:\n self.shared_session = app.session\n\n assert isinstance(app, ProcessApplication), app\n return app"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Read the data encoding the ApplicationSpecificInformation object and decode it into its constituent parts.
|
def read(self, istream):
super(ApplicationSpecificInformation, self).read(istream)
tstream = BytearrayStream(istream.read(self.length))
self.application_namespace.read(tstream)
self.application_data.read(tstream)
self.is_oversized(tstream)
self.validate()
|
[
"def decode(self, data):\n\t\traise NotImplementedError()",
"def __init__(self, application_namespace=None, application_data=None):\n super(ApplicationSpecificInformation, self).__init__(\n Tags.APPLICATION_SPECIFIC_INFORMATION)\n\n if application_namespace is None:\n self.application_namespace = ApplicationNamespace()\n else:\n self.application_namespace = application_namespace\n\n if application_data is None:\n self.application_data = ApplicationData()\n else:\n self.application_data = application_data\n\n self.validate()",
"def create(cls, application_namespace, application_data):\n namespace = ApplicationNamespace(application_namespace)\n data = ApplicationData(application_data)\n return ApplicationSpecificInformation(\n application_namespace=namespace, application_data=data)",
"def read_auxinfo_data(self):\n availability_mask = self.read_byte()\n\n if is_available(availability_mask, AuxInfoEntry.DataFlag.DATETIME):\n self.auxinfo_last_milliseconds = to_milliseconds(self.read_growing_datetime(self.auxinfo_last_milliseconds))\n\n if is_available(availability_mask, AuxInfoEntry.DataFlag.ASK_TOTAL):\n self.auxinfo_last_ask_total = self.read_relative(self.auxinfo_last_ask_total)\n\n if is_available(availability_mask, AuxInfoEntry.DataFlag.BID_TOTAL):\n self.auxinfo_last_bid_total = self.read_relative(self.auxinfo_last_bid_total)\n\n if is_available(availability_mask, AuxInfoEntry.DataFlag.OI):\n self.auxinfo_last_oi = self.read_relative(self.auxinfo_last_oi)\n\n if is_available(availability_mask, AuxInfoEntry.DataFlag.PRICE):\n self.auxinfo_last_price = self.read_relative(self.auxinfo_last_price)\n\n if is_available(availability_mask, AuxInfoEntry.DataFlag.SESSION_INFO):\n self.auxinfo_last_hi_limit = self.read_leb128()\n self.auxinfo_last_low_limit = self.read_leb128()\n self.auxinfo_last_deposit = self.read_double()\n\n if is_available(availability_mask, AuxInfoEntry.DataFlag.RATE):\n self.auxinfo_last_rate = self.read_double()\n\n if is_available(availability_mask, AuxInfoEntry.DataFlag.MESSAGE):\n message = self.read_string()\n else:\n message = \"\"\n\n timestamp = to_datetime(self.auxinfo_last_milliseconds).replace(tzinfo=self.to_zone)\n\n return AuxInfoEntry(timestamp, self.auxinfo_last_price, self.auxinfo_last_ask_total, self.auxinfo_last_bid_total, self.auxinfo_last_oi, self.auxinfo_last_hi_limit, self.auxinfo_last_low_limit, self.auxinfo_last_deposit, self.auxinfo_last_rate, message)",
"def decode(cls, data):\n raise NotImplementedError()",
"def _read(self, sacc_data: sacc.Sacc):",
"def decode(self, data): # pragma: no cover\n encoding = getattr(self, 'encoding', 'ascii')\n return data.decode(encoding, 'ignore')",
"def parse_info_packet(self, data):\r\n\r\n self.serial = data[0:5]\r\n self.firmware_version = data[5]\r\n self.bsl_major_version = data[6]\r\n self.bsl_minor_version = data[7]\r\n self.app_major_version = data[8]\r\n self.app_minor_version = data[9]\r\n self.in_mode_bsl = (False, True)[data[10]]\r\n self.on_charger = (False, True)[data[11]]",
"def _readMetaInfo(self, validate=None):\n if validate is None:\n validate = self._validate\n data = self._getPlist(METAINFO_FILENAME)\n if validate and not isinstance(data, dict):\n raise UFOLibError(\"metainfo.plist is not properly formatted.\")\n try:\n formatVersionMajor = data[\"formatVersion\"]\n except KeyError:\n raise UFOLibError(\n f\"Missing required formatVersion in '{METAINFO_FILENAME}' on {self.fs}\"\n )\n formatVersionMinor = data.setdefault(\"formatVersionMinor\", 0)\n\n try:\n formatVersion = UFOFormatVersion((formatVersionMajor, formatVersionMinor))\n except ValueError as e:\n unsupportedMsg = (\n f\"Unsupported UFO format ({formatVersionMajor}.{formatVersionMinor}) \"\n f\"in '{METAINFO_FILENAME}' on {self.fs}\"\n )\n if validate:\n from fontTools.ufoLib.errors import UnsupportedUFOFormat\n\n raise UnsupportedUFOFormat(unsupportedMsg) from e\n\n formatVersion = UFOFormatVersion.default()\n logger.warning(\n \"%s. Assuming the latest supported version (%s). \"\n \"Some data may be skipped or parsed incorrectly\",\n unsupportedMsg,\n formatVersion,\n )\n data[\"formatVersionTuple\"] = formatVersion\n return data",
"def readExistingMetaData(self: object) -> dict[str, list[str]]:\n\t\twith exiv.Image(f\"{self.rootPath}/{self.fileName}\") as f:\n\t\t\tdata = f.read_xmp()\n\t\treturn data",
"def read(self, encoding: str = 'ascii') -> dict:\n\n header: typing.Dict[str, typing.Tuple] = {}\n if not self.path:\n return header\n\n with open(self.path, 'rb') as fp:\n # loop over the bytemap, read and store the decoded values\n for name, (nbytes, dtype) in self.bytemap().items():\n res = [dtype(fp.read(n).strip().decode(encoding=encoding))\n for n in nbytes]\n header[name] = res[0] if len(res) == 1 else res\n return header",
"def parse(self):\n self.get_iphone_system_information()\n self.get_iphone_applications()\n self.get_iphone_iTunes_information()\n self.get_iphone_iBooks_infomation()\n self.get_backup_information()\n self.get_status_information()",
"def readInfo(self, info, validate=None):\n if validate is None:\n validate = self._validate\n infoDict = self._readInfo(validate)\n infoDataToSet = {}\n # version 1\n if self._formatVersion == UFOFormatVersion.FORMAT_1_0:\n for attr in fontInfoAttributesVersion1:\n value = infoDict.get(attr)\n if value is not None:\n infoDataToSet[attr] = value\n infoDataToSet = _convertFontInfoDataVersion1ToVersion2(infoDataToSet)\n infoDataToSet = _convertFontInfoDataVersion2ToVersion3(infoDataToSet)\n # version 2\n elif self._formatVersion == UFOFormatVersion.FORMAT_2_0:\n for attr, dataValidationDict in list(\n fontInfoAttributesVersion2ValueData.items()\n ):\n value = infoDict.get(attr)\n if value is None:\n continue\n infoDataToSet[attr] = value\n infoDataToSet = _convertFontInfoDataVersion2ToVersion3(infoDataToSet)\n # version 3.x\n elif self._formatVersion.major == UFOFormatVersion.FORMAT_3_0.major:\n for attr, dataValidationDict in list(\n fontInfoAttributesVersion3ValueData.items()\n ):\n value = infoDict.get(attr)\n if value is None:\n continue\n infoDataToSet[attr] = value\n # unsupported version\n else:\n raise NotImplementedError(self._formatVersion)\n # validate data\n if validate:\n infoDataToSet = validateInfoVersion3Data(infoDataToSet)\n # populate the object\n for attr, value in list(infoDataToSet.items()):\n try:\n setattr(info, attr, value)\n except AttributeError:\n raise UFOLibError(\n \"The supplied info object does not support setting a necessary attribute (%s).\"\n % attr\n )",
"def _get_app_data(self):\n return self._get_base_app_data()",
"def decode_to_native(self, data):\n raise NotImplementedError",
"def read(self):\n self.exif_dict = piexif.load(self.filename)",
"def decode(cls, stream):\n _, reserved, _ = cls.header.unpack(stream.read(4))\n # read the rest of user info\n user_data = list(cls.sub_items(stream))\n return cls(user_data=user_data, reserved=reserved)",
"def _read_primary_header(self):\n\n self._check_magic_number()\n\n self.f.seek(0)\n self.time, = np.fromfile(self.f, dtype='<f8', count=1)\n self._nbodies_tot, self._ncomp = np.fromfile(self.f, dtype=np.uint32,count=2)\n\n data_start = 16 # guaranteed first component location...\n\n # now read the component headers\n for comp in range(0,self._ncomp):\n self.f.seek(data_start)\n next_comp = self._read_spl_component_header()\n data_start = next_comp",
"def _get_dict(self, entry):\n res = self.iface.readMap(self.__handle, self.__folder,\n entry, self.appid,\n byte_arrays=True, utf8_strings=True)\n if res == 'None':\n raise EntryNotFoundError(u'Entry %s not found' % entry)\n res = self._decode(res)\n return res"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Write the data encoding the ApplicationSpecificInformation object to a stream.
|
def write(self, ostream):
tstream = BytearrayStream()
self.application_namespace.write(tstream)
self.application_data.write(tstream)
self.length = tstream.length()
super(ApplicationSpecificInformation, self).write(ostream)
ostream.write(tstream.buffer)
|
[
"def write(self, data, metadata):\n raise NotImplementedError",
"def _encode_to_stream(self, output_stream, data, options=None, **kwargs):\n output_stream.write(self._encode(data, options=options, **kwargs))",
"def serialize(self, data):\n if isinstance(data[0], dict):\n self.write_metadata(data[0])\n data = data[1:]\n else:\n self.write_metadata({})\n\n super(BaseMapXMLWriter, self).serialize(data)",
"def write_signature_info(self, signature_info):\n pass",
"def _do_dump(\n self, stream: BinaryIO, data: int, context: Any, all_fields: StrDict\n ) -> None:\n try:\n encoded_int = self._encode_integer_fn(data)\n except (ValueError, OverflowError) as err:\n raise errors.UnserializableValueError(\n field=self, value=data, reason=str(err)\n )\n\n if self.max_bytes is not None and len(encoded_int) > self.max_bytes:\n raise errors.ValueSizeError(field=self, value=data)\n\n stream.write(encoded_int)",
"def write_to_file(self, data):",
"def write(self, data):\r\n if self.stream is False:\r\n return\r\n if isinstance(data, Exception):\r\n data = unicode(SafeString(data, self.encoding,\r\n self.encoding_errors, self.decoding_errors))\r\n try:\r\n self.stream.write(data)\r\n except UnicodeEncodeError:\r\n self.stream.write(data.encode(self.encoding, self.encoding_errors))\r\n except TypeError: # in Python 3, stderr expects unicode\r\n if self.stream in (sys.stderr, sys.stdout):\r\n self.stream.buffer.write(data) # write bytes to raw stream\r\n else:\r\n self.stream.write(unicode(data, self.encoding,\r\n self.decoding_errors))",
"def serialize(self, data):\n raise NotImplementedError()",
"def write_meta(self, file_object):\n meta = self._gen_meta()\n file_object.write(meta[\"magic_number\"].encode(\"UTF-8\"))\n file_object.write(meta[\"data_length\"].to_bytes(8, \"big\", signed = False))\n file_object.write(meta[\"word_length\"].to_bytes(8, \"big\", signed = False))\n file_object.write(\"DICT_START\".encode(\"utf-8\"))\n file_object.write(str(meta[\"encode_dict\"]).encode(\"utf-8\"))\n file_object.write(\"DICT_END\".encode(\"utf-8\"))",
"def write(self, data):\n self.logger.debug(data)",
"def write_meta(self, data: dict[str, object]) -> None:\n meta_bytes = json.dumps(data).encode(\"utf-8\", errors=\"ignore\")\n self._write(b\"M%s%s\" % (len(meta_bytes).to_bytes(4, \"big\"), meta_bytes))",
"def write(self):\n if self.exif_dict != {}:\n exif_bytes = piexif.dump(self.exif_dict)\n piexif.insert(exif_bytes, self.filename)",
"def read(self, istream):\n super(ApplicationSpecificInformation, self).read(istream)\n tstream = BytearrayStream(istream.read(self.length))\n\n self.application_namespace.read(tstream)\n self.application_data.read(tstream)\n\n self.is_oversized(tstream)\n self.validate()",
"def serialize(self, data) -> str:\n pass",
"def _write(self, *args, **kwargs):\n raise NotImplementedError('Writing VASP standard streams files is not supported.')",
"def write(self):\n for data_object in self.data_list:\n data_object.write()",
"def write_sdk_info(self):\n self.write(destination=self.output_directory, filename=\"sdkinfo.py\", template_name=\"sdkinfo.py.tpl\",\n version=self.api_version,\n product_accronym=self._product_accronym,\n sdk_class_prefix=self._sdk_class_prefix,\n sdk_root_api=self.api_root,\n sdk_api_prefix=self.api_prefix,\n product_name=self._product_name,\n sdk_name=self._sdk_name,\n header=self.header_content)",
"def write_to(self, stream: StreamWrapper):\n if self.base_building is None:\n stream.write_bool(False)\n else:\n stream.write_bool(True)\n stream.write_int(self.base_building)\n stream.write_int(len(self.build_resources))\n for key, value in self.build_resources.items():\n stream.write_int(key)\n stream.write_int(value)\n stream.write_int(self.max_health)\n stream.write_int(self.max_workers)\n stream.write_int(len(self.work_resources))\n for key, value in self.work_resources.items():\n stream.write_int(key)\n stream.write_int(value)\n stream.write_bool(self.produce_worker)\n if self.produce_resource is None:\n stream.write_bool(False)\n else:\n stream.write_bool(True)\n stream.write_int(self.produce_resource)\n stream.write_int(self.produce_amount)\n stream.write_int(self.produce_score)\n stream.write_bool(self.harvest)\n stream.write_int(self.work_amount)",
"def encode(self, debug_info):\n out = StringIO.StringIO()\n # +0: base offset\n self._write_long(out, debug_info.base_offset)\n # +4: type tag\n tag = debug_info.tag\n out.write(tag)\n if tag == 'LINE':\n # file name\n self._write_string(out, debug_info.src_file)\n # entries\n for e in debug_info.entries:\n self._write_long(out, e.src_line)\n self._write_long(out, e.offset)\n elif tag == 'HEAD':\n out.write(\"DBGV01\\0\\0\")\n out.write(debug_info.data)\n else: # any\n out.write(debug_info.data)\n # retrieve result\n res = out.getvalue()\n out.close()\n return res"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Construct an ApplicationSpecificInformation object from provided data and namespace values.
|
def create(cls, application_namespace, application_data):
namespace = ApplicationNamespace(application_namespace)
data = ApplicationData(application_data)
return ApplicationSpecificInformation(
application_namespace=namespace, application_data=data)
|
[
"def __init__(self, application_namespace=None, application_data=None):\n super(ApplicationSpecificInformation, self).__init__(\n Tags.APPLICATION_SPECIFIC_INFORMATION)\n\n if application_namespace is None:\n self.application_namespace = ApplicationNamespace()\n else:\n self.application_namespace = application_namespace\n\n if application_data is None:\n self.application_data = ApplicationData()\n else:\n self.application_data = application_data\n\n self.validate()",
"def __init__(self, value=None):\n super(ApplicationData, self).__init__(value, Tags.APPLICATION_DATA)",
"def _create_application_request(app_metadata, template):\n app_metadata.validate([\"author\", \"description\", \"name\"])\n request = {\n \"Author\": app_metadata.author,\n \"Description\": app_metadata.description,\n \"HomePageUrl\": app_metadata.home_page_url,\n \"Labels\": app_metadata.labels,\n \"LicenseBody\": app_metadata.license_body,\n \"LicenseUrl\": app_metadata.license_url,\n \"Name\": app_metadata.name,\n \"ReadmeBody\": app_metadata.readme_body,\n \"ReadmeUrl\": app_metadata.readme_url,\n \"SemanticVersion\": app_metadata.semantic_version,\n \"SourceCodeUrl\": app_metadata.source_code_url,\n \"SpdxLicenseId\": app_metadata.spdx_license_id,\n \"TemplateBody\": template,\n }\n # Remove None values\n return {k: v for k, v in request.items() if v}",
"def process_object( self, obj ):\n metadata = obj.get( 'metadata', {} )\n namespace = metadata.get( \"namespace\", '' )\n name = metadata.get( \"name\", '' )\n labels = metadata.get( 'labels', {} )\n\n return DeploymentInfo( name, namespace, labels )",
"def info(self):\n assr_info = {}\n\n assr_info['ID'] = self.get('ID')\n assr_info['label'] = self.get('label')\n assr_info['assessor_id'] = assr_info['ID']\n assr_info['assessor_label'] = assr_info['label']\n assr_info['project_id'] = self.get('project')\n assr_info['project_label'] = assr_info['project_id']\n assr_info['subject_id'] = self.parent().get('xnat:subject_ID')\n assr_info['subject_label'] = self.parent().subject\n assr_info['session_id'] = self.parent().get('ID')\n assr_info['session_label'] = self.parent().get('label')\n xmltype = '{http://www.w3.org/2001/XMLSchema-instance}type'\n assr_info['xsiType'] = self.get(xmltype).lower()\n\n if assr_info['xsiType'].lower() == DEFAULT_FS_DATATYPE.lower():\n # FreeSurfer\n assr_info['procstatus'] = self.get('fs:procstatus')\n assr_info['qcstatus'] = self.get('xnat:validation/status')\n assr_info['version'] = self.get('fs:procversion')\n assr_info['jobid'] = self.get('fs:jobid')\n assr_info['jobstartdate'] = self.get('fs:jobstartdate')\n assr_info['memused'] = self.get('fs:memused')\n assr_info['walltimeused'] = self.get('fs:walltimeused')\n assr_info['jobnode'] = self.get('fs:jobnode')\n assr_info['proctype'] = 'FreeSurfer'\n\n elif assr_info['xsiType'].lower() == DEFAULT_DATATYPE.lower():\n # genProcData\n assr_info['procstatus'] = self.get('proc:procstatus')\n assr_info['proctype'] = self.get('proc:proctype')\n assr_info['qcstatus'] = self.get('xnat:validation/status')\n assr_info['version'] = self.get('proc:procversion')\n assr_info['jobid'] = self.get('proc:jobid')\n assr_info['jobstartdate'] = self.get('proc:jobstartdate')\n assr_info['memused'] = self.get('proc:memused')\n assr_info['walltimeused'] = self.get('proc:walltimeused')\n assr_info['jobnode'] = self.get('proc:jobnode')\n else:\n msg = 'Warning:unknown xsitype for assessor: %s'\n print(msg % assr_info['xsiType'])\n\n return assr_info",
"def _make_data(cls, data: 'Data_Header') -> 'dict[str, Any]': # type: ignore[override]\n return {\n 'magic_number': data.magic_number.data,\n 'version_major': data.version.major,\n 'version_minor': data.version.minor,\n 'thiszone': data.thiszone,\n 'sigfigs': data.sigfigs,\n 'snaplen': data.snaplen,\n 'network': data.network,\n }",
"def __init__(self, runtime_info: Dict[str, Any]) -> None:\n\n super().__init__(runtime_info, SimulatorControlType.RUNTIME)\n self.raw_info = runtime_info\n self.availability = runtime_info.get(\"availability\")\n self.build_version = runtime_info[\"buildversion\"]\n self.bundle_path = runtime_info[\"bundlePath\"].replace(\"\\\\/\", \"/\")\n self.identifier = runtime_info[\"identifier\"]\n self.is_available = runtime_info[\"isAvailable\"]\n self.name = runtime_info[\"name\"]\n self.version = runtime_info[\"version\"]",
"def applicant_data(data) :\n \n return {\n \"name\" : data[1],\n \"gender\" : data[5],\n \"dob\" : data[6],\n \"phone\" : data[7],\n \"address\" : data[8],\n \"following_company\" : data[11],\n \"cv_file_path\" : data[9],\n \"cv_updated_at\" : data[10],\n \"notifications\" : data[12],\n }",
"def _get_base_app_data(self):\n app_data = super()._get_base_app_data()\n app_data.update(\n {\n \"modelName\": self.model.RESOURCE_NAME,\n \"state\": APP_DATA_STATE_SUCCESS,\n \"player\": settings.VIDEO_PLAYER,\n \"uploadPollInterval\": settings.FRONT_UPLOAD_POLL_INTERVAL,\n # front is expecting duration in milliseconds\n \"attendanceDelay\": settings.ATTENDANCE_PUSH_DELAY * 1000,\n # In certain context, such as embedding the resource in content,\n # we want to collapse the dashboard.\n \"dashboardCollapsed\": \"custom_embedded_resource\" in self.request.POST,\n }\n )\n\n if self.request.resolver_match.app_name:\n app_data.update(\n {\n \"appName\": self.request.resolver_match.app_name,\n }\n )\n\n return app_data",
"def read(self, istream):\n super(ApplicationSpecificInformation, self).read(istream)\n tstream = BytearrayStream(istream.read(self.length))\n\n self.application_namespace.read(tstream)\n self.application_data.read(tstream)\n\n self.is_oversized(tstream)\n self.validate()",
"def get_template_data_for(self, ar):\n info = None\n template = ar.getTemplate()\n ar_sampletype_uid = api.get_uid(ar.getSampleType())\n\n if template:\n info = self.get_base_info(template)\n\n analyses = template.getAnalyses()\n partition_analyses = map(\n lambda x: (x.get(\"partition\"), x.get(\"service_uid\")), analyses)\n\n analyses_by_partition = defaultdict(list)\n for partition, service_uid in partition_analyses:\n analyses_by_partition[partition].append(service_uid)\n\n sampletypes_by_partition = defaultdict(list)\n for part in template.getPartitions():\n part_id = part.get(\"part_id\")\n sampletype_uid = part.get('sampletype_uid', ar_sampletype_uid)\n sampletypes_by_partition[part_id] = sampletype_uid\n\n partitions = map(lambda p: p.get(\"part_id\"),\n template.getPartitions())\n info.update({\n \"analyses\": analyses_by_partition,\n \"partitions\": partitions,\n \"sample_types\": sampletypes_by_partition,\n })\n else:\n info = {\n \"analyses\": {},\n \"partitions\": [],\n \"sample_types\": {},\n }\n return info",
"def __init__(self, value=None):\n super(ApplicationNamespace, self).__init__(\n value, Tags.APPLICATION_NAMESPACE)",
"def __init__(self, lookin_data: LookinData) -> None:\n super().__init__()\n self._lookin_device = lookin_data.lookin_device\n self._lookin_protocol = lookin_data.lookin_protocol\n self._lookin_udp_subs = lookin_data.lookin_udp_subs\n self._attr_device_info = DeviceInfo(\n identifiers={(DOMAIN, self._lookin_device.id)},\n name=self._lookin_device.name,\n manufacturer=\"LOOKin\",\n model=\"LOOKin Remote2\",\n sw_version=self._lookin_device.firmware,\n )",
"def make_object(self, data):\n return Deployment(**data)",
"def _parse_app_info(self, app_info):\n # The app name is the first part of the app information\n app_name = app_info[0]\n # The secret key is the second part of the app information\n secret_key = app_info[1]\n\n return (app_name, secret_key)",
"def objectMap(self, data={}):\n om = ObjectMap(data)\n om.compname = self.compname\n om.modname = self.modname\n om.classname = self.classname\n return om",
"def infoFromData(data):\n assert isinstance(data, (Data1D, Data2D))\n\n info_item = QtGui.QStandardItem(\"Info\")\n\n title_item = QtGui.QStandardItem(\"Title: \" + data.title)\n info_item.appendRow(title_item)\n run_item = QtGui.QStandardItem(\"Run: \" + str(data.run))\n info_item.appendRow(run_item)\n type_item = QtGui.QStandardItem(\"Type: \" + str(data.__class__.__name__))\n info_item.appendRow(type_item)\n\n if data.path:\n path_item = QtGui.QStandardItem(\"Path: \" + data.path)\n info_item.appendRow(path_item)\n\n if data.instrument:\n instr_item = QtGui.QStandardItem(\"Instrument: \" + data.instrument)\n info_item.appendRow(instr_item)\n\n process_item = QtGui.QStandardItem(\"Process\")\n if isinstance(data.process, list) and data.process:\n for process in data.process:\n if process is None:\n continue\n process_date = process.date\n process_date_item = QtGui.QStandardItem(\"Date: \" + process_date)\n process_item.appendRow(process_date_item)\n\n process_descr = process.description\n process_descr_item = QtGui.QStandardItem(\"Description: \" + process_descr)\n process_item.appendRow(process_descr_item)\n\n process_name = process.name\n process_name_item = QtGui.QStandardItem(\"Name: \" + process_name)\n process_item.appendRow(process_name_item)\n\n info_item.appendRow(process_item)\n\n return info_item",
"def construct_info(name: str, proto_obj, version=5, fus_object=None, GUID=None) -> None:\n\n proto_obj.info.version = version\n\n if fus_object is not None:\n proto_obj.info.name = fus_object.name\n elif name is not None:\n proto_obj.info.name = name\n else:\n raise ValueError(\"Cannot construct info from no name or fus_object\")\n\n if GUID is not None:\n proto_obj.info.GUID = str(GUID)\n else:\n try:\n # attempt to get entity token\n proto_obj.info.GUID = fus_object.entityToken\n except:\n # fails and gets new uuid\n proto_obj.info.GUID = str(uuid.uuid4())",
"def parse(self):\n self.get_iphone_system_information()\n self.get_iphone_applications()\n self.get_iphone_iTunes_information()\n self.get_iphone_iBooks_infomation()\n self.get_backup_information()\n self.get_status_information()"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Juan's code.Perform a biclustering, plot a heatmap with dendrograms on each axis.
|
def plot_bicluster(data, row_linkage, col_linkage, x_label, y_label,
row_nclusters=10, col_nclusters=3):
fig = plt.figure(figsize=(10, 10))
# Compute and plot row-wise dendrogram
# `add_axes` takes a "rectangle" input to add a subplot to a figure.
# The figure is considered to have side-length 1 on each side, and its
# bottom-left corner is at (0, 0).
# The measurements passed to `add_axes` are the left, bottom, width, and
# height of the subplot. Thus, to draw the left dendrogram (for the rows),
# we create a rectangle whose bottom-left corner is at (0.09, 0.1), and
# measuring 0.2 in width and 0.6 in height.
ax1 = fig.add_axes([0.09, 0.1, 0.2, 0.6])
# For a given number of clusters, we can obtain a cut of the linkage
# tree by looking at the corresponding distance annotation in the linkage
# matrix.
threshold_r = (row_linkage[-row_nclusters, 2] +
row_linkage[-row_nclusters+1, 2]) / 2
dendrogram(row_linkage, orientation='left', color_threshold=threshold_r)
# Compute and plot column-wise dendogram
# See notes above for explanation of parameters to `add_axes`
ax2 = fig.add_axes([0.3, 0.71, 0.6, 0.2])
threshold_c = (col_linkage[-col_nclusters, 2] +
col_linkage[-col_nclusters+1, 2]) / 2
dendrogram(col_linkage, color_threshold=threshold_c)
# Hide axes labels
ax1.set_xticks([])
ax1.set_yticks([])
ax2.set_xticks([])
ax2.set_yticks([])
# Plot data heatmap
ax = fig.add_axes([0.3, 0.1, 0.6, 0.6])
# Sort data by the dendogram leaves
idx_rows = leaves_list(row_linkage)
data = data[idx_rows, :]
idx_cols = leaves_list(col_linkage)
data = data[:, idx_cols]
im = ax.matshow(data, aspect='auto', origin='lower', cmap='YlGnBu_r')
ax.set_xticks([])
ax.set_yticks([])
# Axis labels
plt.xlabel(x_label)
plt.ylabel(y_label, labelpad=125)
# Plot legend
axcolor = fig.add_axes([0.91, 0.1, 0.02, 0.6])
plt.colorbar(im, cax=axcolor)
# display the plot
plt.show()
|
[
"def myDendrogram(shopping_data):\r\n dataframe = shopping_data.values\r\n Z = hierarchy.linkage(dataframe, 'centroid')\r\n plt.figure()\r\n plt.xlabel('Node ID')\r\n plt.ylabel('Euclidean distance')\r\n plt.title('Agglomerative Clustering')\r\n dn = hierarchy.dendrogram(Z)\r\n plt.show()",
"def draw_heatmap(k_means, number_of_clusters, counts, data, header, title, xlabel, ylabel, file_name):\n\n plt.figure()\n plt.imshow(k_means[0], interpolation='none')\n plt.title(title)\n plt.ylabel(ylabel)\n plt.yticks(range(number_of_clusters), [str(i) + \": \" + str(counts[i]) for i in range(number_of_clusters)])\n plt.xlabel(xlabel)\n plt.xticks(range(len(data[0])), header, fontsize=4, rotation=90)\n plt.bone()\n plt.colorbar()\n plt.savefig(file_name + '.pdf', bbox_inches='tight')\n plt.close()",
"def heatmap():\n data=getdata()\n TGs=sorted(data.keys())\n for titgroup in TGs:\n thisN=[]\n thisH=[]\n for residue in sorted(data[titgroup].keys()):\n Hval=0.0\n Nval=0.0\n for atom in ['H','N']:\n if data[titgroup][residue].has_key(atom):\n x=data[titgroup][residue][atom]\n #\n # -----\n #\n if x=='absent':\n print 'abs'\n if atom=='H':\n Hval=-20\n else:\n Nval=-20\n else:\n if x[0]=='q':\n x=x[1:]\n x=x.split(';')[0]\n if x[0] in ['<','>']:\n x=x[1:]\n x=float(x)\n if atom=='H':\n Hval=20\n else:\n Nval=20\n #\n #\n thisN.append(Nval)\n thisH.append(Hval)\n for y in range(10):\n Ndata.append(thisN)\n Hdata.append(thisH)\n #\n #\n import TwoDplots\n blue_red1 = TwoDplots.LinearSegmentedColormap('BlueRed1', cdict1)\n #\n plt.imshow(Ndata,interpolation='nearest',cmap=blue_red1)\n cbar=plt.colorbar()\n cbar.set_label('score')\n #\n plt.yticks(range(5,105,10),TGs)\n plt.ylim([0,100])\n plt.show()\n return",
"def split(image, plot=False):\n iimage = segmentation.clear_border(np.logical_not(image))\n\n downsample = 1\n char_width = 30\n #resize_to = (45, 27)\n #resize_to = (41, 25)\n resize_to = (38, 23)\n # weight given to the y coordinate\n y_wieght = 0.1\n\n\n # x coordinate of every lit up pixle\n x = np.asarray(np.vstack(np.where(iimage > 0)), dtype=np.float)\n # needs to be 2d for the clustering alg.\n x = x.T[::downsample, :]\n\n x[:,0] *= y_wieght\n #x = x.reshape(len(x), 1)\n # make 6 clusters using single linkage\n\n linkage_method = 'single'\n\n while True:\n Z = fastcluster.linkage(x, method=linkage_method)\n labels = fcluster(Z, t=6, criterion='maxclust')\n\n # try kmeans? this is for debugging\n #centers, _ = kmeans(x, k_or_guess=6)\n #labels, _ = vq(x, centers)\n\n unique_labels = np.unique(labels)\n\n # single linkage can fail to give 6 clusters in the face\n # of equal distances. So let's fall back to ward\n if len(unique_labels) != 6:\n if linkage_method == 'ward':\n raise Exception('Sorry!!!!')\n linkage_method = 'ward'\n continue\n\n cluster_xlims = []\n sizes = []\n for i in unique_labels:\n x_coords = x[labels==i][:,1]\n #print 'Cluster %d has %d elements' % (i, len(x_coords))\n sizes.append(len(x_coords))\n\n cluster_xlims.append((np.min(x_coords), np.max(x_coords)))\n\n if np.min(sizes) < 75 / downsample:\n bad_cluster = unique_labels[np.argmin(sizes)]\n #print 'REMOVING CLUSTER', bad_cluster\n\n x = x[labels != bad_cluster]\n else:\n break\n\n cluster_xlims.sort(key=lambda x: x[0])\n\n chars = []\n for xlim in cluster_xlims:\n char = np.zeros((iimage.shape[0], char_width), dtype=np.float)\n w = xlim[1] - xlim[0]\n\n try:\n # try to embed the character into a white background\n # before shrinking to the final output size\n char[:, char_width/2-w/2:char_width/2+w/2] = iimage[:, xlim[0]:xlim[1]]\n\n char = transform.resize(char, output_shape=resize_to)\n\n except ValueError:\n # but if it doesn't fit, shrink it to fit\n # when shrinking, we want it to be float\n char = transform.resize(1.0*iimage[:, xlim[0]:xlim[1]],\n output_shape=resize_to)\n # but then we need to threshold it back\n\n #char = filter.threshold_adaptive(char, block_size=resize_to[1])\n chars.append(np.asarray(char, dtype=np.bool))\n #chars.append(char)\n\n\n if plot:\n fig, axes = pp.subplots(ncols=6)\n for ax, char in zip(axes, chars):\n ax.imshow(char)\n\n return chars",
"def display_heatmap(self,key1='leiden_clusters',key2='leiden_clusters',colorbar=True,**kwargs):\n sam1=self.sam1\n sam2=self.sam2\n samap=self.samap\n from samap import q, pd\n import matplotlib.pyplot as plt\n cl1 = q(sam1.adata.obs[key1])\n cl2 = q(sam2.adata.obs[key2])\n species = q(samap.adata.obs['species']).astype('object')\n samap.adata.obs['mapping_labels'] = pd.Categorical(species + '_' + np.append(cl1,cl2).astype('str').astype('object'))\n _,labels1,labels2,mapping_scores = _compute_csim(samap,key='mapping_labels')\n mapping_scores/=20\n fig,ax = plt.subplots(nrows=1,ncols=1)\n im = ax.imshow(mapping_scores,**kwargs)\n ax.set_xticks(np.arange(labels2.size))\n ax.set_yticks(np.arange(labels1.size))\n ax.set_xticklabels(labels2,rotation=90)\n ax.set_yticklabels(labels1)\n h = 10\n w = labels2.size*10/labels1.size\n fig.set_size_inches((w,h))\n if colorbar:\n fig.colorbar(im,shrink=0.5)\n fig.tight_layout()\n return fig,pd.DataFrame(data=mapping_scores,index=labels1,columns=labels2)",
"def plot(corpus,fname):\n tfidf_vectorizer = TfidfVectorizer()\n tfidf_matrix = tfidf_vectorizer.fit_transform(corpus)\n print('Begin prepare matrices:',tfidf_matrix.shape)\n def print_tfidf():\n # print words and tfidfs:\n words = tfidf_vectorizer.get_feature_names()\n for i in range(len(corpus)):\n if i<5:\n print('----Document %d----' % (i))\n for j in range(len(words)):\n if tfidf_matrix[i, j] > 1e-5:\n print(words[j], tfidf_matrix[i, j]) # .encode('utf-8')\n print_tfidf()\n\n dist = 1 - cosine_similarity(tfidf_matrix)\n\n print('\\nBegin print img:')\n linkage_matrix = ward(dist) #define the linkage_matrix using ward clustering pre-computed distances\n print('line 68: linkage_matrix = ward(dist)')\n fig, ax = plt.subplots(figsize=(20, 600)) # set size\n ax = dendrogram(\n linkage_matrix,\n leaf_font_size=6,\n orientation=\"right\"\n # ,\n # truncate_mode='lastp', # show only the last p merged clusters\n # p=12, # show only the last p merged clusters\n # leaf_rotation=90.,\n # show_contracted=True, # to get a distribution impression in truncated branches\n\n ) # labels=[i for i in range(len(corpus))]\n\n print('line 71: ax = dendrogram(...)')\n plt.tick_params(\\\n axis= 'x', # changes apply to the x-axis\n which='both', # both major and minor ticks are affected\n bottom='off', # ticks along the bottom edge are off\n top='off', # ticks along the top edge are off\n labelbottom='off')\n print('line 78: plt.tick_params')\n plt.tight_layout() #show plot with tight layout # plt.show()\n print('line 80: plt.tight_layout()')\n\n plt.savefig('../pic/ward_clusters-%s.png'%(fname), dpi=100) #save figure as ward_clusters\n return ax",
"def represent_cluster(index):\n M = np.zeros((280,280))\n for y in range(10):\n for x in range(10):\n if index == indexes[10*y+x]:\n M[y*28:(y+1)*28,x*28:(x+1)*28] = random[10*y+x].reshape((28,28))\n im, ax = plt.subplots()\n plt.imshow(M, cmap='bwr', vmax = np.amax(M), vmin = -np.amax(M))\n plt.colorbar()\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n plt.title('cluster '+str(index))\n #plt.gca().set_axis_off()\n plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, \n hspace = 0, wspace = 0)\n plt.margins(0,0)\n plt.gca().xaxis.set_major_locator(plt.NullLocator())\n plt.gca().yaxis.set_major_locator(plt.NullLocator())\n plt.savefig(str(index), bbox_inches = 'tight',\n pad_inches = 0)",
"def heatmap(dfr, outfilename=None, title=None, params=None):\n # Decide on figure layout size: a minimum size is required for\n # aesthetics, and a maximum to avoid core dumps on rendering.\n # If we hit the maximum size, we should modify font size.\n maxfigsize = 120\n calcfigsize = dfr.shape[0] * 1.1\n figsize = min(max(8, calcfigsize), maxfigsize)\n if figsize == maxfigsize:\n scale = maxfigsize / calcfigsize\n sns.set_context(\"notebook\", font_scale=scale)\n\n # Add a colorbar?\n if params.classes is None:\n col_cb = None\n else:\n col_cb = get_colorbar(dfr, params.classes)\n\n # Add attributes to parameter object, and draw heatmap\n params.colorbar = col_cb\n params.figsize = figsize\n params.linewidths = 0.25\n fig = get_clustermap(dfr, params, title=title)\n\n # Save to file\n if outfilename:\n fig.savefig(outfilename)\n\n # Return clustermap\n return fig",
"def sns_clustermap(df: pd.DataFrame, title=\"Clustermap\", z=None,\n genes_of_interest: list = None,show_all=True, labels=True,\n cmap='inferno', sample_clust=True, gene_clust=True, bar_label='log$_2$FC',\n save_dir=\"./clustermap\", save_plot=False, save_fmt='pdf', file_name=None) -> sns.matrix.ClusterGrid:\n # TODO: Z-score 1 or 0 is axis NOT T/F (0=rows, 1=cols)\n if df.isnull().values.any().any():\n df.dropna(axis=0, inplace=True)\n if genes_of_interest is None:\n heatmap = sns.clustermap(df, row_cluster=gene_clust, figsize=(12,10),\n col_cluster=sample_clust,\n yticklabels=1, cbar_kws={'label': bar_label},\n cmap=cmap, center=0, z_score=z)\n\n else:\n heatmap = sns.clustermap(df.loc[genes_of_interest,:], figsize=(10,8),\n row_cluster=gene_clust, col_cluster=sample_clust,\n yticklabels=1, cbar_kws={'label': bar_label},\n cmap=cmap, center=0, z_score=z)\n # format the figure\n fig = heatmap.fig\n # figw, figh = (10,8)\n # fig.subplots_adjust(left=1/figw, right=1-1/figw, bottom=1/figh, top=1-1/figh)\n\n fig.suptitle(title)\n # fig.set_size(20)\n # TODO: find some way to scale this with the data rather than just making everything huge\n heatmap.fig.set_size_inches(10, 10, forward=True)\n # format the ax object\n ax = fig.axes[0]\n if df.shape[0] > 10:\n helpers.add_extended_ticks(ax, tick_len=8, x_ticks=False, rotation=45)\n # else:\n # may not need this\n # formatters.add_ticks(ax)\n # TODO: adjust figure width\n if df.shape[1] > 10:\n helpers.add_extended_ticks(ax, tick_len=8, x_ticks=True, rotation=45)\n # else:\n # may not need this\n # formatters.add_ticks(ax)\n # helpers.set_text_size(ax.yaxis.label, 10)\n if save_plot:\n if file_name is None:\n file_name = title\n save_path = os.path.join(save_dir, file_name+\".\"+save_fmt)\n heatmap.savefig(save_path, save_fmt, dpi=400)\n return heatmap",
"def plot_feat_dendrogram(df: pd.DataFrame):\n corr = np.round(scipy.stats.spearmanr(df).correlation, 4)\n corr_condensed = hc.distance.squareform(1-corr)\n z = hc.linkage(corr_condensed, method='average')\n fig = plt.figure(figsize=(10,6))\n plt.title('Dendrogram of features based on spearman correlations', fontsize='medium')\n plt.xticks(fontsize='xx-small')\n hc.dendrogram(z, labels=df.columns, orientation='left', leaf_font_size='small')\n plt.show()",
"def subdivide(attr, connectivity, minClusterSize=5, maxClusterSize=100, mergeThreshold=1.0, show=False):\n\n # Get the number of samples -- i.e. the number entities being clustered.\n nSamples = attr.shape[0]\n\n # Run the routine that determines the constrained merges.\n (children, n_components, n_leaves, parents, distances) = \\\n ward_tree(attr, connectivity=connectivity, return_distance=True)\n\n if show:\n # Initialize clusters.\n clusters = {}\n for i in range(nSamples):\n clusters[i] = set()\n clusters[i].add(i)\n\n # Assemble a linkage matrix like the one used by the 'dendrogram' routine.\n nr = children.shape[0]\n lm = np.zeros((nr, 4))\n cidx = nSamples\n for i in range(nr):\n cid1 = children[i, 0]\n cid2 = children[i, 1]\n icd = distances[i] # inter-cluster distance\n clusters[cidx] = clusters[cid1].union(clusters[cid2])\n nx = len(clusters[cidx])\n cidx += 1\n lm[i] = [cid1, cid2, icd, nx]\n\n # Make a dendrogram plot.\n pyplot.figure(11, figsize=(25, 10))\n pyplot.title('Hierarchical Clustering Dendrogram')\n pyplot.xlabel('sample index')\n pyplot.ylabel('distance')\n dendrogram(lm, leaf_rotation=90., leaf_font_size=8)\n pyplot.show()\n\n # A function to convert a cluster into a string.\n def clusterString(s):\n r = '[%3d] {%s}' % (len(s), ','.join(['%s' %x for x in sorted(s)]))\n return r\n\n # Initialize the table of clusters.\n clusters = {}\n for i in range(nSamples):\n clusters[i] = set()\n clusters[i].add(i)\n\n nr = children.shape[0]\n cidx = nSamples\n for i in range(nr):\n cid1 = children[i, 0]\n cid2 = children[i, 1]\n icd = distances[i]\n\n if show:\n print('proposed merge: [%.2f] %d + %d -> %d' % (icd, cid1, cid2, cidx))\n\n if cid1 in clusters and cid2 in clusters:\n n1 = len(clusters[cid1])\n n2 = len(clusters[cid2])\n if (icd < mergeThreshold and n1 + n2 < maxClusterSize) or n1 < minClusterSize or n2 < minClusterSize:\n if show:\n print('merging: [%.2f] %s + %s' % (icd, clusterString(clusters[cid1]), clusterString(clusters[cid2])))\n clusters[cidx] = clusters[cid1].union(clusters[cid2])\n del clusters[cid1]\n del clusters[cid2]\n else:\n if show:\n print('rejected: dist=%.2f size1=%d size2=%d' % (icd, len(clusters[cid1]), len(clusters[cid2])))\n else:\n if show:\n print('rejected: %d=%d %d=%d' % (cid1, cid1 in clusters, cid2, cid2 in clusters))\n\n cidx += 1\n\n if show:\n print('final clusters:')\n for cid in clusters:\n print('%s' % clusterString(clusters[cid]))\n\n # Set the final labels.\n labels = np.zeros(nSamples, dtype=np.int)\n clusterLabel = 0\n for cid in clusters:\n clusterLabel += 1\n for ix in clusters[cid]:\n labels[ix] = clusterLabel\n\n return(labels)",
"def heatmap(self):\n plt.imshow(self.M)\n plt.yticks([])\n plt.xticks(np.arange(self.size[1]))\n plt.show()",
"def heatmap_headmap(df_obj,sensorData,epoch_no):\n voltmatrix,subID = avgVolt_stimulus(df_obj,sensorData,epoch_no)\n\n fig = plt.figure(1,figsize=(6.5,5.5))\n gridspec.GridSpec(3,3)\n\n #1\n plt.subplot2grid((3,3),(0,0), colspan=2,rowspan=3)\n ax = sns.heatmap(voltmatrix, xticklabels=stimulus,cmap='RdBu_r', vmin=-1, vmax=1)\n ax.set(yticklabels=[])\n ax.set(xlabel='stimulus', ylabel='<-- channels')\n ax.set_title('sub '+str(subID)+' Epoch '+str(epoch_no).zfill(3))\n #2\n ax1 = plt.subplot2grid((3,3),(0,2))\n mask,xi,yi,zi = interpolate_mesh(sensorData,voltmatrix[:,0])\n snapPlots = plot_head(ax1,mask,xi,yi,zi,stimulus[0],sensorData)\n #3\n ax2 = plt.subplot2grid((3,3),(1,2))\n mask,xi,yi,zi = interpolate_mesh(sensorData,voltmatrix[:,1])\n snapPlots = plot_head(ax2,mask,xi,yi,zi,stimulus[1],sensorData)\n #4\n ax3 = plt.subplot2grid((3,3),(2,2))\n mask,xi,yi,zi = interpolate_mesh(sensorData,voltmatrix[:,2])\n snapPlots = plot_head(ax3, mask,xi,yi,zi,stimulus[2],sensorData)\n\n fig.tight_layout()\n fig.savefig(subID+'_Epoch_eegSensors_'+str(epoch_no).zfill(4)+'.png')",
"def heatmaps_sepcies_dist(self, herbis_dist, carnis_dist, cmax_animals):\n width_island = len(herbis_dist[0])\n height_island = len(herbis_dist)\n # Herbivores distribution\n im = self.ax4.imshow(herbis_dist, cmap='viridis')\n self.ax4.set_title('Herbivore distribution', fontsize=self.font)\n self.fig.colorbar(im, ax=self.ax4, orientation='vertical', max=cmax_animals['Herbivore'])\n self.ax4.set_xticks(range(width_island))\n self.ax4.set_xticklabels(range(1, 1 + width_island), fontsize=self.font_axes)\n self.ax4.set_yticks(range(height_island))\n self.ax4.set_yticklabels(range(1, 1 + height_island), fontsize=self.font_axes)\n\n # Carnivores distribution\n im = self.ax6.imshow(carnis_dist, cmap='viridis')\n self.ax6.set_title('Carnivore distribution', fontsize=self.font)\n self.fig.colorbar(im, ax=self.ax6, orientation='vertical', max=cmax_animals['Carnivore'])\n self.ax6.set_xticks(range(width_island))\n self.ax6.set_xticklabels(range(1, 1 + width_island), fontsize=self.font_axes)\n self.ax6.set_yticks(range(height_island))\n self.ax6.set_yticklabels(range(1, 1 + height_island), fontsize=self.font_axes)",
"def investigate_diagnostic_clusters(self):\n # To start with we will do a 1 up one down plot where we have the\n # hierarchical on top of the 99 ITS2 sequences that have the host data associated with them\n # on bottom we will plot an annotation of the host group. We will hope to see clustering.\n # We will need to do this for each of the C and D clades. Start with C as this is the most abundant\n if self.coral == 'Pocillopora':\n fig = plt.figure(figsize=(11, 6))\n # 4 down 1 across\n gs = gridspec.GridSpec(11, 2)\n axes = []\n plot_tyes = ['hier', 'anot']\n hier_ax = plt.subplot(gs[0:4,:])\n seq_bars_ax = plt.subplot(gs[4:6, :])\n seq_leg_ax = plt.subplot(gs[6:7, :])\n anot_ax = plt.subplot(gs[7:8,:])\n anot_leg_ax = plt.subplot(gs[8:9, :])\n island_ax = plt.subplot(gs[9:10, :])\n island_leg_ax = plt.subplot(gs[10:11, :])\n elif self.coral == \"Porites\":\n fig = plt.figure(figsize=(11, 6))\n # 4 down 1 across\n gs = gridspec.GridSpec(13, 2)\n axes = []\n plot_tyes = ['hier', 'anot']\n hier_ax = plt.subplot(gs[0:4, :])\n seq_bars_ax = plt.subplot(gs[4:6, :])\n seq_leg_ax = plt.subplot(gs[6:7, :])\n anot_ax = plt.subplot(gs[7:8, :])\n anot_leg_ax = plt.subplot(gs[8:9, :])\n anot_sub_ax = plt.subplot(gs[9:10, :])\n anot_sub_leg_ax = plt.subplot(gs[10:11, :])\n island_ax = plt.subplot(gs[11:12, :])\n island_leg_ax = plt.subplot(gs[12:13, :])\n if self.genus == 'Cladocopium':\n if self.dist_method == 'braycurtis':\n dist_df_path = os.path.join(self.input_dir, \"2020-05-19_01-11-37.777185.braycurtis_sample_distances_C_sqrt.dist\")\n elif self.dist_method == 'unifrac':\n dist_df_path = os.path.join(self.input_dir,\n \"2020-05-19_01-11-37.777185_unifrac_btwn_sample_distances_C_sqrt.dist\")\n elif self.genus == 'Durusdinium':\n if self.dist_method == 'braycurtis':\n dist_df_path = os.path.join(self.input_dir, \"2020-05-19_01-11-37.777185.braycurtis_sample_distances_D_sqrt.dist\")\n elif self.dist_method == 'unifrac':\n dist_df_path = os.path.join(self.input_dir,\n \"2020-05-19_01-11-37.777185_unifrac_btwn_sample_distances_D_sqrt.dist\")\n sph_plot = SPHierarchical(dist_output_path=dist_df_path, no_plotting=True)\n sample_names_in_current_dist = [sph_plot.obj_uid_to_obj_name_dict[_] for _ in sph_plot.dist_df.index.values]\n samples_to_keep = [_ for _ in sample_names_in_current_dist if _ in self.counts_df_with_host.index.values]\n sph_plot = SPHierarchical(\n dist_output_path=dist_df_path, ax=hier_ax,\n sample_names_included=samples_to_keep)\n sph_plot.plot()\n hier_ax.spines['right'].set_visible(False)\n hier_ax.spines['top'].set_visible(False)\n hier_ax.set_ylabel('Dissimilarity')\n hier_ax.set_title(f'{self.coral} - {self.genus} - {self.dist_method}')\n\n spb_plot = SPBars(\n seq_count_table_path=os.path.join(self.input_dir, \"98_20200331_DBV_2020-05-19_01-11-37.777185.seqs.absolute.abund_and_meta.txt\"),\n profile_count_table_path=os.path.join(self.input_dir, \"98_20200331_DBV_2020-05-19_01-11-37.777185.profiles.absolute.abund_and_meta.txt\"),\n plot_type='seq_only', legend=True, relative_abundance=True, sample_uids_included=sph_plot.dendrogram_sample_order_uid, bar_ax=seq_bars_ax, seq_leg_ax=seq_leg_ax, limit_genera=[f'{self.genus[0]}']\n )\n spb_plot.plot()\n self._turn_off_spine_and_ticks(seq_bars_ax)\n seq_bars_ax.set_ylabel(\"ITS2\\nseqs\")\n\n # Finally we want to plot up some rectanles that will be the host_group annotations\n # And the island annotations\n # Problem TARA_CO-0000697 anot_sub_ax\n if self.coral == 'Porites':\n self._plot_annotations_and_legends(anot_ax=anot_ax, color_map_name='Dark2', leg_ax=anot_leg_ax,\n sample_to_annotation_dict={s: g[0] for s, g in self.sample_to_host_group_dict.items()}, sph_plot=sph_plot)\n anot_ax.set_ylabel(\"HostGroup\")\n self._plot_annotations_and_legends(anot_ax=anot_sub_ax, color_map_name='Set1', leg_ax=anot_sub_leg_ax, sample_to_annotation_dict=self.sample_to_host_group_dict, sph_plot=sph_plot)\n anot_sub_ax.set_ylabel(\"HostGroup\\nsub\")\n elif self.coral == 'Pocillopora':\n self._plot_annotations_and_legends(anot_ax=anot_ax, color_map_name='Set1', leg_ax=anot_leg_ax,\n sample_to_annotation_dict=self.sample_to_host_group_dict,\n sph_plot=sph_plot)\n anot_ax.set_ylabel(\"Host group\")\n self._plot_annotations_and_legends(anot_ax=island_ax, color_map_name='Set3', leg_ax=island_leg_ax,\n sample_to_annotation_dict=self.sample_to_island_dict, sph_plot=sph_plot)\n island_ax.set_ylabel(\"Island\")\n plt.savefig(os.path.join(self.figure_dir, f\"host_diagnostic_{self.coral}_{self.genus}_{self.dist_method}.png\"), dpi=600)\n plt.savefig(\n os.path.join(self.figure_dir, f\"host_diagnostic_{self.coral}_{self.genus}_{self.dist_method}.svg\"),\n dpi=600)\n foo = 'bar'",
"def plot_parallel( data, columns, indx, scale = 0):\n \n #length = len(data[0])\n if scale == 1:\n dataNp = np.array(data)\n std = StandardScaler().fit_transform(dataNp)\n data = pd.DataFrame( std, columns = columns)\n else:\n data = pd.DataFrame( data, columns = columns)\n \n data['clusters'] = np.arange( data.shape[0] )\n dataIndex = indx.copy()\n dataIndex.append( data.shape[1] -1)\n ax = parallel_coordinates( data.iloc[:, dataIndex], 'clusters')\n #,use_columns = True)\n # xticks = np.arange(len(dataIndex) -1) )\n ax.set_title('Parallel Coordinates Plot')\n ax.set_ylabel('Feature Value')\n ax.set_xlabel('Features')\n plt.show()\n #ax.grid(b = False)\n #plt.axis('off')\n #ax.set_xticks([])\n # ax.set_yticks([])\n \n \n \n return ax",
"def findclusters(shopping_data):\r\n\r\n rows = {} #dictionary for saving each row from the data frame\r\n count= {} # to keep count of points in every cluster\r\n\r\n last_10_cluster =[]\r\n\r\n for i in range(1,101):\r\n rows[i] = shopping_data.ix[i].values\r\n count[i]=1\r\n\r\n clust = set()\r\n\r\n #while loop where all the clustering is performed\r\n while len(rows)>1:\r\n minimum = 99999\r\n arg1 = 0\r\n arg2 = 0\r\n for rowi in rows:\r\n for rowj in rows:\r\n if(rowi!=rowj):\r\n dist = Euclidean_Distance(rows[rowi],rows[rowj])\r\n if(minimum > dist):\r\n arg1 = rowi\r\n arg2 = rowj\r\n minimum = dist\r\n\r\n row1 = rows[arg1]\r\n row2 = rows[arg2]\r\n ct1 = count[arg1]\r\n ct2 = count[arg2]\r\n row_avg = Average(row1,row2,ct1,ct2)\r\n\r\n #once the cluster is formed the original data points are popped\r\n rows.pop(arg1)\r\n rows.pop(arg2)\r\n count.pop(arg1)\r\n count.pop(arg2)\r\n\r\n s = str(arg1)+\"-\"+str(arg2)\r\n clust.add(s)\r\n rows[s] = row_avg\r\n count[s] = ct1+ct2\r\n minval = min (ct1,ct2)\r\n\r\n if(len(rows)<11):\r\n last_10_cluster.append(minval)\r\n\r\n\r\n print(\"The last 10 minimum cluster sizes are\")\r\n for val in last_10_cluster:\r\n print(str(val))\r\n\r\n myDendrogram(shopping_data)",
"def heatmap(tfidf_matrix, title, xlabel, ylabel, xticklabels, yticklabels):\r\n\r\n # Plot it out\r\n fig, ax = plt.subplots()\r\n c = ax.pcolor(tfidf_matrix, edgecolors='k', linestyle='dashed', cmap=plt.cm.Blues, linewidths=0.2, vmin=0.0,\r\n vmax=1.0)\r\n\r\n # put the major ticks at the middle of each cell\r\n ax.set_yticks(np.arange(tfidf_matrix.shape[0]) + 0.5, minor=False)\r\n ax.set_xticks(np.arange(tfidf_matrix.shape[1]) + 0.5, minor=False)\r\n\r\n # set tick labels\r\n # ax.set_xticklabels(np.arange(1,tfidf_matrix.shape[1]+1), minor=False)\r\n ax.set_xticklabels(xticklabels, minor=False, rotation='vertical')\r\n ax.set_yticklabels(yticklabels, minor=False)\r\n\r\n # set title and x/y labels\r\n plt.title(title)\r\n plt.xlabel(xlabel)\r\n plt.ylabel(ylabel)\r\n\r\n # Remove last blank column\r\n # plt.xlim( (0, tfidf_matrix.shape[1]) )\r\n for i in range(tfidf_matrix.shape[0]):\r\n for j in range(tfidf_matrix.shape[1]):\r\n c = round(tfidf_matrix[i, j], 2)\r\n ax.text(j, i, str(c))\r\n\r\n plt.show()",
"def plot_cluster_composition(self,scaled=False,no_legend=False,ind_plot=False):\n\n colors = list(cm.afmhot(numpy.linspace(0, 0.5, len(self.param_range))));\n\n if ~ind_plot:\n fig, axes = plt.subplots(1,1,sharex=True)\n make_nice_axis(axes);\n else:\n fig, axes = plt.subplots(2,2,sharex=True)\n make_nice_axis(axes[0]) ;\n make_nice_axis(axes[1]);\n make_nice_axis(axes[2]);\n make_nice_axis(axes[3]);\n\n files = list(self.cluster_distribution.keys());\n count_file = 0;\n binding_size = [];\n store_all_means =[];\n self.N_tot = {};\n for file in files:\n if ((self.input_params[count_file]['N_A']) and (scaled)):\n if self.input_params[count_file]['seq_A'].count('A'):\n binding_size.append(self.input_params[count_file]['N_A']*(float((self.input_params[count_file]['seq_A'].count('A'))))*(self.input_params[count_file]['N_bs_AB']+self.input_params[count_file]['N_bs_AC']));\n else:\n binding_size.append(1.0)\n else:\n binding_size.append(1.0);\n\n self.N_tot[count_file] = {};\n traj = list(self.cluster_distribution[file].keys());\n\n size_of_traj = [];\n for tr in traj:\n size_of_traj.append((len(self.cluster_distribution[file][tr].keys())))\n longest_size = max(size_of_traj);\n\n Na = [];\n Nb = [];\n Nc = [];\n Ntot = [];\n count = 0;\n for tr in traj:\n if (len(self.cluster_distribution[file][tr].keys()) == longest_size):\n\n self.N_tot[count_file][count] = [];\n\n time_points = [int(x) for x in self.cluster_distribution[file][tr].keys()];\n\n for t in self.cluster_distribution[file][tr].keys():\n Nc.append([]);\n Nb.append([]);\n Na.append([]);\n Ntot.append([]);\n Nc[count].append((self.cluster_distribution[file][tr][t]['count_types']['C']))\n Nb[count].append((self.cluster_distribution[file][tr][t]['count_types']['B']))\n Na[count].append((self.cluster_distribution[file][tr][t]['count_types']['A']))\n Ntot[count].append(sum(self.cluster_distribution[file][tr][t]['count_types'].values()));\n\n if ~ind_plot:\n axes.plot(time_points,numpy.array(Ntot[count])/float(binding_size[count_file]),color='grey',lw=0.1);\n\n self.N_tot[count_file][count] = numpy.array(Ntot[count])/float(binding_size[count_file]);\n count = count+1;\n if ~ind_plot:\n N_tot_mean = numpy.array(Ntot[0]);\n for p in numpy.arange(1,len(self.N_tot[count_file])):\n N_tot_mean=N_tot_mean+numpy.array(Ntot[p]);\n N_tot_mean = (N_tot_mean)/float(len(self.N_tot[count_file]));\n store_all_means.append([]);\n store_all_means[count_file] = N_tot_mean/binding_size[count_file] ;\n axes.plot(time_points,N_tot_mean/binding_size[count_file],color=colors[count_file],lw=2);\n count_file = count_file +1;\n\n if ~ind_plot:\n if ~no_legend:\n axes.legend(bbox_to_anchor=(1.05,1.1));\n axes.set_xlabel('Time');\n axes.set_ylabel('Number of chains');\n return(N_tot_mean,time_points,axes,store_all_means)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Creates a grid ('quilt') out of an bunch of input patches in patch_data. PARAMS
|
def form_quilt(quilt_w, patch_data):
n_patches = len(patch_data)
quilt_ls = []
for i in range(0, len(patch_data), quilt_w):
# start the row to have something to hstack to
q_row = patch_data[i]
for j in range(i+1, i+quilt_w):
q_row = np.hstack((q_row, patch_data[j]))
quilt_ls.append(q_row)
quilt = quilt_ls[0]
for i in range(1, len(quilt_ls)):
quilt = np.vstack((quilt, quilt_ls[i]))
return quilt
|
[
"def create_patches_test_data(imgs, patch_size, stride, padding):\n # Extract patches from input images\n img_patches = [img_crop(imgs[i], patch_size, patch_size, stride, padding) for i in range(len(imgs))]\n\n # Linearize list of patches, code from tf_aerial_images.py\n img_patches = np.asarray([img_patches[i][j] for i in range(len(img_patches)) for j in range(len(img_patches[i]))])\n\n return img_patches",
"def extract_patches_batch(data: np.ndarray, sourceAxes: Tuple, patchSize: Tuple,\n patchStride: Tuple = None, batchStart: int = 0, batchSize: int = 0):\n\n return CppWrapper.extract_patches_batch(data, sourceAxes, patchSize, patchStride, batchStart, batchSize)",
"def extract_patches(img, patch_size=(3, 3), stride=(1, 1)):\n assert type(patch_size) in [int, tuple], 'patch size should be int or tuple int'\n assert type(stride) in [int, tuple], 'stride size should be int or tuple int'\n if type(stride) is int:\n stride = (stride, stride)\n if type(patch_size) is int:\n patch_size = (patch_size, patch_size)\n patches = img.unfold(2, patch_size[0], stride[0]).unfold(3, patch_size[1], stride[1]) \n patches = patches.contiguous().view(img.shape[0], img.shape[1], -1, patch_size[0], patch_size[1])\n patches = patches.transpose(1, 2)\n return patches",
"def patch_batch_prepare(image, length_stride_list, width_stride_list, patch_size):\n min_x, min_y = 0, 0\n minibatch_patches = []\n img_width, img_length = image.shape\n\n for stride_y in length_stride_list + [0]:\n for stride_x in width_stride_list + [-(img_width - patch_size)]:\n patch = image[min_x:min_x + patch_size, min_y:min_y + patch_size]\n minibatch_patches.append(np.expand_dims(patch, axis=2))\n min_x += stride_x\n min_y += stride_y\n \n return minibatch_patches",
"def extract_patches_shuffle(data_dir='/Users/ryutarotanno/DeepLearning/Test_1/data/',\n save_dir='/Users/ryutarotanno/tmp/IPMI/',\n inputfile_name='dt_b1000_lowres_2_',\n outputfile_name='dt_b1000_',\n upsampling_rate=2,\n receptive_field_radius=2,\n input_radius=5,\n no_channels=6,\n sampling_rate=32,\n chunks=True):\n # --------------------- Load the original and down-sampled DTI volumes ------------------------:\n dti_highres_orig = read_dt_volume(nameroot=os.path.join(data_dir, outputfile_name), no_channels=no_channels)\n dti_lowres_orig = read_dt_volume(nameroot=os.path.join(data_dir, inputfile_name), no_channels=no_channels)\n\n dti_highres_orig[:, :, :, 0] += 1 # adding 1 so brain voxels are valued 1 and background as zero.\n dti_lowres_orig[:, :, :, 0] += 1\n\n # Define width of all patches for brevity:\n input_width, receptive_field_width = 2 * input_radius + 1, 2 * receptive_field_radius + 1\n output_radius = (input_width - receptive_field_width + 1) // 2 # output radius in the high-res space.\n\n # Repeat the following proceadure for all possible subpixel shifts:\n shift_indices = [(i, j, k) for k in xrange(upsampling_rate)\n for j in xrange(upsampling_rate)\n for i in xrange(upsampling_rate)]\n\n print(shift_indices)\n\n total_possible_patches = 0\n filenames_list = []\n\n for itr, (shift_x, shift_y, shift_z) in enumerate(shift_indices):\n start_time = timeit.default_timer()\n\n # ---------------------File name and avoid duplication ----------------------------------------:\n filename = 'Shift%04i.h5' % (itr + 1)\n print(\"\\nCreating shifted file %i/%i ...\" %(itr + 1, len(shift_indices)))\n\n if not(os.path.exists(os.path.join(save_dir, filename))):\n\n # --------------------- Preprocess the volumes: padding & shuffling if required ---------------:\n # Pad with zeros so all brain-voxel-centred pathces are extractable and\n # each dimension is divisible by upsampling rate.\n dim_x_highres, dim_y_highres, dim_z_highres, dim_channels = dti_highres_orig.shape\n pad_min = max((input_radius + 1) * upsampling_rate, (output_radius + 1) * upsampling_rate) # padding width\n\n print(\"The size of HR/LR volumes are: %s and %s\" % (dti_highres_orig.shape, dti_lowres_orig.shape))\n print(\"np.mod(upsampling_rate, 2 * pad_min + dim_x_highres) = %i\" % np.mod(upsampling_rate, 2 * pad_min + dim_x_highres))\n\n pad_x = pad_min if np.mod(2 * pad_min + dim_x_highres, upsampling_rate) == 0 \\\n else pad_min + (upsampling_rate - np.mod(2 * pad_min + dim_x_highres, upsampling_rate))\n\n pad_y = pad_min if np.mod(2 * pad_min + dim_y_highres, upsampling_rate) == 0 \\\n else pad_min + (upsampling_rate - np.mod(2 * pad_min + dim_y_highres, upsampling_rate))\n\n pad_z = pad_min if np.mod(2 * pad_min + dim_z_highres, upsampling_rate) == 0 \\\n else pad_min + (upsampling_rate - np.mod(2 * pad_min + dim_z_highres, upsampling_rate))\n\n dti_highres = np.pad(dti_highres_orig,\n pad_width=((pad_min - shift_x, pad_x + shift_x),\n (pad_min - shift_y, pad_y + shift_y),\n (pad_min - shift_z, pad_z + shift_z), (0, 0)),\n mode='constant', constant_values=0)\n\n brain_mask = dti_highres[::upsampling_rate, ::upsampling_rate, ::upsampling_rate, 0] == 1\n\n dti_lowres = np.pad(dti_lowres_orig,\n pad_width=((pad_min - shift_x, pad_x + shift_x),\n (pad_min - shift_y, pad_y + shift_y),\n (pad_min - shift_z, pad_z + shift_z), (0, 0)),\n mode='constant', constant_values=0)\n\n print(\"The size of HR/LR volumes are: %s and %s\" % (dti_highres.shape, dti_lowres.shape))\n\n # Apply reverse shuffling (optional):\n shuffle_indices = [(i, j, k) for k in xrange(upsampling_rate)\n for j in xrange(upsampling_rate)\n for i in xrange(upsampling_rate)]\n shuffled_arrays = []\n\n for c in xrange(no_channels):\n for (i, j, k) in shuffle_indices:\n shuffled_arrays.append(dti_highres[i::upsampling_rate,\n j::upsampling_rate,\n k::upsampling_rate, c + 2])\n\n del dti_highres # delete the original high-res volume from memory\n\n dti_highres = np.stack(shuffled_arrays, axis=3) # this is the reshuffled version.\n\n del shuffled_arrays # delete the original high-res volume from memory\n\n dti_lowres = dti_lowres[0::upsampling_rate, 0::upsampling_rate, 0::upsampling_rate, :]\n print(\"The size of HR/LR volumes after shuffling are: %s and %s\" % (dti_highres.shape, dti_lowres.shape))\n\n # ---------------------------- Extract patches -----------------------------------------:\n # brain_mask = dti_lowres[:, :, :, 0] == 1\n\n # Get all the indices of voxels in the brain and subsample:\n brain_indices = [(i, j, k) for i in xrange(dti_lowres.shape[0])\n for j in xrange(dti_lowres.shape[1])\n for k in xrange(dti_lowres.shape[2]) if brain_mask[i, j, k] == True]\n\n random.shuffle(brain_indices) # shuffle the brain indices\n\n brain_indices_subsampled = random.sample(brain_indices, len(brain_indices) // sampling_rate)\n total_possible_patches += len(brain_indices)\n print('number of effective patches = %i' % len(brain_indices))\n print('number of selected patches = %i' % len(brain_indices_subsampled))\n\n # Construct patch libraries:\n input_library = np.ndarray((len(brain_indices_subsampled),\n 2 * input_radius + 1,\n 2 * input_radius + 1,\n 2 * input_radius + 1,\n no_channels), dtype='float64')\n\n output_library = np.ndarray((len(brain_indices_subsampled),\n 2 * output_radius + 1,\n 2 * output_radius + 1,\n 2 * output_radius + 1,\n no_channels * upsampling_rate**3), dtype='float64')\n\n for patch_idx, (i, j, k) in enumerate(brain_indices_subsampled):\n input_library[patch_idx, :, :, :, :] = dti_lowres[(i - input_radius):(i + input_radius + 1),\n (j - input_radius):(j + input_radius + 1),\n (k - input_radius):(k + input_radius + 1), 2:]\n\n output_library[patch_idx, :, :, :, :] = dti_highres[(i - output_radius): (i + output_radius + 1),\n (j - output_radius): (j + output_radius + 1),\n (k - output_radius): (k + output_radius + 1), :]\n\n del dti_lowres, dti_highres\n\n print(\"The size of input/output libs are: %s and %s\" % (input_library.shape, output_library.shape))\n\n # -------------------------- Save temporarily for merging ------------------------------:\n try:\n create_hdf5(filename=os.path.join(save_dir, filename),\n input_library=input_library,\n output_library=output_library,\n chunks=chunks)\n\n filenames_list.append(os.path.join(save_dir, filename))\n\n end_time = timeit.default_timer()\n print(\"It took %f secs.\" % (end_time - start_time))\n\n except KeyboardInterrupt:\n os.remove(os.path.join(save_dir, filename))\n print(\"removing %s\" % filename)\n raise\n\n # print(\"total number of possible patchs+ %i \\n\" % total_possible_patches)\n\n else:\n print(\" The file exists already move on ...\")\n\n return filenames_list",
"def patchify(images: torch.Tensor, patch_size: int) -> torch.Tensor:\n # N, C, H, W = (batch_size, channels, height, width)\n N, C, H, W = images.shape\n assert H == W and H % patch_size == 0\n\n patch_h = patch_w = H // patch_size\n num_patches = patch_h * patch_w\n patches = images.reshape(shape=(N, C, patch_h, patch_size, patch_w, patch_size))\n patches = torch.einsum(\"nchpwq->nhwpqc\", patches)\n patches = patches.reshape(shape=(N, num_patches, patch_size**2 * C))\n return patches",
"def _partition_data(self, seed=42):\n if self._shuffle:\n saved_seed = np.random.get_state()\n np.random.seed(seed)\n np.random.shuffle(self._patches_indexes)\n np.random.set_state(saved_seed)\n assert len(self._data_part) == 2\n for perc in self._data_part:\n assert (type(perc) is float) and (perc >= 0.) and (perc <= 1.)\n from_, to_ = self._data_part\n idx_from = int(from_ * len(self._patches_indexes))\n idx_to = int(to_ * len(self._patches_indexes))\n if to_ < 1.:\n self._patches_indexes = self._patches_indexes[idx_from:idx_to]\n elif to_ == 1.:\n self._patches_indexes = self._patches_indexes[idx_from:]\n self.patches = self.patches[self._patches_indexes]\n if self._with_gt:\n self.gt_patches = self.gt_patches[self._patches_indexes]\n self._patches_indexes = np.arange(len(self.patches))",
"def _yield_spatial_table(patch, div, spp_col, count_col, x_col, y_col):\n\n # Catch error if you don't use ; after divs in comm_grid in MacroecoDesktop\n try:\n div_split_list = div.replace(';','').split(',')\n except AttributeError:\n div_split_list = str(div).strip(\"()\").split(',')\n\n div_split = (x_col + ':' + div_split_list[0] + ';' +\n y_col + ':' + div_split_list[1])\n\n # Get cell_locs\n # Requires _parse_splits and _product functions to go y inside of x\n x_starts, x_ends = _col_starts_ends(patch, x_col, div_split_list[0])\n x_offset = (x_ends[0] - x_starts[0]) / 2\n x_locs = x_starts + x_offset\n\n y_starts, y_ends = _col_starts_ends(patch, y_col, div_split_list[1])\n y_offset = (y_ends[0] - y_starts[0]) / 2\n y_locs = y_starts + y_offset\n\n cell_locs = _product(x_locs, y_locs)\n\n # Get spp set and count for all cells\n n_spp_list = [] # Number of species in cell\n n_individs_list = []\n spp_set_list = [] # Set object giving unique species IDs in cell\n for cellstring, cellpatch in _yield_subpatches(patch,div_split,name='div'):\n spp_set = set(np.unique(cellpatch.table[spp_col]))\n spp_set_list.append(spp_set)\n n_spp_list.append(len(spp_set))\n n_individs_list.append(np.sum(cellpatch.table[count_col]))\n\n # Create and return dataframe\n df = pd.DataFrame({'cell_loc': cell_locs, 'spp_set': spp_set_list,\n 'n_spp': n_spp_list, 'n_individs': n_individs_list})\n\n return df",
"def tile_image(image: np.ndarray, patch_size: Tuple, patch_stride=None) -> Tuple:\n points = _calculate_tiles(image.shape, patch_size, patch_stride)\n\n # return a list of patches\n patches = []\n\n for i in range(len(points)):\n start_point = points[i]\n end_point = (start_point[0] + patch_size[0], start_point[1] + patch_size[1])\n patch = image[start_point[0]:end_point[0], start_point[1]:end_point[1]]\n patches.append(patch)\n\n return patches, points",
"def assemble_patches(patches, stride, out, fake):\n out_shape = np.zeros(3)\n out_shape[:] = out.shape[:]\n\n # cast patch.shape to ndarray\n patch_shape = np.zeros(3)\n patch_shape[:] = patches.shape[1:]\n\n # compute the number of sections\n num_sections = (out_shape - patch_shape) // stride + 1\n\n # iterate over patches, put them into corresponding place in out\n # also increment pixel weight if it belongs to a patch\n weights_inv = np.zeros_like(out)\n ctr = 0\n for ix in range(int(num_sections[0])):\n for iy in range(int(num_sections[1])):\n for iz in range(int(num_sections[2])):\n slc_x = slice(ix * stride[0], ix * stride[0] + patch_shape[0])\n slc_y = slice(iy * stride[1], iy * stride[1] + patch_shape[1])\n slc_z = slice(iz * stride[2], iz * stride[2] + patch_shape[2])\n out[slc_x, slc_y, slc_z] += patches[ctr, :, :, :]\n weights_inv[slc_x, slc_y, slc_z] += 1.0\n ctr += 1\n\n # weight resulting image\n out /= weights_inv",
"def extract_all_patches(Xtr, patch_width):\n # We will work on images and patches of shape (None, width, height, 3)\n Xtr = vec2img(Xtr)\n img_width = Xtr.shape[1]\n patch_per_side = img_width // patch_width\n n_patches = patch_per_side**2\n\n coords = np.arange(0, img_width - patch_width + 1, patch_width)\n top_left_X, top_left_Y = np.meshgrid(coords, coords)\n top_left_X = top_left_X.flatten()\n top_left_Y = top_left_Y.flatten()\n top_left_X = top_left_X.repeat(patch_width * patch_width)\\\n .reshape(n_patches, patch_width, patch_width)\n top_left_Y = top_left_Y.repeat(patch_width * patch_width)\\\n .reshape(n_patches, patch_width, patch_width)\n X, Y = np.meshgrid(range(patch_width), range(patch_width))\n X = np.expand_dims(X, axis=0).repeat(n_patches, axis=0)\n Y = np.expand_dims(Y, axis=0).repeat(n_patches, axis=0)\n X += top_left_X\n Y += top_left_Y\n\n patches = Xtr[:, Y, X, :]\n return patches",
"def _extract_3d_patches(arr, patch_radius):\n if isinstance(patch_radius, int):\n patch_radius = np.ones(3, dtype=int) * patch_radius\n if len(patch_radius) != 3:\n raise ValueError(\"patch_radius should have length 3\")\n else:\n patch_radius = np.asarray(patch_radius, dtype=int)\n patch_size = 2 * patch_radius + 1\n\n dim = arr.shape[-1]\n\n all_patches = []\n\n # loop around and find the 3D patch for each direction\n for i in range(patch_radius[0], arr.shape[0] -\n patch_radius[0], 1):\n for j in range(patch_radius[1], arr.shape[1] -\n patch_radius[1], 1):\n for k in range(patch_radius[2], arr.shape[2] -\n patch_radius[2], 1):\n\n ix1 = i - patch_radius[0]\n ix2 = i + patch_radius[0] + 1\n jx1 = j - patch_radius[1]\n jx2 = j + patch_radius[1] + 1\n kx1 = k - patch_radius[2]\n kx2 = k + patch_radius[2] + 1\n\n X = arr[ix1:ix2, jx1:jx2,\n kx1:kx2].reshape(np.prod(patch_size), dim)\n all_patches.append(X)\n\n return np.array(all_patches).T",
"def patches(self):\n return multiplied(*[p.selection() for p in self._patches])",
"def fig_patches(fig_side,patch_side,filename,\n data=None,mix=None,rand_flip=True):\n L = fig_side\n fig = init_fig(L)\n pl.gray()\n\n if mix!=None:\n ks = np.arange(mix.K,dtype=int)\n ind = np.argsort(mix.amps)\n ks = ks[ind]\n ref = np.arange(mix.K)\n amps = mix.amps[ind]\n cum = np.zeros(mix.K)\n for ii in range(mix.K):\n cum[ii] = np.sum(amps[:ii+1])\n\n for ii in range(L**2):\n if data!=None:\n patch = data[ii,:]\n else:\n rnd = np.random.rand()\n ind = ref[cum>rnd]\n k = ks[ind[0]]\n patch = np.random.multivariate_normal(mix.means[k],mix.covs[k])\n patch = np.array(patch) # is this necessary?\n \n if rand_flip:\n p = Patches(np.atleast_2d(patch),None,\n patched=True,flip=False,\n rand_flip=rand_flip)\n patch = p.data \n\n ax = fig.add_subplot(L,L,ii+1)\n ax.imshow(patch.reshape((patch_side,patch_side)),\n origin='lower',interpolation='nearest',\n vmin=np.min(patch)*1.001,vmax=np.max(patch)*0.999)\n ax.set_xticklabels([])\n ax.set_yticklabels([])\n\n fig.savefig(filename)",
"def gridwise_sample(imgarray, patchsize, rs):\r\n patchidx = []\r\n nrows, ncols, nbands = imgarray.shape\r\n patchsamples = np.zeros(shape=(0, patchsize, patchsize, nbands),\r\n dtype=imgarray.dtype)\r\n for i in range(round(nrows / patchsize)):\r\n for j in range(round(ncols / patchsize)):\r\n if i+1 <= int(nrows / patchsize) and j+1 <= int(ncols / patchsize):\r\n tocat = imgarray[i * patchsize:(i + 1) * patchsize,\r\n j * patchsize:(j + 1) * patchsize, :]\r\n tocat = np.expand_dims(tocat, axis=0) / rs\r\n patchsamples = np.concatenate((patchsamples, tocat), axis=0)\r\n patchidx.append([i, j])\r\n elif i+1 <= int(nrows / patchsize) and j+1 >= int(ncols / patchsize):\r\n tocat = imgarray[i * patchsize:(i + 1) * patchsize, -patchsize:, :]\r\n tocat = np.expand_dims(tocat, axis=0) / rs\r\n patchsamples = np.concatenate((patchsamples, tocat), axis=0)\r\n patchidx.append([i, j])\r\n elif i+1 >= int(nrows / patchsize) and j+1 <= int(ncols / patchsize):\r\n tocat = imgarray[-patchsize:, j * patchsize:(j + 1) * patchsize, :]\r\n tocat = np.expand_dims(tocat, axis=0) / rs\r\n patchsamples = np.concatenate((patchsamples, tocat), axis=0)\r\n patchidx.append([i, j])\r\n elif i+1 >= int(nrows / patchsize) and j+1 >= int(ncols / patchsize):\r\n tocat = imgarray[-patchsize:, -patchsize:, :]\r\n tocat = np.expand_dims(tocat, axis=0) / rs\r\n patchsamples = np.concatenate((patchsamples, tocat), axis=0)\r\n patchidx.append([i, j])\r\n\r\n return patchsamples, patchidx",
"def reconstruct_infer_patches(predictions, infer_dir, params):\n\n # define params - converting all to python native variables as they may be imported as numpy\n patch_size = params.infer_dims\n overlap = params.infer_patch_overlap\n data_prefix = [str(item) for item in params.data_prefix]\n data_format = params.data_format\n data_plane = params.data_plane\n\n # for sliding window 2d patches - must be same as in _tf_patches_infer above\n ksizes = [1] + patch_size + [1]\n strides = [1, patch_size[0] / overlap[0], patch_size[1] / overlap[1], 1]\n rates = [1, 1, 1, 1]\n\n # define necessary functions\n def extract_patches(x):\n return tf.image.extract_patches(x, sizes=ksizes, strides=strides, rates=rates, padding='SAME')\n\n def extract_patches_inverse(x, y):\n with tf.GradientTape(persistent=True) as tape:\n _x = tf.zeros_like(x)\n tape.watch(_x)\n _y = extract_patches(_x)\n grad = tape.gradient(_y, _x)\n # Divide by grad, to \"average\" together the overlapping patches\n # otherwise they would simply sum up\n return tape.gradient(_y, _x, output_gradients=y) / grad\n\n # load original data as a dummy and convert channel dim size to match output [batch, x, y, z, channel]\n data = load_multicon_preserve_size(infer_dir, data_prefix, data_format, data_plane)\n data = np.zeros((data.shape[0:4] + (params.output_filters,)), dtype=np.float32)\n # data = data[:, :, :, [0]] if params.data_format == 'channels_last' else data[:, [0], :, :]\n\n # get shape of patches as they would have been generated during inference\n dummy_shape = tf.shape(input=extract_patches(data))\n\n # convert channels dimension to actual output_filters\n if params.data_format == 'channels_last':\n dummy_shape = dummy_shape[:-1] + [params.output_filters]\n else:\n dummy_shape = [dummy_shape[0], params.output_filters] + dummy_shape[2:]\n\n # reshape predictions to original patch shape\n predictions = tf.reshape(predictions, dummy_shape)\n\n # reconstruct\n reconstructed = extract_patches_inverse(data, predictions)\n output = np.squeeze(reconstructed.numpy())\n\n return output",
"def build_patches(brick, proj_size=100):\n patches = []\n\n # Get the patch FITS file\n path = phat_brick_path(brick, 'F814W')\n with fits.open(path) as f:\n header = fits.getheader(f, 0)\n wcs = astropy.wcs.WCS(header)\n\n # degree per pixel\n pixel_scale = np.mean(\n np.sqrt(astropy.wcs.utils.proj_plane_pixel_scales(wcs) ** 2.))\n\n theta = np.rad2deg(np.arctan(proj_size / (785. * 10. ** 3.)))\n\n n_pix_side_min = theta / pixel_scale\n\n # Number of boxes, in each dimension so each box is *at least*\n # proj_size on each size.\n nx = np.floor(header['NAXIS1'] / n_pix_side_min)\n ny = np.floor(header['NAXIS2'] / n_pix_side_min)\n\n x_edges = np.linspace(0, header['NAXIS1'], num=nx + 1,\n endpoint=True, dtype=int)\n y_edges = np.linspace(0, header['NAXIS2'], num=ny + 1,\n endpoint=True, dtype=int)\n\n patch_num = 1\n for i in xrange(nx):\n for j in xrange(ny):\n x1 = x_edges[i]\n x2 = x_edges[i + 1]\n y1 = y_edges[i]\n y2 = y_edges[i + 1]\n xy_verts = np.array([[x1, y1],\n [x1, y2],\n [x2, y2],\n [x2, y1]])\n radec = wcs.all_pix2world(xy_verts, 0)\n # projected arcsec^2\n area_proj = (y2 - y1) * (x2 - x1) * (pixel_scale * 3600.) ** 2.\n # area in pc^2, de-projected\n pc_per_arcsec = 785. * 10. ** 3. * np.tan(np.deg2rad(1. / 3600))\n area = area_proj * (pc_per_arcsec) ** 2. / np.cos(77 * np.pi / 180.) # NOQA\n ra0 = radec[:, 0].mean()\n dec0 = radec[:, 1].mean()\n r_kpc, phi = compute_patch_gal_coords(ra0, dec0)\n patch = {'patch': '{0:02d}_{1:03d}'.format(brick, patch_num),\n 'brick': brick,\n 'poly': radec.tolist(),\n 'ra0': ra0,\n 'dec0': dec0,\n 'r_kpc': r_kpc,\n 'phi': phi,\n 'area_proj': area_proj,\n 'area': area}\n patches.append(patch)\n patch_num += 1\n\n return patches",
"def make_centered_rotated_patches(photfile, patch_dir, img_dir, ind_file, name,\n PA_final=45.,\n patch_size=25, start=0, end=None,\n do_shift=True, do_rotation=True,\n floor=1.e-5):\n assert end != -1, 'Use actual end, not -1'\n f = pf.open(photfile)\n data = f[1].data\n f.close()\n\n # only gri get to vote on rotation angle\n angles = data['fracdev_g'] * data['devphi_g']\n angles += (1. - data['fracdev_g']) * data['expphi_g']\n for f in 'ri':\n angles += data['fracdev_' + f] * data['devphi_' + f]\n angles += (1. - data['fracdev_' + f]) * data['expphi_' + f]\n angles /= 3.\n\n # read spec z file with indicies in first column\n info = np.loadtxt(ind_file)\n if end is None:\n end = len(info[:, 0])\n inds = info[start:end, 0].astype(np.int)\n\n os.chdir(img_dir)\n for i in inds:\n print i\n patch_file = patch_dir + name + '_%s.fits' % str(data['specobjid'][i])\n if os.path.exists(patch_file):\n continue\n\n run = str(data['run'][i])\n field = str(data['field'][i])\n camcol = str(data['camcol'][i])\n\n nz = 6 - len(run)\n filled_run = '0' * nz + run\n nz = 4 - len(field)\n filled_field = '0' * nz + field\n\n filts = 'ugriz'\n frames = ['./%s/frame-%s-%s-%s-%s.fits.bz2' % (run, f, filled_run,\n camcol, filled_field)\n for f in 'ugriz']\n\n out_patch_data = np.zeros((patch_size ** 2., 5))\n od = np.zeros((patch_size ** 2., 5))\n for j in range(5):\n # check that image exists\n if not os.path.exists(frames[j]):\n print os.getcwd()\n print frames[j]\n assert False, 'Image frame has not been downloaded.'\n\n # unpack data and read image\n img_file = frames[j]\n os.system('bzip2 -d %s' % frames[j])\n f = pf.open(frames[j][:-4])\n os.system('bzip2 %s' % frames[j][:-4])\n img = f[0].data\n f.close()\n\n # floor the row and col centers\n flrr = np.floor(data['rowc_' + filts[j]][i])\n flrc = np.floor(data['colc_' + filts[j]][i])\n\n # get patch centered on the floored centers\n patch = get_orig_patch(img, patch_size, flrr, flrc)\n if floor is not None:\n patch = np.maximum(floor, patch)\n\n if do_shift | do_rotation:\n pmx = patch.max()\n rng = pmx - floor\n patch = (patch - floor) / rng\n shift, rotation = None, None\n if do_shift:\n # find subpixel shift and move to center of pixel\n dltr = data['rowc_' + filts[j]][i] - flrr - 0.5\n dltc = data['colc_' + filts[j]][i] - flrc - 0.5\n shift = -1. * np.array([dltr, dltc])\n tform = AffineTransform(translation=shift)\n patch = warp(patch, tform)\n if do_rotation:\n # rotate by the model angle\n rotation = -45. - angles[i]\n patch = rotate(patch, rotation)\n \n # restore the image brighness\n patch = patch * rng + floor\n try:\n out_patch_data[:, j] = patch.ravel()\n except:\n f = open(img_dir + 'failedinds.txt', 'a')\n f.write('%d\\n' % i)\n f.close()\n\n hdu = pf.PrimaryHDU(out_patch_data)\n hdu.writeto(patch_file)",
"def _patch_slices(self, i, j, k, radius):\n g00 = self._curve.metric.component_matrix(0, 0)\n r = radius\n return (\n slice(max(g00.xidx, i-r), i+r+1),\n slice(max(g00.yidx, j-r), j+r+1),\n slice(k-r, k+r+1)\n )"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Compute the reconstruction error of the array `XV`, which should be just np.dot(X, V). Both XV and original should be 01 normalized. PARAMS
|
def get_reconstruction_error(XV, original, alpha):
err_arr = []
loss_arr = []
for i in range(len(XV)):
err = np.sqrt(np.sum((XV[i]-original[i])**2))
err_arr.append(err)
err_arr = np.array(err_arr)
# Get the stats
err_mean = np.average(err_arr)
err_sd = np.sqrt(np.var(err_arr))
return err_arr, err_mean, err_sd
|
[
"def reconstruction_error(self, X):\n \n Z = self.reconstruct_input(X) \n L = self.loss(X,Z)\n return T.mean(L)",
"def compute_reconstruction_error(self, X0, X0RM=None):\n if X0RM is None:\n _,X0RM,_,_,_=self.mean_field_approximate_inference(X0,NMF=self.NMF,rand_init_H=False)\n if self.visible_type==\"Multinoulli\":\n self.rec_error=0\n for m in range(self.M):\n self.rec_error=self.rec_error+numpy.mean(numpy.abs(X0RM[m]-X0[m]))\n else:\n self.rec_error=numpy.mean(numpy.abs(X0RM-X0))\n return self.rec_error",
"def v_err(self):\n if self.outbound_basis:\n return norm(self.outbound_v) - norm(self.inbound_v)\n else:\n return norm(self.inbound_v) - norm(self.outbound_v)",
"def vae_loss(x, xr, z_mu, z_log_sigma2, x_sigma2):\n loss, data_loss, kldiv_loss = None, None, None\n # TODO: Implement the VAE pointwise loss calculation.\n # Remember:\n # 1. The covariance matrix of the posterior is diagonal.\n # 2. You need to average over the batch dimension.\n # ====== YOUR CODE: ======\n flat_it = lambda a: a.view(a.shape[0],-1)\n x = flat_it(x)\n xr = flat_it(xr)\n\n data_loss = (x-xr) ** 2\n data_loss = data_loss.sum() / data_loss.numel() / x_sigma2\n\n kldiv_loss = z_log_sigma2.exp().sum(dim=1)\n kldiv_loss += (z_mu ** 2).sum(dim=1)\n kldiv_loss -= z_mu.size(1)\n kldiv_loss -= z_log_sigma2.sum(dim=1)\n kldiv_loss = kldiv_loss.sum() / kldiv_loss.numel()\n\n\n loss = data_loss + kldiv_loss\n # ========================\n\n return loss, data_loss, kldiv_loss",
"def impact_parameter_error(true_x, reco_x, true_y, reco_y):\n return np.sqrt((reco_x - true_x) ** 2 + (reco_y - true_y) ** 2)",
"def transform(X,V,in_place=False):\n Xk = check_arrays(X)\n if not in_place:\n Xk = Xk.copy()\n n, p = Xk.shape\n N_COMP = V.shape[1]\n if p != V.shape[0]:\n raise ValueError(\"The argument must have the same number of \"\n \"columns than the datset used to fit the \"\n \"estimator.\")\n U = np.zeros((n, N_COMP))\n d = np.zeros((N_COMP))\n for k in range(N_COMP):\n # Project on component j\n vk = V[:, k].reshape(-1, 1)\n uk = np.dot(X, vk)\n uk /= np.linalg.norm(uk)\n U[:, k] = uk[:, 0]\n dk = compute_d(Xk, uk, vk)\n d[k] = dk\n # Residualize\n Xk -= dk * np.dot(uk, vk.T)\n return U,d",
"def error(pars, func, x, y):\n return rms(func(pars, x) - y)",
"def calculate_crossval_err ( self ):\n xval_err = 0.0\n for i in xrange( self.obs.npt ):\n if self.xval[i] == -1:\n difference = self.obs.observations[ i, :self.obs.nbands[i] ] - \\\n self.rt.brf[ i, :self.obs.nbands[i] ]\n inv_obs_covar = self.obs.obsinvcovar[i]\n part1 = np.dot ( inv_obs_covar, difference )\n xval_err += np.dot( part1, difference )\n \n for j in xrange ( self.obs.nbands[i] ):\n info_str = \"Doy: %d Obs #%d: \" % ( self.obs.doys[i], i )\n info_str = info_str + \"B%d Obs: %g Model: %g Dif: %g\" % \\\n ( j+1, self.obs.observations[ i, j ], \\\n self.rt.brf [i,j], self.obs.observations[ i, j ] - \\\n self.rt.brf [i,j] )\n self.logger.info ( info_str )\n return ( xval_err, self.params_x, self.rt.brf, self.obs.observations )",
"def reconstruct(self, X):\n assert len(X.shape) == 2, f\"X must be a NxK matrix. Got: {X.shape}\"\n (K, N) = X.shape\n assert K > 0, f\"dimensionality of state representation must be at least 1. Got: {K}\"\n D = self.mean.shape[0]\n\n Y = self.V @ X + self.mean\n\n assert Y.shape == (D, N), f\"Y shape mismatch. Expected: {(D, N)}. Got: {Y.shape}\"\n return Y",
"def rescale_V(V, om, V_max, om_max):\n ########## Code starts here ##########\n V_tilde = np.zeros(len(V))\n for i in range(len(V)):\n \tV_tilde[i] = np.amin([.5,np.absolute(V[i]/om[i]),np.absolute(V[i])]) # set to V to be minimum of V constraint, calculated value of V_tilde w/ om_tilde set to 1 (om constraint), and current value\n ########## Code ends here ##########\n return V_tilde",
"def decomposition_error(X, decomp):\n # Collect square errors of each corresponding cells in X and the decomposition\n square_errors = []\n square_xs = []\n for i in range(X.shape[0]):\n for j in range(X.shape[1]):\n # sq_er metric is all that is needed for MSE\n sq_er = (X[i,j] - decomp[i,j])**2\n square_errors.append(sq_er)\n # square_x norm is the distance from a cell in the decomposition and\n # the point of origin. Necessary for the NMSE metric.\n square_xs.append(decomp[i,j]**2)\n # Mean Square Error as the sum of squares divided by the size of the matrix.\n MSE = np.sum(square_errors)/X.size\n\n # Normalized Mean Square Error\n NMSE_denominator = np.sum(square_xs)/X.size\n NMSE= MSE/NMSE_denominator\n\n # Peak Signal to Noise Ratio\n PSNR = 20 * math.log((255/np.sqrt(MSE)), 10)\n\n # Root Mean Standard Deviation\n RMSD = np.sqrt(MSE)\n\n # Normalized Root Mean Standard Deviation.\n NRMSD = RMSD/np.mean(square_errors)\n\n return MSE, NMSE, RMSD, NRMSD, PSNR",
"def _estimate_error(self):\n dtc = float(self.dt)\n delb = self.delb\n\n if self.num_fields == 1:\n ks = self.ks\n self.error_func.dat.data[:] = 0.0\n for i in range(self.num_stages):\n self.error_func += dtc * delb[i] * ks[i]\n else:\n k = self.stages\n for i in range(self.num_fields):\n self.error_func.dat.data[i][:] = 0.0\n for s in range(self.num_stages):\n for i in range(self.num_fields):\n self.error_func.dat.data[i][:] += \\\n dtc * delb[s] * k.dat.data[self.num_fields*s+i][:]\n\n return norm(self.error_func)",
"def uAvProductErrorProp(u, v, S):\n u = np.matrix(u).reshape(1,3)\n v = np.matrix(v).reshape(1,3)\n rows = S.shape[0]\n cols = S.shape[1]\n SUM = 0\n for i in range(rows):\n for j in range(cols):\n SUM += (u[0,i]*v[0,j]*S[i,j])**2\n return np.sqrt(SUM)",
"def reconstruction_error_limited(self, X, limit):\n \n Z = self.reconstruct_input_limited(X, limit) \n L = self.loss(X,Z)\n return T.mean(L)",
"def predict(self):\n\n m, n = self.X.shape\n pdist = 1e9 #very large number\n\n # convert ndarrays to matrices for cleaner code\n V = np.matrix(self.X)\n W = np.matrix(np.random.rand(m, self.k))\n\n # VV^T calculated ahead of time\n VV = V * V.T\n\n # flags and counters for checking convergence\n dist = 0\n converged = False\n convgraph = np.zeros(self.maxiter / 10)\n\n for i in range(self.maxiter):\n\n # multiplicative update step, Euclidean error reducing\n num = VV * W\n denom = (W * (W.T * VV * W)) + (VV * W * (W.T * W))\n # W = np.multiply(W, np.divide(num, denom))\n\n W = np.divide(np.multiply(W, num), denom)\n\n # W = W .* (XX*W) ./ (W*(W'*XX*W) + XX*W*(W'*W));\n # W = W ./ norm(W);\n\n # normalize W TODO: check if L2 norm working similar to MATLAB\n W /= np.linalg.norm(W, 2)\n\n # every 10 iterations, check convergence\n if i % 10 == 0:\n dist = frobenius(V, W*W.T*V)\n convgraph[i/10] = dist\n\n if pdist - dist < self.stopconv:\n converged = True\n break\n\n pdist = dist\n\n return NMFResult((np.array(W),), convgraph, dist, converged)",
"def get_error_vector(self):\n return self.yerr",
"def find_closest_TRS_to_multivector(V):\n def residual_cost(biv_params):\n R = TRS_biv_params_to_biv(biv_params)\n return np.sum(np.abs(R.value - V.value)**2)\n x0 = np.random.randn(7) * 0.00001\n res = minimize(residual_cost, x0, method='L-BFGS-B')\n return TRS_biv_params_to_rotor(res.x).clean(0.00001).normal()",
"def get_error(self, X, Y):\n \n A_L = self.forward(X)\n return losses[self.loss]['error'](A_L, Y)",
"def get_vali_error(self, x, y_val, H_val, para):\n y_pred = np.dot(H_val, x)\n return np.linalg.norm(y_val - y_pred, 2)**2 / len(y_val) / 2."
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Locate where cuda is installed on the system. Return a dict with values 'home', 'nvcc', 'sdk', 'include' and 'lib' and values giving the absolute path to each directory. Looks for the CUDAHOME environment variable. If not found, searches $PATH for 'cuda' and 'nvcc'.
|
def locate_cuda():
home = None
if platform.architecture()[0]=='64bit':
arch = '64'
else:
arch = ''
if 'CUDAHOME' in os.environ:
home = os.environ['CUDAHOME']
nvcc = pjoin(home, 'bin', 'nvcc')
else:
# Otherwise search PATH for cuda and nvcc
for element in os.environ['PATH'].split(os.pathsep):
if element.find('cuda')>-1:
home = element.rstrip('/bin')
nvcc = pjoin(home, 'bin', 'nvcc')
elif element.find('nvcc')>-1:
nvcc = os.path.abspath(element)
home = os.path.dirname(os.path.dirname(element))
if not home:
raise EnvironmentError('The nvcc binary could not be located be '
'located in your $PATH. Either add it to your path, or set '
'the CUDAHOME environment variable.')
cudaconfig = {'home':home, 'nvcc':nvcc,
'sdk':pjoin(home, 'samples'),
'include':pjoin(home, 'include'),
'lib':pjoin(home, 'lib'+arch) }
for key, val in cudaconfig.items():
if not os.path.exists(val):
raise EnvironmentError('The CUDA path {:s} could not be located in {:s}'.format(key, val))
if 'CUDACOMPUTE' in os.environ:
cudaconfig['sm'] = '{:d}'.format(int(10*float(os.environ['CUDACOMPUTE'])))
cudaconfig['compute'] = '{:d}'.format(int(10*float(os.environ['CUDACOMPUTE'])))
else:
raise EnvironmentError("The 'CUDACOMPUTE' environment variable was "
"was not set.")
# print("-gencode=arch=compute_{:s},code=sm_{:s}".format(cudaconfig['compute'],cudaconfig['sm']))
return cudaconfig
|
[
"def locate_cuda():\n \n # first check if the CUDAHOME env variable is in use\n if 'CUDAHOME' in os.environ:\n home = os.environ['CUDAHOME']\n nvcc = join(home, 'bin', 'nvcc')\n else:\n # otherwise, search the PATH for NVCC\n nvcc = find_in_path('nvcc', os.environ['PATH'])\n if nvcc is None:\n raise EnvironmentError('The nvcc binary could not be located in your $PATH. Either add it to your path, or set $CUDAHOME')\n home = os.path.dirname(os.path.dirname(nvcc))\n cudaconfig = {'home': home, 'nvcc': nvcc, 'include': join(home, 'include'), 'lib64': join(home, 'lib64')}\n \n for k, v in cudaconfig.iteritems():\n if not os.path.exists(v):\n raise EnvironmentError('The CUDA %s path could not be located in %s' % (k, v))\n\n return cudaconfig",
"def getCudaPaths():\n\n\t# determine defaults\n\tif os.name == 'posix':\n\t\tbin_path = '/usr/local/cuda/bin'\n\t\tlib_path = '/usr/local/cuda/lib'\n\t\tinc_path = '/usr/local/cuda/include'\n\telse:\n\t\traise ValueError, 'Error: unknown OS. Where is nvcc installed?'\n\t \n\tif platform.machine()[-2:] == '64':\n\t\tlib_path += '64'\n\n\t# override with environement variables\n\tif 'CUDA_BIN_PATH' in os.environ:\n\t\tbin_path = os.path.abspath(os.environ['CUDA_BIN_PATH'])\n\tif 'CUDA_LIB_PATH' in os.environ:\n\t\tlib_path = os.path.abspath(os.environ['CUDA_LIB_PATH'])\n\tif 'CUDA_INC_PATH' in os.environ:\n\t\tinc_path = os.path.abspath(os.environ['CUDA_INC_PATH'])\n\n\treturn (bin_path,lib_path,inc_path)",
"def _find_home():\n\n # this is used below to make fix up encoding issues that sometimes crop up\n # in py2.x but not in py3.x\n if PY2:\n decodepath = lambda pth: pth.decode(sys.getfilesystemencoding())\n elif PY3:\n decodepath = lambda pth: pth\n\n # First find the home directory - this is inspired by the scheme ipython\n # uses to identify \"home\"\n if os.name == 'posix':\n # Linux, Unix, AIX, OS X\n if 'HOME' in os.environ:\n homedir = decodepath(os.environ['HOME'])\n else:\n raise OSError('Could not find unix home directory to search for '\n 'astropy config dir')\n elif os.name == 'nt': # This is for all modern Windows (NT or after)\n if 'MSYSTEM' in os.environ and os.environ.get('HOME'):\n # Likely using an msys shell; use whatever it is using for its\n # $HOME directory\n homedir = decodepath(os.environ['HOME'])\n # Next try for a network home\n elif 'HOMESHARE' in os.environ:\n homedir = decodepath(os.environ['HOMESHARE'])\n # See if there's a local home\n elif 'HOMEDRIVE' in os.environ and 'HOMEPATH' in os.environ:\n homedir = os.path.join(os.environ['HOMEDRIVE'],\n os.environ['HOMEPATH'])\n homedir = decodepath(homedir)\n # Maybe a user profile?\n elif 'USERPROFILE' in os.environ:\n homedir = decodepath(os.path.join(os.environ['USERPROFILE']))\n else:\n try:\n from .six.moves import winreg as wreg\n shell_folders = r'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders'\n key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, shell_folders)\n\n homedir = wreg.QueryValueEx(key, 'Personal')[0]\n homedir = decodepath(homedir)\n key.Close()\n except:\n # As a final possible resort, see if HOME is present\n if 'HOME' in os.environ:\n homedir = decodepath(os.environ['HOME'])\n else:\n raise OSError('Could not find windows home directory to '\n 'search for astropy config dir')\n else:\n # for other platforms, try HOME, although it probably isn't there\n if 'HOME' in os.environ:\n homedir = decodepath(os.environ['HOME'])\n else:\n raise OSError('Could not find a home directory to search for '\n 'astropy config dir - are you on an unspported '\n 'platform?')\n return homedir",
"def get_cuda_info():\n use_cuda = False\n multi_gpu = False\n\n if torch.cuda.is_available() and os.environ['CUDA_VISIBLE_DEVICES'] != \"\":\n gpu_ids = os.environ['CUDA_VISIBLE_DEVICES'].split()\n use_cuda = True\n logging.info('CUDA support is active')\n\n if len(gpu_ids) > 1:\n logging.info('MultiGPU support is active')\n multi_gpu = True\n\n return use_cuda, multi_gpu",
"def _get_device_dirs():\n try:\n user_devices = LabConfig().get('DEFAULT', 'user_devices')\n except (LabConfig.NoOptionError, LabConfig.NoSectionError):\n user_devices = 'user_devices'\n # Split on commas, remove whitespace:\n user_devices = [s.strip() for s in user_devices.split(',')]\n return _get_import_paths(['labscript_devices'] + user_devices)",
"def check_cuda():\n is_available = cuda.is_available()\n is_initialized = cuda.is_initialized()\n device_count = cuda.device_count()\n\n logger.info(f\"[CUDA] is_available: {is_available}, is_initialized: {is_initialized}.\")\n logger.info(f\"Found {device_count} CUDA device(s).\")\n for device_id in range(device_count):\n logger.info(f\"[cuda:{device_id}] {cuda.get_device_properties(device_id)}\")\n\n if is_available:\n logger.info(f\"Current device: [cuda:{cuda.current_device()}] ({cuda.get_device_name()}, Compute Capability: {cuda.get_device_capability()})\")\n\n return device_count",
"def _gpu_info_subprocess():\n total_gpus = 0\n total_mem = 0\n try:\n import py3nvml.py3nvml\n py3nvml.py3nvml.nvmlInit()\n total_gpus = py3nvml.py3nvml.nvmlDeviceGetCount()\n\n import os\n cudavis = os.getenv(\"CUDA_VISIBLE_DEVICES\")\n if cudavis is not None:\n lencudavis = len(cudavis)\n if lencudavis == 0:\n total_gpus = 0\n else:\n total_gpus =\\\n min(total_gpus,\n os.getenv(\"CUDA_VISIBLE_DEVICES\").count(\",\") + 1)\n\n total_mem = \\\n min([py3nvml.py3nvml.nvmlDeviceGetMemoryInfo(\n py3nvml.py3nvml.nvmlDeviceGetHandleByIndex(i)).total for i in\n range(total_gpus)])\n except NVMLError as e:\n print(\"No GPU, setting total_gpus=0 and total_mem=0\")\n print(e)\n sys.stdout.flush()\n return total_gpus, total_mem",
"def get_cuda_devices():\n mask = os.environ['CUDA_VISIBLE_DEVICES']\n if mask == '':\n return []\n else:\n return [int(d.strip()) for d in mask.split(',')]",
"def get_home_path(self):\n\n if sys.platform == 'win32':\n drive = os.environ['HOMEDRIVE']\n path = os.environ['HOMEPATH']\n path = os.path.join(drive, path)\n elif sys.platform == 'linux2':\n path = os.environ['HOME']\n else: # assume UNIX, whatever\n path = os.environ['HOME']\n\n return path",
"def locate_hdf5():\n\n home = None\n if platform.architecture()[0]=='64bit':\n arch = '64'\n else:\n arch = ''\n if 'HDF5_BASE' in os.environ:\n home = os.environ['HDF5_BASE']\n else:\n raise EnvironmentError('Unable to locate the HDF libraries on '\n 'this system. Set the HDF5_BASE environment variable.')\n\n hdfconfig = {'home':home,\n 'lib':pjoin(home, 'lib'),\n 'include':pjoin(home, 'include')}\n for key, val in hdfconfig.items():\n if not os.path.exists(val):\n raise EnvironmentError('Could not locate {:s} in path {:s}'.format(key, val))\n return hdfconfig",
"def get_cudnn_version():\n if get_platform() == \"win32\":\n system_root = os.environ.get(\"SYSTEMROOT\", \"C:\\\\Windows\")\n cuda_path = os.environ.get(\"CUDA_PATH\", \"%CUDA_PATH%\")\n where_cmd = os.path.join(system_root, \"System32\", \"where\")\n cudnn_cmd = '{} /R \"{}\\\\bin\" cudnn*.dll'.format(where_cmd, cuda_path)\n elif get_platform() == \"darwin\":\n # CUDA libraries and drivers can be found in /usr/local/cuda/. See\n cudnn_cmd = \"ls /usr/local/cuda/lib/libcudnn*\"\n else:\n cudnn_cmd = 'ldconfig -p | grep libcudnn | rev | cut -d\" \" -f1 | rev'\n rc, out, _ = run(cudnn_cmd)\n # find will return 1 if there are permission errors or if not found\n if len(out) == 0 or (rc != 1 and rc != 0):\n l = os.environ.get(\"CUDNN_LIBRARY\")\n if l is not None and os.path.isfile(l):\n return os.path.realpath(l)\n return None\n files = set()\n for fn in out.split(\"\\n\"):\n fn = os.path.realpath(fn) # eliminate symbolic links\n if os.path.isfile(fn):\n files.add(fn)\n if not files:\n return None\n # Alphabetize the result because the order is non-deterministic otherwise\n files = list(sorted(files))\n if len(files) == 1:\n return files[0]\n result = \"\\n\".join(files)\n return \"Probably one of the following:\\n{}\".format(result)",
"def get_gpu_volume_mounts():\n volume_specs = {}\n\n if FLAGS.nvidia_lib_dir:\n volume_specs['nvidia-libraries'] = (FLAGS.nvidia_lib_dir, '/usr/lib/nvidia')\n\n if FLAGS.cuda_lib_dir:\n cuda_library_files = ['libcuda.so', 'libcuda.so.1', 'libcudart.so']\n for cuda_library_file in cuda_library_files:\n lib_name = cuda_library_file.split('.')[0]\n volume_specs['cuda-libraries-%s' % lib_name] = (\n os.path.join(FLAGS.cuda_lib_dir, cuda_library_file),\n os.path.join('/usr/lib/cuda/', cuda_library_file))\n return volume_specs",
"def _get_foreach_kernels_supported_devices() -> List[str]:\n return [\"cuda\", torch._C._get_privateuse1_backend_name()]",
"def xdg_config_home():\n return Path(os.environ.get(\"XDG_CONFIG_HOME\", Path.home() / \".config\"))",
"def find_cinder_install():\n try:\n import cinder\n return os.path.dirname(cinder.__file__)\n except ImportError:\n try:\n out = exec_cmd(\"python -c 'import cinder; print(cinder.__file__)'\")\n return os.path.dirname(out)\n except subprocess.CalledProcessError:\n try:\n out = exec_cmd(\n \"python3 -c 'import cinder; print(cinder.__file__)'\")\n return os.path.dirname(out)\n except subprocess.CalledProcessError:\n dlog(\"Could not determine Cinder install location. Cinder \"\n \"must either be installed in the currently running \"\n \"python or in the system python\")\n raise",
"def locate_diy():\n home = None\n if platform.architecture()[0]=='64bit':\n arch = '64'\n else:\n arch = ''\n if 'DIY_BASE' in os.environ:\n home = os.environ['DIY_BASE']\n else:\n raise EnvironmentError('Unable to locate the DIY libraries on '\n 'this system. Set the DIY_BASE environment variable.')\n\n # diyconfig = {'home':home,\n # 'lib':pjoin(home, 'lib'),\n # 'include':pjoin(home, 'include')}\n\n diyconfig = {'home':home,\n 'include':pjoin(home, 'include')}\n\n for key, val in diyconfig.items():\n if not os.path.exists(val):\n raise EnvironmentError('Could not locate {:s} in path {:s}'.format(key, val))\n return diyconfig",
"def find_config():\n\n # Point to with an environment variable\n if os.environ.get('HAPPI_CFG', False):\n happi_cfg = os.environ.get('HAPPI_CFG')\n logger.debug(\"Found $HAPPI_CFG specification for Client \"\n \"configuration at %s\", happi_cfg)\n return happi_cfg\n # Search in the current directory and home directory\n else:\n config_dirs = [os.environ.get('XDG_CONFIG_HOME', \".\"),\n os.path.expanduser('~/.config'),\n platformdirs.user_config_dir(\"happi\")]\n for directory in config_dirs:\n logger.debug('Searching for Happi config in %s', directory)\n for path in ('.happi.cfg', 'happi.cfg'):\n full_path = os.path.join(directory, path)\n\n if os.path.exists(full_path):\n logger.debug(\"Found configuration file at %r\", full_path)\n return full_path\n # If found nothing\n raise OSError(\"No happi configuration file found. Check HAPPI_CFG.\")",
"def get_home_dir():\n\n isdir = os.path.isdir\n env = os.environ\n \n # first, check py2exe distribution root directory for _ipython.\n # This overrides all. Normally does not exist.\n \n if '\\\\library.zip\\\\' in IPython.__file__.lower():\n root, rest = IPython.__file__.lower().split('library.zip')\n if isdir(root + '_ipython'):\n os.environ[\"IPYKITROOT\"] = root.rstrip('\\\\')\n return root\n \n try:\n homedir = env['HOME']\n if not isdir(homedir):\n # in case a user stuck some string which does NOT resolve to a\n # valid path, it's as good as if we hadn't foud it\n raise KeyError\n return homedir\n except KeyError:\n if os.name == 'posix':\n raise HomeDirError,'undefined $HOME, IPython can not proceed.'\n elif os.name == 'nt':\n # For some strange reason, win9x returns 'nt' for os.name.\n try:\n homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])\n if not isdir(homedir):\n homedir = os.path.join(env['USERPROFILE'])\n if not isdir(homedir):\n raise HomeDirError\n return homedir\n except:\n try:\n # Use the registry to get the 'My Documents' folder.\n import _winreg as wreg\n key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,\n \"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\")\n homedir = wreg.QueryValueEx(key,'Personal')[0]\n key.Close()\n if not isdir(homedir):\n e = ('Invalid \"Personal\" folder registry key '\n 'typically \"My Documents\".\\n'\n 'Value: %s\\n'\n 'This is not a valid directory on your system.' %\n homedir)\n raise HomeDirError(e)\n return homedir\n except HomeDirError:\n raise\n except:\n return 'C:\\\\'\n elif os.name == 'dos':\n # Desperate, may do absurd things in classic MacOS. May work under DOS.\n return 'C:\\\\'\n else:\n raise HomeDirError,'support for your operating system not implemented.'",
"def get_kernel_registration_files(ort_root=None, include_cuda=False):\n\n if not ort_root:\n ort_root = os.path.dirname(os.path.abspath(__file__)) + \"/../..\"\n\n provider_path = ort_root + \"/onnxruntime/core/providers/{ep}/{ep}_execution_provider.cc\"\n contrib_provider_path = ort_root + \"/onnxruntime/contrib_ops/{ep}/{ep}_contrib_kernels.cc\"\n training_provider_path = ort_root + \"/orttraining/orttraining/training_ops/{ep}/{ep}_training_kernels.cc\"\n provider_paths = [\n provider_path.format(ep=\"cpu\"),\n contrib_provider_path.format(ep=\"cpu\"),\n training_provider_path.format(ep=\"cpu\"),\n ]\n\n if include_cuda:\n provider_paths.append(provider_path.format(ep=\"cuda\"))\n provider_paths.append(contrib_provider_path.format(ep=\"cuda\"))\n provider_paths.append(training_provider_path.format(ep=\"cuda\"))\n\n provider_paths = [os.path.abspath(p) for p in provider_paths]\n\n return provider_paths"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Locate where the HDF5 libraries are located on the system. Returns a dict with keys 'home', 'lib' and 'include' and values giving the absolute path to each directory. Looks for the HDF5HOME environment variable.
|
def locate_hdf5():
home = None
if platform.architecture()[0]=='64bit':
arch = '64'
else:
arch = ''
if 'HDF5_BASE' in os.environ:
home = os.environ['HDF5_BASE']
else:
raise EnvironmentError('Unable to locate the HDF libraries on '
'this system. Set the HDF5_BASE environment variable.')
hdfconfig = {'home':home,
'lib':pjoin(home, 'lib'),
'include':pjoin(home, 'include')}
for key, val in hdfconfig.items():
if not os.path.exists(val):
raise EnvironmentError('Could not locate {:s} in path {:s}'.format(key, val))
return hdfconfig
|
[
"def _find_home():\n\n # this is used below to make fix up encoding issues that sometimes crop up\n # in py2.x but not in py3.x\n if PY2:\n decodepath = lambda pth: pth.decode(sys.getfilesystemencoding())\n elif PY3:\n decodepath = lambda pth: pth\n\n # First find the home directory - this is inspired by the scheme ipython\n # uses to identify \"home\"\n if os.name == 'posix':\n # Linux, Unix, AIX, OS X\n if 'HOME' in os.environ:\n homedir = decodepath(os.environ['HOME'])\n else:\n raise OSError('Could not find unix home directory to search for '\n 'astropy config dir')\n elif os.name == 'nt': # This is for all modern Windows (NT or after)\n if 'MSYSTEM' in os.environ and os.environ.get('HOME'):\n # Likely using an msys shell; use whatever it is using for its\n # $HOME directory\n homedir = decodepath(os.environ['HOME'])\n # Next try for a network home\n elif 'HOMESHARE' in os.environ:\n homedir = decodepath(os.environ['HOMESHARE'])\n # See if there's a local home\n elif 'HOMEDRIVE' in os.environ and 'HOMEPATH' in os.environ:\n homedir = os.path.join(os.environ['HOMEDRIVE'],\n os.environ['HOMEPATH'])\n homedir = decodepath(homedir)\n # Maybe a user profile?\n elif 'USERPROFILE' in os.environ:\n homedir = decodepath(os.path.join(os.environ['USERPROFILE']))\n else:\n try:\n from .six.moves import winreg as wreg\n shell_folders = r'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders'\n key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, shell_folders)\n\n homedir = wreg.QueryValueEx(key, 'Personal')[0]\n homedir = decodepath(homedir)\n key.Close()\n except:\n # As a final possible resort, see if HOME is present\n if 'HOME' in os.environ:\n homedir = decodepath(os.environ['HOME'])\n else:\n raise OSError('Could not find windows home directory to '\n 'search for astropy config dir')\n else:\n # for other platforms, try HOME, although it probably isn't there\n if 'HOME' in os.environ:\n homedir = decodepath(os.environ['HOME'])\n else:\n raise OSError('Could not find a home directory to search for '\n 'astropy config dir - are you on an unspported '\n 'platform?')\n return homedir",
"def locate_diy():\n home = None\n if platform.architecture()[0]=='64bit':\n arch = '64'\n else:\n arch = ''\n if 'DIY_BASE' in os.environ:\n home = os.environ['DIY_BASE']\n else:\n raise EnvironmentError('Unable to locate the DIY libraries on '\n 'this system. Set the DIY_BASE environment variable.')\n\n # diyconfig = {'home':home,\n # 'lib':pjoin(home, 'lib'),\n # 'include':pjoin(home, 'include')}\n\n diyconfig = {'home':home,\n 'include':pjoin(home, 'include')}\n\n for key, val in diyconfig.items():\n if not os.path.exists(val):\n raise EnvironmentError('Could not locate {:s} in path {:s}'.format(key, val))\n return diyconfig",
"def setup_paths():\n paths = {}\n if FIASCO_RC.is_file():\n config = configparser.ConfigParser()\n config.read(FIASCO_RC)\n if 'database' in config:\n paths = dict(config['database'])\n\n if 'ascii_dbase_root' not in paths:\n paths['ascii_dbase_root'] = FIASCO_HOME / 'chianti_dbase'\n if 'hdf5_dbase_root' not in paths:\n paths['hdf5_dbase_root'] = FIASCO_HOME / 'chianti_dbase.h5'\n\n return paths",
"def get_home_dir():\n\n isdir = os.path.isdir\n env = os.environ\n \n # first, check py2exe distribution root directory for _ipython.\n # This overrides all. Normally does not exist.\n \n if '\\\\library.zip\\\\' in IPython.__file__.lower():\n root, rest = IPython.__file__.lower().split('library.zip')\n if isdir(root + '_ipython'):\n os.environ[\"IPYKITROOT\"] = root.rstrip('\\\\')\n return root\n \n try:\n homedir = env['HOME']\n if not isdir(homedir):\n # in case a user stuck some string which does NOT resolve to a\n # valid path, it's as good as if we hadn't foud it\n raise KeyError\n return homedir\n except KeyError:\n if os.name == 'posix':\n raise HomeDirError,'undefined $HOME, IPython can not proceed.'\n elif os.name == 'nt':\n # For some strange reason, win9x returns 'nt' for os.name.\n try:\n homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])\n if not isdir(homedir):\n homedir = os.path.join(env['USERPROFILE'])\n if not isdir(homedir):\n raise HomeDirError\n return homedir\n except:\n try:\n # Use the registry to get the 'My Documents' folder.\n import _winreg as wreg\n key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,\n \"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\")\n homedir = wreg.QueryValueEx(key,'Personal')[0]\n key.Close()\n if not isdir(homedir):\n e = ('Invalid \"Personal\" folder registry key '\n 'typically \"My Documents\".\\n'\n 'Value: %s\\n'\n 'This is not a valid directory on your system.' %\n homedir)\n raise HomeDirError(e)\n return homedir\n except HomeDirError:\n raise\n except:\n return 'C:\\\\'\n elif os.name == 'dos':\n # Desperate, may do absurd things in classic MacOS. May work under DOS.\n return 'C:\\\\'\n else:\n raise HomeDirError,'support for your operating system not implemented.'",
"def get_clhep_info():\n res = {}\n clhepExec = os.getenv('CLHEP_CONFIG', 'clhep-config')\n # get include dir\n if not os.getenv('CLHEP_INCLUDE_DIRS'):\n r = subprocess.run([clhepExec, '--include'], stdout=subprocess.PIPE)\n res['include'] = re.findall(r'-I\\s?\\\"?([^\\s\\\"]+)\\\"?', r.stdout.decode())\n else:\n res['include'] = os.getenv('CLHEP_INCLUDE_DIRS').split(':')\n # get libraries to link\n if not os.getenv('CLHEP_LIBRARIES'):\n r = subprocess.run([clhepExec, '--libs'], stdout=subprocess.PIPE)\n res['libs'] = re.findall(r'-l\\s?\\\"?([^\\s\\\"]+)\\\"?', r.stdout.decode())\n else:\n res['libs'] = os.getenv('CLHEP_LIBRARIES').split()\n if not os.getenv('CLHEP_LIB_DIRS'):\n r = subprocess.run([clhepExec, '--libs'], stdout=subprocess.PIPE)\n res['lib_dirs'] = re.findall(r'-L\\s?\\\"?([^\\s\\\"]+)\\\"?', r.stdout.decode())\n else:\n res['lib_dirs'] = os.getenv('CLHEP_LIB_DIRS').split(':')\n return res",
"def get_home_path(self):\n\n if sys.platform == 'win32':\n drive = os.environ['HOMEDRIVE']\n path = os.environ['HOMEPATH']\n path = os.path.join(drive, path)\n elif sys.platform == 'linux2':\n path = os.environ['HOME']\n else: # assume UNIX, whatever\n path = os.environ['HOME']\n\n return path",
"def get_data_home_dir():\n home_dir = get_home_dir()\n return os.path.join(home_dir, 'datasets')",
"def get_pth_dir(executable):\n output = runner.run([\n executable,\n '-c',\n 'import json, sys; print(json.dumps([sys.prefix, sys.version_info]))'\n ]).std_out\n prefix, version_parts = json.loads(output)\n version = '{0}.{1}'.format(version_parts[0], version_parts[1])\n if os.name == 'nt':\n return '{0}/Lib/site-packages'.format(prefix)\n elif os.name == 'posix':\n return '{0}/lib/python{1}/site-packages'.format(prefix, version)\n else:\n raise NonRecoverableError('Unsupported OS: {0}'.format(os.name))",
"def libdirfind():\n libdir = DEWELIBDIR\n if libdir and os.path.exists(libdir):\n return libdir\n elif libdir:\n raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT),\n libdir)\n\n thisdir = os.path.abspath(os.path.dirname(__file__))\n libdir = os.path.join(thisdir, 'libs')\n if libdir and os.path.exists(libdir):\n return libdir\n elif libdir:\n raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT),\n libdir)",
"def gethomepaths(self):\n cwd = os.getcwd()\n home_dir = os.path.expanduser('~')\n os.chdir(home_dir)\n fs_dir = os.path.abspath('.')\n\tos.chdir(cwd) # I hope this will always get you back to the original place...\n if home_dir!= fs_dir:\n return [home_dir, fs_dir]\n else:\n return [home_dir]",
"def traits_home():\n global _traits_home\n\n if _traits_home is None:\n _traits_home = verify_path(join(ETSConfig.application_data, \"traits\"))\n\n return _traits_home",
"def find_lib_path():\n curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))\n dll_path = [curr_path, os.path.join(curr_path, '../../lib/'),\n os.path.join(curr_path, './lib/'),\n os.path.join(sys.prefix, 'dlr'),\n os.path.join(sys.prefix, 'local', 'dlr'),\n os.path.join(sys.exec_prefix, 'local', 'dlr'),\n os.path.join(os.path.expanduser('~'), '.local', 'dlr')]\n if sys.platform == 'win32':\n if platform.architecture()[0] == '64bit':\n dll_path.append(os.path.join(curr_path, '../../windows/x64/Release/'))\n # hack for pip installation when copy all parent source directory here\n dll_path.append(os.path.join(curr_path, './windows/x64/Release/'))\n else:\n dll_path.append(os.path.join(curr_path, '../../windows/Release/'))\n # hack for pip installation when copy all parent source directory here\n dll_path.append(os.path.join(curr_path, './windows/Release/'))\n dll_path = [os.path.join(p, 'dlr.dll') for p in dll_path]\n elif sys.platform.startswith('linux') or sys.platform.startswith('freebsd'):\n dll_path = [os.path.join(p, 'libdlr.so') for p in dll_path]\n elif sys.platform == 'darwin':\n dll_path = [os.path.join(p, 'libdlr.dylib') for p in dll_path]\n\n lib_path = [p for p in dll_path if os.path.exists(p) and os.path.isfile(p)]\n\n if not lib_path and not os.environ.get('DLR_BUILD_DOC', False):\n raise DLRLibraryNotFound(\n 'Cannot find DLR Library in the candidate path, ' +\n 'List of candidates:\\n' + ('\\n'.join(dll_path)))\n return lib_path",
"def setup_python_path(self):\n self.prepare_environment_variables()\n fixed_paths = self.prepare_libraries()\n fixed_paths += self.prepare_code_directories()\n return fixed_paths",
"def go_home(self):\n return [self.putrootfh_op()] + self.lookup_path(self.homedir)",
"def getFlexPaths(env):\n\n\t# determine defaults\n\tif os.name == 'posix':\n\t\tinc_path = ['/usr/include']\n\telse:\n\t\traise ValueError, 'Error: unknown OS. Where is FLEX installed?'\n\n\t# override with environement variables\n\tif 'FLEX_INC_PATH' in os.environ:\n\t\tinc_path = os.path.abspath(os.environ['FLEX_INC_PATH'])\n\n\treturn (inc_path)",
"def libraries_in_ld_library_path(path_hints=None):\n path_hints = path_hints or spack.util.environment.get_path(\n \"LIBRARY_PATH\"\n ) + spack.util.environment.get_path(\"LD_LIBRARY_PATH\") + spack.util.environment.get_path(\n \"DYLD_LIBRARY_PATH\"\n ) + spack.util.environment.get_path(\n \"DYLD_FALLBACK_LIBRARY_PATH\"\n )\n search_paths = llnl.util.filesystem.search_paths_for_libraries(*path_hints)\n\n path_to_lib = {}\n # Reverse order of search directories so that a lib in the first\n # LD_LIBRARY_PATH entry overrides later entries\n for search_path in reversed(search_paths):\n for lib in os.listdir(search_path):\n lib_path = os.path.join(search_path, lib)\n if llnl.util.filesystem.is_readable_file(lib_path):\n path_to_lib[lib_path] = lib\n return path_to_lib",
"def getBoostPaths():\n\n\t# determine defaults\n\tif os.name == 'posix':\n\t\tbin_path = '/usr/bin'\n\t\tlib_path = '/usr/lib'\n\t\tinc_path = '/usr/include'\n\telse:\n\t\traise ValueError, 'Error: unknown OS. Where is boost installed?'\n\n\t# override with environement variables\n\tif 'BOOST_BIN_PATH' in os.environ:\n\t\tbin_path = os.path.abspath(os.environ['BOOST_BIN_PATH'])\n\tif 'BOOST_LIB_PATH' in os.environ:\n\t\tlib_path = os.path.abspath(os.environ['BOOST_LIB_PATH'])\n\tif 'BOOST_INC_PATH' in os.environ:\n\t\tinc_path = os.path.abspath(os.environ['BOOST_INC_PATH'])\n\n\treturn (bin_path,lib_path,inc_path)",
"def find_config():\n\n # Point to with an environment variable\n if os.environ.get('HAPPI_CFG', False):\n happi_cfg = os.environ.get('HAPPI_CFG')\n logger.debug(\"Found $HAPPI_CFG specification for Client \"\n \"configuration at %s\", happi_cfg)\n return happi_cfg\n # Search in the current directory and home directory\n else:\n config_dirs = [os.environ.get('XDG_CONFIG_HOME', \".\"),\n os.path.expanduser('~/.config'),\n platformdirs.user_config_dir(\"happi\")]\n for directory in config_dirs:\n logger.debug('Searching for Happi config in %s', directory)\n for path in ('.happi.cfg', 'happi.cfg'):\n full_path = os.path.join(directory, path)\n\n if os.path.exists(full_path):\n logger.debug(\"Found configuration file at %r\", full_path)\n return full_path\n # If found nothing\n raise OSError(\"No happi configuration file found. Check HAPPI_CFG.\")",
"def get_home_dir(self):\n return self.home_dir"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Locate where the DIY libraries are located on the system. Returns a dict with keys 'home', 'lib' and 'include' and values giving the absolute path to each directory. Looks for the DIYHOME environment variable.
|
def locate_diy():
home = None
if platform.architecture()[0]=='64bit':
arch = '64'
else:
arch = ''
if 'DIY_BASE' in os.environ:
home = os.environ['DIY_BASE']
else:
raise EnvironmentError('Unable to locate the DIY libraries on '
'this system. Set the DIY_BASE environment variable.')
# diyconfig = {'home':home,
# 'lib':pjoin(home, 'lib'),
# 'include':pjoin(home, 'include')}
diyconfig = {'home':home,
'include':pjoin(home, 'include')}
for key, val in diyconfig.items():
if not os.path.exists(val):
raise EnvironmentError('Could not locate {:s} in path {:s}'.format(key, val))
return diyconfig
|
[
"def libdirfind():\n libdir = DEWELIBDIR\n if libdir and os.path.exists(libdir):\n return libdir\n elif libdir:\n raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT),\n libdir)\n\n thisdir = os.path.abspath(os.path.dirname(__file__))\n libdir = os.path.join(thisdir, 'libs')\n if libdir and os.path.exists(libdir):\n return libdir\n elif libdir:\n raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT),\n libdir)",
"def find_lib_path():\n curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))\n dll_path = [curr_path, os.path.join(curr_path, '../../lib/'),\n os.path.join(curr_path, './lib/'),\n os.path.join(sys.prefix, 'dlr'),\n os.path.join(sys.prefix, 'local', 'dlr'),\n os.path.join(sys.exec_prefix, 'local', 'dlr'),\n os.path.join(os.path.expanduser('~'), '.local', 'dlr')]\n if sys.platform == 'win32':\n if platform.architecture()[0] == '64bit':\n dll_path.append(os.path.join(curr_path, '../../windows/x64/Release/'))\n # hack for pip installation when copy all parent source directory here\n dll_path.append(os.path.join(curr_path, './windows/x64/Release/'))\n else:\n dll_path.append(os.path.join(curr_path, '../../windows/Release/'))\n # hack for pip installation when copy all parent source directory here\n dll_path.append(os.path.join(curr_path, './windows/Release/'))\n dll_path = [os.path.join(p, 'dlr.dll') for p in dll_path]\n elif sys.platform.startswith('linux') or sys.platform.startswith('freebsd'):\n dll_path = [os.path.join(p, 'libdlr.so') for p in dll_path]\n elif sys.platform == 'darwin':\n dll_path = [os.path.join(p, 'libdlr.dylib') for p in dll_path]\n\n lib_path = [p for p in dll_path if os.path.exists(p) and os.path.isfile(p)]\n\n if not lib_path and not os.environ.get('DLR_BUILD_DOC', False):\n raise DLRLibraryNotFound(\n 'Cannot find DLR Library in the candidate path, ' +\n 'List of candidates:\\n' + ('\\n'.join(dll_path)))\n return lib_path",
"def directories():\n\treturn {\n\t\t\"CURRENT_DIR\": os.getcwd(),\n\t\t\"HOME_DIR\": os.path.expanduser(\"~\"),\n\t\t\"BASE_DIR\": os.path.dirname(__file__),\n\t}",
"def _find_home():\n\n # this is used below to make fix up encoding issues that sometimes crop up\n # in py2.x but not in py3.x\n if PY2:\n decodepath = lambda pth: pth.decode(sys.getfilesystemencoding())\n elif PY3:\n decodepath = lambda pth: pth\n\n # First find the home directory - this is inspired by the scheme ipython\n # uses to identify \"home\"\n if os.name == 'posix':\n # Linux, Unix, AIX, OS X\n if 'HOME' in os.environ:\n homedir = decodepath(os.environ['HOME'])\n else:\n raise OSError('Could not find unix home directory to search for '\n 'astropy config dir')\n elif os.name == 'nt': # This is for all modern Windows (NT or after)\n if 'MSYSTEM' in os.environ and os.environ.get('HOME'):\n # Likely using an msys shell; use whatever it is using for its\n # $HOME directory\n homedir = decodepath(os.environ['HOME'])\n # Next try for a network home\n elif 'HOMESHARE' in os.environ:\n homedir = decodepath(os.environ['HOMESHARE'])\n # See if there's a local home\n elif 'HOMEDRIVE' in os.environ and 'HOMEPATH' in os.environ:\n homedir = os.path.join(os.environ['HOMEDRIVE'],\n os.environ['HOMEPATH'])\n homedir = decodepath(homedir)\n # Maybe a user profile?\n elif 'USERPROFILE' in os.environ:\n homedir = decodepath(os.path.join(os.environ['USERPROFILE']))\n else:\n try:\n from .six.moves import winreg as wreg\n shell_folders = r'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders'\n key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, shell_folders)\n\n homedir = wreg.QueryValueEx(key, 'Personal')[0]\n homedir = decodepath(homedir)\n key.Close()\n except:\n # As a final possible resort, see if HOME is present\n if 'HOME' in os.environ:\n homedir = decodepath(os.environ['HOME'])\n else:\n raise OSError('Could not find windows home directory to '\n 'search for astropy config dir')\n else:\n # for other platforms, try HOME, although it probably isn't there\n if 'HOME' in os.environ:\n homedir = decodepath(os.environ['HOME'])\n else:\n raise OSError('Could not find a home directory to search for '\n 'astropy config dir - are you on an unspported '\n 'platform?')\n return homedir",
"def getBoostPaths():\n\n\t# determine defaults\n\tif os.name == 'posix':\n\t\tbin_path = '/usr/bin'\n\t\tlib_path = '/usr/lib'\n\t\tinc_path = '/usr/include'\n\telse:\n\t\traise ValueError, 'Error: unknown OS. Where is boost installed?'\n\n\t# override with environement variables\n\tif 'BOOST_BIN_PATH' in os.environ:\n\t\tbin_path = os.path.abspath(os.environ['BOOST_BIN_PATH'])\n\tif 'BOOST_LIB_PATH' in os.environ:\n\t\tlib_path = os.path.abspath(os.environ['BOOST_LIB_PATH'])\n\tif 'BOOST_INC_PATH' in os.environ:\n\t\tinc_path = os.path.abspath(os.environ['BOOST_INC_PATH'])\n\n\treturn (bin_path,lib_path,inc_path)",
"def setup_python_path(self):\n self.prepare_environment_variables()\n fixed_paths = self.prepare_libraries()\n fixed_paths += self.prepare_code_directories()\n return fixed_paths",
"def locate_hdf5():\n\n home = None\n if platform.architecture()[0]=='64bit':\n arch = '64'\n else:\n arch = ''\n if 'HDF5_BASE' in os.environ:\n home = os.environ['HDF5_BASE']\n else:\n raise EnvironmentError('Unable to locate the HDF libraries on '\n 'this system. Set the HDF5_BASE environment variable.')\n\n hdfconfig = {'home':home,\n 'lib':pjoin(home, 'lib'),\n 'include':pjoin(home, 'include')}\n for key, val in hdfconfig.items():\n if not os.path.exists(val):\n raise EnvironmentError('Could not locate {:s} in path {:s}'.format(key, val))\n return hdfconfig",
"def libraries_in_ld_library_path(path_hints=None):\n path_hints = path_hints or spack.util.environment.get_path(\n \"LIBRARY_PATH\"\n ) + spack.util.environment.get_path(\"LD_LIBRARY_PATH\") + spack.util.environment.get_path(\n \"DYLD_LIBRARY_PATH\"\n ) + spack.util.environment.get_path(\n \"DYLD_FALLBACK_LIBRARY_PATH\"\n )\n search_paths = llnl.util.filesystem.search_paths_for_libraries(*path_hints)\n\n path_to_lib = {}\n # Reverse order of search directories so that a lib in the first\n # LD_LIBRARY_PATH entry overrides later entries\n for search_path in reversed(search_paths):\n for lib in os.listdir(search_path):\n lib_path = os.path.join(search_path, lib)\n if llnl.util.filesystem.is_readable_file(lib_path):\n path_to_lib[lib_path] = lib\n return path_to_lib",
"def gethomepaths(self):\n cwd = os.getcwd()\n home_dir = os.path.expanduser('~')\n os.chdir(home_dir)\n fs_dir = os.path.abspath('.')\n\tos.chdir(cwd) # I hope this will always get you back to the original place...\n if home_dir!= fs_dir:\n return [home_dir, fs_dir]\n else:\n return [home_dir]",
"def auto_detect_base_directories():\n auto_rootdirs = None\n if PLATFORM == 'linux':\n auto_rootdirs = ('/usr', '/usr/local', '/opt')\n elif PLATFORM == 'osx':\n auto_rootdirs = ('/usr/local', '/opt')\n elif PLATFORM == 'mingw64':\n auto_rootdirs = ('/mingw64',)\n elif PLATFORM == 'windows':\n auto_rootdirs = ()\n\n auto_include_directories = []\n auto_library_directories = []\n for j in auto_rootdirs:\n if os.path.isdir(j):\n path_include = os.path.join(j, 'include')\n path_library = os.path.join(j, 'lib')\n if os.path.isdir(path_include):\n auto_include_directories.append(path_include)\n if os.path.isdir(path_library):\n auto_library_directories.append(path_library)\n\n return auto_rootdirs, auto_include_directories, auto_library_directories",
"def getOcelotPaths():\n\t\n\ttry:\n\t\tllvm_config_path = which('OcelotConfig')\n\texcept:\n\t\traise ValueError, 'Error: Failed to find OcelotConfig, make sure ' + \\\n\t\t\t'it is on your PATH'\n\t\n\t# determine defaults\n\tbin_path = os.popen('OcelotConfig --bindir').read().split()\n\tlib_path = os.popen('OcelotConfig --libdir').read().split()\n\tinc_path = os.popen('OcelotConfig --includedir').read().split()\n\tcflags = os.popen('OcelotConfig --cppflags').read().split()\n\tlflags = os.popen('OcelotConfig --ldflags').read().split()\n\tlibs = os.popen('OcelotConfig --libs').read().split()\n\t\n\treturn (bin_path,lib_path,inc_path,cflags,lflags,libs)",
"def _guess_paths(library_path=None):\n\n if library_path is None:\n library_path = (\n CI.Config.library_path or\n (CI.Config.library_file and dirname(CI.Config.library_file))\n )\n\n if library_path is None:\n raise RuntimeError(\n 'No library path set, try setting '\n 'clang.cindex.Config.set_library_path'\n )\n\n known_paths = [\n library_path + '/../lib/clang', # default value\n library_path + '/../clang', # gentoo\n library_path + '/clang', # opensuse\n library_path + '/', # Google\n '/usr/lib64/clang', # x86_64 (openSUSE, Fedora)\n '/usr/lib/clang'\n ]\n\n for path in known_paths:\n for pattern in ('/include', '/*/include'):\n for include_dir in glob.glob(path + pattern):\n clang_args = ['-I%s' % include_dir]\n if can_find_clang_headers(clang_args):\n return [include_dir]\n return []",
"def find_lib_path():\n basename = 'fast_svmlight_loader'\n if sys.platform == 'win32':\n lib_name = '{}.dll'.format(basename)\n elif sys.platform.startswith('linux'):\n lib_name = 'lib{}.so'.format(basename)\n elif sys.platform == 'darwin':\n lib_name = 'lib{}.dylib'.format(basename)\n else:\n raise RuntimeError('Unsupported operating system')\n\n curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))\n # List possible locations for the library file\n dll_path = [curr_path, os.path.join(curr_path, '../../lib/'),\n os.path.join(curr_path, './lib/'),\n os.path.join(sys.prefix, 'fast_svmlight_loader')]\n # Windows hack: additional candidate locations\n if sys.platform == 'win32':\n if platform.architecture()[0] == '64bit':\n dll_path.append(os.path.join(curr_path, '../../windows/x64/Release/'))\n # hack for pip installation when copy all parent source directory here\n dll_path.append(os.path.join(curr_path, './windows/x64/Release/'))\n else:\n dll_path.append(os.path.join(curr_path, '../../windows/Release/'))\n # hack for pip installation when copy all parent source directory here\n dll_path.append(os.path.join(curr_path, './windows/Release/'))\n # Now examine all candidate locations for the library file\n dll_path = [os.path.join(p, lib_name) for p in dll_path]\n lib_path = [p for p in dll_path if os.path.exists(p) and os.path.isfile(p)]\n\n if not lib_path:\n raise FastSVMLightLoaderLibraryNotFound(\n 'Cannot find library {} in the candidate path: '.format(lib_name) +\n 'List of candidates:\\n' + ('\\n'.join(dll_path)))\n return lib_path",
"def find_lib(libname, env=None):\n prefix, ext = DLLNAMEMAP[sys.platform]\n fullname = '%s%s%s' % (prefix, libname, ext)\n candidates = [\n os.path.join(get_conda_lib_dir(), fullname),\n fullname,\n ]\n\n # Check overriding environment variable\n if env:\n envpath = os.environ.get(env, '')\n else:\n envpath = None\n\n if envpath:\n if os.path.isdir(envpath):\n envpath = os.path.join(envpath, fullname)\n return [envpath]\n else:\n return candidates",
"def _ask_ld_for_paths(self):\n\n try:\n ld = Popen(['ld', '--verbose'], stdin=DEVNULL, stdout=PIPE)\n output = ld.stdout.read().decode()\n except:\n return []\n\n search_dirs = re.compile(r'SEARCH_DIR\\(([^)]*)\\)').findall(output)\n return [d.strip(' \"') for d in search_dirs]",
"def setup_paths():\n paths = {}\n if FIASCO_RC.is_file():\n config = configparser.ConfigParser()\n config.read(FIASCO_RC)\n if 'database' in config:\n paths = dict(config['database'])\n\n if 'ascii_dbase_root' not in paths:\n paths['ascii_dbase_root'] = FIASCO_HOME / 'chianti_dbase'\n if 'hdf5_dbase_root' not in paths:\n paths['hdf5_dbase_root'] = FIASCO_HOME / 'chianti_dbase.h5'\n\n return paths",
"def find_lib_path() -> List[str]:\n curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))\n dll_path = [\n # normal, after installation `lib` is copied into Python package tree.\n os.path.join(curr_path, 'lib'),\n # editable installation, no copying is performed.\n os.path.join(curr_path, os.path.pardir, os.path.pardir, 'lib'),\n # use libxgboost from a system prefix, if available. This should be the last\n # option.\n os.path.join(sys.prefix, 'lib'),\n ]\n\n if sys.platform == 'win32':\n if platform.architecture()[0] == '64bit':\n dll_path.append(\n os.path.join(curr_path, '../../windows/x64/Release/'))\n # hack for pip installation when copy all parent source\n # directory here\n dll_path.append(os.path.join(curr_path, './windows/x64/Release/'))\n else:\n dll_path.append(os.path.join(curr_path, '../../windows/Release/'))\n # hack for pip installation when copy all parent source\n # directory here\n dll_path.append(os.path.join(curr_path, './windows/Release/'))\n dll_path = [os.path.join(p, 'xgboost.dll') for p in dll_path]\n elif sys.platform.startswith(('linux', 'freebsd', 'emscripten')):\n dll_path = [os.path.join(p, 'libxgboost.so') for p in dll_path]\n elif sys.platform == 'darwin':\n dll_path = [os.path.join(p, 'libxgboost.dylib') for p in dll_path]\n elif sys.platform == 'cygwin':\n dll_path = [os.path.join(p, 'cygxgboost.dll') for p in dll_path]\n if platform.system() == 'OS400':\n dll_path = [os.path.join(p, 'libxgboost.so') for p in dll_path]\n\n lib_path = [p for p in dll_path if os.path.exists(p) and os.path.isfile(p)]\n\n # XGBOOST_BUILD_DOC is defined by sphinx conf.\n if not lib_path and not os.environ.get('XGBOOST_BUILD_DOC', False):\n link = 'https://xgboost.readthedocs.io/en/latest/build.html'\n msg = 'Cannot find XGBoost Library in the candidate path. ' + 'List of candidates:\\n- ' + ('\\n- '.join(dll_path)) + '\\nXGBoost Python package path: ' + curr_path + '\\nsys.prefix: ' + sys.prefix + '\\nSee: ' + link + ' for installing XGBoost.'\n raise XGBoostLibraryNotFound(msg)\n return lib_path",
"def Paths(self) -> DllImportSearchPath:",
"def get_library_paths(project_path: str):\n path = (\n os.path.join(project_path, 'cauldron.json')\n if not project_path.endswith('cauldron.json') else\n project_path\n )\n directory = os.path.dirname(path)\n\n with open(path, 'r') as f:\n settings = json.load(f)\n\n def listify(value):\n return [value] if isinstance(value, str) else list(value)\n\n folders = listify(settings.get('library_folders') or ['libs'])\n\n # Include the remote shared library folder as well\n folders.append('../__cauldron_shared_libs')\n\n results = [\n environ.paths.clean(os.path.join(directory, folder))\n for folder in folders\n ]\n return [r for r in results if os.path.exists(r) and os.path.isdir(r)]"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
generates license file for the project
|
def generate_license() -> None:
license_result = os.system(f"lice {LICENSE} -o '{ORGANIZATION}' -p {REPO_NAME} > {PROJECT_DIRECTORY}/LICENSE")
if license_result: # it means that return code is not 0, print exception
print(license_result)
|
[
"def license(outfile=sys.stdout):\n # Looks like we're maintaining this in parallel with the LICENSE\n # file. I'd like to avoid that, but I don't see how. The MIT\n # license text itself won't change, but the copyright years will\n # from time to time, and the copyright holder could as well.\n license_str = \"\"\"\\\nOneTime version %s.\n\nCopyright (c) 2004-2013 Karl Fogel\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\"\"\" % __version__\n outfile.write(license_str)",
"def GenerateLicenseFile(args: argparse.Namespace):\n # Convert the path separators to the OS specific ones\n extra_third_party_dirs = args.extra_third_party_dirs\n if extra_third_party_dirs is not None:\n extra_third_party_dirs = [\n os.path.normpath(path) for path in extra_third_party_dirs\n ]\n\n if args.gn_target is not None:\n third_party_dirs = FindThirdPartyDeps(args.gn_out_dir, args.gn_target,\n args.target_os,\n extra_third_party_dirs,\n args.extra_allowed_dirs)\n\n # Sanity-check to raise a build error if invalid gn_... settings are\n # somehow passed to this script.\n if not third_party_dirs:\n raise RuntimeError(\"No deps found.\")\n\n else:\n third_party_dirs = FindThirdPartyDirs(PRUNE_PATHS, _REPOSITORY_ROOT,\n extra_third_party_dirs)\n\n metadatas = {}\n for d in third_party_dirs:\n try:\n md = ParseDir(d,\n _REPOSITORY_ROOT,\n require_license_file=True,\n enable_warnings=args.enable_warnings)\n if md:\n metadatas[d] = md\n except LicenseError as lic_exp:\n # TODO(phajdan.jr): Convert to fatal error (http://crbug.com/39240).\n print(f\"Error: {lic_exp}\")\n continue\n\n if args.format == 'spdx':\n license_txt = GenerateLicenseFileSpdx(metadatas, args.spdx_link,\n args.spdx_root, args.spdx_doc_name,\n args.spdx_doc_namespace)\n elif args.format == 'txt':\n license_txt = GenerateLicenseFilePlainText(metadatas)\n\n elif args.format == 'csv':\n license_txt = GenerateLicenseFileCsv(metadatas)\n\n else:\n raise ValueError(f'Unknown license format: {args.format}')\n\n if args.output_file:\n with open(args.output_file, 'w', encoding='utf-8') as f:\n f.write(license_txt)\n print(f\"\\n ---- \\nWrote license data to file {args.output_file}\")\n else:\n print(license_txt)",
"def GenerateNoticeFile():\n\n third_party_dirs = _FindThirdPartyDirs()\n\n # Don't forget Chromium's LICENSE file\n content = [_ReadFile('LICENSE')]\n\n # We provide attribution for all third-party directories.\n # TODO(steveblock): Limit this to only code used by the WebView binary.\n for directory in sorted(third_party_dirs):\n metadata = licenses.ParseDir(directory, REPOSITORY_ROOT,\n require_license_file=False)\n license_file = metadata['License File']\n if license_file and license_file != licenses.NOT_SHIPPED:\n content.append(_ReadFile(license_file))\n\n return '\\n'.join(content)",
"def test_create_iceberg_add_license_from_file(self):\n pass",
"def get_license_file(headers: dict, name: str, url: str):\n response = requests.get(url, headers=headers)\n if 200 <= response.status_code < 300: # Usually 200\n content = json.loads(response.text)['body']\n\n else:\n print(f\"\\nAPI request failed when getting license file.\")\n server_message = json.loads(response.text)[\"message\"]\n print(f\"Error {response.status_code}: {response.reason} \"\n f\"({server_message})\")\n exit()\n\n try:\n (consts.TEMPLATE_DIR / \"licenses\" / name).mkdir(parents=True)\n print(f\"\\nDirectory `{consts.TEMPLATE_DIR / 'licenses' / name}` \"\n \"created.\")\n\n except FileExistsError:\n print(f\"\\nDirectory `{consts.TEMPLATE_DIR / 'licenses' / name}` \"\n \"already exists. Skippping step.\")\n\n try:\n file_name = \"UNLICENSE\" if name.upper() == \"UNLICENSE\" else \"LICENSE\"\n with open(\n consts.TEMPLATE_DIR / \"licenses\" / name / file_name, \"x\"\n ) as f:\n f.write(content)\n print(f\"`{name}` license file created.\")\n\n except FileExistsError:\n print(f\"`{name}` license file already exists. Skippping step.\")",
"def license_export(data):\n resources = config_utils.get_resources(\"sentieon\", data[\"config\"])\n server = resources.get(\"keyfile\")\n if not server:\n raise ValueError(\"Need to set resources keyfile with URL:port of license server, local license file or \"\n \"environmental variables to export \\n\"\n \"http://bcbio-nextgen.readthedocs.io/en/latest/contents/configuration.html#resources\")\n if isinstance(server, basestring):\n return \"export SENTIEON_LICENSE=%s && \" % server\n else:\n assert isinstance(server, dict), server\n exports = \"\"\n for key, val in server.items():\n exports += \"export %s=%s && \" % (key.upper(), val)\n return exports",
"def _dump_license(self, file):\n file.write(self.license.encode(\"utf-8\"))",
"def GenerateCopyrightHeader():\n return COPYRIGHT_HEADER_TEMPLATE % datetime.date.today().year",
"def install_license():\n\n conf_file_second = os.path.join(\"/bootflash\", options[\"split_config_second\"])\n tmp_file_second = conf_file_second + \".tmp\"\n tmp_file_write = open(tmp_file_second, 'w')\n for file in os.listdir(\"/bootflash/poap_files\"):\n if file.endswith(\".lic\"):\n poap_log(\"Installing license file: %s\" % file)\n conf_file_second = os.path.join(\"/bootflash\", options[\"split_config_second\"])\n tmp_file_second = conf_file_second + \".tmp\"\n\n tmp_file_write.write(\"install license bootflash:poap_files/%s\\n\" % file)\n poap_log(\"Installed license succesfully.\")\n tmp_file_write.close()\n with open(conf_file_second, 'r') as read_file, open (tmp_file_second, 'a+') as write_file:\n write_file.write(read_file.read())\n os.rename(tmp_file_second, conf_file_second)\n\n poap_log(\"Installed all licenses succesfully.\")",
"def step_add_license(context):\n jlink = context.jlink\n assert jlink.add_license(str(context.text))",
"def get_license(file):\n # Collect the license\n lic = ''\n for line in file:\n if line.startswith('#include') or line.startswith('#ifndef'):\n break\n else:\n lic += line\n return lic",
"def getLicenseUrl():",
"def bumplicense(ctx):\n\n res = run(\"find . -name '*.go' | grep -v dev-env\")\n for file in res.stdout.splitlines():\n res = run(\"grep -q License {}\".format(file), warn=True)\n if not res.ok:\n run(r\"sed -i '1s/^/\\/\\/ SPDX-License-Identifier:Apache-2.0\\n\\n/' \" + file)",
"def show_license(self):\n self.__log.call()\n _TextDialog(\n self, __license__, title=\"%s copyright and license\" % self.title())",
"def GenerateLicenseFileCsv(\n metadata: Dict[str, Dict[str, Any]],\n repo_root: str = _REPOSITORY_ROOT,\n) -> str:\n csv_content = io.StringIO()\n csv_writer = csv.writer(csv_content, quoting=csv.QUOTE_NONNUMERIC)\n\n # These values are applied statically to all dependencies which are included\n # in the exported CSV.\n # Static fields:\n # * Name of binary which uses dependency,\n # * License text for library included in product,\n # * Mirrored source for reciprocal licences.\n # * Signoff date.\n static_data = [\"Chromium\", \"Yes\", \"Yes\", \"N/A\"]\n\n # Add informative CSV header row to make it clear which columns represent\n # which data in the review spreadsheet.\n csv_writer.writerow([\n \"Library Name\", \"Link to LICENSE file\", \"License Name\",\n \"Binary which uses library\", \"License text for library included?\",\n \"Source code for library includes the mirrored source?\",\n \"Authorization date\"\n ])\n\n # Start with Chromium's LICENSE file\n csv_writer.writerow([\n \"Chromium\",\n \"https://chromium.googlesource.com/chromium/src.git/+/refs/heads/main/LICENSE\",\n \"Chromium\"\n ] + static_data)\n\n # Add necessary third_party.\n for directory in sorted(metadata):\n dir_metadata = metadata[directory]\n\n # Only third party libraries which are shipped as part of a final product\n # are in scope for license review.\n if dir_metadata['Shipped'] == NO:\n continue\n\n data_row = [dir_metadata['Name'] or \"UNKNOWN\"]\n\n urls = []\n for lic in dir_metadata['License File']:\n # The review process requires that a link is provided to each license\n # which is included. We can achieve this by combining a static\n # Chromium googlesource URL with the relative path to the license\n # file from the top level Chromium src directory.\n lic_url = (\n \"https://chromium.googlesource.com/chromium/src.git/+/refs/heads/main/\"\n + os.path.relpath(lic, repo_root))\n\n # Since these are URLs and not paths, replace any Windows path `\\`\n # separators with a `/`\n urls.append(lic_url.replace(\"\\\\\", \"/\"))\n\n data_row.append(\", \".join(urls) or \"UNKNOWN\")\n data_row.append(dir_metadata[\"License\"] or \"UNKNOWN\")\n\n # Join the default data which applies to each row\n csv_writer.writerow(data_row + static_data)\n\n return csv_content.getvalue()",
"def generate_project_file(self):\n self._create_project_content()\n common_util.file_generate(self.project_file, self.project_content)",
"def license_plate(self) -> str:\n return self._license_plate(self.license_formats)",
"def license(request):\n if not License.objects.all().exists():\n template = get_template('license_404.html')\n return HttpResponseNotFound(template.render(RequestContext(request)))\n else:\n latestLicense = License.objects.latest()\n currentSignedLicenseQ = LicenseAgreement.objects.filter(\n user=request.user, text=latestLicense)\n nextPage = request.GET[\n 'next'] if 'next' in request.GET.keys() else None\n if not currentSignedLicenseQ.exists():\n if request.method == 'POST':\n form = LicenseAgreementForm(\n request.user, latestLicense, data=request.POST)\n if form.is_valid():\n form.save()\n if nextPage:\n return redirect(nextPage)\n else:\n return render(request, 'license_signed.html')\n else:\n return render(request, 'license.html', RequestContext(request, {'form': form, 'next': nextPage}))\n else:\n form = LicenseAgreementForm(request.user, latestLicense)\n return render(request, 'license.html', RequestContext(request, {'form': form, 'next': nextPage}))\n elif currentSignedLicenseQ.count() == 1:\n if nextPage:\n return redirect(nextPage)\n else:\n return render(request, 'license_up_to_date.html', RequestContext(request, {'license': latestLicense}))\n else:\n raise RuntimeError(\n 'Impossible condition occured. Please contact an administrator or developer')",
"def test_licenses():\n toml_file = os.path.normpath(\n os.path.join(os.path.dirname(os.path.realpath(__file__)), \"../../../Cargo.toml\")\n )\n utils.run_cmd(\"cargo deny --manifest-path {} check licenses\".format(toml_file))"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
is the policy different between rew_loc and prev_diff_rew_loc? An important question is the below, what happens when you are in the previous reward location?
|
def policy_changed_with_rew_loc(pk_ctr,state_seq,rew_loc,prev_diff_rew_loc,if_is_rew_loc=False):
if prev_diff_rew_loc is not None:
same_as_prev_pol = (((state_seq[pk_ctr]-rew_loc)>0)== #direction to reward with location
((state_seq[pk_ctr]-prev_diff_rew_loc)>0)) #direction to reward with prev location
else:
same_as_prev_pol = False
if state_seq[pk_ctr]==prev_diff_rew_loc:
same_as_prev_pol = if_is_rew_loc
return same_as_prev_pol
|
[
"def get_reward(self):\n\n # Premise is sound, as we want to reward highest when sim.pose x,y,z is \n # essentially equal target_pos x,y,z (making the product of discount rate\n # and pose diff essentially 0 -- therefore, reward would be close to 1).\n #reward = 1.-.3*(abs(self.sim.pose[:3] - self.target_pos).sum())\n \n # rrm - discounting the error\n #reward = 1.-.3*(abs(self.sim.pose[:3] - self.target_pos).sum())\n reward = 2.-.2*(abs(self.sim.pose[:3] - self.target_pos).sum())\n \n # By experience in running, this reward gets negative quickly. We need to\n # scale it, so it can hopefully learn more efficiently.\n # Let's see what happens when we just cap the negative reward at -1\n \"\"\"\n if reward > 1.0:\n print(\"Reward is > 1: {0}\".format(reward))\n reward = 1.0\n elif reward < -1.0:\n print(\"Reward is < 1: {0}\".format(reward))\n reward = -1.0\n \"\"\"\n\n # Works pretty well... Trying something different below\n \"\"\"\n if reward > 0 and reward < 0.5:\n reward = reward * 2\n elif reward > 0.5:\n reward = reward * 4\n elif reward < -1.0:\n #print(\"Reward is < 1: {0}\".format(reward))\n reward = -1.0\n \"\"\"\n\n # Works well, but what if we provide extra reward (or penalize more) based on z coordinate (for hovering)\n \"\"\"\n absoluteZDiff = abs(self.sim.pose[2] - self.target_pos[2])\n if reward > 0 and reward < 0.5 and absoluteZDiff < 1:\n reward = reward * 3\n elif reward >= 0.5 and reward < 0.8 and absoluteZDiff < 1:\n reward = reward * 4\n elif reward >= 0.8 and absoluteZDiff < 1:\n reward = reward * 5\n elif reward > -1.0 and absoluteZDiff > 2:\n reward = -3.0 # penalize more for bad z\n else:\n reward = -1.0 # Cap it here\n \"\"\"\n \n # Instead of comparing to target z, compare to last z\n origTargetZDiff = abs(self.reward_last_z - self.target_pos[2])\n self.reward_last_z = self.reward_this_z\n self.reward_this_z = self.sim.pose[2]\n \n # diff between current z and last z\n lastZDiff = abs(self.reward_last_z - self.reward_this_z)\n # diff betwen current z and target z\n targetZDiff = abs(self.reward_this_z - self.target_pos[2])\n \n \"\"\"\n if lastZDiff < 0.1:\n if reward > 0 and reward < 0.5:\n reward = 0.5\n elif reward >= 0.5 and reward < 0.8:\n reward = 0.8\n elif reward >= 0.8 and reward < 1:\n reward = 1.0\n elif reward < -1.0:\n reward = -1.0 # Cap it here\n\n if reward > 0 and targetZDiff < 2:\n reward = reward * 1.2\n\n if (targetZDiff < origTargetZDiff):\n if reward > 0:\n reward = reward * 1.5\n else:\n reward = reward * 0.5\n \"\"\"\n \n if reward < -1.0:\n reward = -1.0\n \n return reward",
"def prev_reward(self):\n return [env.prev_reward() for env in self._envs]",
"def get_weight_changes(reward, rec_nrn_trace, nrn_nrn_trace):\n\n delta_w_rec_nrn = rec_nrn_trace*reward\n delta_w_nrn_nrn = nrn_nrn_trace*reward\n\n return delta_w_rec_nrn, delta_w_nrn_nrn",
"def get_reward(self):\n alpha = 0.2\n max_reward = 1.0\n pos_reward = 10.\n reward_spread = 1.0\n #reward = 1.-.3*(abs(self.sim.pose[:3] - self.target_pos)).sum() # Original\n #reward = 1 / np.exp(np.sum(np.abs(self.sim.pose - self.target_pos)*alpha)) #v1\n #reward = 1.-.3*(abs(self.sim.pose[:3] - self.target_pos)).sum() #v2\n #reward = 1.-alpha*(abs(self.sim.pose - self.target_pos)).sum() #v3\n #reward = 30.-alpha*( pos_reward*(abs(self.sim.pose[:3] - self.target_pos[:3])) + abs(self.sim.pose[3:] - self.target_pos[3:])).sum() #v4, 5\n #reward = 1 / np.exp(np.sum(np.abs(self.sim.pose - self.target_pos)*alpha)) #v6\n #reward = np.tanh(max_reward - np.sqrt(np.abs(self.sim.pose - self.target_pos).sum())) #v7\n #reward = 1.-alpha*((self.target_pos - self.sim.pose) / reward_spread).sum() #v8\n #reward = np.tanh(1.-alpha*((self.target_pos - self.sim.pose) / reward_spread).sum()) #v9\n #reward = np.tanh(max_reward-alpha*(abs(self.sim.pose - self.target_pos)).sum()) / reward_spread #v10\n #reward = np.tanh((max_reward-alpha*(abs(self.sim.pose - self.target_pos)).sum()) / reward_spread) #v10\n #reward = np.tanh((max_reward-alpha*(pos_reward * abs(self.sim.pose[:3] - self.target_pos[:3]) + abs(self.sim.pose[3:] - self.target_pos[3:])).sum()) / reward_spread) #v11\n reward = np.tanh(max_reward-alpha*((abs(self.sim.pose - self.target_pos)).sum())) / reward_spread #v12\n #reward += pos_reward - np.abs(self.sim.pose[2] - self.target_pos[2]) #Special Z axis reward\n #reward = np.tanh((max_reward-alpha*((abs(self.sim.pose - self.target_pos)).sum())) / reward_spread) #v13\n return reward",
"def _compute_reward(self, observations, done):\n\n # We only consider the plane, the fluctuation in z is due mainly to wave\n current_position = Point()\n current_position.x = observations[0]\n current_position.y = observations[1]\n\n distance_from_des_point = self.get_distance_from_desired_point(current_position)\n distance_difference = distance_from_des_point - self.previous_distance_from_des_point\n\n\n if not done:\n\n # If there has been a decrease in the distance to the desired point, we reward it\n if distance_difference < 0.0:\n rospy.logwarn(\"DECREASE IN DISTANCE GOOD\")\n reward = self.closer_to_point_reward\n else:\n rospy.logerr(\"ENCREASE IN DISTANCE BAD\")\n reward = -1*self.closer_to_point_reward\n\n else:\n\n if self.is_in_desired_position(current_position, self.desired_point_epsilon):\n reward = self.done_reward\n else:\n reward = -1*self.done_reward\n\n\n self.previous_distance_from_des_point = distance_from_des_point\n\n\n rospy.logdebug(\"reward=\" + str(reward))\n self.cumulated_reward += reward\n rospy.logdebug(\"Cumulated_reward=\" + str(self.cumulated_reward))\n self.cumulated_steps += 1\n rospy.logdebug(\"Cumulated_steps=\" + str(self.cumulated_steps))\n\n return reward",
"def compute_reward(self, obs, action):\n pass",
"def _update_reward(self, old_state_key, action, elapsed_time, new_state_key):\n reward = 0.0\n if old_state_key == self.STATE_PLAY_SHOW:\n if action in [self.ACTION_LEFT, self.ACTION_RIGHT]:\n if action == self.position:\n reward = 1.0\n else:\n reward = -1.0\n return reward",
"def _get_reward(self):\n current_state = self.env.getState()\n #print(\"State =\",current_state)\n #print(\"len State =\",len(current_state))\n ball_proximity = current_state[53]\n goal_proximity = current_state[15]\n ball_dist = 1.0 - ball_proximity\n goal_dist = 1.0 - goal_proximity\n kickable = current_state[12]\n ball_ang_sin_rad = current_state[51]\n ball_ang_cos_rad = current_state[52]\n ball_ang_rad = math.acos(ball_ang_cos_rad)\n if ball_ang_sin_rad < 0:\n ball_ang_rad *= -1.\n goal_ang_sin_rad = current_state[13]\n goal_ang_cos_rad = current_state[14]\n goal_ang_rad = math.acos(goal_ang_cos_rad)\n if goal_ang_sin_rad < 0:\n goal_ang_rad *= -1.\n alpha = max(ball_ang_rad, goal_ang_rad) - min(ball_ang_rad, goal_ang_rad)\n ball_dist_goal = math.sqrt(ball_dist*ball_dist + goal_dist*goal_dist -\n 2.*ball_dist*goal_dist*math.cos(alpha))\n # Compute the difference in ball proximity from the last step\n if not self.first_step:\n ball_prox_delta = ball_proximity - self.old_ball_prox\n kickable_delta = kickable - self.old_kickable\n ball_dist_goal_delta = ball_dist_goal - self.old_ball_dist_goal\n self.old_ball_prox = ball_proximity\n self.old_kickable = kickable\n self.old_ball_dist_goal = ball_dist_goal\n #print(self.env.playerOnBall())\n #print(self.env.playerOnBall().unum)\n #print(self.env.getUnum())\n reward = 0\n if not self.first_step:\n '''# Reward the agent for moving towards the ball\n reward += ball_prox_delta\n if kickable_delta > 0 and not self.got_kickable_reward:\n reward += 1.\n self.got_kickable_reward = True\n # Reward the agent for kicking towards the goal\n reward += 0.6 * -ball_dist_goal_delta\n # Reward the agent for scoring\n if self.status == hfo_py.GOAL:\n reward += 5.0'''\n '''reward = self.__move_to_ball_reward(kickable_delta, ball_prox_delta) + \\\n 3. * self.__kick_to_goal_reward(ball_dist_goal_delta) + \\\n self.__EOT_reward();'''\n mtb = self.__move_to_ball_reward(kickable_delta, ball_prox_delta)\n ktg = 3. * self.__kick_to_goal_reward(ball_dist_goal_delta)\n eot = self.__EOT_reward()\n reward = mtb + ktg + eot\n #print(\"mtb: %.06f ktg: %.06f eot: %.06f\"%(mtb,ktg,eot))\n \n self.first_step = False\n #print(\"r =\",reward)\n return reward",
"def _get_reward(self):\n current_state = self.env.getState()\n ball_proximity = current_state[53]\n goal_proximity = current_state[15]\n ball_dist = 1.0 - ball_proximity\n goal_dist = 1.0 - goal_proximity\n kickable = current_state[12]\n ball_ang_sin_rad = current_state[51]\n ball_ang_cos_rad = current_state[52]\n ball_ang_rad = math.acos(ball_ang_cos_rad)\n if ball_ang_sin_rad < 0:\n ball_ang_rad *= -1.\n goal_ang_sin_rad = current_state[13]\n goal_ang_cos_rad = current_state[14]\n goal_ang_rad = math.acos(goal_ang_cos_rad)\n if goal_ang_sin_rad < 0:\n goal_ang_rad *= -1.\n alpha = max(ball_ang_rad, goal_ang_rad) - min(ball_ang_rad, goal_ang_rad)\n ball_dist_goal = math.sqrt(ball_dist*ball_dist + goal_dist*goal_dist -\n 2.*ball_dist*goal_dist*math.cos(alpha))\n # Compute the difference in ball proximity from the last step\n if not self.first_step:\n ball_prox_delta = ball_proximity - self.old_ball_prox\n kickable_delta = kickable - self.old_kickable\n ball_dist_goal_delta = ball_dist_goal - self.old_ball_dist_goal\n self.old_ball_prox = ball_proximity\n self.old_kickable = kickable\n self.old_ball_dist_goal = ball_dist_goal\n\n reward = 0\n if not self.first_step:\n # Reward the agent for moving towards the ball\n reward += ball_prox_delta\n if kickable_delta > 0 and not self.got_kickable_reward:\n reward += 1.\n self.got_kickable_reward = True\n # Reward the agent for kicking towards the goal\n reward += 3.0 * -ball_dist_goal_delta\n # Reward the agent for scoring\n if self.status == hfo_py.GOAL:\n reward += 5.0\n self.first_step = False\n return reward",
"def _update_reward(self, old_state_key, action, elapsed_time, new_state_key):\n pass",
"def calc_reward_point(self, piece, rewards):\n\n # for reward in rewards:",
"def reward(self):\n\n w_temp = self.config['temperature_w_in_reward']\n w_light = self.config['light_w_in_reward']\n w_cost = self.config['cost_w_in_reward']\n\n cost = self._calculate_cost_and_update_energy_source()\n temp, light = (self.inside_sensors['first']['temperature'],\n self.inside_sensors['first']['light'])\n req = self.user_requests\n\n temp_penalty = abs(temp - req['temp_desired'])\n\n light_penalty = abs(light - req['light_desired'])\n\n reward = (cost * w_cost) \\\n + (temp_penalty * w_temp) \\\n + (light_penalty * w_light)\n\n return -(reward + self.action_penalty)",
"def _calc_step_reward(self, obs, action, reward_state):\n reward, reward_state = self._reward_module.compute_reward(\n obs, action, reward_state)\n return reward, reward_state",
"def update_reward(self):\n reward = 0\n factor = 0\n reward_final = self.replay_memory.memory[-1].reward\n if reward_final >= 19:\n factor = 1\n for idx, transition in enumerate(self.replay_memory.memory[::-1]):\n #print(transition)\n reward_final = self.discount_factor * reward_final\n reward = transition.reward + factor * reward_final\n print(reward)\n # if factor != 1:\n # factor = factor -1\n # reward_final = self.discount_factor * reward_final\n # idx starts at 0\n self.replay_memory.memory[-(idx+1)] = Transition(\n transition.state, transition.action, reward)",
"def get_reward(self, player: PlayerData, state: GameState, previous_action: np.ndarray) -> float:\n raise NotImplementedError",
"def absolute_mod_distance_reward(pred, target, base):\n return absolute_distance_reward(pred, target, base, mod_abs_diff)",
"def reward(self):\n return self._r_sum",
"def _get_rewards(self):\n\n self.reward = np.zeros(4)\n\n for i in range(len(self.pot_new_state)):\n if self.terminal:\n self.reward[i] = 0 # 0 reward staying at termnial state\n else:\n # +10 if reaching the positive termnial state\n if np.all(self.pot_new_state[i] == self.reward_state):\n self.reward[i] = 10\n\n # -100 reaching the negative termnial state\n elif np.all(self.pot_new_state[i] == self.dic_states['s11']):\n self.reward[i] = -100\n\n # -1 for any other state\n else:\n self.reward[i] = -1\n\n self.reward = np.reshape(self.reward, (4, 1))\n\n return",
"def compute_reward(self, action):\n\n r = np.zeros_like(action, dtype=float)\n\n cur_his = self.history[self.t]\n nex_his = self.history[self.t + 1]\n # cur_his = self.history[self.t-1]\n # nex_his = self.history[self.t]\n\n # compute for each training instance in a batch\n for i, a in enumerate(action):\n y_p = cur_his[self.col_name_to_ind[\"y_close\"], i]\n x_p = cur_his[self.col_name_to_ind[\"x_close\"], i]\n nex_y_p = nex_his[self.col_name_to_ind[\"y_close\"], i]\n nex_x_p = nex_his[self.col_name_to_ind[\"x_close\"], i]\n\n if a == 0: # take no position on the spread at time t (current time step)\n if self.position[i] != 0:\n # need to exit at current time step\n self.cash[i] = self.port_val_minus_com[i]\n self.port_val[i] = self.port_val_minus_com[i]\n\n # compute reward (no change since no position on the spread)\n r[i] = 0\n\n # record the current situation\n self.position[i] = 0\n self.quantity['y'][i] = 0\n self.quantity['x'][i] = 0\n elif a == 1: # long the spread: long Y and short X\n if self.position[i] == 2:\n # need to exit at current time step\n self.cash[i] = self.port_val_minus_com[i]\n\n # quantity of each stock will change when the current position is not previous position\n if self.position[i] != 1:\n # compute quantity from cash\n self.quantity['y'][i] = int(2.0 * self.cash[i] / 3.0 / y_p)\n self.quantity['x'][i] = int(2.0 * self.cash[i] / 3.0 / x_p)\n self.short_side_init_price[i] = x_p\n\n # compute entering commission\n enter_commission = (incur_commission(y_p, self.quantity['y'][i])\n + incur_commission(x_p, self.quantity['x'][i]))\n\n # cash remaining after entering a position\n # initial cash - investment amount and commission\n self.cash[i] -= (0.5 * self.quantity['x'][i] * x_p + self.quantity['y'][i] * y_p\n + enter_commission)\n\n lpv = long_portfolio_value(self.quantity['y'][i], y_p)\n spv = short_portfolio_value(self.quantity['x'][i], x_p, self.short_side_init_price[i])\n current_port_val = self.cash[i] + lpv + spv\n\n lpv_nex = long_portfolio_value(self.quantity['y'][i], nex_y_p)\n spv_nex = short_portfolio_value(self.quantity['x'][i], nex_x_p, self.short_side_init_price[i])\n\n # the zero here can be changed to other positive threshold ...\n if spv_nex <= 0:\n # we loss all the money in the short side\n # so need to exit the long side\n self.port_val_minus_com[i] = (\n self.cash[i] + lpv_nex - incur_commission(nex_y_p, self.quantity['y'][i])\n )\n\n # forced to take position 0. this mean all the assets transformed into cash\n self.position[i] = 0\n self.quantity['y'][i] = 0\n self.quantity['x'][i] = 0\n self.cash[i] = self.port_val_minus_com[i]\n self.port_val[i] = self.port_val_minus_com[i]\n else:\n exit_commission = (incur_commission(nex_y_p, self.quantity['y'][i])\n + incur_commission(nex_x_p, self.quantity['x'][i]))\n self.port_val[i] = self.cash[i] + lpv_nex + spv_nex\n self.port_val_minus_com[i] = self.cash[i] + lpv_nex + spv_nex - exit_commission\n self.position[i] = 1\n\n r[i] = self.port_val_minus_com[i] - current_port_val\n\n elif a == 2: # short the spread: short Y and long X\n if self.position[i] == 1:\n # need to exit at current time step\n self.cash[i] = self.port_val_minus_com[i]\n\n # quantity will change when the current position is not previous position\n if self.position[i] != 2:\n # compute quantity from cash\n self.quantity['y'][i] = int(2.0 * self.cash[i] / 3.0 / y_p)\n self.quantity['x'][i] = int(2.0 * self.cash[i] / 3.0 / x_p)\n self.short_side_init_price[i] = y_p\n\n # compute entering commission\n enter_commission = (incur_commission(y_p, self.quantity['y'][i])\n + incur_commission(x_p, self.quantity['x'][i]))\n\n # cash remaining after entering a position\n # initial cash - investment amount and commission\n self.cash[i] -= (self.quantity['x'][i] * x_p + 0.5 * self.quantity['y'][i] * y_p\n + enter_commission)\n\n lpv = long_portfolio_value(self.quantity['x'][i], x_p)\n spv = short_portfolio_value(self.quantity['y'][i], y_p, self.short_side_init_price[i])\n current_port_val = self.cash[i] + lpv + spv\n\n lpv_nex = long_portfolio_value(self.quantity['x'][i], nex_x_p)\n spv_nex = short_portfolio_value(self.quantity['y'][i], nex_y_p, self.short_side_init_price[i])\n\n if spv_nex <= 0:\n # we loss all the money in the short side\n # so need to exit the long side\n self.port_val_minus_com[i] = (\n self.cash[i] + lpv_nex - incur_commission(nex_x_p, self.quantity['x'][i])\n )\n\n # forced to take position 0. this mean all the assets transformed into cash\n self.position[i] = 0\n self.quantity['y'][i] = 0\n self.quantity['x'][i] = 0\n self.cash[i] = self.port_val_minus_com[i]\n self.port_val[i] = self.port_val_minus_com[i]\n else:\n exit_commission = (incur_commission(nex_y_p, self.quantity['y'][i])\n + incur_commission(nex_x_p, self.quantity['x'][i]))\n self.port_val[i] = self.cash[i] + lpv_nex + spv_nex\n self.port_val_minus_com[i] = self.cash[i] + lpv_nex + spv_nex - exit_commission\n self.position[i] = 2\n\n r[i] = self.port_val_minus_com[i] - current_port_val\n\n return r"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Searches the given html file for images which are referenced in the standard way (src attribute on img tag) and returns them as they are written.
|
def find_referenced_images(html):
with open(html, 'r') as infile:
soup = BeautifulSoup(infile.read(), 'html.parser')
return set(img['src'] for img in soup.find_all('img'))
|
[
"def find_img_tags(document):\n return document.findAll('img')",
"def embed_images_in_html(html_file):\n with open(html_file, 'r') as f:\n s = f.read()\n\n s1 = sub('<img src=\"([a-zA-Z0-9_/\\.]*)\" ', _embed_png, s)\n\n with open(html_file, 'w') as f:\n f.write(s1)",
"def get_specimen_images(html):\n try:\n soup = BeautifulSoup(html, 'html.parser')\n imgs = soup.find_all(\"img\")\n\n for img in imgs:\n yield requests.get(img.get(\"src\"), stream=True, allow_redirects=True)\n except:\n raise",
"def extract_image_urls(self, html_str):\n # do something with regex on the HTML\n # return the list of image URLs\n pass",
"def scrape(self, markup):\n soup = BeautifulSoup(markup, 'html.parser')\n downloadedImageInfos = []\n existingImageInfos = []\n for img in soup.find_all('img'):\n src = img.get('src')\n if src and not src.isspace():\n try:\n cachedImageInfo = self.cachedImagesXml.find('image[@remote=\"%s\"]' % src)\n freshlyDownloadedImageInfo = list(filter(lambda elem: elem['remote'] == src, downloadedImageInfos))\n pathToSaveFile = os.path.join(common.GetUpperLevelDir(), self.sectionName, self.journal, self.imagesFolder)\n if cachedImageInfo is not None:\n img['data-local-src'] = u'%s/%s' % (self.imagesFolder, cachedImageInfo.attrib['local'])\n existingImgInfo = {k: v for k, v in cachedImageInfo.attrib.items() if k in ['local', 'remote', 'linkedLocal', 'linkedRemote']}\n self.loadLinkedImage(soup, img, existingImgInfo, pathToSaveFile)\n existingImageInfos.append(existingImgInfo)\n elif len(freshlyDownloadedImageInfo) > 0:\n freshImgInfo = freshlyDownloadedImageInfo[0]\n img['data-local-src'] = u'%s/%s' % (self.imagesFolder, freshImgInfo['local'])\n self.loadLinkedImage(soup, img, freshImgInfo, pathToSaveFile)\n else:\n downloadedImagePath = self.cnn.DownloadImage(src, pathToSaveFile)\n if downloadedImagePath is not None:\n path, filename = os.path.split(downloadedImagePath)\n img['data-local-src'] = u'%s/%s' % (self.imagesFolder, filename)\n self.logger.info(u'Downloaded image from %s' % src)\n imgInfo = {'remote': src, 'local': filename}\n self.loadLinkedImage(soup, img, imgInfo, pathToSaveFile, True)\n downloadedImageInfos.append(imgInfo)\n time.sleep(self.httpRequestDelaySeconds)\n except:\n self.logger.debug(u'%s: %s: Exception on trying to process image path %s in markup \"%s\"' % (self.sectionName, self.journal, src, markup), exc_info = True)\n\n updatedMarkup = self.fixSelfClosingTags(unicode(soup))\n return {'updatedMarkup': updatedMarkup, 'downloadedImageInfos': downloadedImageInfos, 'existingImageInfos': existingImageInfos }",
"def get_links():\n\n directory = \"../_posts\"\n\n for file in os.scandir(directory):\n filename = os.fsdecode(file)\n print(f\"The file's name with path is: {filename}\")\n if filename.endswith(\".html\"):\n write_teaser_image(filename)\n else:\n print(\"Not an HTML file!\")",
"def __copy_html_images(self, build_folder, output_path):\n success = True\n # copy images directly included in cnxmlplus to the output folder\n with open(output_path, 'r') as f_in:\n html = etree.HTML(f_in.read())\n\n for img in html.findall('.//img'):\n src = img.attrib['src']\n dest = os.path.join(os.path.dirname(output_path), src)\n if not os.path.exists(src) and (not os.path.exists(dest)):\n print_debug_msg(src + \" doesn't exist\")\n\n success = copy_if_newer(src, dest)\n\n return success",
"def image(self):\n ret = \"\"\n html = self.html\n m = re.search(\"<img\\s+[^>]+>\", html, flags=re.M | re.I)\n if m:\n m = re.search(\"src=[\\\"\\']([^\\\"\\']+)\", m.group(0), flags=re.I)\n if m:\n ret = m.group(1)\n return ret",
"def scrape_images(url):\n res = requests.get(url)\n assert res.status_code == 200\n\n regex = re.compile('<img (?:(?:.|\\n)*?)src=\"(.*?([^/]*?))\"[\\s/]*>')\n matches = regex.findall(res.text)\n for image_with_relative_url, image_file_name in matches:\n res_image = requests.get(url + image_with_relative_url)\n assert res.status_code == 200\n\n with open(image_file_name, 'wb') as f:\n f.write(res_image.content)",
"def rel2abs_rpt_img_links(str_html):\r\n debug = False\r\n verbose = False\r\n cc = get_cc()\r\n report_path = cc[mg.CURRENT_REPORT_PATH].parent\r\n report_path = f'{report_path}/'\r\n report_path = percent_encode(report_path)\r\n if mg.PLATFORM == mg.WINDOWS:\r\n report_path = fix_perc_encodings_for_win(report_path)\r\n if debug: print(f'report_path: {report_path}')\r\n file_url_start = (mg.FILE_URL_START_WIN if mg.PLATFORM == mg.WINDOWS \r\n else mg.FILE_URL_START_GEN)\r\n abs_display_content = str_html.replace(\r\n mg.IMG_SRC_START, f'{mg.IMG_SRC_START}{file_url_start}{report_path}')\r\n if debug and verbose: \r\n print(f'From \\n\\n{str_html}\\n\\nto\\n\\n{abs_display_content}')\r\n return abs_display_content",
"def _get_images(ig_url, filename):\n # extensions = ('.png', '.jpg', '.jpeg', '.gif', '.tiff', '.bmp',)\n # vid_extensions = ('.mp4', '.mpeg', '.mpg', '.m4p', '.m4v', '.mp2', '.avi',)\n response = requests.get(ig_url)\n app.logger.debug(response)\n soup = bs(response.text, \"html.parser\")\n app.logger.debug(soup)\n images = [img.get('src') for img in soup.findAll('img') if not re.search(\"^\\/\", img.get('src'))]\n app.logger.debug(images)\n goal, bonus = len(images), 0\n file_count = 1\n for image in images:\n # TODO: The following steps are not fully implemented.\n # Check if the src pointed to actual images, or a web page\n # 1) regex to grab the file extension\n name, ext = path.splitext(image)\n # 2) if file extension exists, confirm it matches known image extensions.\n if ext:\n # extension = 'png' # example, but actually set according to a.\n # a) set the output filename to have the same file extension as original file.\n urllib.request.urlretrieve(image, f\"{filename}_{file_count}.{ext}\")\n else:\n # 3) if no file extension or doesn't match known extensions, assume a web page view.\n recur_goal, recur_found = _get_images(image, f\"filename_{file_count}\")\n goal += recur_goal\n bonus += recur_found\n file_count += 1\n return (goal, file_count + bonus)",
"def extract_pic_url(self):\n dom = DOM(self.page_source)\n tag_list = dom('a.rg_l')\n\n for tag in tag_list[:self.image_dl_per_search]:\n tar_str = re.search('imgurl=(.*)&imgrefurl', tag.attributes['href'])\n try:\n self.pic_url_list.append(tar_str.group(1))\n except:\n print('error parsing', tag)",
"def get_image_url_from_page(html):\n if \"/googlebooks/restricted_logo.gif\" in html:\n return\n else:\n match = re.search(r\"preloadImg.src = '([^']*?)'\", html)\n if not match:\n raise ParsingError, \"No image found in HTML page\"\n else:\n return match.group(1).decode(\"string-escape\")",
"def read_murls(self, urlfile):\n pattern = re.compile(r'''(//\\S+.jpg)''')\n imgs = re.findall(pattern, urlfile)\n imgs = [w.replace('jpg.jpg', 'jpg') for w in imgs]\n imgs = [w.replace('t.jpg', '.jpg') for w in imgs]\n imgs = [w.replace('//t.', 'https://i.') for w in imgs]\n imgs = [w.replace('//tn.', 'https://0a.') for w in imgs]\n imgs = [w.replace('/smalltn/', '/galleries/') for w in imgs]\n \n return self.remove_duplicates(imgs)",
"def get_links(url):\n links = []\n res = requests.get(url,headers=header).content\n s = etree.HTML(res)\n for i in s.xpath('//img/@src'):\n if i.startswith('http') and i.endswith('.jpg'):\n links.append(i)\n # print(links[3])\n return links",
"def add_img_attributes(html: ET.Element, content_dir: Path, markdown: Path) -> ET.Element:\n assert content_dir.is_absolute()\n assert markdown.is_absolute()\n \n def visit(element: ET.Element):\n if element.tag == 'img':\n add_attributes(element, content_dir, markdown)\n return\n \n for child in element:\n visit(child)\n \n visit(html)\n return html",
"def get_image_info(self):\n page = urllib2.urlopen(self.page_url, timeout=1)\n htmlstr = page.read()\n if 'removed' in htmlstr:\n raise ValueError('The Page URL for image ' + self.image_id +\n ' is invalid.')\n for keywords in self.image_info.keys():\n startIndex = htmlstr.find(keywords)\n if startIndex == -1:\n raise RuntimeError('Can not find string ' + keywords + ' in '\n 'the webpage.')\n search_length = 100\n pattern = self.image_info_pattern[keywords]\n search_str = htmlstr[startIndex - search_length :startIndex + search_length]\n match = re.findall(pattern, search_str)\n if match != []:\n if '</b></em>' in match[0]:\n result = match[0].split('</em>')[1]\n else:\n result = match[0]\n self.image_info[keywords] = result",
"def _find_all_images(self, soup, data, url):\n all_images = soup.find_all('img')\n for image in all_images:\n item = normalize_image_data(image, url)\n\n data['images'].append(item)",
"def find_images(folder,img_type):\n pass"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Analyzes the given folder produced by the model manager, storing the results in folder/analysis/html
|
def text_analyze(settings: AnalysisSettings, folder: str):
with open(os.path.join(folder, 'hparams', 'misc.json')) as infile:
misc = json.load(infile)
with np.load(os.path.join(folder, 'results.npz')) as infile:
results = dict(infile.items())
in_html_folder = os.path.join(os.path.dirname(__file__), '../html')
in_html_folder = os.path.abspath(in_html_folder)
out_html_folder = os.path.abspath(os.path.join(folder, 'analysis', 'html'))
cwd = os.getcwd()
if os.path.exists(out_html_folder):
shutil.rmtree(out_html_folder)
shutil.copytree(in_html_folder, out_html_folder)
os.chdir(cwd)
with open(os.path.join(in_html_folder, 'index.html'), 'r') as infile:
soup = BeautifulSoup(infile.read(), 'html.parser')
for key, val in misc.items():
_set_all(soup, key.replace('_', '-'), val)
_set_all(soup, 'trials-count', results['final_perf_train'].shape[0])
_set_all(soup, 'trials-train-best-performance', results['final_perf_train'].max())
_set_all(soup, 'trials-train-best-loss', results['final_loss_train'].min())
_set_all(soup, 'trials-train-mean-performance', results['final_perf_train'].mean())
_set_all(soup, 'trials-train-std-performance', results['final_perf_train'].std())
_set_all(soup, 'trials-train-mean-loss', results['final_loss_train'].mean())
_set_all(soup, 'trials-train-std-loss', results['final_loss_train'].std())
_set_all(soup, 'trials-val-best-performance', results['final_perf_val'].max())
_set_all(soup, 'trials-val-best-loss', results['final_loss_val'].min())
_set_all(soup, 'trials-val-mean-performance', results['final_perf_val'].mean())
_set_all(soup, 'trials-val-std-performance', results['final_perf_val'].std())
_set_all(soup, 'trials-val-mean-loss', results['final_loss_val'].mean())
_set_all(soup, 'trials-val-std-loss', results['final_loss_val'].std())
_set_all(soup, 'initial-half-cycle', misc['initial_cycle_time'] // 2)
if misc['batch_sweep_trials_each'] <= 0:
soup.find(id='batch-size-sweep-other').string = ''
else:
soup.find(id='batch-size-sweep-fastest').string = ''
if math.isnan(misc['second_lr_num_trials']):
soup.find(id='second-lr-sweep').string = ''
else:
soup.find(id='no-second-lr-sweep').string = ''
if not settings.hparam_selection_specifics:
soup.find(id='initial-lr-sweep').string = ''
soup.find(id='batch-size-sweep').string = ''
soup.find(id='no-second-lr-sweep').string = ''
soup.find(id='second-lr-sweep').string = ''
if not settings.hparam_selection_specific_imgs:
for div in soup.select('.hparam-figures'):
div.string = ''
if not settings.training_metric_imgs:
for div in soup.select('.trial-figures'):
div.string = ''
with open(os.path.join(out_html_folder, 'index.html'), 'w') as outfile:
outfile.write(str(soup))
|
[
"def results_analysis(dataset, model_folder='results/models/model_85/'):\n # load atlas\n atlas_tsv, _ = load_atlas(custom_tsv=True)\n # load classification\n df_classification = pd.read_csv(os.path.join(model_folder, 'predictions', dataset, 'df_classification.csv'))\n for target in ['disease', 'sex', 'age']:\n scores_path = os.path.join(model_folder, 'attribution_maps/GC', dataset, target, 'normalized_scores.csv')\n normalized_scores = pd.read_csv(scores_path)\n # merge df_classification with normalized_scores\n merge = normalized_scores.merge(df_classification, on=['participant_id', 'session_id'])\n d = {}\n # define classes\n if target in ['disease', 'sex']:\n classes = ['TP', 'TN', 'FP', 'FN']\n else:\n # age\n classes = [1, -1]\n # rename target\n if target == 'disease':\n target = 'diagnosis'\n # compute class analysis\n cols_class = ['diagnosis_class', 'sex_class', 'age_class']\n for class_ in classes:\n d[class_] = MIR(merge[merge[target + '_class'] == class_].drop(columns=cols_class), atlas_tsv, concat_df=True)\n # save analysis\n output_path = os.path.join(model_folder, 'analysis', dataset, 'summary_MIR_{}.csv'.format(target))\n final_df = pd.concat(d.values(), axis=1, keys=d.keys())\n final_df.to_csv(output_path, index=False)",
"def analyze_files():\n jsdl_path = None # Path of the jobstate.log file\n run_directory_writable = (\n False # Flag to indicate if we can write to the run directory\n )\n dagman_out_path = None # Path to the dagman.out file\n\n global workflow_base_dir, dag_path\n\n # Get the dag file if it was not specified by the user\n if dag_path is None:\n dag_path = find_file(input_dir, \".dag\")\n logger.info(\"using %s, use the --dag option to override\" % (dag_path))\n\n # Build dagman.out path\n dagman_out_path = dag_path + \".dagman.out\"\n\n # Check if we can write to the run directory\n run_directory_writable = os.access(input_dir, os.W_OK)\n\n # Invoke monitord if requested\n if run_monitord:\n if output_dir is not None:\n # If output_dir is specified, invoke monitord with that path\n invoke_monitord(\"%s.dagman.out\" % (dag_path), output_dir)\n # jobstate.log file uses wf_uuid as prefix\n jsdl_path = os.path.join(output_dir, get_jsdl_filename(input_dir))\n else:\n if run_directory_writable:\n # Run directory is writable, write monitord output to jobstate.log file\n jsdl_path = os.path.join(input_dir, jsdl_filename)\n # Invoke monitord\n invoke_monitord(\"%s.dagman.out\" % (dag_path), None)\n else:\n # User must provide the --output-dir option\n raise AnalyzerError(\n input_dir\n + \" is not writable. \"\n + \"User must specify directory for new monitord logs with the --output-dir option,\"\n + \" exiting...\"\n )\n else:\n if output_dir is not None:\n # jobstate.log file uses wf_uuid as prefix and is inside output_dir\n jsdl_path = os.path.join(output_dir, get_jsdl_filename(input_dir))\n else:\n jsdl_path = os.path.join(input_dir, jsdl_filename)\n\n # Compare timestamps of jsdl_path with dagman_out_path\n try:\n jsdl_stat = os.stat(jsdl_path)\n except Exception:\n raise AnalyzerError(\"could not access \" + jsdl_path + \", exiting...\")\n\n try:\n dagman_out_stat = os.stat(dagman_out_path)\n except Exception:\n raise AnalyzerError(\"could not access \" + dagman_out_path + \", exiting...\")\n\n # Compare mtime for both files\n if dagman_out_stat[8] > jsdl_stat[8]:\n logger.warning(\n \"jobstate.log older than the dagman.out file, workflow logs may not be up to date...\"\n )\n\n # Try to parse workflow parameters from braindump.txt file\n wfparams = utils.slurp_braindb(input_dir)\n if \"submit_dir\" in wfparams:\n workflow_base_dir = os.path.normpath(wfparams[\"submit_dir\"])\n elif \"jsd\" in wfparams:\n workflow_base_dir = os.path.dirname(os.path.normpath(wfparams[\"jsd\"]))\n\n # First we learn about jobs by going through the dag file\n parse_dag_file(dag_path)\n\n # Read logfile\n parse_jobstate_log(jsdl_path)\n\n # Process our jobs\n analyze()\n\n # Print summary of our analysis\n if summary_mode:\n # PM-1762 in the files mode we don't determine workflow status\n print_top_summary(workflow_status=None)\n else:\n # This is non summary mode despite of the name (go figure)\n print_summary()\n\n # PM-1039\n check_for_wf_start()\n\n if failed > 0:\n # Workflow has failures, exit with exitcode 2\n raise WorkflowFailureError(\"One or more workflows failed\")\n\n # Workflow has no failures, exit with exitcode 0\n return",
"def annotation_stats_and_analysis(dir, language):\r\n\tannotations=get_annotations(dir, language)\r\n\twith open(f'{dir}/analysis_results.txt', 'w', encoding='utf8') as outfile:\r\n\t\tterms_a1_neutral, terms_a2_neutral, terms_a1_positive, terms_a2_positive, terms_a1_negative, terms_a2_negative, vocab, model=get_annotation_stats(annotations, 'en')\r\n\t\tplot_most_frequent_terms(terms_a1_neutral, terms_a1_positive, terms_a1_negative, 1, language, vocab, model)\r\n\t\tplot_most_frequent_terms(terms_a2_neutral, terms_a2_positive, terms_a2_negative, 2, language, vocab, model)\r\n\t\tfull_ner(annotations, language, 1, outfile)\r\n\t\tfull_ner(annotations, language, 2, outfile)\r\n\t\tanalyse_sentiment(annotations, outfile)",
"def RunFolderUpdateAnalysis(folder, noOverwrite=False, removeBoundStates=True):\n\t\n\t#walk all h5 files files \n\tfor dirpath, subfolders, files in os.walk(folder):\n\t\tfor file in filter(lambda s: s.endswith(\".h5\"), files):\n\t\t\tfilename = os.path.join(dirpath, file)\n\t\t\tRunFileUpdateAnalysis(filename, noOverwrite, removeBoundStates=removeBoundStates)\n\t\t\tCheckIonizationProbabilitiesConsistensy(filename)",
"def _analyze(self):\n os.makedirs(self.figures, exist_ok=True)\n os.makedirs(self.mirna_targets_dir, exist_ok=True)\n\n self._copy_read_counts()\n # \"conditions.csv\" files must be made for rbiomir\n self._create_conditions_file()\n self._run_rscript()\n self._clean_up()",
"def generate_scienceie_prediction_folder(\n self, dev_folder: pathlib.Path, pred_folder: pathlib.Path\n ):\n science_ie_data_utils = ScienceIEDataUtils(\n folderpath=dev_folder, ignore_warnings=True\n )\n file_ids = science_ie_data_utils.get_file_ids()\n\n for file_id in file_ids:\n with self.msg_printer.loading(\n f\"Generating Science IE results for file {file_id}\"\n ):\n text = science_ie_data_utils.get_text_from_fileid(file_id)\n sents = science_ie_data_utils.get_sents(text)\n try:\n assert bool(text.split()), f\"File {file_id} does not have any text\"\n except AssertionError:\n continue\n\n try:\n assert len(sents) > 0\n except AssertionError:\n continue\n\n conll_filepath = pred_folder.joinpath(f\"{file_id}.conll\")\n ann_filepath = pred_folder.joinpath(f\"{file_id}.ann\")\n conll_lines = []\n\n for sent in sents:\n line = [token.text for token in sent]\n line = \" \".join(line)\n prediction_classnames = self.on_user_input(line=line)\n\n tag_names = [line.split()]\n for namespace in [\"TASK\", \"PROCESS\", \"MATERIAL\"]:\n # List[str] - List of predicted classnames\n classnames_ = prediction_classnames[namespace][0].split()\n tag_names.append(classnames_)\n assert len(line.split()) == len(\n classnames_\n ), f\"len sent: {len(line.split())}, len task_tag_name: {len(classnames_)}\"\n\n zipped_text_tag_names = list(zip(*tag_names))\n\n for text_tag_name in zipped_text_tag_names:\n token, task_tag, process_tag, material_tag = text_tag_name\n conll_line = \" \".join(\n [token, task_tag, process_tag, material_tag]\n )\n conll_lines.append(conll_line)\n\n with open(conll_filepath, \"w\") as fp:\n fp.writelines(\"\\n\".join(conll_lines))\n fp.write(\"\\n\")\n\n science_ie_data_utils.write_ann_file_from_conll_file(\n conll_filepath=conll_filepath, ann_filepath=ann_filepath, text=text\n )",
"def analyze_directory(dir_path):\n \n setup()\n\n if not os.path.exists(os.path.join(dir_path, 'successful')):\n os.makedirs(os.path.join(dir_path, 'successful'))\n\n if not os.path.exists(os.path.join(dir_path, 'useless')):\n os.makedirs(os.path.join(dir_path, 'useless'))\n\n\n for filename in os.listdir(dir_path):\n \n #For now only supports .apk files\n if not filename.endswith(\".apk\"):\n continue\n\n else:\n apk_path = os.path.join(dir_path, filename) #Set full apk path to currently analyzed .apk file\n decoded_apk_path = dec.decode(apk_path) #Decode apk \n\n try:\n name = extr.get_package_name(decoded_apk_path)\n except extr.NoManifestError:\n print(\"No Manifest was found for this apk. Moving to useless folder\")\n os.rename(apk_path, os.path.join(dir_path, 'useless', filename))\n continue\n\n new_fn = name + '.apk' \n \n #extract config files if possible\n try:\n accessibility_config_file_list = extr.get_accessibility_config_files(decoded_apk_path)\n except extr.NoManifestError:\n print(\"No Manifest was found for this apk. Moving to useless folder\")\n os.rename(apk_path, os.path.join(dir_path, 'useless', new_fn))\n continue\n \n #check if config files were found\n if not accessibility_config_file_list:\n print(\"App doesnt use accessibility\")\n os.rename(apk_path, os.path.join(dir_path, 'useless', new_fn))\n continue\n\n if accessibility_config_file_list is None:\n print('App uses accessibility but no config found')\n continue\n else:\n\n #Extract Accessibility Service descriptions and action phrases\n if not os.path.isfile(strings_xml_path):\n print(\"Failed locate strings.xml. Resuming analysis...\")\n os.rename(apk_path, os.path.join(dir_path, 'useless', new_fn))\n continue\n else:\n with open('samples.csv', 'a') as csv_file:\n writer = csv.writer(csv_file)\n writer.writerow(name.split())\n\n action_phrases, od, ed = get_action_phrases(accessibility_config_file_list)\n if(od is None):\n print(\"Failed to extract descriptions. Resuming analysis...\")\n #os.rename(apk_path, os.path.join(dir_path, 'useless', new_fn))\n continue\n category, stemmed_action_phrases = nlp.get_functionality_category(action_phrases)\n if(category == 'uncategorized'):\n print_descriptions(od, ed)\n print(action_phrases)\n print(stemmed_action_phrases)\n print(colored('Could not categorize app\\'s functionality', 'yellow'))\n print(name)\n inp = input('Enter y to abort:\\n')\n if(inp == 'y'):\n print('Aborting analysis...\\nCleaning up...')\n cleanup()\n exit(0)\n print('Resuming analysis...')\n continue\n \n else:\n print_descriptions(od, ed)\n print(stemmed_action_phrases)\n print(colored(('App was categorized into category: ' + category),'green'))\n print(name)\n inp = input('Enter y to abort:\\n')\n if(inp == 'y'):\n print('Aborting analysis...\\nCleaning up...')\n cleanup()\n exit(0)\n os.rename(apk_path, os.path.join(dir_path, 'successful', new_fn))\n subprocess.call(['sort', '-u', 'samples.csv', '-o', 'samples.csv'])\n print('Done!')\n\n #clean directory\n cleanup()",
"def run(self):\n rootdir = self.req_1.output().path\n newpath = self.output().path\n for src_dir, dirs, files in os.walk(rootdir):\n dst_dir = src_dir.replace(rootdir, newpath, 1)\n if not os.path.exists(dst_dir):\n os.makedirs(dst_dir)\n counter = 0\n for file_ in files:\n src_file = os.path.join(src_dir, file_)\n shutil.copy(src_file, dst_dir)\n counter += 1\n if \"train\" in dst_dir and counter > 50:\n break\n elif \"test\" in dst_dir and counter > 10:\n break",
"def execute_sourcemeter(self):\n # Clean output directory\n shutil.rmtree(os.path.join(self.output_path, self.projectname), True)\n os.makedirs(self.output_path, exist_ok=True)\n template_path = os.path.dirname(os.path.realpath(__file__)) + '/../../templates'\n failure_happened = False\n\n '''\n # try maven\n if os.path.exists(os.path.join(self.input_path, 'pom.xml')):\n logger.info(\"Trying out maven...\")\n self.prepare_template(os.path.join(template_path, 'build-maven.sh'))\n self.prepare_template(os.path.join(template_path, 'analyze-maven.sh'))\n\n try:\n subprocess.run(os.path.join(self.output_path, 'analyze-maven.sh'), shell=True)\n except Exception:\n sys.exit(1)\n pass\n\n if not self.is_output_produced():\n shutil.rmtree(os.path.join(self.output_path, self.projectname), True)\n failure_happened = True\n\n # try ant\n if os.path.exists(os.path.join(self.input_path, 'build.xml')) and failure_happened:\n logger.info(\"Trying out ant...\")\n self.prepare_template(os.path.join(template_path, 'build-ant.sh'))\n self.prepare_template(os.path.join(template_path, 'analyze-ant.sh'))\n\n try:\n subprocess.run(os.path.join(self.output_path, 'analyze-ant.sh'), shell=True)\n except Exception:\n pass\n\n if not self.is_output_produced():\n shutil.rmtree(os.path.join(self.output_path, self.projectname), True)\n failure_happened = True\n '''\n # Currently, we only use directory-based analysis\n failure_happened = True\n\n # use directory based analysis otherwise\n if failure_happened:\n logger.info(\"Trying out directory analysis for java...\")\n self.prepare_template(os.path.join(template_path, 'analyze-dir.sh'))\n\n if self.input_path.endswith(\"/\"):\n self.input_path = self.input_path[:-1]\n\n if self.output_path.endswith(\"/\"):\n self.output_path = self.output_path[:-1]\n\n try:\n subprocess.run(os.path.join(self.output_path, 'analyze-dir.sh'), shell=True)\n except Exception:\n pass\n\n if not self.is_output_produced():\n raise FileNotFoundError('Problem in using mecoshark! No output was produced!')",
"def evaluate_model(model, in_data, out_dir, name):\n log = logging.getLogger('evaluate_model')\n\n log.info('Evaluating model.')\n\n out_path = Path(out_dir) / f'{name}.html'\n\n data = pd.read_parquet(in_data)\n\n test = data[data.istest == True].drop('istest', axis=1)\n\n label = ['points']\n\n X = test.drop(label, axis=1)\n\n y = test[label]\n\n loaded_model = pickle.load(open(model, 'rb'))\n\n predictions = loaded_model.predict(X)\n\n y['predictions'] = predictions\n\n preds_path = Path(out_dir) / 'predictions.parquet.gzip'\n\n y.to_parquet(str(preds_path), compression='gzip')\n\n pweave.weave('report.pmd', doctype=\"md2html\", output=out_path)\n\n log.info('Success! Report saved to {out_path}')\n\n flag = Path(out_dir) / '.SUCCESS'\n\n flag.touch()",
"def collect_dataset(java_folder, max_classes=None):\n\n os.chdir(Path(Config.home_aibolit_folder(), 'scripts'))\n if not java_folder:\n java_folder = Path('target/01').absolute()\n print('Analyzing {} dir:'.format(java_folder))\n\n print('Current working directory: ', Path(os.getcwd()))\n print('Directory with JAVA classes: ', java_folder)\n print('Filtering java files...')\n\n filter_cmd = ['make', 'filter']\n metrics_cmd = ['make', 'metrics']\n if java_folder is not None:\n filter_cmd.append(f'dir={java_folder}')\n metrics_cmd.append(f'dir={java_folder}')\n if max_classes is not None:\n filter_cmd.append(f'max_classes={max_classes}')\n\n result = subprocess.run(filter_cmd, stdout=subprocess.PIPE)\n if result.returncode != 0:\n print(result.stderr)\n exit(2)\n else:\n print(result.stdout)\n\n print('Download PMD and compute metrics...')\n result = subprocess.run(metrics_cmd, stdout=subprocess.PIPE)\n if result.returncode != 0:\n print(result.stderr)\n exit(2)\n else:\n print(result.stdout)\n\n print('Compute patterns...')\n result = subprocess.run(['make', 'patterns'], stdout=subprocess.PIPE)\n if result.returncode != 0:\n print(result.stderr)\n exit(3)\n else:\n print(result.stdout)\n\n print('Build halstead jar...')\n result = subprocess.run(['make', 'build_halstead'], stdout=subprocess.PIPE)\n if result.returncode != 0:\n print(result.stderr)\n exit(4)\n else:\n print(result.stdout)\n\n print('Run halstead jar...')\n result = subprocess.run(['make', 'hl'], stdout=subprocess.PIPE)\n if result.returncode != 0:\n print(result.stderr)\n exit(5)\n else:\n print(result.stdout)\n\n print('Merge results and create dataset...')\n result = subprocess.run(['make', 'merge'], stdout=subprocess.PIPE)\n if result.returncode != 0:\n print(result.stderr)\n exit(6)\n else:\n print(result.stdout)",
"def save_all_results(self, path, experiment_title, dataset_name, training_size, test_accuracy, noise=None):\n\n # We initialize a list with all the folder needed to save the results\n folders_name = [experiment_title, self.tuning_method]\n\n # We adjust add an element to the list if there's a method type\n if self.method_type is not None:\n folders_name.append(self.method_type)\n\n # We create all folder expected in the folder Results (if they don't already exist)\n for folder_name in folders_name:\n path = os.path.join(path, folder_name.upper(), '')\n self.create_folder(path)\n\n # We save all important data for the ExperimentAnalyst in the path concerned\n self.__save_tuning_summary(path, experiment_title, dataset_name, training_size, noise, test_accuracy)\n self.__save_accuracy_history(path)\n self.__save_accuracy_history(path, best_accuracy=True)\n self.__save_hyperparameters(path)",
"def make_output_paths(self):\n if jedli_global.ask_output_filename:\n self.new_file = asksaveasfilename(title= \"Choose a name for the output file\",\n initialdir=jedli_global.output_folder,\n filetypes=[(\"html files\", \".html\")])\n if not self.new_file.endswith(\".html\"):\n self.new_file += \".html\"\n self.main_dir, self.base_filename = os.path.split(self.new_file)\n self.base_filename = os.path.splitext(self.base_filename)[0]\n else:\n if self.checklist_name is not None:\n self.base_filename = self.checklist_name.split(\"/\")[-1].split(\".\")[0]\n else:\n self.base_filename = re.sub(\"\\W+\", \"\", self.words[0])\n self.main_dir = self.make_dir(jedli_global.output_folder, self.base_filename)\n \n if self.index_type == \"Context Search\":\n self.new_file = os.path.join(self.main_dir, \"{}_in_context.html\".format(self.base_filename)) \n else:\n self.new_file = os.path.join(self.main_dir, \"index_{}.html\".format(self.base_filename))\n \n self.data_dir = self.make_dir(self.main_dir, \"data\")\n self.json_pth = os.path.join(self.data_dir, \"{}_datecount.json\".format(self.base_filename))\n self.graph_pth = os.path.join(self.data_dir, \"{}_graph.html\".format(self.base_filename))\n self.table_pth = os.path.join(self.data_dir, \"{}_table.html\".format(self.base_filename))",
"def content_analysis():\n analysis = ContentAnalysisModel()\n path = os.path.join(constants.TMP_FOLDER,\n constants.UPLOAD_FOLDER,\n session['id'], 'content_analysis/')\n if os.path.isdir(path):\n dictionary_names = [name for name in os.listdir(path)]\n else:\n dictionary_names = []\n if request.method == 'GET':\n if 'dictionary_labels' in session:\n dict_labels = session['dictionary_labels']\n else:\n dict_labels = []\n if 'active_dictionaries' in session:\n active_dicts = session['active_dictionaries']\n else:\n active_dicts = [True] * len(dict_labels)\n if 'toggle_all_value' in session:\n toggle_all_value = session['toggle_all_value']\n else:\n toggle_all_value = True\n if 'formula' in session:\n formula = session['formula']\n else:\n formula = \"\"\n return render_template('contentanalysis.html',\n dictionary_labels=dict_labels,\n active_dictionaries=active_dicts,\n toggle_all_value=toggle_all_value,\n itm=\"content-analysis\",\n formula=formula)\n else:\n num_active_docs = detect_active_docs()\n active_dicts = ContentAnalysisReceiver().options_from_front_end(\n ).active_dicts\n dict_labels = ContentAnalysisReceiver().options_from_front_end(\n ).dict_labels\n session['formula'] = ContentAnalysisReceiver().options_from_front_end(\n ).formula\n if len(dict_labels) == 0:\n dict_labels = [os.path.splitext(dict_name)[0]\n for dict_name in dictionary_names]\n active_dicts = [True] * len(dict_labels)\n num_active_dicts = active_dicts.count(True)\n if num_active_docs == 0 and num_active_dicts == 0:\n return error(\"At least 1 active document and 1 active \"\n \"dictionary are required to perform a \"\n \"content analysis.\")\n elif num_active_docs == 0:\n return error(\"At least 1 active document is required to perform \"\n \"a content analysis.\")\n elif num_active_dicts == 0:\n return error(\"At least 1 active dictionary is required to perform\"\n \" a content analysis.\")\n file_manager = load_file_manager()\n active_files = file_manager.get_active_files()\n for file in active_files:\n analysis.add_file(file_name=file.name,\n label=file.label,\n content=file.load_contents())\n for dict_name, dict_label, active in zip(dictionary_names,\n dict_labels,\n active_dicts):\n if active:\n f = open(os.path.join(path, dict_name), \"r\")\n content = f.read()\n analysis.add_dictionary(file_name=dict_name,\n label=dict_label,\n content=content)\n result_table, corpus_raw_counts_table, files_raw_counts_tables,\\\n formula_errors = analysis.analyze()\n if len(formula_errors) != 0 or result_table is None:\n return error(formula_errors)\n data = {\"result_table\": result_table,\n \"dictionary_labels\": dict_labels,\n \"active_dictionaries\": active_dicts,\n \"corpus_raw_counts_table\": corpus_raw_counts_table,\n \"files_raw_counts_tables\": files_raw_counts_tables,\n \"error\": False}\n return json.dumps(data)",
"def analyze_files(self) -> None:\r\n try:\r\n files = os.listdir(self.directory)\r\n except FileNotFoundError:\r\n raise FileNotFoundError(f\"{self.directory} not exists! Please provide a valid directory!\")\r\n else:\r\n for file in files:\r\n if file.endswith(\".py\"):\r\n self.file_stats(os.path.join(self.directory,file))",
"def scan(folder, amp_threshold, plot):\r\n files = get_files(Path(folder))\r\n length_s = 0\r\n length_s_above_threshold = 0\r\n\r\n print(f'{len(files)} have been found and will be analyzed.')\r\n\r\n for wavfile in files:\r\n analysis = analyze_wav(wavfile, amp_threshold, plot)\r\n length_s += analysis['length_s']\r\n length_s_above_threshold += analysis['length_s_above_threshold']\r\n\r\n print(f'{len(files)} files have been analyzed')\r\n print(f'Overall Length: {round(length_s)} s / {round(length_s/60)} m / {round(length_s/60/60)} h')\r\n print(f'Overall Length (above Treshold (amp > {amp_threshold})): {round(length_s_above_threshold)} s / {round(length_s_above_threshold/60)} m')",
"def index_dir(self, root, **args):\n\n self.multifield = args['multifield']\n self.positional = args['positional']\n self.stemming = args['stem']\n self.permuterm = args['permuterm']\n self.suggestion = args['suggestion']\n\n if self.multifield:\n for field, _ in SAR_Project.fields:\n self.index[field] = {}\n\n print(\"Root : \" + root)\n\n if self.suggestion:\n self.spellsuggester = SpellSuggester(root)\n\n for dir, subdirs, files in os.walk(root):\n for filename in files:\n if filename.endswith('.json'):\n fullname = os.path.join(dir, filename)\n\n self.index_file(fullname)\n\n if self.stemming:\n self.make_stemming()\n\n if self.permuterm:\n self.make_permuterm()",
"def batchAnalyzeFolder(folderPath) -> int:\n \n import analyzeflow\n \n if not os.path.isdir(folderPath):\n logger.error(f'error: batchAnalyzeFolder() did not find folder path: {folderPath}')\n return\n\n files = os.listdir(folderPath)\n files = sorted(files)\n \n # count tif files\n tifList = []\n for file in files:\n if not file.endswith('.tif'):\n continue\n tifList.append(file)\n \n numTif = len(tifList)\n\n for idx, tifFile in enumerate(tifList):\n # if not file.endswith('.tif'):\n # continue\n tifPath = os.path.join(folderPath, tifFile)\n\n logger.info(f'=== tif file {idx+1} of {numTif}')\n logger.info(f' path: {tifPath}')\n \n kff = analyzeflow.kymFlowFile(tifPath)\n\n kff.analyzeFlowWithRadon() # do actual kym radon analysis\n kff.saveAnalysis() # save result to csv\n\n logger.info(f'Done processing {numTif} tif files in folder {folderPath}.')\n\n return numTif",
"def _analyze(ctx, consortium, workspace, details, validate_buckets):\n if workspace:\n if not consortium:\n consortium = _consortium_from_workspace(ctx.obj['config'], workspace)\n workspace_names = [(consortium, workspace)]\n else:\n workspace_names = fetch_workspace_names(ctx.obj['output_path'], requested_consortium_name=consortium, workspace_name=workspace)\n\n import os\n import contextlib\n with contextlib.suppress(FileNotFoundError):\n os.remove(f\"{ctx.obj['output_path']}/analysis.ndjson\")\n\n file_name = f\"{ctx.obj['output_path']}/analysis.ndjson\"\n logging.info(f\"writing to {file_name}\")\n with Pool(maxtasksperchild=1) as pool:\n for consortium_name, workspace_name in workspace_names:\n pool.starmap(_print_analysis, [(ctx.obj['output_path'], consortium_name, workspace_name, details, validate_buckets, ctx.obj['config'], file_name)])"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Load data from a file and convert to binary using the given cutoff, and only keep the first dim_feature columns. (for MNIST data, the last column is label and should be ignored)
|
def get_data(filename, dim_feature, cutoff=0.5):
data = np.loadtxt(filename, dtype=float, delimiter=",")
data_labels = data[:, dim_feature]
data = data[:, xrange(dim_feature)]
## convert to binary
data = np.greater_equal(data, cutoff).astype(int)
return (data_labels, data)
|
[
"def extract_sklearn_features_categorical(categories, categories_to_val_map,\n dataset):\n dataset_binary = []\n for row in dataset.iterrows():\n row = list(row[1][categories])\n row_binary = binarize_categorical_row(\n categories, categories_to_val_map, row)\n dataset_binary.append(row_binary)\n return np.asarray(dataset_binary)",
"def load_word2vec_binary(fname):\n vocab = []\n vectors = None\n\n with open(fname) as fin:\n header = fin.readline()\n vocab_size, vector_size = map(int, header.split())\n\n vectors = np.empty((vocab_size, vector_size), dtype=np.float)\n binary_len = np.dtype(np.float32).itemsize * vector_size\n for line_no in xrange(vocab_size):\n word = ''\n while True:\n ch = fin.read(1)\n if ch == ' ':\n break\n word += ch\n vocab.append(word.strip())\n\n vector = np.fromstring(fin.read(binary_len), np.float32)\n vectors[line_no] = vector\n return pd.DataFrame(vectors, index=vocab)",
"def load_data_bin(filePath):\n \n dataFile = open(filePath)\n \n data = []\n labels = []\n for sample in dataFile:\n fields = sample.strip('\\n').split('\\t')\n fields = [int(x) for x in fields] \n labels.append(fields[0])\n data.append(fields[1:])\n dataFile.close()\n return data, labels",
"def load_caffe() -> Any:\n if not os.path.isfile(caffemodel):\n download_caffe_model()\n model = cv.dnn.readNetFromCaffe(prototxt, caffemodel)\n pts = np.load(np_hull)\n # add the cluster centers as 1x1 convolutions to the model\n class8 = model.getLayerId(\"class8_ab\")\n conv8 = model.getLayerId(\"conv8_313_rh\")\n pts = pts.transpose().reshape(2, 313, 1, 1)\n model.getLayer(class8).blobs = [pts.astype(\"float32\")]\n model.getLayer(conv8).blobs = [np.full([1, 313], 2.606, dtype=\"float32\")]\n return model",
"def binarization(data_file_name, conversion_dict):\n\n\toutput_file_name = data_file_name.split(\".\")\n\toutput_file_name = output_file_name[0]+\"_binary.csv\"\n\n\tdata = open(data_file_name, \"r\")\n\tcmpt = 0\n\tindexToVariableName = {}\n\tindexOfVariableToDelete = []\n\tidentifiant_index = \"undef\"\n\tvariables_keep_index = []\n\n\t# Select Column to Write\n\tfor line in data:\n\t\tlineWithoutBackN = line.split(\"\\n\")\n\t\tlineWithoutBackN = lineWithoutBackN[0]\n\t\tlineInArray = lineWithoutBackN.split(\";\")\n\t\tif(cmpt==0):\n\t\t\tindex = 0\n\t\t\tfor variable in lineInArray:\n\n\t\t\t\tPossibleValueToBinaryValue = conversion_dict[variable]\n\n\t\t\t\t# catch the identifiant variable\n\t\t\t\tif(variable == \"\\Clinical\\Sampling\\OMICID\"):\n\t\t\t\t\tidentifiant_index = index\n\t\t\t\t\tvariables_keep_index.append(identifiant_index)\n\n\t\t\t\t# catch the variable with binary values in description file\n\t\t\t\tif(len(PossibleValueToBinaryValue.values()) > 0):\n\t\t\t\t\t# scan the binary values for ERROR entry\n\t\t\t\t\tif(\"ERROR\" not in PossibleValueToBinaryValue.values()):\n\t\t\t\t\t\tvariables_keep_index.append(index)\n\n\t\t\t\tindexToVariableName[index] = variable\t\t\t\n\t\t\t\tindex += 1\n\t\tcmpt += 1\n\tdata.close()\n\t\t\n\n\t# Perform the conversion\n\tdata = open(data_file_name, \"r\")\n\tdata_converted = open(output_file_name, \"w\")\n\tcmpt =0\n\theader_new = \"\"\n\tfor line in data:\n\t\tlineWithoutBackN = line.split(\"\\n\")\n\t\tlineWithoutBackN = lineWithoutBackN[0]\n\t\tlineInArray = lineWithoutBackN.split(\";\")\n\n\t\tline_new = \"\"\n\n\t\tif(cmpt == 0):\n\t\t\tindex = 0\n\t\t\tfor variable in lineInArray:\n\t\t\t\tif(index in variables_keep_index):\n\t\t\t\t\theader_new += variable +\";\" \n\t\t\t\tindex += 1\n\t\t\theader_new = header_new[:-1]\n\t\t\tdata_converted.write(header_new+\"\\n\")\n\n\n\t\telse:\n\t\t\tindex = 0\n\t\t\tfor scalar in lineInArray:\n\t\t\t\tvariable_name = indexToVariableName[index]\n\t\t\t\tif(index in variables_keep_index):\n\t\t\t\t\tPossibleValueToBinaryValue = conversion_dict[variable_name]\n\t\t\t\t\tif(index != identifiant_index):\n\t\t\t\t\t\tscalar_new = PossibleValueToBinaryValue[scalar]\n\t\t\t\t\telse:\n\t\t\t\t\t\tscalar_new = scalar\n\n\t\t\t\t\tline_new += scalar_new +\";\"\n\n\t\t\t\tindex += 1\n\t\t\tline_new = line_new[:-1]\n\t\t\tdata_converted.write(line_new+\"\\n\")\n\t\tcmpt += 1\n\tdata_converted.close()\n\tdata.close()",
"def read_training_data():\n data_file = open('../RPCRunner/data/data', 'rb')\n labels_file = open('../RPCRunner/data/labels', 'rb')\n labels = np.loadtxt(labels_file, dtype=np.int8)\n data = np.fromstring(np.array([data_file.read(650) for i in labels]),\n dtype=np.uint8)\n return np.reshape(data, (-1, 650)), labels",
"def test_binarizer_remove_first(self):\n n_cuts = 3\n one_hot_encoder = OneHotEncoder(sparse=True)\n expected_binarization = one_hot_encoder.fit_transform(\n self.default_expected_intervals)\n\n binarizer = FeaturesBinarizer(method='quantile', n_cuts=n_cuts,\n detect_column_type=\"auto\",\n remove_first=True)\n\n binarizer.fit(self.features)\n binarized_array = binarizer.transform(self.features)\n self.assertEqual(binarized_array.__class__, csr.csr_matrix)\n\n expected_binarization_without_first = \\\n np.delete(expected_binarization.toarray(), [0, 4, 8, 10], 1)\n\n np.testing.assert_array_equal(expected_binarization_without_first,\n binarized_array.toarray())\n\n return",
"def encode_data_as_binary(self, x_train, x_test):\n\n x_train_bin = np.array(x_train > self.bthreshold, dtype=np.float32)\n x_test_bin = np.array(x_test > self.bthreshold, dtype=np.float32)\n\n self.Helpers.logger.info(\"Data converted to binary encoding!\")\n\n return x_train_bin, x_test_bin",
"def create_criteo_dataset(file, embed_dim=8, read_part=True, sample_num=100000, test_size=0.2):\n names = ['label', 'I1', 'I2', 'I3', 'I4', 'I5', 'I6', 'I7', 'I8', 'I9', 'I10', 'I11',\n 'I12', 'I13', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'C10', 'C11',\n 'C12', 'C13', 'C14', 'C15', 'C16', 'C17', 'C18', 'C19', 'C20', 'C21', 'C22',\n 'C23', 'C24', 'C25', 'C26']\n\n if read_part:\n data_df = pd.read_csv(file, sep='\\t', iterator=True, header=None,\n names=names)\n data_df = data_df.get_chunk(sample_num)\n\n else:\n data_df = pd.read_csv(file, sep='\\t', header=None, names=names)\n\n sparse_features = ['C' + str(i) for i in range(1, 27)]\n dense_features = ['I' + str(i) for i in range(1, 14)]\n features = sparse_features + dense_features\n\n data_df[sparse_features] = data_df[sparse_features].fillna('-1')\n data_df[dense_features] = data_df[dense_features].fillna(0)\n\n # Bin continuous data into intervals.\n est = KBinsDiscretizer(n_bins=100, encode='ordinal', strategy='uniform')\n data_df[dense_features] = est.fit_transform(data_df[dense_features])\n\n for feat in sparse_features:\n le = LabelEncoder()\n data_df[feat] = le.fit_transform(data_df[feat])\n\n # ==============Feature Engineering===================\n\n # ====================================================\n feature_columns = [sparseFeature(feat, int(data_df[feat].max()) + 1, embed_dim=embed_dim)\n for feat in features]\n train, test = train_test_split(data_df, test_size=test_size)\n\n train_X = train[features].values.astype('int32')\n train_y = train['label'].values.astype('int32')\n test_X = test[features].values.astype('int32')\n test_y = test['label'].values.astype('int32')\n\n return feature_columns, (train_X, train_y), (test_X, test_y)",
"def read_binary_mask(mask_fname: str) -> np.ndarray:\n mask = cv2.imread(mask_fname, cv2.IMREAD_GRAYSCALE)\n if mask is None:\n raise FileNotFoundError(f\"Cannot find {mask_fname}\")\n\n cv2.threshold(mask, thresh=0, maxval=1, type=cv2.THRESH_BINARY, dst=mask)\n return mask",
"def bin_data(data,column_names):\n\n # Get basic column statistics and bin sizes\n nfeats = len(column_names)\n bin_stats = {'min': data.min(),\n 'max': data.max()}\n print(bin_stats)\n column_bin_size = (bin_stats['max'] * (1 + 10**-6) - bin_stats['min'])/200\n\n # Transform data into bin positions for fast binning\n data = ((data - bin_stats['min'])/column_bin_size).apply(np.floor)\n data_ind = pandas.notnull(data) # Handle NaN values\n data[~data_ind] = 255 # Handle NaN values\n data = data.astype(np.uint16) # cast to save memory\n data[data==200] = 199 # in case of numerical precision issues\n\n # initialize bins, try to be memory efficient\n nrows = data.shape[0]\n if nrows < 2**8:\n dtype = np.uint8\n elif nrows < 2**16:\n dtype = np.uint16\n elif nrows < 2**32:\n dtype = np.uint32\n else:\n dtype = np.uint64\n bins = np.zeros((nfeats,nfeats,200,200),dtype=dtype)\n\n # Create a linear index for feature bins\n linear_index = []\n\n # Bin the data\n for feat1 in range(nfeats):\n name1 = column_names[feat1]\n feat1_tf = data[name1] * 200 # Convert to linear matrix index\n\n for feat2 in range(feat1+1,nfeats):\n name2 = column_names[feat2]\n \n # Remove all NaN values\n feat2_tf = data[name2]\n feat2_tf = feat2_tf[data_ind[name1] & data_ind[name2]]\n \n if feat2_tf.size<=1:\n continue\n \n # sort linear matrix indices\n feat2_sort = np.sort(feat1_tf[data_ind[name1] & data_ind[name2]] + feat2_tf)\n \n # Do math to get the indices\n ind2 = np.diff(feat2_sort) \n ind2 = np.nonzero(ind2)[0] # nonzeros are cumulative sum of all bin values\n ind2 = np.append(ind2,feat2_sort.size-1)\n # print(feat2_sort.shape)\n rows = (feat2_sort[ind2]/200).astype(np.uint8) # calculate row from linear index\n cols = np.mod(feat2_sort[ind2],200) # calculate column from linear index\n counts = np.diff(ind2) # calculate the number of values in each bin\n bins[feat1,feat2,rows[0],cols[0]] = ind2[0] + 1\n bins[feat1,feat2,rows[1:],cols[1:]] = counts\n linear_index.append([feat1,feat2])\n return bins, bin_stats, linear_index",
"def _read_binary_matrix(filename):\n with tf.gfile.GFile(filename, \"rb\") as f:\n s = f.read()\n magic = int(np.frombuffer(s, \"int32\", 1))\n ndim = int(np.frombuffer(s, \"int32\", 1, 4))\n eff_dim = max(3, ndim)\n raw_dims = np.frombuffer(s, \"int32\", eff_dim, 8)\n dims = []\n for i in range(0, ndim):\n dims.append(raw_dims[i])\n\n dtype_map = {507333717: \"int8\",\n 507333716: \"int32\",\n 507333713: \"float\",\n 507333715: \"double\"}\n data = np.frombuffer(s, dtype_map[magic], offset=8 + eff_dim * 4)\n data = data.reshape(tuple(dims))\n return data",
"def load_featuredf():\n with open('intermediate/features/featuredf.pkl', 'rb') as f:\n fdf = pickle.load(f)\n\n # exclude Treasure Island\n fdf = fdf[(fdf.lon < -122.375) | (fdf.lat < 37.805)]\n\n # exclude piers off Mission Bay\n fdf = fdf.drop([5662, 6742], axis=0)\n\n return fdf",
"def read_features_from_file(filename, desc_dim=132):\n\n print filename\n f = np.loadtxt(filename)\n\n if f.shape[0] == 0:\n f = np.zeros((1, desc_dim))\n print filename\n return f[:, :4], f[:, 4:] # feature locations, descriptors",
"def extract_obsmode_data(files, bin_data=True, bin_res=0.125, label_only=False, labels=\"clean\"):\n\n if labels == \"clean\":\n belloni_turned = convert_belloni.convert_belloni_clean()\n else:\n belloni_states = convert_belloni.main()\n belloni_turned = convert_belloni.turn_states(belloni_states)\n\n\n d_all = []\n for f in files:\n fstring = f.split(\"_\")[1]\n if fstring in belloni_turned:\n state = belloni_turned[fstring]\n else:\n state = None\n if label_only:\n continue\n\n d = np.loadtxt(f)\n dt_data = d[1:,0]-d[:-1,0]\n\n dt_min = np.min(dt_data)\n\n ## compute nbins, if nbins is <=1, don't bin\n ## because target resolution is smaller than\n ## native resolution, and we don't resample.\n nbins = int(bin_res/dt_min)\n if nbins <= 1:\n print(\"Target resolution smaller than native time resolution. Not binning!\")\n bin_data=False\n\n ### split data with breaks\n breaks = np.where(dt_data > 0.008)[0]\n if len(breaks) == 0:\n dtemp = d\n if bin_data:\n dshort = bin_lightcurve(dtemp, nbins)\n else:\n dshort = dtemp\n d_all.append([dshort, state, fstring])\n else:\n for i,b in enumerate(breaks):\n if i == 0:\n if b == 0:\n continue\n else:\n dtemp = d[:b]\n if bin_data:\n dshort = bin_lightcurve(dtemp, nbins)\n else:\n dshort = dtemp\n\n else:\n dtemp = d[breaks[i-1]+1:b]\n if bin_data:\n dshort = bin_lightcurve(dtemp, nbins)\n else:\n dshort = dtemp\n\n d_all.append([dshort, state, fstring])\n\n ## last segment\n dtemp = d[b+1:]\n if bin_data:\n dshort = bin_lightcurve(dtemp, nbins)\n else:\n dshort = dtemp\n\n d_all.append([dshort, state, fstring])\n\n return d_all",
"def load_test_data():\n testDataFile = \"../data/traindata_test.txt\"\n wordToVecDictFile = \"../data/glove/glove.6B.50d.txt\"\n X = FeatureProcessing.testFeatureProcess(testDataFile,wordToVecDictFile,window_size)\n return X",
"def uncompress_features_labels(self, file):\n \n features = []\n labels = []\n \n with ZipFile(file) as zipf:\n # Progress bar\n filenames_pbar = tqdm(zipf.namelist(), unit='files')\n \n # Get features and labels from all files\n for filename in filenames_pbar:\n # Check if the file is a directory\n if not filename.endswith('/'):\n with zipf.open(filename) as image_file:\n image = Image.open(image_file)\n image.load()\n \n # Load image data as 1-dimensional array\n # Use float32 to save on memory space\n feature = np.array(image, dtype=np.float32).flatten()\n \n # Get the letter from the filename\n label = os.path.split(filename)[1][0]\n \n # Append current feature and label\n features.append(feature)\n labels.append(label)\n \n return np.array(features), np.array(labels)",
"def multiclass_dataset(train_files,test_files,\n label=0.9,bias=1.,\n scale_min=0., scale_max=1.,scale_prop=\"local\",\n feature_key=\"features\",target_key=\"target_midi\"):\n # read all features\n features = []\n targets = []\n feature = []\n target = []\n for file in train_files:\n data = shelve.open(file)\n print file,\"feature shape:\", data[feature_key].shape\n feature.append(data[feature_key])\n target.append(data[target_key])\n data.close()\n features.append(feature)\n targets.append(target)\n feature = []\n target = []\n for file in test_files:\n data = shelve.open(file)\n print file,\"feature shape:\", data[feature_key].shape\n feature.append(data[feature_key])\n target.append(data[target_key])\n data.close()\n features.append(feature)\n targets.append(target)\n \n # make data preprocessing\n data_preprocessing(features,bias,scale_min,scale_max,0,scale_prop)\n\n # make targets\n \n # check how many pitch classes we have\n all_keys = []\n for el in targets[0]:\n all_keys += el.tolist()\n for el in targets[1]:\n all_keys += el.tolist()\n classes = list(set(all_keys))\n classes.sort()\n print \"classes:\", classes\n print \"nr classes:\",len(classes)\n \n # make (binary) target data\n cl_targets = []\n targ = []\n for piece in targets[0]:\n target = np.ones((len(piece), len(classes))) * (-1)*label\n for n in range(len(piece)):\n ind = classes.index( piece[n] )\n target[n,ind] = label\n targ.append(target)\n cl_targets.append(targ)\n targ = []\n for piece in targets[1]:\n target = np.ones((len(piece), len(classes))) * (-1)*label\n for n in range(len(piece)):\n ind = classes.index( piece[n] )\n target[n,ind] = label\n targ.append(target)\n cl_targets.append(targ)\n \n # make train and test data\n trainin = features[0]\n testin = features[1]\n trainout = cl_targets[0]\n testout = cl_targets[1]\n\n return trainin, trainout, testin, testout",
"def load_data(filename, train_features, target_features):\n engine = create_engine('sqlite:///output/' + filename+'.db')\n df = pd.read_sql_table(filename, engine)\n\n Y = df.loc[:,target_features]\n X = df.loc[:,train_features]\n \n return X, Y",
"def multiclass_anytime(data_file,train_range,test_range,\n label=0.9,bias=1.,\n scale_min=0., scale_max=1.,scale_prop=\"local\",\n feature_key=\"features\",target_key=\"targets\"):\n # read features and targets\n features = []\n targets = []\n data = shelve.open(data_file)\n feature = []\n feature.append(data[feature_key])\n features.append(feature) # because of the double list needed by data_preproc\n targets.append(data[target_key])\n data.close()\n \n # make data preprocessing\n data_preprocessing(features,bias,scale_min,scale_max,0,scale_prop)\n \n # scale targets\n mins,maxs = calc_minmax(targets)\n channels = len(mins)\n scale_data(targets,mins,maxs,(-1)*label*np.ones(channels),\n label*np.ones(channels),\"local\")\n \n # make train and test data\n trainin = []\n testin = []\n trainout = []\n testout = []\n trainin.append(features[0][0][train_range[0]:train_range[1]])\n trainout.append(targets[0][train_range[0]:train_range[1]])\n testin.append(features[0][0][test_range[0]:test_range[1]])\n testout.append(targets[0][test_range[0]:test_range[1]])\n\n return trainin, trainout, testin, testout"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
y is n X d, x is n X p returns y_res, an n X d matrix such that the ith column of y_res contains the residuals of the ith column of y after regressing out x.
|
def regress_out(y, x):
regr = linear_model.LinearRegression(True)
n = y.shape[0]
# if x is a n X 1 vector in the format (n,), change it's size to (n,1)
if x.ndim == 1:
x = x.reshape(-1,1)
if get_dim(y) == 2 :
d = y.shape[1]
y_res = zeros([n,d])
for i in range(d):
regr.fit(x, y[:,i].ravel())
pred = regr.predict(x)
y_res[:,i] = y[:,i] - pred
else:
if y.ndim == 2:
y = y.reshape(-1,) # make a (n,1) vector to (n,) vector
regr.fit(x, y)
pred = regr.predict(x)
y_res = y - pred
return y_res
|
[
"def regress(X, y):\n w = np.linalg.solve(np.dot(X.T, X), np.dot(X.T, y))\n return w",
"def regression(Y, X):\n # Add a constant column to X\n X = numpy.hstack((numpy.array([[1]*X.shape[0]]).T, X))\n (coeffs, residuals, rank, s) = numpy.linalg.lstsq(X, numpy.transpose(Y))\n return coeffs",
"def residuals(self): \n\t\treturn np.subtract(self.y, self.predict(self.X))",
"def residuals(parameters: tuple[float, float, float], y_values: np.ndarray, x_values: np.ndarray):\n err = estimate_ys(x_values, parameters) - y_values\n return err",
"def nu_linregress(x, y):\n cols = ['slope', 'intercept', 'rvalue', 'pvalue', 'stderr']\n # Make sure x and y are arrays\n x = np.asarray(x)\n y = np.asarray(y)\n n = len(x)\n # means in vector form\n xmean = np.mean(x, None)\n ymean = np.mean(y, None)\n # average sum of squares:\n ssxm, ssxym, ssyxm, ssym = np.cov(x, y, bias=True).flat\n r_num = ssxym\n r_den = np.sqrt(ssxm * ssym)\n # Estimate correlation\n r = r_num / r_den\n # test for numerical error propagation\n if r > 1.0:\n r = 1.0\n elif r < -1.0:\n r = -1.0\n # estimate degrees of freedom\n df = n - 2\n slope = r_num / ssxm\n intercept = ymean - slope * xmean\n # Estimate t-statistic\n t = r * np.sqrt(df / ((1.0 - r) * (1.0 + r)))\n # Get the pvalue\n prob = 2 * t_sf(t, df)\n # get the estimated standard error\n sterrest = np.sqrt((1 - r * r) * ssym / ssxm / df)\n return dict(zip(cols, [slope, intercept, r, prob, sterrest]))",
"def _ssr_reduced_model(y, x, term_slices, params, keys):\n ind = _not_slice(term_slices, keys, x.shape[1])\n params1 = params[ind]\n ssr = np.subtract(y, x[:, ind].dot(params1))\n ssr = ssr.T.dot(ssr)\n df_resid = len(y) - len(params1)\n return ssr, df_resid",
"def xr_linregress(x, y, dim=\"time\"):\n # align the nan Values before...\n x = x.where(~np.isnan(y))\n y = y.where(~np.isnan(x))\n # TODO: think about making this optional? Right now I err on the side of caution\n\n # Inspired by this post https://stackoverflow.com/a/60352716 but adjusted, so that\n # results are exactly as with scipy.stats.linregress for 1d vectors.\n\n n = y.notnull().sum(dim)\n\n nanmask = np.isnan(y).all(dim)\n\n xmean = x.mean(dim)\n ymean = y.mean(dim)\n xstd = x.std(dim)\n ystd = y.std(dim)\n\n cov = ((x - xmean) * (y - ymean)).sum(dim) / (n)\n cor = cov / (xstd * ystd)\n\n slope = cov / (xstd**2)\n intercept = ymean - xmean * slope\n\n df = n - 2\n TINY = 1.0e-20\n tstats = cor * np.sqrt(df / ((1.0 - cor + TINY) * (1.0 + cor + TINY)))\n stderr = slope / tstats\n\n pval = (\n xr.apply_ufunc(\n stats.distributions.t.sf,\n abs(tstats),\n df,\n dask=\"parallelized\",\n output_dtypes=[y.dtype],\n )\n * 2\n )\n\n return xr.Dataset(\n {\n \"slope\": slope,\n \"intercept\": intercept,\n \"r_value\": cor.fillna(0).where(~nanmask),\n \"p_value\": pval,\n \"std_err\": stderr.where(~np.isinf(stderr), 0),\n }\n )",
"def residual(self, x):\n return np.asarray(\n [prior['residual'](x[prior['index']]) for prior in self.prior_list]\n )",
"def prepare_y(y):\n if len(y.shape) > 1:\n if y.shape[1] == 1:\n y = y.ravel()\n else:\n raise ValueError(\"Y has to be a vector of response values\")\n return y",
"def draw_residuals(model, X, y):\n split = train_test_split(X, y, random_state=123)\n X_train, X_test, y_train, y_test = split\n\n scaler = StandardScaler()\n X_train_rs = scaler.fit_transform(X_train)\n X_test_rs = scaler.transform(X_test)\n\n visualizer = ResidualsPlot(model, alpha=0.15)\n visualizer.fit(X_train_rs, y_train['target'])\n visualizer.score(X_test_rs, y_test['target'])\n visualizer.poof()",
"def ridge_regression(self, X, y):\n self.reg = Ridge().fit(X, y) \n if(self.coef is None):\n self.coef = self.reg.coef_\n self.intercept = self.reg.intercept_\n else:\n self.reg.coef_ = self.coef\n self.reg.intercept_ = self.intercept\n \n return self.reg.predict(X)",
"def fit_regression(X, y):\n # Adding bias to the model by adding an element 1 to all x vectors\n X_biased = [np.append([1], x) for x in X]\n\n # Solving X^TXw = X^Ty, in Ax=B form, A=X^TX and B=X^Ty\n return np.linalg.solve(np.dot(np.transpose(X_biased), X_biased), np.dot(np.transpose(X_biased), y))",
"def regress_out(self, a, b): # -> ndarray[Any, dtype[Unknown]]:\n ...",
"def residual_jacobian(self, x):\n sres = np.zeros((len(self.prior_list), len(x)))\n for iprior, prior in enumerate(self.prior_list):\n sres[iprior, prior['index']] = prior['residual_dx'](\n x[prior['index']]\n )\n\n return sres",
"def regress_all(data_x, data_y):\n\n\tignore_zero = np.seterr(all = \"ignore\")\n\t\n\tlist_x = [data_x, np.log(data_x), data_x, np.log(data_x)]\n\tlist_y = [data_y, data_y, np.log(data_y), np.log(data_y)]\n\t\n\t# Calculation of constants for regression models: slope, intercept, r and p\n\tlist_r = [int() for i in xrange(4)] \t# list of r values for the methods\n\tlist_r2 = [int() for i in xrange(4)] # list of r2 values for the methods\n\tlist_slope = [int() for i in xrange(4)]\t\t\t\t\t\t\t\t# list of slopes\n\tlist_intercept = [int() for i in xrange(4)]\t\t\t\t\t\t\t# list of intercepts\n\tlist_p = [int() for i in xrange(4)]\t\t\t\t\t\t\t\t\t# list of p values\n\tlist_se = [int() for i in xrange(4)]\t\t\t\t\t\t\t\t# list of SE values\n\t\n\t# Models - calculating regressions\n\tfor i in xrange(len(list_x)):\n\t\tslope_lin, inter_lin, r_lin, p_lin, se_lin = scs.linregress(list_x[i],list_y[i])\n\t\tlist_slope[i] = slope_lin\n\t\tlist_r[i] = r_lin\n\t\tlist_r2[i] = r_lin**2\n\t\tlist_p[i] = p_lin\n\t\tlist_se[i] = se_lin\n\t\tif i < 2:\n\t\t\tlist_intercept[i] = inter_lin\n\t\telse:\n\t\t\tlist_intercept[i] = np.exp(inter_lin)\n\t\t\t\n\treturn list_slope, list_intercept, list_r, list_r2, list_p, list_se",
"def fit(x,y):\n x_in = np.vstack([x, np.ones(len(x))]).T #Stacking the array x with ones to form the array (log x, 1) \n y_in = np.log(y).T\n b,a = np.linalg.lstsq(x_in,y_in,rcond=None)[0] #Performing least squares regression \n return np.exp(a),b",
"def eval(self, y):\n if not isinstance(y, np.ndarray):\n print(\"ERROR: argument passed to Interpolant.eval is not np.ndarray\")\n exit(1)\n elif y.shape[-1] != self.dim:\n print(\"ERROR: argument passed to Interpolant.eval is incorrect dimension\")\n exit(1)\n\n #num_points = y.shape[0]\n # output = np.zeros(num_points)\n # for i in range(num_points):\n # point_counter = 0\n # for index, data in enumerate(self.data_points):\n # for j in range(self.data_points[index].points.shape[1]):\n # output[i] += self.coefficients[point_counter] * self.linfunc.basis_functions[index](\n # self.data_points[index].points[:, j], y[:, i])\n # point_counter += 1\n # return output\n\n output = 0\n point_counter = 0\n for index, data in enumerate(self.data_points):\n for j in range(self.data_points[index].numpoints):\n output += self.coefficients[point_counter] * self.linfunc.basis_functions[index](\n self.data_points[index].points[j, :], y)\n point_counter += 1\n\n return output",
"def linear_regression(X,y):\n\t\t\n\t\ttranspose_X=np.transpose(X);# implements the formula (X'*X)^-1*X'*y \n\t\tX=np.matmul(transpose_X,X);\n\t\tX=np.linalg.inv(X);\n\t\tX=np.matmul(X,transpose_X);\n\t\tX=np.matmul(X,y);\n\t\t\n\t\treturn X;",
"def get_residual_diagnostics(self) -> 'LinearRegressionMLE':\n\n self.rss = (self.resid**2).sum() \n self.s2 = self.rss / (n - p)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Return the Amino Acid Substitution classification type.
|
def classification_type(self) -> ClassificationType:
return ClassificationType.AMINO_ACID_SUBSTITUTION
|
[
"def classify(self):\n\n if self.annotation_type == None or self.annotation_type not in self._annotation_classifications:\n return None\n\n try:\n classification = self._annotation_classifications[self.annotation_type][self.attributes['assertion']]\n except KeyError:\n classification = self.annotation_type\n if self.attributes['temporality'] != 'current':\n classification += ' - {}'.format(self.attributes['temporality'].title())\n\n # Exclude any annotations of a surgical site infection that doesn't have anatomy\n # TODO: Implement coreference resolution in `from_markup()`\n\n self._classification = classification\n return classification",
"def var_subtype(self):\n if self.is_snp:\n if self.is_transition:\n return \"ts\"\n elif len(self.ALT) == 1:\n return \"tv\"\n else: # multiple ALT alleles. unclear\n return \"unknown\"\n elif self.is_indel:\n if self.is_deletion:\n return \"del\"\n elif len(self.ALT) == 1:\n return \"ins\"\n else: # multiple ALT alleles. unclear\n return \"unknown\"\n elif self.is_sv:\n if self.INFO['SVTYPE'] == \"BND\":\n return \"complex\"\n elif self.is_sv_precise:\n return self.INFO['SVTYPE']\n else:\n return self.ALT[0].type\n else:\n return \"unknown\"",
"def rough_type(anno):\n if anno.type == 'Segment' or stac.is_edu(anno):\n return 'EDU'\n elif stac.is_relation_instance(anno):\n return 'relation'\n else:\n return anno.type",
"def coda_type(self):\n return cursor_get_type(self)",
"def type(self):\n if self.attrs[\"integer\"]:\n return \"Integer Variable\"\n elif self.attrs[\"binary\"]:\n return \"Binary Variable\"\n else:\n return \"Continuous Variable\"",
"def main_role(self, text):\n\t\tclassifications = self.classify(text)\n\t\t\n\t\t#If only one classification, return whatever it is.\n\t\tif len(classifications) == 1:\n\t\t\treturn list(classifications.keys())[0]\n\n\t\t# Now, prioritized order of selection\n\t\tif \"Programming\" in classifications:\n\t\t\treturn \"Programming\"\n\t\tif \"2D\" in classifications:\n\t\t\treturn \"2D\"\n\t\tif \"3D\" in classifications:\n\t\t\treturn \"3D\"\n\t\tif \"Sound\" in classifications:\n\t\t\treturn \"Sound\"\n\t\tif \"Other\" in classifications:\n\t\t\treturn \"Other\"",
"def get_genotype_class(rec, ref, alt):\n if len(ref) == len(alt):\n return 'SNP'\n elif len(ref) < len(alt):\n return 'IN'\n elif len(ref) > len(alt):\n return 'DEL'\n else:\n raise ValueError('INVALID GENOTYPE CLASS \\n' + str(rec))",
"def sequencing_type_mip(self):\n if self.sequencing_type == 'tga':\n return 'wes'\n else:\n return self.sequencing_type",
"def riskType(self):\n if self.riskIncrease == True:\n return 'ARI'\n else:\n return 'ARR'",
"def _compliance_atomType(self):\n if self.resName in ['hoh','tip3']:\n self.atomType = ' oh2'\n elif (self.resName == 'ile' and self.atomType == ' cd1'):\n self.atomType = ' cd '\n elif (self.atomType == 'na ' and (self.resName == 'na' or self.resName == 'sod')):\n self.atomType = 'sod '\n elif (self.atomType == 'cs ' and (self.resName == 'cs' or self.resName == 'ces')):\n self.atomType = 'ces '\n elif (self.atomType == 'cl ' and (self.resName == 'cl' or self.resName == 'cla')):\n self.atomType = 'cla '\n elif (self.atomType == 'ca ' and (self.resName == 'ca' or self.resName == 'cal')):\n self.atomType = 'cal '\n elif (self.atomType == ' k ' and (self.resName == 'k' or self.resName == 'pot')):\n self.atomType = 'pot '",
"def default_aid_type(iati_import, activity, project, activities_globals):\n dat_value = ''\n\n dat_element = activity.find(\"default-aid-type\")\n if not dat_element is None and 'code' in dat_element.attrib.keys():\n if not len(dat_element.attrib['code']) > 3:\n dat_value = dat_element.attrib['code']\n else:\n add_log(iati_import, 'default_aid_type', 'code too long (3 characters allowed)',\n project)\n\n if project.default_aid_type != dat_value:\n project.default_aid_type = dat_value\n project.save(update_fields=['default_aid_type'])\n return ['default_aid_type']\n\n return []",
"def instruction_type(self, instruction):\r\n if re.match(self.RE_A_INSTRUCTION, instruction):\r\n return self.A_INSTRUCTION\r\n if re.match(self.RE_C_INSTRUCTION, instruction):\r\n return self.C_INSTRUCTION\r\n if re.match(self.RE_L_INSTRUCTION, instruction):\r\n return self.L_INSTRUCTION\r\n return",
"def class_type(self):\n ret = self._get_attr(\"classType\")\n return AdditionsFacilityClass(ret)",
"def sequencer_type(\n self,\n ) -> Literal[Sequencers.HISEQX, Sequencers.HISEQGA, Sequencers.NOVASEQ, Sequencers.NOVASEQX]:\n return sequencer_types[self.machine_name]",
"def aliquot_Type(instance):\n return \"{} ({})\".format(instance.Type(), instance.aliquot_type)",
"def get_annotation_types():\r\n # https://www.isip.piconepress.com/projects/tuh_eeg/downloads/tuh_eeg_seizure/v1.5.0/_DOCS/\r\n return get_annotation_csv()[\"class_code\"].str.lower().tolist()",
"def rn_classification(array):\n _class = ['', '', '']\n\n # integer / fraction\n # den length == 1 and den = [1, 1, 1]\n if len(array[1]) == 1 and (array[1][0] == 1).all():\n _class[0] = 'integer'\n else:\n _class[0] = 'fraction'\n\n # rational / irrational for each linear\n for p, lin in enumerate(array):\n if (lin[:, 1:] == 1).all():\n _class[p + 1] = 'rational'\n elif len(lin) == 1 and p == 0:\n # den cannot be simple irrational\n _class[p + 1] = 'simple irrational'\n elif lin.dtype == int_:\n _class[p + 1] = 'mixed irrational'\n else:\n _class[p + 1] = 'composed irrational'\n # if first-type class is 'integer', won't parse for denominator\n if _class[0] == 'integer':\n break\n return _class",
"def get_label_type(data):\n return get_label_for(data, \"type: \")",
"def SIM_SUBTYPE( self ) :\n from constants import SUBTYPES\n if 'non1aTypes' in self.__dict__ :\n return( np.array([ non1aType for non1aType in self.non1aTypes ] ))\n elif 'SIM_NON1a' in self.__dict__ : \n return( np.array([ SUBTYPES[non1aCode] for non1aCode in self.SIM_NON1a ] ))\n elif not self.GENMODEL.startswith('NON') : \n return( np.array([ 'Ia' for i in range(len(self.LUMIPAR)) ]) )"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Return the exact match token type candidates.
|
def exact_match_candidates(self) -> List[List[str]]:
return [
['AminoAcidSubstitution'],
['GeneSymbol', 'AminoAcidSubstitution'],
['HGVS', 'AminoAcidSubstitution'],
['ReferenceSequence', 'AminoAcidSubstitution']
]
|
[
"def get_token_types(self):\r\n \r\n # With help from: https://deplinenoise.wordpress.com/2012/01/04/python-tip-regex-based-tokenizer/\r\n SCANNER = re.compile(r'''\r\n (\\s+) | # whitespace\r\n (//)[^\\n]* | # comments\r\n 0[xX]([0-9A-Fa-f]+) | # hexadecimal integer literals\r\n (\\d+) | # integer literals\r\n (<<|>>) | # multi-char punctuation\r\n ([][(){}<>=,;:*+-/|&~]) | # punctuation \r\n ([A-Za-z_][A-Za-z0-9_]*) | # identifiers\r\n \"\"\"(.*?)\"\"\" | # multi-line string literal\r\n \"((?:[^\"\\n\\\\]|\\\\.)*)\" | # regular string literal\r\n (.) | # an error!\r\n ''', re.DOTALL | re.VERBOSE)\r\n \r\n for match in re.finditer(SCANNER, self.scanner.modified_source_text): \r\n \r\n (space, comment, hexint, integer, mpunct, \r\n punct, word, mstringlit, stringlit, badchar) = match.groups()\r\n \r\n if word: \r\n #-------------------------------------------------------------------\r\n # check if word is an keyword\r\n #-------------------------------------------------------------------\r\n if word in self.symbols.keyword: \r\n keyword_token = Token(word, \"keyword\") \r\n self.token_list.append(keyword_token)\r\n #-------------------------------------------------------------------\r\n # check if word is an identifier\r\n #-------------------------------------------------------------------\r\n else:\r\n identifier_token = Token(word, \"identifier\") \r\n self.token_list.append(identifier_token)\r\n #-------------------------------------------------------------------\r\n # check if word is an integerConstant\r\n #-------------------------------------------------------------------\r\n if integer:\r\n Int_token = Token(integer, \"integerConstant\") \r\n self.token_list.append(Int_token)\r\n #-------------------------------------------------------------------\r\n # check if word is an symbol \r\n #-------------------------------------------------------------------\r\n if punct: \r\n symbol_token = Token(punct, \"symbol\") \r\n self.token_list.append(symbol_token)\r\n #-------------------------------------------------------------------\r\n # check if word is an stringConstant\r\n #------------------------------------------------------------------- \r\n if stringlit: \r\n string_token = Token(stringlit, \"stringConstant\") \r\n self.token_list.append(string_token) \r\n #-------------------------------------------------------------------\r\n # append EOF token\r\n #------------------------------------------------------------------- \r\n EOF_token = Token(self.endmark, \"EOF\") \r\n self.token_list.append(EOF_token) \r\n \r\n return self.token_list",
"def get_string_match_types(self):\n raise errors.Unimplemented()",
"def _token_pattern_matches(tokens, search_tokens, match_type, ignore_case, glob_method):\n\n # search tokens may be of any type (e.g. bool when matching against token meta data)\n if not isinstance(search_tokens, (list, tuple, set)):\n search_tokens = [search_tokens]\n elif isinstance(search_tokens, (list, tuple, set)) and not search_tokens:\n raise ValueError('`search_tokens` must not be empty')\n\n matches = [np.repeat(False, repeats=len(dtok)) for dtok in tokens]\n\n for dtok, dmatches in zip(tokens, matches):\n for pat in search_tokens:\n pat_match = token_match(pat, dtok, match_type=match_type, ignore_case=ignore_case, glob_method=glob_method)\n\n dmatches |= pat_match\n\n return matches",
"def _build_lookup(self):\n\n lookup = []\n for token_type in sorted(self._token_types, key=len, reverse=True):\n # No bound checking for all punctuation tokens\n bound_check = bool(set(token_type) - set(string.punctuation))\n lookup.append((token_type, bound_check))\n return lookup",
"def match_token_patterns(self, doc, pattern=[]):\n self.matched_sents = []\n self.matcher.add(\"PDFTokens\", \n self.collect_sents, \n *pattern) # add pattern\n matches = self.matcher(doc)\n return matches",
"def match(self, *types: List[TokenType]) -> bool:\n for token_type in types:\n if self.check(token_type):\n self.advance()\n return True\n return False",
"def find_action_matching_tokens(self, tokens):\n\n for a in self.actions:\n \n log(\" examining action %s\" % a[1])\n\n # Does the token count match?\n if len(tokens) != len(a[0]):\n continue\n\n # Try to match the tokens\n matched_noun_tokens = []\n match_count = 0\n for i in range(len(a[0])):\n \n # Is the token definition a tuple? If so, the token type\n # is the first part, and a qualifying function the second\n if isinstance(a[0][i], tuple):\n t = a[0][i][0]\n f = a[0][i][1]\n else:\n t = a[0][i]\n f = None\n\n if t == NOUN_TOKEN or MULTI_TOKEN:\n \n # We are expecting a noun -- is it legal?\n log(\"NOUN_TOKEN\")\n if self.grammar.legal_noun_token(tokens[i]):\n \n # Is there a qualifying function?\n if f == None or f() == True:\n log(\"matched noun token\")\n matched_noun_tokens.append((tokens[i], t))\n match_count += 1\n else:\n log(\"noun token matched but qualifying function returned False\")\n\n if t == HELD_TOKEN:\n \n # We are expecting a noun -- is it legal?\n log(\"HELD_TOKEN\")\n if self.grammar.legal_noun_token(tokens[i]):\n log(\"matched noun token\")\n matched_noun_tokens.append((tokens[i], t))\n match_count += 1\n\n elif t == tokens[i]:\n log(\"matched: %s\" % t)\n match_count += 1\n \n if match_count == len(a[0]):\n return (a, matched_noun_tokens)\n \n return (None, None)",
"def match_any_genus_type(self, match):\n pass",
"def global_matches(self, text):\r\n import keyword\r\n matches = []\r\n n = len(text)\r\n for list in [keyword.kwlist,\r\n __builtin__.__dict__,\r\n self.namespace]:\r\n for word in list:\r\n if word[:n] == text and word != \"__builtins__\":\r\n matches.append(word)\r\n return matches",
"def _collect_patterns(self):\n patterns = []\n type_stmt = self.type_stmt\n while all([hasattr(type_stmt, 'i_typedef') and\n type_stmt.i_typedef is not None]):\n patterns.extend(type_stmt.search('pattern'))\n type_stmt = type_stmt.i_typedef.search_one('type')\n patterns.extend(type_stmt.search('pattern'))\n\n return patterns",
"def match(self, *types: Union[TokenType, List[TokenType]]):\n\n for token_type in types:\n if self.check(token_type):\n self.step()\n return True\n return False",
"def valid_types(self):\n types = re.sub(r'[ ]?,[ ]?', ',', self.node.content_types).split(',')\n return [t.lower() for t in types]",
"def arg_types(self) -> List[ast.Type]:",
"def global_matches(self, text):\n import keyword\n matches = []\n seen = {\"__builtins__\"}\n n = len(text)\n for word in keyword.kwlist:\n if word[:n] == text:\n seen.add(word)\n matches.append(word)\n for nspace in [self.namespace, __builtin__.__dict__]:\n for word, val in nspace.items():\n if word[:n] == text and word not in seen:\n seen.add(word)\n matches.append(self._callable_postfix(val, word))\n return matches",
"def get_returntype_words(self) -> [str]:\r\n return self.return_type.tokens",
"def candidate_expansion_terms(tokens, k, model, model_format):\n candidates = set()\n if model_format == 'word2vec':\n for token in tokens:\n # check if the token is in the vocabulary\n if token in model.vocab.keys():\n result = model.similar_by_word(token)\n limit = k if len(result) > k else len(result)\n # iterate through the most similar words\n for i in range(limit):\n candidates.add(result[i][0])\n elif model_format == 'fasttext':\n for token in tokens:\n # check if the token is in the vocabulary\n if token in model.wv.vocab:\n result = model.most_similar(token)\n limit = k if len(result) > k else len(result)\n # iterate through the most similar words\n for i in range(limit):\n candidates.add(result[i][0])\n else:\n raise Exception('Model type incorrect')\n # return list of candidates\n candidates = list(candidates)\n return candidates",
"def _match_any(self, regexs, text, options=None, search=False):\n match = None\n regex = None\n operator = 'search' if search else 'match'\n for regex in regexs:\n if options is not None:\n match = getattr(re, operator)(regex, text, options)\n else:\n match = getattr(re, operator)(regex, text)\n if match:\n break\n return match, regex",
"def matches(self, *args):\r\n return _osgDB.basic_type_wrapper_matches(self, *args)",
"def get_matches(lf, candidate_set, match_values=[1, -1]):\n matches = []\n for c in candidate_set:\n label = lf(c)\n if label in match_values:\n matches.append(c)\n print((\"%s matches\") % len(matches))\n return matches"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Check if calc_countdown returns days, hours and minutes.
|
def test_calc_countdown(self):
# FIXME: This will break when there is 0 seconds/hours/days left
pattern = re.compile(r"\d* days, \d* hours, \d* minutes")
countdown = calc_countdown(self.job)
assert pattern.match(countdown)
|
[
"def can_countdown():\n if get_current_round(g) != \"day\":\n return False, 'It is not day.'\n elif not is_player_alive(g, user_id):\n return False, 'You are not in the game.'\n # get list of all alive\n # get list of votes\n # if list of votes == all alive - 1\n elif len(get_all_alive(g))- 1 == len(get_all_votes(g).keys()):\n return True, None\n else:\n return False, 'Can not start countdown now.'",
"def countdown(code, input):\n error = '{red}Please use correct format: %scountdown <year> <month> <day>' % code.prefix\n text = input.group(2).split()\n if text[0].isdigit() and text[1].isdigit() and text[2].isdigit() and len(text) == 3:\n diff = datetime.datetime(int(text[0]), int(text[1]), int(text[2])) - datetime.datetime.today()\n code.say(\n str(diff.days) + \"-days \" + str(diff.seconds / 60 / 60) +\n \"-hours \" + str(diff.seconds / 60 - diff.seconds / 60 / 60 * 60) +\n \"-minutes until \" + text[0] + \" \" + text[1] + \" \" + text[2])\n else:\n code.say(error)",
"def check_times(self):\r\n if self.in_time and self.out_time and not (self.in_time == self.out_time):\r\n return False\r\n return True",
"def test_countdown(conversation): # pylint: disable=redefined-outer-name\n\n assert conversation.message('/mycountdown') == ''\n\n conversation.bot.config['issue37']['countdown']['mycountdown'] = 1534906800\n assert conversation.message('/mycountdown').endswith(' ago\\n')\n\n conversation.bot.config['issue37']['countdown']['mycountdown'] = 15349068000\n assert not conversation.message('/mycountdown').endswith(' ago\\n')",
"def check_time(iteration, start, end):\r\n return start <= iteration % 24 < end",
"def check_time(self):\r\n return int(str(self.get_hour())+str(self.get_min()))",
"def test_TIMEoperations():\n # test CCSDS.TIME.isCDStimeFormat()\n if CCSDS.TIME.isCDStimeFormat(CCSDS.TIME.TIME_FORMAT_CDS1) != True:\n return False\n if CCSDS.TIME.isCDStimeFormat(CCSDS.TIME.TIME_FORMAT_CDS2) != True:\n return False\n if CCSDS.TIME.isCDStimeFormat(CCSDS.TIME.TIME_FORMAT_CDS3) != True:\n return False\n if CCSDS.TIME.isCDStimeFormat(CCSDS.TIME.TIME_FORMAT_CUC0) != False:\n return False\n if CCSDS.TIME.isCDStimeFormat(CCSDS.TIME.TIME_FORMAT_CUC1) != False:\n return False\n if CCSDS.TIME.isCDStimeFormat(CCSDS.TIME.TIME_FORMAT_CUC2) != False:\n return False\n if CCSDS.TIME.isCDStimeFormat(CCSDS.TIME.TIME_FORMAT_CUC3) != False:\n return False\n if CCSDS.TIME.isCDStimeFormat(CCSDS.TIME.TIME_FORMAT_CUC4) != False:\n return False\n if CCSDS.TIME.isCDStimeFormat(99) != False:\n return False\n # test CCSDS.TIME.isCUCtimeFormat()\n if CCSDS.TIME.isCUCtimeFormat(CCSDS.TIME.TIME_FORMAT_CDS1) != False:\n return False\n if CCSDS.TIME.isCUCtimeFormat(CCSDS.TIME.TIME_FORMAT_CDS2) != False:\n return False\n if CCSDS.TIME.isCUCtimeFormat(CCSDS.TIME.TIME_FORMAT_CDS3) != False:\n return False\n if CCSDS.TIME.isCUCtimeFormat(CCSDS.TIME.TIME_FORMAT_CUC0) != True:\n return False\n if CCSDS.TIME.isCUCtimeFormat(CCSDS.TIME.TIME_FORMAT_CUC1) != True:\n return False\n if CCSDS.TIME.isCUCtimeFormat(CCSDS.TIME.TIME_FORMAT_CUC2) != True:\n return False\n if CCSDS.TIME.isCUCtimeFormat(CCSDS.TIME.TIME_FORMAT_CUC3) != True:\n return False\n if CCSDS.TIME.isCUCtimeFormat(CCSDS.TIME.TIME_FORMAT_CUC4) != True:\n return False\n if CCSDS.TIME.isCUCtimeFormat(99) != False:\n return False\n # test CCSDS.TIME.timeFormat()\n if CCSDS.TIME.timeFormat(\"CDS1\") != CCSDS.TIME.TIME_FORMAT_CDS1:\n return False\n if CCSDS.TIME.timeFormat(\"CDS2\") != CCSDS.TIME.TIME_FORMAT_CDS2:\n return False\n if CCSDS.TIME.timeFormat(\"CDS3\") != CCSDS.TIME.TIME_FORMAT_CDS3:\n return False\n if CCSDS.TIME.timeFormat(\"CUC0\") != CCSDS.TIME.TIME_FORMAT_CUC0:\n return False\n if CCSDS.TIME.timeFormat(\"CUC1\") != CCSDS.TIME.TIME_FORMAT_CUC1:\n return False\n if CCSDS.TIME.timeFormat(\"CUC2\") != CCSDS.TIME.TIME_FORMAT_CUC2:\n return False\n if CCSDS.TIME.timeFormat(\"CUC3\") != CCSDS.TIME.TIME_FORMAT_CUC3:\n return False\n if CCSDS.TIME.timeFormat(\"CUC4\") != CCSDS.TIME.TIME_FORMAT_CUC4:\n return False\n if CCSDS.TIME.timeFormat(\"???\") != None:\n return False\n # test CCSDS.TIME.timeFormatStr()\n if CCSDS.TIME.timeFormatStr(CCSDS.TIME.TIME_FORMAT_CDS1) != \"CDS1\":\n return False\n if CCSDS.TIME.timeFormatStr(CCSDS.TIME.TIME_FORMAT_CDS2) != \"CDS2\":\n return False\n if CCSDS.TIME.timeFormatStr(CCSDS.TIME.TIME_FORMAT_CDS3) != \"CDS3\":\n return False\n if CCSDS.TIME.timeFormatStr(CCSDS.TIME.TIME_FORMAT_CUC0) != \"CUC0\":\n return False\n if CCSDS.TIME.timeFormatStr(CCSDS.TIME.TIME_FORMAT_CUC1) != \"CUC1\":\n return False\n if CCSDS.TIME.timeFormatStr(CCSDS.TIME.TIME_FORMAT_CUC2) != \"CUC2\":\n return False\n if CCSDS.TIME.timeFormatStr(CCSDS.TIME.TIME_FORMAT_CUC3) != \"CUC3\":\n return False\n if CCSDS.TIME.timeFormatStr(CCSDS.TIME.TIME_FORMAT_CUC4) != \"CUC4\":\n return False\n if CCSDS.TIME.timeFormatStr(99) != \"???\":\n return False\n # other tests\n actualTime1 = UTIL.TIME.getActualTime()\n actualTime1Str = \"%.6f\" % actualTime1\n actualTimeStr = UTIL.TIME.getASDtimeStr(actualTime1)\n actualTime2 = UTIL.TIME.getTimeFromASDstr(actualTimeStr)\n actualTime2Str = \"%6f\" % actualTime1\n print(\"actual time =\", actualTimeStr)\n if actualTime1Str != actualTime2Str:\n print(\"Time conversions not symmetrical:\", actualTime1Str, actualTime2Str)\n return False\n zeroTime = 0.0\n zeroTimeStr1 = UTIL.TIME.getASDtimeStr(zeroTime)\n if zeroTimeStr1 != \"1970.001.00.00.00.000\":\n print(\"Invalid ASD zero time 1:\", zeroTimeStr1)\n return False\n zeroTimeStr2 = UTIL.TIME.getASDtimeStr(zeroTime, withMicros=True)\n if zeroTimeStr2 != \"1970.001.00.00.00.000000\":\n print(\"Invalid ASD zero time 2:\", zeroTimeStr2)\n return False\n if not test_ERTandCDS1(UTIL.TCO.GPS_MISSION_EPOCH_STR,\n UTIL.TCO.GPS_MISSION_EPOCH_DELTA):\n return False\n if not test_ERTandCDS1(UTIL.TCO.TAI_MISSION_EPOCH_STR,\n UTIL.TCO.TAI_MISSION_EPOCH_DELTA):\n print(\"!!! Warning: negative time values are not supported on this platform !!!\")\n if not test_ERTandCDS2(UTIL.TCO.GPS_MISSION_EPOCH_STR,\n UTIL.TCO.GPS_MISSION_EPOCH_DELTA):\n return False\n if not test_ERTandCDS2(UTIL.TCO.TAI_MISSION_EPOCH_STR,\n UTIL.TCO.TAI_MISSION_EPOCH_DELTA):\n print(\"!!! Warning: negative time values are not supported on this platform !!!\")\n if not test_ERTandCDS3(UTIL.TCO.GPS_MISSION_EPOCH_STR,\n UTIL.TCO.GPS_MISSION_EPOCH_DELTA):\n return False\n if not test_ERTandCDS3(UTIL.TCO.TAI_MISSION_EPOCH_STR,\n UTIL.TCO.TAI_MISSION_EPOCH_DELTA):\n print(\"!!! Warning: negative time values are not supported on this platform !!!\")\n zeroEpochTime1 = UTIL.TCO.correlateFromOBTmissionEpoch(zeroTime)\n if zeroEpochTime1 != 0:\n zeroEpochTime1Str = UTIL.TIME.getASDtimeStr(zeroEpochTime1)\n print(\"Invalid zero epoch time:\", zeroEpochTime1Str)\n return False\n zeroEpochTime2 = correlateOBTcucPFC17(testData.ZERO_CUC2_TIME_FIELD)\n if zeroEpochTime2 != 0:\n zeroEpochTime2Str = UTIL.TIME.getASDtimeStr(zeroEpochTime2)\n print(\"Invalid zero epoch time:\", zeroEpochTime2Str)\n return False\n UTIL.TCO.setOBTmissionEpochStr(UTIL.TCO.GPS_MISSION_EPOCH_STR)\n UTIL.TCO.setOBTleapSeconds(UTIL.TCO.GPS_LEAP_SECONDS_2009)\n cucTime1 = correlateOBTcucPFC17(testData.CUC2_TIME1_FIELD)\n cucTime1Str = UTIL.TIME.getASDtimeStr(cucTime1, withMicros=True)\n if cucTime1Str != testData.CUC2_TIME1_STR:\n print(\"Invalid CUC time 1:\", cucTime1Str)\n return False\n cucTime2 = correlateOBTcucPFC17(testData.CUC2_TIME2_FIELD)\n cucTime2Str = UTIL.TIME.getASDtimeStr(cucTime2, withMicros=True)\n if cucTime2Str != testData.CUC2_TIME2_STR:\n print(\"Invalid CUC time 2:\", cucTime2Str)\n return False\n cucTime3 = correlateOBTcucPFC17(testData.CUC2_TIME3_FIELD)\n cucTime3Str = UTIL.TIME.getASDtimeStr(cucTime3, withMicros=True)\n if cucTime3Str != testData.CUC2_TIME3_STR:\n print(\"Invalid CUC time 3:\", cucTime3Str)\n return False\n cucTime4 = correlateOBTcucPFC17(testData.CUC2_TIME4_FIELD)\n cucTime4Str = UTIL.TIME.getASDtimeStr(cucTime4, withMicros=True)\n if cucTime4Str != testData.CUC2_TIME4_STR:\n print(\"Invalid CUC time 4:\", cucTime4Str)\n return False\n cucTime5 = correlateOBTcucPFC17(testData.CUC2_TIME5_FIELD)\n cucTime5Str = UTIL.TIME.getASDtimeStr(cucTime5, withMicros=True)\n if cucTime5Str != testData.CUC2_TIME5_STR:\n print(\"Invalid CUC time 5:\", cucTime5Str)\n return False\n cucTime6 = correlateOBTcucPFC17(testData.CUC2_TIME6_FIELD)\n cucTime6Str = UTIL.TIME.getASDtimeStr(cucTime6, withMicros=True)\n if cucTime6Str != testData.CUC2_TIME6_STR:\n print(\"Invalid CUC time 6:\", cucTime6Str)\n return False\n return True",
"async def countdown(ctx, *args):\n num_dict = {'0': ':zero:',\n '1': ':one:',\n '2': ':two:',\n '3': ':three:',\n '4': ':four:',\n '5': ':five:',\n '6': ':six:',\n '7': ':seven:',\n '8': ':eight:',\n '9': ':nine:', }\n\n clock_dict = {0.08: ':clock1:',\n 0.17: ':clock2:',\n 0.25: ':clock3:',\n 0.33: ':clock4:',\n 0.42: ':clock5:',\n 0.5: ':clock6:',\n 0.58: ':clock7:',\n 0.67: ':clock8:',\n 0.75: ':clock9:',\n 0.83: ':clock10:',\n 0.92: ':clock11:',\n 1.0: ':clock12:', }\n\n countdown_limit = 60 * 60 * 24\n os.environ['TZ'] = 'Europe/London'\n\n def time_to_emoji(time_secs):\n duration = ' '.join(str(strftime('%H:%M:%S', gmtime(time_secs))))\n for i in duration:\n if i.isdigit():\n duration = duration.replace(str(i), num_dict[str(i)])\n\n return duration\n\n if args == ():\n await ctx.channel.send('No duration provided.')\n raise Exception('No argument provided.')\n\n duration = ' '.join(args)\n user = ctx.message.author\n print('\\nCountdown by {0}'.format(user))\n\n current_time = datetime.now()\n print('Start:', current_time)\n current_time_secs = current_time.timestamp()\n\n cal = parsedatetime.Calendar()\n time_struct, parse_status = cal.parse(duration)\n countdown_time = datetime(*time_struct[:6])\n print('End:', countdown_time)\n countdown_time_secs = countdown_time.timestamp()\n\n time_difference_secs = np.ceil(countdown_time_secs - current_time_secs)\n print('Duration:', time_difference_secs)\n\n if np.linalg.norm(time_difference_secs) == 0:\n await ctx.channel.send(\"That's not a proper duration. Try again you numpty.\")\n raise TypeError(\"Argument not recognised.\")\n\n clock_emoji = ':clock12:'\n if time_difference_secs > countdown_limit:\n await ctx.channel.send('Countdown time too long.')\n raise ValueError('Countdown length exceeds limit.')\n else:\n message = await ctx.channel.send(time_to_emoji(time_difference_secs) + ' ' + clock_emoji)\n\n time_secs = time_difference_secs\n while time_secs > 0:\n await asyncio.sleep(1)\n time_secs -= 1\n fraction = round(1 - (time_secs / time_difference_secs), 2)\n for i in clock_dict:\n if fraction >= i:\n clock_emoji = clock_dict[i]\n\n await message.edit(content=(time_to_emoji(time_secs) + ' ' + clock_emoji))\n\n await message.delete(delay=1)\n await ctx.channel.send(content='Countdown for {0.mention} has finished.'.format(user))",
"def check_in_time(self):\r\n if self.out_time and not self.in_time:\r\n return False\r\n return True",
"def interval_validation(request_interval):\n \"\"\"Write your code here\"\"\"\n # Here we just declare the two variables with datetime object and the method to validate the interval duration for 30mins.\n t1 = datetime.datetime.strptime(request_interval[0], \"%H:%M\")\n t2 = datetime.datetime.strptime(request_interval[1], \"%H:%M\")\n # Method:\n if ((t2 - t1).seconds) / 60 == 30:\n return True\n else:\n return False",
"def check_reminder_date(self, kwargs: dict) -> None:\n days_to_reminder_date = (datetime.today() - self.reminder_date).days\n divisor = None\n if self.repeat_type == DAYS:\n divisor = self.repeat_freq\n elif self.repeat_type == WEEKS:\n divisor = self.repeat_freq * 7\n elif self.repeat_type == MONTHS:\n divisor = self.repeat_freq * 30\n\n if days_to_reminder_date % divisor == 0:\n self.send_reminder()\n self.log(\"Erinnerungstag! Erinnerung gesendet.\")",
"def _calculate_ct_time(self, hospital_date, ct_date):\n\n ct_diff = ct_date - hospital_date\n tdeltamin = ct_diff.total_seconds()/60.0\n\n if tdeltamin < 0 or tdeltamin > 60:\n return 2\n else:\n return 1",
"def total_time_in_city(self):\r\n arrive = self.data1[0][3][-1][0]\r\n departue = self.data2[0][3][0][1]\r\n fmt = '%Y-%m-%d %H:%M:%S'\r\n total_time = str(datetime.strptime(departue, fmt) - \\\r\n datetime.strptime(arrive, fmt))\r\n divide = total_time.split()\r\n if len(divide) == 1:\r\n return False\r\n elif divide[-1][1] == \":\":\r\n divide[-1] = \"0\" + divide[-1]\r\n hours1 = int(divide[0]) * 24\r\n hours2 = int(divide[-1][0:2])\r\n hours3 = round(int(divide[-1][3:5]) / 60, 1)\r\n hours_total = hours1 + hours2 + hours3\r\n results = [(self.data1[0][3][-1][-1], (arrive, departue), \\\r\n total_time, True, hours_total)]\r\n return results",
"def check_time_correct(self):\r\n if self.get_hour() == '' or self.get_min() == '' or len(str(self.get_hour())+str(self.get_min())) != 4:\r\n messagebox.showerror(\"Ok\", \"Please enter a valid time. Use the format HH:MM\")\r\n self.refresh()\r\n else:\r\n if int(self.get_hour()) >= 24 or int(self.get_min()) > 59:\r\n messagebox.showerror(\"Ok\", \"Please enter a valid time. Use the format HH:MM\")\r\n self.refresh()\r\n else:\r\n self.selection()",
"def test_as_days(self):\n self.assertEqual(1, Duration(65 * 60 * 24).as_days)",
"def check_alarm_input(alarm_time):\n if len(alarm_time) == 1:\n if alarm_time[0] < 24 and alarm_time[0] >= 0:\n return True\n if len(alarm_time) == 2: \n if alarm_time[0] < 24 and alarm_time[0] >= 0 and alarm_time[1] < 60 and alarm_time[1] >= 0:\n return True\n elif len(alarm_time) == 3: \n if alarm_time[0] < 24 and alarm_time[0] >= 0 and alarm_time[1] < 60 and alarm_time[1] >= 0 and alarm_time[2] < 60 and alarm_time[2] >= 0:\n return True\n return False",
"def test_num_elapsed_days(self):\n today = _today()\n elapsed = num_elapsed_days(today)\n self.assertIsInstance(elapsed, int)\n self.assertEqual(elapsed, (today - datetime.date(2001, 1, 1)).days)",
"def check_period(self, return_value):\n if self.period is not None:\n # period should work\n if self.timer_elapsed:\n # timer has elapsed\n self.timer_elapsed = False\n return True\n else:\n # timer is working\n return False\n return return_value",
"def days():\n return hours() % 24"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Get the place id for place of given name and location Returns place id as string for candidate with highest probability, or empty string if no candidate found
|
def get_place_id(name: str, location: Optional[str]) -> Optional[str]:
place_id = None
result = ''
if location is None:
result = gmaps.find_place(name, 'textquery')
else:
result = gmaps.find_place(name + ', ' + location, 'textquery')
if len(result['candidates']) >= 1:
place_id = result['candidates'][0]['place_id']
return place_id
|
[
"def return_location(research):\n with urllib.request.urlopen(research, timeout=4) as url:\n data = json.loads(url.read().decode())\n\n data_place_id = data[\"results\"][0][\"place_id\"]\n\n return data_place_id",
"def choose_place_name_to_put_token(self):\n prob = collections.Counter()\n for hunted in self.player.game.hunted:\n possible_places = hunted.phand + hunted.played\n for card in possible_places:\n prob[card.name] += (1 / len(possible_places))\n total_prob_denominator = 0\n\n for cardname in prob:\n total_prob_denominator += prob[card]\n\n return random.choices(list(prob.keys()), weights=prob.values())[0]",
"def resolve_place(place):\n\n place = re.sub(prov, '', place)\n place = place.strip()\n\n try:\n rs = scraperwiki.sqlite.select(\"name, lat, long FROM geo_cache WHERE key = ?\", (place))\n if len(rs) > 0:\n name = rs[0]['name']\n lat = float(rs[0]['lat'])\n lng = float(rs['0']['long'])\n\n return (name, (lat, lng))\n except:\n # geo_cache is empty\n pass\n\n print \"Sleeping for %s seconds (geo api)\" % geo_sleep.time\n time.sleep(geo_sleep.time)\n\n try:\n codes = geo.geocode('%s, IT' % place, exactly_one=False)\n geo_sleep.reset()\n except geocoders.google.GQueryError:\n # fallback\n codes = gn.geocode('%s, IT' % place, exactly_one=False)\n except geocoders.google.GTooManyQueriesError:\n # fallback\n codes = gn.geocode('%s, IT' % place, exactly_one=False)\n geo_sleep.increment()\n \n if codes:\n ret = codes[0]\n else:\n codes = ('?', (None, None))\n \n data = {\n 'key': place,\n 'name': ret[0],\n 'lat': float(ret[1][0]),\n 'long': float(ret[1][1]),\n }\n scraperwiki.sqlite.save(unique_keys=['key'], data=data, table_name=\"geo_cache\")\n\n return (data['name'], (data['lat'], data['long']))",
"def build_place_id_url(location: str) -> str:\r\n base_url = \"https://maps.googleapis.com/maps/api/place/findplacefromtext/json\"\r\n query_parameters = [(\"input\", location), (\"inputtype\", \"textquery\"), (\"key\", GOOGLE_API_KEY)]\r\n return base_url + \"?\" + urllib.parse.urlencode(query_parameters)",
"def get_place_id(place_id):\n catch_place = storage.get('Place', place_id)\n if catch_place is None:\n abort(404)\n return jsonify(catch_place.to_dict())",
"def _get_one_location_by_name(screen, name):\n template = cv2.imread('assets/cards/' + name + '.png')\n result = cv2.matchTemplate(screen, template, cv2.TM_CCOEFF_NORMED)\n _, _, _, loc = cv2.minMaxLoc(result)\n return name, loc",
"def search_business_name(place_id):\n\n place = gmaps.place(place_id, fields=['name'])\n return place['result']['name']",
"def get_name_id(self, name):\n\n table = 'names'\n\n result = self.fuzzy_match_name(name)\n\n if result is None:\n result = name.replace(',', '')\n\n query1 = f\"INSERT INTO {table} (Name) VALUES (%s);\"\n self._cursor.execute(query1, (result,))\n mydb.commit()\n\n query2 = f\"SELECT ID FROM {table} WHERE Name LIKE (%s);\"\n self._cursor.execute(query2, (result+'%',))\n mydb.commit()\n\n id = self._cursor.fetchone()\n\n return id[0]",
"def get_or_create_place_id(self, street_address, lang, name=\"\", url=\"\"):\n address_data = clean_street_address(street_address)\n street_address = address_data.get(\"street_address\", None)\n if not street_address:\n return\n\n espoo_loc_id = self.location_cache.get(street_address, None)\n if espoo_loc_id:\n return espoo_loc_id\n\n address_lang = lang\n if address_lang not in ADDRESS_LANGUAGES:\n # pick the first preferred language (e.g. Finnish) if lang (e.g. English) has no address translations\n address_lang = ADDRESS_LANGUAGES[0]\n # do not use street addresses, we want metadata for espoo event locations too!\n filter_params = {\n \"data_source__in\": (self.tprek_data_source, self.data_source),\n \"deleted\": False,\n \"street_address_\" + address_lang + \"__icontains\": street_address,\n }\n # prefer tprek, prefer existing event locations\n places = Place.objects.filter(**filter_params).order_by(\n \"-data_source\", \"-n_events\"\n )\n place = places.first() # Choose one place arbitrarily if many.\n if len(places) > 1:\n logger.warning(\n 'Several tprek and/or espoo id match the address \"{}\".'.format(\n street_address\n )\n )\n if not place:\n origin_id = self._get_next_place_id(\"espoo\")\n # address must be saved in the right language!\n address_data[\"street_address_\" + address_lang] = address_data.pop(\n \"street_address\"\n )\n address_data.update(\n {\n \"publisher\": self.organization,\n \"origin_id\": origin_id,\n \"id\": \"espoo:%s\" % origin_id,\n \"data_source\": self.data_source,\n \"name_\" + lang: name,\n \"info_url_\" + lang: url,\n }\n )\n place = Place(**address_data)\n place.save()\n elif place.data_source == self.data_source:\n # update metadata in the given language if the place belongs to espoo:\n setattr(place, \"name_\" + lang, name)\n setattr(place, \"info_url_\" + lang, url)\n setattr(place, \"street_address_\" + address_lang, street_address)\n place.save(\n update_fields=[\n \"name_\" + lang,\n \"info_url_\" + lang,\n \"street_address_\" + lang,\n ]\n )\n # Cached the location to speed up\n self.location_cache.update(\n {street_address: place.id}\n ) # location cache need not care about address language\n return place.id",
"def get_location_id(url: str) -> str:\n loc_id = parse(LOCATION_FORMAT, url)\n if loc_id is not None and not isinstance(loc_id, Match):\n if len(loc_id.spans) != 1: # pragma: no cover\n raise ValueError(f\"Format error: {url}\")\n return loc_id[0]\n raise ValueError(f\"{url} not a recognized format\") # pragma: no cover",
"def get_place(self, key):\n # check if key is valid\n if key != \"\" and self._places.has_key(key):\n # return place\n return self._places[key]\n return None",
"def get_team_placement(teamlink, eventid):\r\n page = requests.get(\"https://ctftime.org%s\" % teamlink)\r\n tree = html.fromstring(page.content)\r\n placement = tree.xpath(\r\n '//*/table/tr/td[3]/a[@href=\"/event/%s\"]'\r\n '/../../td[@class=\"place\"]/text()'\r\n % eventid)\r\n try:\r\n return int(placement[0])\r\n except IndexError:\r\n # did not participate, give worst rating ever\r\n return float('inf')",
"def get_main_place():\n\t\treturn Place.objects.get(name = MAIN_PLACE_NAME)",
"def _GetGooglePlaceFoodType(place):\n for quick_string in constants.QUICK_STRINGS:\n if quick_string in [i.lower() for i in place['name'].split()]:\n return 'quick'\n for sit_down_string in constants.SIT_DOWN_STRINGS:\n if sit_down_string in [i.lower() for i in place['name'].split()]:\n return 'sit-down'\n for coffee_string in constants.COFFEE_STRINGS:\n if coffee_string in [i.lower() for i in place['name'].split()]:\n return 'coffee'\n return 'food'",
"def choose_place_name_to_put_token(self):\n place_option = []\n for hunted in self.player.game.hunted:\n for card in hunted.played:\n if card.name not in place_option:\n place_option.append(card.name)\n for card in hunted.phand:\n if card.name not in place_option:\n place_option.append(card.name)\n return random.choice(place_option)",
"def _search_id_by_name(self):\n candidate_id = None\n for item in items:\n if item[\"name\"]==self.name:\n candidate_id = item[\"id\"]\n if candidate_id==None:\n raise InvalidItemIDError\n return candidate_id",
"def generatePlaceOCDID(city, state):\n ocdid = generateStateOCDID(state)\n ocdid += TURBOVOTE_PLACEOCDID\n ocdid += city.lower().replace(' ','_')\n\n return ocdid",
"def _find_best_match(self,\r\n address,\r\n search_extent=None,\r\n location=None,\r\n distance=None,\r\n out_sr=None,\r\n category=None,\r\n out_fields=\"*\",\r\n magic_key=None,\r\n for_storage=False):\r\n candidates = self._geocode(address, search_extent, location, distance,\r\n out_sr, category, out_fields, 1, magic_key, for_storage)\r\n if candidates:\r\n location = candidates[0]['location']\r\n return location['y'], location['x']",
"def get_location_id_from_package_id(locations, hash_table, package_id):\r\n\r\n # get package bucket from hash table\r\n package = hash_table.get_package(package_id)\r\n\r\n # return location id after searching for it through\r\n return get_location_id_from_address(locations, package[1], package[3], package[4])"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Get all links from a list of URLs
|
def get_all_links(url_list):
full_link_list = []
skipped_urls = []
for idx, url in enumerate(url_list):
# progress_bar(idx+1, len(url_list))
try:
link_list = get_list_of_links(url)
except (UnicodeError, IndexError):
skipped_urls.append(url)
link_list = []
full_link_list = full_link_list + link_list
full_link_list = full_link_list + url_list
full_link_list = list(set(full_link_list))
# print("\nSkipped %d URLs" % len(skipped_urls))
return full_link_list
|
[
"def _extract_url_links(base_url, html):\n print('extract url links')\n soup = BeautifulSoup(html, \"html.parser\")\n anchors = soup.find_all('a')\n print('anchors: ', anchors)\n links = []\n for anchor in anchors:\n href = anchor.get('href')\n link = urljoin(base_url, href)\n links.append(link)\n print('links: ', links)\n return links",
"def get_all_website_links(url):\n print(f\"Crawling {url}.\")\n urls = set()\n session = requests.Session()\n retry = Retry(connect=3, backoff_factor=0.5)\n adapter = HTTPAdapter(max_retries=retry)\n session.mount('http://', adapter)\n session.mount('https://', adapter)\n res = session.get(url)\n soup = BeautifulSoup(res.text, 'lxml')\n \n for a_tag in soup.findAll(\"a\"):\n try:\n href = a_tag.attrs.get(\"href\")\n if not \"https://gambuuze\" in href:\n continue\n if not is_valid(href):\n continue\n if href in urls:\n continue\n urls.add(href)\n all_urls.add(href)\n except Exception as e:\n print(e)\n continue\n return urls",
"def get_all_links(url, SEED_DOMAIN):\r\n\thtml = get_html(url)\r\n\tsoup = BeautifulSoup(html, \"html5lib\")\r\n\tall_urls = []\r\n\r\n\ttry:\r\n\t\tfor link in soup.find_all('a'):\r\n\t\t\t# print(link)\r\n\t\t\tall_urls.append(link.get('href'))\r\n\texcept Exception as e:\r\n\t\tprint(e)\r\n\r\n\tresult_urls = []\r\n\r\n\tfor url in all_urls:\r\n\t\tdomain = urlparse(url).netloc\r\n\r\n\t\tif domain == SEED_DOMAIN:\r\n\t\t\tresult_urls.append(url)\r\n\r\n\treturn result_urls, html",
"def extract_next_links(self, url_data):\n try:\n outputLinks = []\n etree_parser = etree.parse(StringIO(url_data['content'].decode('utf-8')), etree.HTMLParser()) #Parsing through the content of the file and then decoded \n for data in etree_parser.xpath(\"//@href\"): #Getting data with 'href' so as to obtain the links\n to_append = data\n if bool(urlparse(data).netloc) == False: #To check if link is in absolute or relative form\n to_append = urljoin(url_data[\"url\"], data) #To convert relative form to absolute form \n outputLinks.append(to_append)\n except:\n pass #To let errors pass\n return outputLinks",
"def get_all_website_links(url):\n # all URLs of `url`\n urls = []\n # domain name of the URL without the protocol\n domain_name = urlparse(url).netloc\n # initialize an HTTP session\n session = HTMLSession()\n # make HTTP request & retrieve response\n response = session.get(url)\n # execute Javascript\n try:\n response.html.render()\n except:\n pass\n soup = BeautifulSoup(response.html.html, \"html.parser\")\n for a_tag in soup.findAll(\"a\"):\n href = a_tag.attrs.get(\"href\")\n if href == \"\" or href is None:\n # href empty tag\n continue\n # join the URL if it's relative (not absolute link)\n href = urljoin(url, href)\n parsed_href = urlparse(href)\n # remove URL GET parameters, URL fragments, etc.\n href = parsed_href.scheme + \"://\" + parsed_href.netloc + parsed_href.path\n if not is_valid(href):\n # not a valid URL\n continue\n if href in urls:\n # already in the set\n continue\n if '/category/' in href:\n continue\n if href.endswith('/executive'):\n continue\n if href.endswith('/senate'):\n continue\n if href.endswith('/house-of-representatives'):\n continue\n if href.endswith('/judiciary'):\n continue\n if href.endswith('/foreign-policy'):\n continue\n if href.endswith('/elections'):\n continue\n if domain_name not in href:\n continue\n if len(re.findall('/politics/', href)) > 0:\n urls.append(href)\n\n return urls",
"def scrap_links(self, url):\n response = self.session.get(url)\n response.raise_for_status()\n return response.links()",
"def scrape(self, url):\n soup = self.create_soup(url)\n \n #find all contents inside of \"a\" tags\n urls = soup.find_all(\"a\")\n urls_list = list()\n \n #append each URL to a list\n #remove the first and last few urls (they do not link to tables)\n for i in range(4, len(urls) - 4):\n url_href = urls[i]['href']\n urls_list.append(url_href)\n \n return urls_list",
"def get_links(self, normalize=False):\n from urllib import unquote\n for (_,e) in self.walk():\n if isinstance(e, HTMLElement) and e.tag == 'a' and e['href']:\n url = unquote(e['href'])\n if normalize:\n url = self.root.normalize_url(url)\n yield (e.get_text(), url)\n return",
"def search_for_links(self):\n urls = {\n util.schemeless(util.fragmentless(url), slashes=False)\n for url in self.domain_urls\n if not util.in_webmention_blocklist(util.domain_from_link(url))\n }\n if not urls:\n return []\n\n # Search syntax: https://www.reddit.com/wiki/search\n url_query = ' OR '.join(f'site:\"{u}\" OR selftext:\"{u}\"' for u in urls)\n return self.get_activities(\n search_query=url_query, group_id=gr_source.SEARCH, etag=self.last_activities_etag,\n fetch_replies=False, fetch_likes=False, fetch_shares=False, count=50)",
"def get_links(url):\n html = requests.get(url).content\n soup = BeautifulSoup(html, \"html.parser\")\n \n links = []\n for link in soup.findAll('a', attrs={'href': re.compile(\".pdf\")}):\n links.append(base_url + link.get('href'))\n return links",
"def get_links(url):\n links = []\n res = requests.get(url,headers=header).content\n s = etree.HTML(res)\n for i in s.xpath('//img/@src'):\n if i.startswith('http') and i.endswith('.jpg'):\n links.append(i)\n # print(links[3])\n return links",
"def GetUrls(titles):\r\n links = []\r\n for title in titles:\r\n page = wikipedia.page(title)\r\n links.append(page.url)\r\n return links",
"def get_links(html):\n #a regular expression to extract all links from the webpage\n webpage_regex = re.compile('<a [^>] +href=[\"\\'](.*?)[\"\\']',re.IGNORECASE)\n return webpage_regex.findall(html)",
"def get_links(html):\r\n\t# a regular expression to extract all links from the webpage\r\n\twebpage_regex = re.compile('<a[^>]+href=[\"\\'](.*?)[\"\\']', \r\n\t\tre.IGNORECASE)\r\n\treturn webpage_regex.findall(html)",
"def get_links(self):\n return (e[2] for e in self.parse() if e[0].tag == 'a')",
"def extract_links_from_hotels_list(self, hotels_list):\n links_list = [hotel[\"url\"] for hotel in hotels_list]\n return links_list",
"def get_urls_from_html(self):\n if self.html is None:\n logging.error('HTML not available cannot get URLs')\n return None\n else:\n raw_urls = self.html.xpath('//a/@href')\n logging.debug(raw_urls)\n return shuffle([self.urls.add(self.absolute_url(self.normalize(url))) for url in raw_urls])",
"def get_links(html, url=None, local=True, external=True):\n def normalize_link(link):\n if urlsplit(link).scheme in ('http', 'https', ''):\n if '#' in link:\n link = link[:link.index('#')]\n if url:\n link = urljoin(url, link)\n if not local and common.same_domain(url, link):\n # local links not included\n link = None\n if not external and not common.same_domain(url, link):\n # external links not included\n link = None\n else:\n link = None # ignore mailto, etc\n return link\n a_links = a_re.search(html)\n js_links = js_re.findall(html)\n links = []\n for link in a_links + js_links:\n try:\n link = normalize_link(link)\n except UnicodeError:\n pass\n else:\n if link and link not in links:\n links.append(link)\n return links",
"def GetUrlAnchors(self):\n log = Log('GetUrlAnchors')\n #print \"00\"\n self.ResetLastError()\n\n for anchor in self.GetAnchorList():\n yield anchor"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Make AhoCorasick automaton from a list of strings
|
def init_automaton(string_list):
A = ahocorasick.Automaton()
for idx, s in enumerate(string_list):
A.add_word(s, (idx, s))
return A
|
[
"def parse_string_to_automata(string):\n\tlist_of_states = []\n\tno_rubish = find_between(string, '\\[', '\\]')\n\tfor i in no_rubish.split(','):\n\t\tstate_strings = find_between(i, '/').split(' ')\n\t\tlist_of_states.append(State(i.strip()[0], int(state_strings[0]), int(state_strings[1]), int(state_strings[2]), int(state_strings[3])))\n\treturn list_of_states",
"def from_strings_list(list):\n cptr = pyniNVCategory.n_createCategoryFromNVStrings(list)\n return nvcategory(cptr)",
"def parse_input(inputfile) :\n inp = open(inputfile, 'r')\n lines = inp.readlines()\n inp.close()\n\n ll = []\n tnames = []\n nl = 0\n for l in lines :\n nl = nl + 1\n if l.startswith(\"--\"):\n continue\n elif l.strip() == '' :\n continue\n elif l.startswith('task') :\n l = l.lstrip('task')\n task = parse_ptask(l)\n ll.append(task_automaton(task['name'], task['ctime'], task['deadline'], task['max_inst']))\n tnames.append(task['name'])\n elif l.startswith('pdtask') :\n l = l.lstrip('pdtask')\n task = parse_ptask(l)\n ll.append(task_automaton(task['name'], task['ctime'], task['deadline'], task['max_inst']))\n ll.append(periodic_automaton(task['name']+\"_arr\", task['name'], task['period']))\n tnames.append(task['name'])\n elif l.startswith('ptask') :\n l = l.lstrip('ptask')\n task = parse_ptask(l)\n ll.append(task_impldline_automaton(task['name'], task['ctime'], task['name']+\"_arr\"))\n ll.append(periodic_automaton(task['name']+\"_arr\", task['name'], task['period']))\n tnames.append(task['name'])\n elif l.startswith('stask') :\n l = l.lstrip('stask')\n task = parse_ptask(l)\n ll.append(task_impldline_automaton(task['name'], task['ctime'], task['name']+\"_arr\"))\n ll.append(sporadic_automaton(task['name']+\"_arr\", task['name'], task['period']))\n tnames.append(task['name'])\n elif l.startswith(\"sched\") :\n l = l.lstrip(\"sched\")\n s = [x.strip() for x in l.split(',')]\n ll.append(sched_automaton(s[0], s[1:], False))\n elif l.startswith(\"idlesched\") :\n l = l.lstrip(\"idlesched\")\n s = [x.strip() for x in l.split(',')]\n ll.append(sched_automaton(s[0], s[1:], True))\n elif l.startswith('periodic') :\n l = l.lstrip('periodc')\n per = parse_periodic(l)\n ll.append(periodic_automaton(per['name']+\"_arr\", per['name'], per['period']))\n elif l.startswith('offset_periodic') :\n l = l.lstrip('offset_periodc')\n per = parse_periodic_with_offset(l)\n ll.append(periodic_offset_automaton(per['name']+\"_arr\", per['name'], per['period'], per['offset']))\n elif l.startswith('sporadic') :\n l = l.lstrip('sporadic')\n per = parse_periodic(l)\n ll.append(sporadic_automaton(per['name']+\"_arr\", per['name'], per['period']))\n elif l.startswith('merge') :\n l = l.lstrip('merge')\n mer = parse_merge(l)\n ll.append(merge_automaton(mer['name'], mer['list'], mer['tname']))\n elif l.startswith('curve') :\n l = l.lstrip('curve') \n cur = parse_curve(l)\n ll.append(arrival_curve_automaton(cur['name'], cur['tname'], cur['burst'], cur['period']))\n else :\n print(\"ERROR in parsing the input file\")\n print(\"At line: \", nl);\n exit\n ll.append(miss_automaton(\"dline\", tnames))\n return ll",
"def __init__(self, motif_string):\n self.motif = []\n rule = \"is\"\n seq = \"\"\n for c in motif_string:\n if c == '{':\n rule = \"not\"\n seq = \"\"\n elif c == '}':\n self.motif.append((rule, seq))\n rule = \"is\"\n seq = \"\"\n elif c == '[':\n rule = \"or\"\n seq = \"\"\n elif c == ']':\n self.motif.append((rule, seq))\n rule = \"is\"\n seq = \"\"\n else:\n if rule != \"is\":\n seq += c\n else:\n self.motif.append((rule, c))",
"def _construct_dataset_from_list_of_strings(\n cls, config: DatasetConfig\n ) -> \"Dataset\":\n assert isinstance(config.selection, list)\n datasets: List[\"Dataset\"] = []\n selections: List[str] = deepcopy(cast(List[str], config.selection))\n for selection in selections:\n config.selection = selection\n dataset = Dataset.from_config(config)\n assert isinstance(dataset, Dataset)\n datasets.append(dataset)\n\n # Reset `selections`.\n config.selection = selections\n\n return cls.concatenate(datasets)",
"def contracted_strings_to_tensor_terms(pdaggerq_list_of_strings):\n tensor_terms = []\n for pq_string in pdaggerq_list_of_strings:\n coeff = float(pq_string[0])\n single_tensor_term = []\n actions = []\n for ts in pq_string[1:]:\n bs = string_to_baseterm(ts)\n if isinstance(bs, TensorTermAction):\n actions.append(bs)\n else:\n single_tensor_term.append(bs)\n tensor_terms.append(\n TensorTerm(base_terms=tuple(single_tensor_term), coefficient=coeff,\n permutation_ops=actions)\n )\n return tensor_terms",
"def convert2aa(sequence):\r\n\r\n # sequence = \"\".join([x.upper() for x in sequence]) # converts lowercase to uppercase\r\n\r\n number_of_codons = len(sequence)/3\r\n aa_seq = []\r\n\r\n for nmbr in list(range(1, int(number_of_codons)+1)): # goes through each codon converting it to an aa\r\n\r\n if \"\".join([x.upper() for x in sequence])[nmbr*3-3:nmbr*3] in codon2aa:\r\n aa_seq.append(codon2aa[\"\".join([x.upper() for x in sequence])[nmbr*3-3:nmbr*3]])\r\n else:\r\n aa_seq.append(\"XXX\")\r\n\r\n return \"\".join(aa_seq)",
"def load_data(file):\n\n start=set() # start states\n transitions=list() # transitions: [input, start, end] \n accept=set() # accept states\n alphabet=set() # set of all input symbols\n states=set() # set of all states\n\n beginning=True \n \n for line in file:\n # start states\n if re.search(r\"^\\[(.)+\\]\\n$\", line) and beginning:\n start.add(line[1:-2])\n states.add(line[1:-2])\n\n else:\n match=re.search(r\"^((.)+),\\[((.)+)\\]->\\[((.)+)\\]\\n$\", line)\n # transitions\n if match:\n beginning=False\n transitions.append([match.group(3), match.group(1), match.group(5)]) \n alphabet.add(match.group(1))\n states.add(match.group(3))\n states.add(match.group(5))\n \n # accept states\n elif re.search(r\"^\\[(.)+\\]\\n$\", line) and not beginning:\n accept.add(line[1:-2])\n states.add(line[1:-2])\n \n # wrong file format\n else:\n raise SyntaxError(\"Wrong format!\")\n\n return Automaton(states,alphabet,transitions,start,accept)",
"def automaton_gen(ltl_f):\r\n\r\n # Call SPOT\r\n if windows:\r\n with open('aut_gen_caller.sh', 'w') as f_in:\r\n f_in.write('#! /bin/sh' + '\\n')\r\n f_in.write('ltl2tgba -B -f')\r\n f_in.write(' \"' + ltl_f + '\" ')\r\n f_in.write('-H --output=aut_output.txt')\r\n\r\n t_s_aut_gen = time.time()\r\n subprocess.call(\"bash ./aut_gen_caller.sh\")\r\n t_f_aut_gen = time.time()\r\n dt_aut_gen = t_f_aut_gen - t_s_aut_gen # time for generating automaton by SPOT\r\n else:\r\n call_spot = spot+\" -B -f\" +\" '\" + ltl_f +\"' \"+ \"-H --output=./aut_output.txt\"\r\n t_s_aut_gen = time.time()\r\n subprocess.call(call_spot, shell=True)\r\n t_f_aut_gen = time.time()\r\n dt_aut_gen = t_f_aut_gen - t_s_aut_gen # time for generating automaton by SPOT\r\n\r\n # Parse output\r\n # transitions: list of 3-tuples (state,label,state)\r\n error_flag = False\r\n with open('aut_output.txt', 'r') as f_hoa:\r\n l = f_hoa.readline()\r\n\r\n if l == '':\r\n error_flag = True\r\n else:\r\n while l.find('States') < 0:\r\n l = f_hoa.readline()\r\n\r\n n_states = l[8:-1]\r\n\r\n while l.find('Start') < 0:\r\n l = f_hoa.readline()\r\n\r\n Q0 = list(l[7:-1]) # for 1 initial state\r\n\r\n while l.find('AP') < 0:\r\n l = f_hoa.readline()\r\n\r\n n_var = int(l[4:4+l[4:].find(' ')])\r\n var_all = [] # the name of all variables\r\n map_var = {} # mapping of variables to integers from 0 to n-1\r\n ind_b = [i+2 for i in list(find_all(l, ' \"'))]\r\n ind_f = list(find_all(l, '\" '))\r\n ind_f.append(l.rfind('\"'))\r\n if len(ind_b) != len(ind_f):\r\n error_flag = True\r\n else:\r\n var_all = [l[ind_b[i]:ind_f[i]] for i in range(len(ind_b))]\r\n map_var = {str(i):var_all[i] for i in range(n_var)}\r\n\r\n while l.find('Acceptance') < 0:\r\n l = f_hoa.readline()\r\n\r\n if l[11:14] != ' 1 ':\r\n error_flag = True\r\n Q_acc = []\r\n Q_acc_lab = l[l.find('Inf')+4:l.find(')')] # for 1 accepting label\r\n\r\n l = f_hoa.readline()\r\n while l.find('BODY') < 0:\r\n l = f_hoa.readline()\r\n l = f_hoa.readline()\r\n\r\n delta = []\r\n n_tr = 0 # number of transitions\r\n while l.find('END') < 0:\r\n if l[7:].find(' ') < 0:\r\n s_end = 7 + l[7:].find('\\n')\r\n else:\r\n s_end = 7 + l[7:].find(' ')\r\n s_temp = l[7:s_end]\r\n if l.find('{'+Q_acc_lab+'}') >= 0:\r\n Q_acc.append(s_temp)\r\n l = f_hoa.readline()\r\n while (l.find('State') < 0) & (l.find('END') < 0):\r\n tr_temp = l[1:l.find(']')]\r\n\r\n # replace with variable names\r\n tr_temp = tr_temp.replace('t','T') # variable names should not contain t\r\n tr_temp = tr_temp.replace('!','~')\r\n pattern = re.compile(\"|\".join(map_var.keys()))\r\n tr_temp = pattern.sub(lambda m: map_var[m.group(0)], tr_temp)\r\n\r\n tr_temp = tr_temp.split(' | ')\r\n tr_temp = [' '.join(cl.split('&')) for cl in tr_temp]\r\n\r\n next_s_temp = l[l.find(']')+2:-1]\r\n delta.append((s_temp, tr_temp, next_s_temp))\r\n n_tr += 1\r\n l = f_hoa.readline()\r\n\r\n Q = list(set([tr[0] for tr in delta]))\r\n Q.sort()\r\n\r\n # initiate state names by 'q'\r\n Q = ['q'+q for q in Q]\r\n Q0 = ['q'+q for q in Q0]\r\n Q_acc = ['q'+q for q in Q_acc]\r\n delta = [('q'+tr[0], tr[1], 'q'+tr[2]) for tr in delta]\r\n\r\n return (Q, Q0, delta, Q_acc, error_flag, dt_aut_gen)",
"def from_qusetta(circuit: List[str]) -> qiskit.QuantumCircuit:\n n, new_circuit = -1, []\n for gate in circuit:\n g, params, qubits = qs.gate_info(gate)\n n = max(max(qubits), n)\n new_circuit.append((g.lower(), params, qubits))\n\n qiskit_circuit = qiskit.QuantumCircuit(n + 1)\n for g, params, qubits in new_circuit:\n # ibm is weird and reversed their qubits from everyone else.\n # So we reverse them here.\n qubits = tuple(n - q for q in qubits)\n getattr(qiskit_circuit, g)(*(params + qubits))\n\n return qiskit_circuit",
"def make_token_seq(seq):\n ret = []\n for name in seq: ret.append(make_token(name))\n return ret",
"def create_expressions(str_list):\n return [expr(s) for s in str_list]",
"def build_string_object(strlist, encoder):\n\n obj = Rgb6()\n\n for strsym in strlist:\n splitname = strsym[0].split(\"_\")\n\n if splitname[0] != \"NAME\":\n continue\n\n bank = int(splitname[1], 16)\n offset = int(splitname[2], 16)\n\n encoded_string = encoder(strsym[1])\n\n sec = Rgb6Section()\n sec.name = \"Attr Table Name %X_%X\" % (bank, offset)\n sec.sectype = Rgb6Section.ROMX\n sec.org = 0x4000 + offset\n sec.bank = bank\n sec.datsec.data = encoded_string + (b\"\\x00\" * (0x10 - len(encoded_string)))\n\n obj.sections.append(sec)\n\n return obj",
"def load_fa_from_user() -> FiniteAutomaton:\n\n atom = input(\"Enter the analyzed lexical atom:\").strip().rstrip()\n alphabet = input(\n \"Enter the alphabet (semicolon separated):\").strip().rstrip().split(';')\n states = set()\n initial_state = input(\"Enter the initial state:\").strip().rstrip()\n final_states = list(input(\n \"Enter the final states (semicolon separated):\").strip().rstrip().split(';'))\n transitions = {}\n print(\"Enter the transitions (from;to;symbols/symbol). E.g.: q0;q1;1,2,3. Press enter with an empty line to stop.\")\n while True:\n line = input(\">> \")\n if not line:\n break\n\n prefix_state, sufix_state, symbols = line.strip().rstrip().split(';')\n states.add(prefix_state)\n states.add(sufix_state)\n symbols = list(symbols.split(','))\n if prefix_state in transitions:\n transitions[prefix_state].append(\n Transition(sufix_state, symbols))\n else:\n transitions[prefix_state] = [\n Transition(sufix_state, symbols)]\n\n states = sorted(list(states))\n return FiniteAutomaton(atom, alphabet, states, initial_state, final_states, transitions)",
"def __buildFSA(self, list_strings, cap = False):\n\n if cap:\n string2Fsa = self.__stringCap2Fsa\n else:\n string2Fsa = self.__string2Fsa\n\n list_fsa = map(lambda s: string2Fsa(s), list_strings)\n return self.__mergeFSA(list_fsa)",
"def get_all_automata():\n return [\n WeightedTomitasGrammars.get_automaton_1(),\n WeightedTomitasGrammars.get_automaton_2(),\n WeightedTomitasGrammars.get_automaton_3(),\n WeightedTomitasGrammars.get_automaton_4(),\n WeightedTomitasGrammars.get_automaton_5(),\n WeightedTomitasGrammars.get_automaton_6(),\n WeightedTomitasGrammars.get_automaton_7()\n ]",
"def make_master_chains_dict(size_of_ngram, text_strings_list):\n\n chains = {}\n for text_string in text_strings_list:\n chains = add_text_to_chains(chains, size_of_ngram, text_string)\n \n return chains",
"def build_fst_from_arc_list(arc_list):\n\n arc_fst = SimpleFST()\n\n for arc in arc_list:\n if len(arc) > 2:\n for state_id in range(arc_fst.num_states, max(arc[:2])+1):\n arc_fst.add_state()\n\n arc_fst.set_start(arc_list[0][0])\n\n for arc in arc_list:\n if len(arc) > 2:\n arc_fst.add_arc(*arc)\n else:\n arc_fst.set_final(*arc)\n\n return arc_fst",
"def automaton_abstraction(aut):\n\n # Compute partition\n partition_list = bisimilarity_partition(aut)\n\n # Construct new automaton based on bisimularity results\n new_aut = data_structure.Automaton(aut.alphabet, aut.collection)\n new_aut.set_kind(aut.aut_kind)\n\n state_map = {} # Mapping of old state -> new_state\n for number, partition in enumerate(partition_list):\n # Decide on marker property of the partition\n assert len(partition) > 0\n # Get a value from the set without modifying it\n state = iter(partition).next()\n\n new_state = new_aut.add_new_state(marked = state.marked, num = number)\n for state in partition:\n state_map[state] = new_state\n\n # Set initial state\n new_aut.initial = state_map[aut.initial]\n\n # Add edges\n #\n # Since the Automaton silently drops duplicate edges, we will have unique\n # edges\n for state in aut.get_states():\n for edge in state.get_outgoing():\n new_aut.add_edge_data(state_map[state], state_map[edge.succ],\n edge.label)\n\n # Clearing local data\n state_map.clear()\n\n return new_aut",
"def translateSequence(seq):\n aa = ''\n for i in xrange(0, len(seq), 3):\n aa += codonToAminoAcid(seq[i:i+3])\n return aa"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Return 1 if company URL, 0 otherwise
|
def get_reward(url, A_company, company_urls):
if sum(check_strings(A_company, company_urls, url)) > 0:
return 1
return 0
|
[
"def abnormal_URL(self):\n\n servers = whois.whois(self._url).name_servers\n safe_URL = [True for server in servers if server.split('.')[1].lower() in ('citizenhawk', 'ultimatesoftware')]\n return 2 if len(safe_URL) == 0 else 0",
"def is_dataone_url(url):\n\n res = url.find('dataone.org')\n if res is not -1:\n return True\n else:\n return False",
"def url_exists(self, url: str) -> Union[int, bool]:\n if url.endswith(\"svg\"):\n self.c.execute(\"SELECT id FROM flags WHERE url=%s\", (url,))\n else:\n self.c.execute(\"SELECT id FROM pages WHERE url=%s\", (url,))\n resp = self.c.fetchone()\n return resp[0] if resp else False",
"def socialNetworkIntegration():\r\n try:\r\n soclialNetwork = Components.objects.get(name__exact=\"social_network\")\r\n return soclialNetwork.is_enabled\r\n except ObjectDoesNotExist, e:\r\n if settings.DEBUG:\r\n print_exc()\r\n return -1\r\n except:\r\n print_exc()\r\n return -1",
"def shortened_URL(self):\n domain = tldextract.extract(self._url).domain\n return 0 if domain in self._url else 2",
"def get_request_website():\n return request and getattr(request, 'website', False) or False",
"def default_validation(url):\n return bool(urlparse(url).scheme)",
"def check_url_format(self):\n if re.match('^https?://www.walgreens.com/store/c/.+/ID=prod\\d+-product$', self.product_page_url):\n return True\n return False",
"def se_puede_acceder_a_url(url_):\n try:\n respuesta = urllib2.urlopen(url_)\n return respuesta.code == 200\n except (urllib2.HTTPError, urllib2.URLError) as error:\n LOGGER.warning('Error al acceder a la URL %s. Error: %s', url_, error)\n return False",
"def check_url_format(self):\r\n #m = re.match(\"^http://www.amazon.com/dp/[a-zA-Z0-9]+$\", self.product_page_url)\r\n m = re.match(r\"^http://www.statelinetack.com/.*?$\", self.product_page_url)\r\n return not not m",
"def isURLDataHere(self) -> \"SbBool\":\n return _coin.SoWWWInline_isURLDataHere(self)",
"def get_status_of_url(self, long_url: str):\n document = self.db.unsafe_links.find_one({'long_url': long_url})\n if document is None:\n return None\n return document['status']",
"def hasUrl(self):\n return self._hasUrl",
"def site_exist(self):\n return self.site_count != 0",
"def is_ldap_upc_site(self):",
"def is_hosted(self):\n return self.hosted_by is not None",
"def check_shortener(url):\n file = open(PATH + 'shorteners.txt', 'r')\n for line in file:\n with_www = \"www.\" + line.strip()\n if line.strip() == url['host'].lower() or with_www == url['host'].lower():\n file.close()\n return 1\n file.close()\n return 0",
"def is_social(self) -> bool:\n return False if self.type in ('link', 'portfolio') else True",
"def is_org(nlp, text, company_name):\n \n doc = nlp(text) #select text of the news\n for t in doc.ents:\n \t# print(t)\n \tif t.lower_ == company_name: #if company name is called\n \t\tif t.label_ == \"ORG\": #check they actually mean the company\n \t\t\treturn True\n return False"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Returns false or a decomposition of the GeneratorId specific to the AWS CIS Foundations Benchmark ruleset
|
def is_cis_ruleset(self):
# GeneratorId identifies the specific compliance matched. Examples:
# arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0/rule/1.3
genid_regex = re.search(
'^arn:.*?:ruleset/cis-aws-foundations-benchmark/v/(?P<version>.*?)/rule/(?P<rule>.*?)$',
self.generator_id)
if not genid_regex:
return False
return {
'ruleset': 'cis-aws-foundations-benchmark',
'version': genid_regex.group('version'),
'ruleid': genid_regex.group('rule')
}
|
[
"def is_well_generated(self):\n return True",
"def test_combination_id(self):\n self._test_combination(labels=False)",
"def test(mfcc, correctID, models, k=5):\n bestModel = -1\n print(\"TODO\")\n\n return 1 if (bestModel == correctID) else 0",
"def sagittalFlag(): \n slicingDim = params.WhichExperiment.Dataset.slicingInfo.slicingDim\n nucleus_index = params.WhichExperiment.Nucleus.Index[0]\n return (nucleus_index == 1) and (slicingDim == 2)",
"def is_well_generated(self):\n return self.number_of_simple_reflections() == self.rank()",
"def is_aws_fsbp_ruleset(self):\n\n # Generator Id example:\n # aws-foundational-security-best-practices/v/1.0.0/CloudTrail.1\n genid_regex = re.search(\n '^aws-foundational-security-best-practices/v/(?P<version>.*?)/(?P<rule>.*?)$',\n self.generator_id)\n\n if not genid_regex:\n return False\n\n return {\n 'ruleset': 'aws-foundational-security-best-practices',\n 'version': genid_regex.group('version'),\n 'ruleid': genid_regex.group('rule')\n }",
"def get_generator_classifier(self):\n return self.generator_classifier",
"def getOpticId(self) -> int:\n ...",
"def get_sdmname(candcollection):\n\n datasetId = candcollection.metadata.datasetId\n uid = get_uid(candcollection)\n outputDatasetId = 'realfast_{0}_{1}'.format(datasetId, uid.rsplit('/')[-1])\n\n return outputDatasetId",
"def data_and_simulation_are_consistent(config: OptimizerConfig) -> bool: # pragma: no cover\n\n data_var_names = sorted(config.data.inputs.keys())\n dataset_ok = True\n missing_names: Set[str] = set()\n data_output_name: Optional[str] = None\n if config.data.folder.is_dir() or config.data.files:\n df = config.data.load_dataframe()\n df_col_names = sorted(df.columns.tolist())\n data_output_name = config.data.output_column\n missing_names = set(data_var_names).union([data_output_name]).difference(df_col_names)\n if missing_names:\n logging.error(\n \"One or more columns expected by the config file are missing from the data: \"\n + \", \".join(sorted(missing_names))\n )\n try:\n Dataset(df, config.data)\n except ValueError as e:\n logging.error(f\"Constructing Dataset object raised a ValueError: {e}\")\n dataset_ok = False\n simulator = config.get_simulator()\n data_generator = SimulatedDataGenerator(simulator)\n simulation_var_names = sorted(data_generator.parameter_space.parameter_names)\n input_names_consistent = data_var_names == simulation_var_names\n if not input_names_consistent: # pragma: no cover\n logging.error(\"Inputs in the config file must match those of the data generator (simulator)\")\n logging.error(f\"Inputs in the config: {', '.join(data_var_names)}\")\n logging.error(f\"Inputs allowed by data generator: {', '.join(simulation_var_names)}\")\n simulation_output_name = data_generator.objective_col_name\n output_names_consistent = (data_output_name == simulation_output_name) or data_output_name is None\n if not output_names_consistent:\n logging.error(\"Output in the config file must match objective of the data generator (simulator)\")\n logging.error(f\"Output in the config: {data_output_name}\")\n logging.error(f\"Objective of the data generator: {simulation_output_name}\")\n return input_names_consistent and output_names_consistent and not missing_names and dataset_ok",
"def new_benchmark_ad():\n return True",
"def is_demultiplexing_possible(self, flow_cell: FlowCellDirectoryData) -> bool:\n LOG.info(f\"Check if demultiplexing is possible for {flow_cell.id}\")\n demultiplexing_possible = True\n if not flow_cell.is_flow_cell_ready():\n demultiplexing_possible = False\n\n if not flow_cell.sample_sheet_exists():\n LOG.warning(f\"Could not find sample sheet in flow cell directory for {flow_cell.id}\")\n demultiplexing_possible = False\n\n if not self.is_sample_sheet_in_housekeeper(flow_cell_id=flow_cell.id):\n LOG.warning(f\"Could not find sample sheet in Housekeeper for {flow_cell.id}\")\n demultiplexing_possible = False\n\n if (\n flow_cell.has_demultiplexing_started_locally()\n or flow_cell.has_demultiplexing_started_on_sequencer()\n ):\n LOG.warning(\"Demultiplexing has already been started\")\n demultiplexing_possible = False\n\n if self.flow_cell_out_dir_path(flow_cell=flow_cell).exists():\n LOG.warning(\"Flow cell out dir exists\")\n demultiplexing_possible = False\n\n if self.is_demultiplexing_completed(flow_cell):\n LOG.warning(f\"Demultiplexing is already completed for flow cell {flow_cell.id}\")\n demultiplexing_possible = False\n return demultiplexing_possible",
"def areNormalGenerated(self) -> \"SbBool\":\n return _coin.SoReorganizeAction_areNormalGenerated(self)",
"def shouldBelongToSameOutcomeMeasurement(self, template):\n gid = self.token.getAnnotationAttribute(self.type, 'group')\n oid = self.token.getAnnotationAttribute(self.type, 'outcome')\n tid = self.token.getAnnotationAttribute(self.type, 'time')\n csID = self.token.getAnnotationAttribute(self.type, 'compareSet')\n\n gid2 = template.token.getAnnotationAttribute(template.type, 'group')\n oid2 = template.token.getAnnotationAttribute(template.type, 'outcome')\n tid2 = template.token.getAnnotationAttribute(template.type, 'time')\n csID2 = template.token.getAnnotationAttribute(template.type, 'compareSet')\n\n return len(gid) > 0 and len(oid) > 0 and gid == gid2 and oid == oid2 and tid == tid2 and csID == csID2",
"def is_seed(mutation: dict) -> bool:\n return 'orig_seed' in mutation",
"def areVPNodesGenerated(self) -> \"SbBool\":\n return _coin.SoReorganizeAction_areVPNodesGenerated(self)",
"def getGeneratorName(self):\n # type: () -> str",
"def isgenerator(obj):\r\n return (isgeneratorfunction(obj)\r\n or getattr(obj, 'testGenerator', None) is not None)",
"def areTexCoordsGenerated(self) -> \"SbBool\":\n return _coin.SoReorganizeAction_areTexCoordsGenerated(self)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Returns false or a decomposition of the GeneratorId specific to the AWS Foundational Security Best Practices ruleset
|
def is_aws_fsbp_ruleset(self):
# Generator Id example:
# aws-foundational-security-best-practices/v/1.0.0/CloudTrail.1
genid_regex = re.search(
'^aws-foundational-security-best-practices/v/(?P<version>.*?)/(?P<rule>.*?)$',
self.generator_id)
if not genid_regex:
return False
return {
'ruleset': 'aws-foundational-security-best-practices',
'version': genid_regex.group('version'),
'ruleid': genid_regex.group('rule')
}
|
[
"def is_well_generated(self):\n return True",
"def _generate_expected_sg_rules(self, prs):\n # Get all the needed cidrs:\n prs = self._gbp_plugin.get_policy_rule_set(self._context, prs)\n\n providing_ptg_cidrs = self._get_cidrs_from_ptgs(\n prs['providing_policy_target_groups'])\n if len(prs['providing_policy_target_groups']):\n self.assertTrue(len(providing_ptg_cidrs))\n\n consuming_ptg_cidrs = self._get_cidrs_from_ptgs(\n prs['consuming_policy_target_groups'])\n if len(prs['consuming_policy_target_groups']):\n self.assertTrue(len(consuming_ptg_cidrs))\n\n l3p_cidrs = self._get_tenant_l3ps(prs)\n\n providing_ep_cidrs = self._get_cidrs_from_ep(\n prs['providing_external_policies'], l3p_cidrs)\n\n consuming_ep_cidrs = self._get_cidrs_from_ep(\n prs['consuming_external_policies'], l3p_cidrs)\n\n consumers = consuming_ep_cidrs | consuming_ptg_cidrs\n providers = providing_ptg_cidrs | providing_ep_cidrs\n\n mapping = self._get_prs_mapping(prs['id'])\n provided_sg = mapping.provided_sg_id\n consumed_sg = mapping.consumed_sg_id\n # IN: from consumer to provider\n # OUT: from provider to consumer\n # Egress rules are always generic (to 0.0.0.0/0)\n # Igress rules are filtered by subnet\n # Only allow rules are verified\n prules = self._get_prs_enforced_rules(prs)\n expected_rules = []\n in_bi = [gconst.GP_DIRECTION_IN, gconst.GP_DIRECTION_BI]\n out_bi = [gconst.GP_DIRECTION_OUT, gconst.GP_DIRECTION_BI]\n # Redirect action is treated as implicit allow\n allow_action_types = [gconst.GP_ACTION_ALLOW,\n gconst.GP_ACTION_REDIRECT]\n for pr in prules:\n if any(self.show_policy_action(x)['policy_action']['action_type']\n in allow_action_types for x in pr['policy_actions']):\n classifier = self.show_policy_classifier(\n pr['policy_classifier_id'])['policy_classifier']\n protocol = classifier['protocol']\n if classifier['port_range']:\n port_min, port_max = (\n gpdb.GroupPolicyDbPlugin._get_min_max_ports_from_range(\n classifier['port_range']))\n else:\n port_min, port_max = None, None\n if classifier['direction'] in in_bi:\n # If direction IN/BI, consumer cidrs go into provider SG\n for cidr in consumers:\n attrs = {'security_group_id': [provided_sg],\n 'direction': ['ingress'],\n 'protocol': [protocol],\n 'remote_ip_prefix': [cidr]}\n if port_min is not None:\n attrs['port_range_min'] = [port_min]\n if port_max is not None:\n attrs['port_range_max'] = [port_max]\n expected_rules.append(attrs)\n # And consumer SG have egress allowed\n for cidr in providers:\n attrs = {'security_group_id': [consumed_sg],\n 'direction': ['egress'],\n 'protocol': [protocol],\n 'remote_ip_prefix': [cidr]}\n if port_min is not None:\n attrs['port_range_min'] = [port_min]\n if port_max is not None:\n attrs['port_range_max'] = [port_max]\n expected_rules.append(attrs)\n if classifier['direction'] in out_bi:\n # If direction OUT/BI, provider CIDRs go into consumer SG\n for cidr in providers:\n attrs = {'security_group_id': [consumed_sg],\n 'direction': ['ingress'],\n 'protocol': [protocol],\n 'remote_ip_prefix': [cidr]}\n if port_min is not None:\n attrs['port_range_min'] = [port_min]\n if port_max is not None:\n attrs['port_range_max'] = [port_max]\n expected_rules.append(attrs)\n # And provider SG have egress allowed\n for cidr in consumers:\n attrs = {'security_group_id': [provided_sg],\n 'direction': ['egress'],\n 'protocol': [protocol],\n 'remote_ip_prefix': [cidr]}\n if port_min is not None:\n attrs['port_range_min'] = [port_min]\n if port_max is not None:\n attrs['port_range_max'] = [port_max]\n expected_rules.append(attrs)\n return expected_rules",
"def is_cis_ruleset(self):\n\n # GeneratorId identifies the specific compliance matched. Examples:\n # arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0/rule/1.3\n genid_regex = re.search(\n '^arn:.*?:ruleset/cis-aws-foundations-benchmark/v/(?P<version>.*?)/rule/(?P<rule>.*?)$',\n self.generator_id)\n\n if not genid_regex:\n return False\n\n return {\n 'ruleset': 'cis-aws-foundations-benchmark',\n 'version': genid_regex.group('version'),\n 'ruleid': genid_regex.group('rule')\n }",
"def _is_private_creator(self, group, element):\n return group % 2 != 0 and \\\n element > 0x0000 and element < 0x00ff",
"def validAggressor(cls, idAggressor):\n for item in cls.readAll().values():\n if item.get('idAggressor') == idAggressor:\n return True\n return False",
"def test_generate_disabled(self):\n result = rule_promotion.generate_rule_promotion(config=self.config)\n assert_equal(result, False)",
"def test_get_group__valid_id(self):\n\n self.assertEqual(\n entities.Group(\n self.config_dict['groups'][0]['id'],\n self.config_dict['groups'][0]['policy'],\n self.config_dict['groups'][0]['experiments'],\n self.config_dict['groups'][0]['trafficAllocation'],\n ),\n self.project_config.get_group('19228'),\n )",
"def test_combination_id(self):\n self._test_combination(labels=False)",
"def _can_generate_regular_certificate(user, course_key, enrollment_mode, course_grade):\n if _is_ccx_course(course_key):\n log.info(f'{course_key} is a CCX course. Certificate cannot be generated for {user.id}.')\n return False\n\n if is_beta_tester(user, course_key):\n log.info(f'{user.id} is a beta tester in {course_key}. Certificate cannot be generated.')\n return False\n\n if not _is_passing_grade(course_grade):\n log.info(f'{user.id} does not have a passing grade in {course_key}. Certificate cannot be generated.')\n return False\n\n if not _can_generate_certificate_common(user, course_key, enrollment_mode):\n log.info(f'One of the common checks failed. Certificate cannot be generated for {user.id} : {course_key}.')\n return False\n\n log.info(f'Regular certificate can be generated for {user.id} : {course_key}')\n return True",
"def supports_sequence_rule_enabler_bank(self):\n return False",
"def areNormalGenerated(self) -> \"SbBool\":\n return _coin.SoReorganizeAction_areNormalGenerated(self)",
"def _can_generate_certificate_common(user, course_key, enrollment_mode):\n if CertificateInvalidation.has_certificate_invalidation(user, course_key):\n # The invalidation list prevents certificate generation\n log.info(f'{user.id} : {course_key} is on the certificate invalidation list. Certificate cannot be generated.')\n return False\n\n if enrollment_mode is None:\n log.info(f'{user.id} : {course_key} does not have an enrollment. Certificate cannot be generated.')\n return False\n\n if not modes_api.is_eligible_for_certificate(enrollment_mode):\n log.info(f'{user.id} : {course_key} has an enrollment mode of {enrollment_mode}, which is not eligible for a '\n f'certificate. Certificate cannot be generated.')\n return False\n\n if not IDVerificationService.user_is_verified(user):\n log.info(f'{user.id} does not have a verified id. Certificate cannot be generated for {course_key}.')\n return False\n\n if not _can_generate_certificate_for_status(user, course_key, enrollment_mode):\n return False\n\n course_overview = get_course_overview_or_none(course_key)\n if not course_overview:\n log.info(f'{course_key} does not a course overview. Certificate cannot be generated for {user.id}.')\n return False\n\n if not has_html_certificates_enabled(course_overview):\n log.info(f'{course_key} does not have HTML certificates enabled. Certificate cannot be generated for '\n f'{user.id}.')\n return False\n\n return True",
"def new_transcript_id_is_valid(grch37_transcript_id: str,\n proposed_grch38_transcript_id: str) -> bool:\n grch37_sequence = get_translated_protein_sequence(ENSEMBL_GRCH37_SERVER, grch37_transcript_id)\n grch38_sequence = get_translated_protein_sequence(ENSEMBL_GRCH38_SERVER, proposed_grch38_transcript_id)\n if grch37_sequence != grch38_sequence:\n print(\"Sequences of {0} and {1} do not match\".format(grch37_transcript_id, proposed_grch38_transcript_id))\n return grch37_sequence == grch38_sequence",
"def sagittalFlag(): \n slicingDim = params.WhichExperiment.Dataset.slicingInfo.slicingDim\n nucleus_index = params.WhichExperiment.Nucleus.Index[0]\n return (nucleus_index == 1) and (slicingDim == 2)",
"def supports_sequence_rule_smart_bank(self):\n return False",
"def desired_generation(self):\n return self._desired_generation",
"def _parse_sc_gids(trans_table, gid_key='sc_gid'):\n sc_gids = list(np.sort(trans_table[gid_key].unique()))\n sc_gids = [int(gid) for gid in sc_gids]\n mask = np.ones(int(1 + max(sc_gids)), dtype=bool)\n\n return sc_gids, mask",
"def verify_identity(self):\n global static_model\n if self.identity == None:\n return False\n if isinstance(self.identity, str):\n if len(self.identity) > 0:\n for pen in static_model.available_pens:\n if self.identity.upper() == pen.identity.upper():\n return True\n return False",
"def is_valid(self):\n return self.identifier is not None and self.identifier != \"\""
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Initialize the class applogger_name determines the log stream name in CW Logs. Use notification_type='SHARR' and security_standard='APP' for applevel logs For orchestrator, specify security_standard='APP' for general log, otherwise specify security_standard and controlid ex. SHARRNotification('APP', None, 'SHARR') > logs to SHARRAPP20210122 ex. SHARRNotification('APP') > logs to ORCHESTRATORAPP20210122 ex. SHARRNotification('AFSBP') > logs to ORCHESTRATORAFSBP20210122 ex. SHARRNotification('AFSBP','EC2.1') > logs to ORCHESTRATORAFSBPEC2.120210122
|
def __init__(self, security_standard, controlid=None, notification_type='ORCHESTRATOR'):
from applogger import LogHandler
self.__security_standard = security_standard
self.__notification_type = notification_type
applogger_name = self.__notification_type + '-' + self.__security_standard
if controlid:
self.__controlid = controlid
applogger_name += '-' + controlid
self.applogger = LogHandler(applogger_name)
|
[
"def initialize_logger(logger, log_name=None):\n \n # Set up general logger and formatting\n logger.setLevel(logging.DEBUG) # listen to everything\n formatter = logging.Formatter('%(asctime)s [%(name)-10s] [%(threadName)-12s] %(message)s [in %(pathname)s:%(lineno)d]')\n \n\n # If file_name provided, add file handler for logs\n if log_name:\n if not os.path.exists(LOG_DIR / f\"{log_name}\"):\n os.mkdir(LOG_DIR / f\"{log_name}\")\n \n file_handler = logging.handlers.RotatingFileHandler(LOG_DIR / f\"{log_name}/{log_name}.log\", maxBytes=1000240, backupCount=5)\n file_handler.setFormatter(formatter)\n file_handler.setLevel(logging.DEBUG)\n logger.addHandler(file_handler)\n \n # Add console handler for logs:\n console_handler = logging.StreamHandler()\n console_handler.setLevel(logging.DEBUG)\n console_handler.setFormatter(formatter)\n logger.addHandler(console_handler)",
"def _init_logger(self):\n #self._logger = logger_factory.make_logger(__name__)",
"def xcLogger( appname ):\n if (sys.platform[:3] == 'win'):\n return logging.handlers.NTEventLogHandler( appname )\n \n return logging.handlers.TimedRotatingFileHandler('/var/log/%s.log' % appname)\n\n #More difficult to configure as it defaults to localhost:514 \n #return logging.handlers.SysLogHandler() ",
"def setUpLogger(name='generalLoggerName', lvl=20, addFH=True, addSH=True):\n logging.setLoggerClass(CharisLogger)\n log = logging.getLogger(name)\n log_dict[name] = log\n log.setLevel(1)\n # add the requested handlers to the log\n if addFH:\n addFileHandler(log, lvl=1)\n # make a stream handler\n if addSH:\n addStreamHandler(log, lvl)\n return log",
"def setup_logging_app_name():\n\n if \"site-packages\" in __file__:\n set_system_variable(\"LOGGING_APP_NAME\", \"gst_packaged_pypi\")",
"def _init_log():\n global log\n\n orig_logger_cls = logging.getLoggerClass()\n logging.setLoggerClass(EyeLogger)\n try:\n log = logging.getLogger('eye')\n log._set_defaults()\n finally:\n logging.setLoggerClass(orig_logger_cls)\n\n return log",
"def _init_logger(self):\n ProctorLoggerFactory.init('proctor',\n ProctorConfig.get_config_value('Proctor', 'console_log_level'),\n ProctorConfig.get_proctor_working_dir(),\n ProctorConfig.get_config_value('Proctor', 'logfile_name'))\n self._logger = ProctorLoggerFactory.getLogger()",
"def __init__(self, account_name, account_key, queue_name=\"logqueue\"):\n self.log = Log()\n self.queue_type = config.ACS_LOGGING_QUEUE_TYPE\n self.queue_name = queue_name\n # self.log.debug(\"Queue type: \" + self.queue_type + \" / \" + self.queue_name)\n\n if self.queue_type == \"AzureStorageQueue\":\n self.createAzureQueues(account_name, account_key)\n elif self.queue_type == \"LocalFile\":\n self.file_queue = open(config.UNPROCESSED_LOG_FILE, 'w+')\n else:\n self.log.error(\"Unknown queue type: \" + queue_type)",
"def configuration_of_the_logs():\n log_formatter = logging.Formatter('%(asctime)s %(levelname)s %(funcName)s(%(lineno)d) %(message)s')\n\n #todo:#Check to see if the folder exist\n my_path = path.dirname(path.realpath(__file__))\n logFile = my_path + '/logs/logs.log'\n\n #The logs.txt file can't be more than 5MB\n my_handler = RotatingFileHandler(logFile, mode='a', maxBytes=5*1024*1024,\n backupCount=2, encoding=None, delay=0)\n my_handler.setFormatter(log_formatter)\n my_handler.setLevel(logging.INFO)\n\n app_log = logging.getLogger('root')\n #app_log.setLevel(logging.INFO)\n app_log.setLevel(logging.INFO)\n\n app_log.addHandler(my_handler)\n #app_log.info('configuraring the logs')\n\n return app_log",
"def setup_logger():\n log = logging.getLogger('contrail_vrouter_provisioning')\n log.setLevel(logging.DEBUG)\n # create rotating file handler which logs even debug messages\n fh = logging.handlers.RotatingFileHandler(LOG_FILENAME,\n maxBytes=64*1024,\n backupCount=2)\n fh.setLevel(logging.DEBUG)\n # create console handler with a higher log level\n ch = logging.StreamHandler()\n ch.setLevel(logging.INFO)\n # create formatter and add it to the handlers\n formatter = logging.Formatter(\n '[%(asctime)s %(name)s(%(lineno)s) %(levelname)s]: %(message)s',\n datefmt='%a %b %d %H:%M:%S %Y')\n fh.setFormatter(formatter)\n ch.setFormatter(formatter)\n # add the handlers to the logger\n log.addHandler(fh)\n log.addHandler(ch)\n\n return log",
"def __init__(self, logger=None):\n if logger is None:\n self.logger = logging.root\n else:\n self.logger = logger",
"def set_application_logger(self):\n logger = logging.getLogger('alertMonitor_logger')\n logger.setLevel(logging.ERROR)\n handler = logging.StreamHandler()\n handler.setLevel(logging.ERROR)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n self.logger = logger",
"def create_logger(self):\n try:\n lg.basicConfig(filename='pre_processing_logger.log', level = lg.INFO ,format='%(asctime)s - %(levelname)s - %(message)s')\n except Exception as e:\n print(e)",
"def createLogger(name):\n return logging.getLogger(name)",
"def _set_logger(self, name=None):\n if name is None:\n cls = self.__class__\n name = '%s.%s' % (cls.__module__, cls.__name__)\n self._logger = logging.getLogger(name)",
"def configure_logging(self) -> None:\n\n # type checking does not seem to recognize that config\n # and homedir were validated/coerced in __init__\n assert self.config is not None\n assert isinstance(self.homedir, Path)\n\n # Convert loglevel text to log type\n loglevel = eval(\"logging.\" + self.config.main.loglevel.upper())\n\n logfile = self.homedir / (self.name + \".log\")\n logging.basicConfig(filename=str(logfile), level=loglevel)",
"def __init__(self, *args, **kw):\n logging.Logger.__init__(self, *args, **kw)\n self.parent = logging.getLogger()",
"def enable_logger(self, log_pkg, log_level=20, logger_name=\"log\"):\r\n # pylint: disable=attribute-defined-outside-init\r\n self.logger = log_pkg.getLogger(logger_name)\r\n self.logger.setLevel(log_level)\r\n\r\n return self.logger",
"def configure_logger():\n logger = logging.getLogger(APP_NAME)\n handler = logging.StreamHandler()\n formatter = logging.Formatter(\"%(asctime)s|\"\n + \"%(name)s| %(levelname)-2s|\"\n + \"%(message)s\")\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n logger.setLevel(logging.DEBUG)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Send notifications to the application CW Logs stream and sns
|
def notify(self):
if self.send_to_sns:
publish_to_sns('SO0111-SHARR_Topic', self.severity + ':' + self.message, AWS_REGION)
self.applogger.add_message(
self.severity + ': ' + self.message
)
if self.logdata:
for line in self.logdata:
self.applogger.add_message(
line
)
self.applogger.flush()
|
[
"def send_notifications():\n CONFIG = create_app().config\n r = Redis(db=1)\n amz = boto.sns.connect_to_region(\"us-west-2\",\n aws_access_key_id=CONFIG[\"AWS_ACCESS_KEY\"],\n aws_secret_access_key=CONFIG[\"AWS_SECRET_KEY\"])\n\n keys = r.hkeys('prkng:push')\n if not keys:\n return\n\n # for each message to push...\n for pid in keys:\n message = r.hget('prkng:push', pid)\n r.hdel('prkng:push', pid)\n device_ids = r.lrange('prkng:push:'+pid, 0, -1)\n r.delete('prkng:push:'+pid)\n\n # if the message looks like a JSON, structure it accordingly\n message_structure = None\n if message.startswith(\"{\") and message.endswith(\"}\"):\n message_structure = \"json\"\n mg_title = \"message-group-{}\".format(datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\"))\n mg_arn = None\n\n if device_ids == [\"all\"]:\n # Automatically publish messages destined for \"all\" via our All Users notification topic\n amz.publish(message=message, message_structure=message_structure,\n target_arn=CONFIG[\"AWS_SNS_TOPICS\"][\"all_users\"])\n elif device_ids == [\"ios\"]:\n # Automatically publish messages destined for all iOS users\n amz.publish(message=message, message_structure=message_structure,\n target_arn=CONFIG[\"AWS_SNS_TOPICS\"][\"ios_users\"])\n elif device_ids == [\"android\"]:\n # Automatically publish messages destined for all Android users\n amz.publish(message=message, message_structure=message_structure,\n target_arn=CONFIG[\"AWS_SNS_TOPICS\"][\"android_users\"])\n elif device_ids == [\"en\"]:\n # Automatically publish messages destined for all English-language users\n amz.publish(message=message, message_structure=message_structure,\n target_arn=CONFIG[\"AWS_SNS_TOPICS\"][\"en_users\"])\n elif device_ids == [\"fr\"]:\n # Automatically publish messages destined for all French-language users\n amz.publish(message=message, message_structure=message_structure,\n target_arn=CONFIG[\"AWS_SNS_TOPICS\"][\"fr_users\"])\n\n if len(device_ids) >= 10:\n # If more than 10 real device IDs at once:\n for id in device_ids:\n if id.startswith(\"arn:aws:sns\") and \"endpoint\" in id:\n # this is a user device ID\n # Create a temporary topic for a manually specified list of users\n if not mg_arn:\n mg_arn = amz.create_topic(mg_title)\n mg_arn = mg_arn[\"CreateTopicResponse\"][\"CreateTopicResult\"][\"TopicArn\"]\n try:\n amz.subscribe(mg_arn, \"application\", id)\n except:\n continue\n elif id.startswith(\"arn:aws:sns\"):\n # this must be a topic ARN, send to it immediately\n amz.publish(message=message, message_structure=message_structure, target_arn=id)\n if mg_arn:\n # send to all user device IDs that we queued up in the prior loop\n amz.publish(message=message, message_structure=message_structure, target_arn=mg_arn)\n else:\n # Less than 10 device IDs or topic ARNs. Send to them immediately\n for id in [x for x in device_ids if x.startswith(\"arn:aws:sns\")]:\n try:\n amz.publish(message=message, message_structure=message_structure, target_arn=id)\n except BotoServerError:\n continue",
"def lambda_handler(event, context):\n webhook_url = os.getenv(\"WEBHOOK_URL\")\n users_to_notify = os.getenv(\"USER_IDS_TO_NOTIFY\")\n parsed_message = []\n for record in event.get(\"Records\", []):\n # convert SNS message component into JSON\n sns_message = json.loads(record[\"Sns\"][\"Message\"])\n\n is_alarm = sns_message.get(\"Trigger\", None)\n if is_alarm:\n parsed_message = parse_service_event(sns_message, is_alarm[\"Namespace\"])\n\n if not parsed_message:\n parsed_message = [\n {\n \"name\": \"Something happened that cannot be parsed! Please check logs.\",\n \"value\": json.dumps(sns_message),\n }\n ]\n\n # prepare discord data\n discord_data = {\n \"username\": \"AWS\",\n \"avatar_url\": \"https://a0.awsstatic.com/libra-css/images/logos/aws_logo_smile_1200x630.png\",\n \"embeds\": [\n {\"color\": 16711680, \"fields\": parsed_message} # red to highlight error\n ],\n }\n\n if users_to_notify:\n users_to_notify = users_to_notify.split(\",\")\n users_to_notify = [\n f\"<@{user_id}>\" for user_id in users_to_notify if user_id\n ]\n discord_data[\"content\"] = \"\".join(users_to_notify)\n\n headers = {\"content-type\": \"application/json\"}\n\n # make the webhook call\n http.request(\n \"POST\", webhook_url, body=json.dumps(discord_data), headers=headers\n )",
"def send_notifications(handler, persons, notes):\n for note in notes:\n person = persons[note.person_record_id]\n subscribe.send_notifications(handler, person, [note])",
"def _log_send_notification(*, notification_type: str, options: Dict, recipients: List, sender: str) -> None:\n pass # pragma: no cover",
"def send_notifications():\n # Send any email related tasks\n for note in EmailNotification.objects.select_related('event', 'account').filter(sent=False):\n note.send()",
"def index(integration):\n request = app.current_request\n validate_signature(request)\n\n try:\n event = request.headers[\"X-GitHub-Event\"]\n except KeyError:\n raise BadRequestError()\n\n sns_topics = SNS.list_topics()[\"Topics\"]\n topic_arns = {t[\"TopicArn\"].rsplit(\":\")[-1]: t[\"TopicArn\"] for t in sns_topics}\n topic = f\"{integration}_{event}\"\n if topic not in topic_arns.keys():\n topic_arns[topic] = SNS.create_topic(Name=topic)[\"TopicArn\"]\n\n SNS.publish(\n TargetArn=topic_arns[topic],\n Subject=event,\n Message=json.dumps({\"default\": json.dumps(request.json_body)}),\n MessageStructure=\"json\",\n )\n\n return {\"Code\": \"Ok\", \"Message\": \"Webhook received.\"}",
"def alert():\n data = request.get_json(force=True)\n\n try:\n validatesns.validate(data)\n except validatesns.ValidationError as err:\n logging.error(err)\n abort(403)\n\n client = nexmo.Client(key=app.config['NEXMO_KEY'], secret=app.config['NEXMO_SECRET'])\n if data['Type'] == 'Notification':\n client.send_message({\n 'from': app.config['NEXMO_FROM'],\n 'to': app.config['NEXMO_TO'],\n 'text': '\\n'.join([data['Subject'], data['Message']]),\n })\n\n if data['Type'] == 'SubscriptionConfirmation':\n urllib.request.urlopen(data['SubscribeURL']).read()\n client.send_message({\n 'from': app.config['NEXMO_FROM'],\n 'to': app.config['NEXMO_TO'],\n 'text': 'Subscribed to ' + data['TopicArn'],\n })\n\n return success_response()",
"def notificationsSend(self, toIds, notification, type, callback):\n j = Json().put(u\"to_ids\", toIds)\n j.put(u\"notification\", notification)\n j.put(u\"type\", java.str(type))\n self.callMethod(u\"notifications.send\", j.getJavaScriptObject(), callback)",
"def send_notification_request(self, data):\n url = \"http://{}:{}/api/{}/notifications/send\".format(\n self.__server_address, self.__server_port, self.API_VERSION)\n headers = {\"content-type\": \"application/json\"}\n\n response = requests.post(url, data=json.dumps(data), headers=headers)\n self.parse_response(response)",
"def send_push_notification(self, application, status):\n context = self.get_email_context(application, status)\n subject = render_to_string(self.notification_subject_template, context)\n # Force subject to a single line to avoid header-injection issues.\n subject = ''.join(subject.splitlines())\n message = render_to_string(self.notification_body_template, context)\n\n push = Pusher(\n app_id=settings.PUSHER_APP_ID,\n key=settings.PUSHER_KEY,\n secret=settings.PUSHER_SECRET,\n host=settings.PUSHER_HOST,\n )\n\n push.trigger(\n 'team-builder-'+str(application.applicant.id),\n 'new_notification',\n {'title': subject, 'message': message}\n )",
"def sendNewAppEmail(request, *args, **kwargs):\n app = kwargs.get('app')\n watchSellers = dashboardModels.WatchSeller.objects.filter(seller_id=app.publisher.id)\n if app and watchSellers:\n massEmailThread = email.MassEmailThread()\n templates = models.NotificationTemplate.objects.filter(name='new_app_inform_buyer')\n for watchSeller in watchSellers:\n if templates:\n subject = templates[0].subject.replace('{param1}', watchSeller.seller.username)\n message = templates[0].template.replace('{param1}', watchSeller.buyer.username).replace('{param2}', watchSeller.seller.username).replace('{param3}', app.app_name)\n massEmailThread.addEmailData(subject=subject, message=message, recipient_list=[watchSeller.buyer.email])\n massEmailThread.start()",
"def websocket(cloud_api, new_temp_test_case_developer_api_key, request):\n log.info('Register and open WebSocket notification channel')\n try:\n configuration = request.param\n except AttributeError:\n configuration = None\n\n ws = WebsSocketNotificationChannel(cloud_api, new_temp_test_case_developer_api_key, configuration)\n yield ws.handler\n ws.close()",
"def send_to_syslog(events, syslog):\r\n for cnt, event in enumerate(events, start=1):\r\n syslog.send(json.dumps(event))\r\n logging.debug('Event %s sent to syslog: %s.', cnt, json.dumps(event))\r\n logging.debug('Total Events: %s ', cnt)",
"def send_to_pubsub_topic(self, stocks):\n pass",
"def send_push_notification(self, *args, **kwargs) -> None:\n if platform.system() == 'Linux':\n raise NotImplementedError\n elif platform.system() == 'Darwin':\n self._send_notification_mac_os(*args, **kwargs)\n elif platform.system() == 'Windows':\n raise NotImplementedError\n else:\n raise NotImplementedError",
"def patchingNotification(self, hostname, arn, subject):\n today = date.today()\n cur_week = self.week_of_month(today)\n cur_day = date.weekday(today)\n \n email_patch = \"\"\"%s has failed over. Server %s is currently the active host.\n \nThis was likely due to patching. DevOps will follow up during regular business hours to verify.\n \nPlease reach out tyour Support Team if you notice any errors or issues in the meantime.\n \nThis is an automated message.\"\"\"\n\n email_no_patch = \"\"\"%s has failed over. Server %s is currently the active host.\n \nThere was no known patching causing this event. DevOps will investigate during regular business hours to verify.\n \nPlease reach out tyour Support Team if you notice any errors or issues in the meantime.\n \nThis is an automated message.\"\"\"\n \n if hostname == self.primary:\n if cur_week == self.primary_week and cur_day == self.primary_day:\n email = email_patch % (self.secondary, self.primary)\n client = boto3.client('sns')\n response = client.publish(\n TopicArn=arn,\n Subject=subject,\n Message=email\n )\n else:\n email = email_no_patch % (self.secondary, self.primary)\n client = boto3.client('sns')\n response = client.publish(\n TopicArn=arn,\n Subject=subject,\n Message=email\n )\n elif hostname == self.secondary:\n if cur_week == self.secondary_week and cur_day == self.secondary_day:\n email = email_patch % (self.primary, self.secondary)\n client = boto3.client('sns')\n response = client.publish(\n TopicArn=arn,\n Subject=subject,\n Message=email\n )\n else:\n email = email_no_patch % (self.primary, self.secondary)\n client = boto3.client('sns')\n response = client.publish(\n TopicArn=arn,\n Subject=subject,\n Message=email\n )\n else:\n print(\"Invalid hostname.\")",
"def configure_user_notifications():\n print('Retrieving notification url...')\n url = NotificationService.get_new_subscription_url()\n USER_CONFIGURATION.set_notification_subscription(url)\n print(f'Please open this url to subscribe to notifications {url}')",
"def sendSyslog(switchlist, text):\n\n cvplogger = logging.getLogger('CvpLogger')\n cvplogger.setLevel(logging.WARNING)\n termlogger = logging.StreamHandler(sys.stdout)\n logwriter = logging.handlers.SysLogHandler(address= SYSLOGSERVER) #, 514))\n cvplogger.addHandler(logwriter)\n cvplogger.addHandler(termlogger)\n for switch in switchlist:\n cvplogger.critical('%s %s' % (text, switch))\n logwriter.close()\n cvplogger.removeHandler(logwriter)\n termlogger.close()\n cvplogger.removeHandler(termlogger)",
"def send_notification(msg):\n target_arn = get_sns_arn()\n if not target_arn:\n return False\n response = sns.publish(TargetArn=target_arn,\n Message=json.dumps({'default': json.dumps(msg)}),\n MessageStructure='json')\n LOGGER.info('-- Notification sent to the SNS topic: ' + target_arn)\n return True"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Add chunks of data from a stream to a queue until the stream is empty.
|
def _enqueue_output(stream, queue):
for line in iter(lambda: stream.read(4096), b''):
queue.put(line)
stream.close()
|
[
"async def next_chunk():\n async for chunk_bytes in stream:\n return chunk_bytes",
"def fill_queue(sock_udp, q_data, count_packets, bytes_per_packet):\n for _ in range(count_packets):\n buf, _ = sock_udp.recvfrom(bytes_per_packet)\n q_data.put(buf)\n cleanup_ifcs()",
"def read_stream(self, stream):\n self.reset()\n for token in stream:\n self._buf.append(token)",
"async def reader_worker(self):\n try:\n while True:\n data = await self.reader.readline()\n print('SOCKET <', data)\n for queue in self.outbound_queues:\n await queue.put(data.decode())\n finally:\n self.reader = None",
"def read_non_blocking(stream):\n if stream:\n while True:\n nxt = b''\n empty = 0\n while not nxt.decode('utf-8').endswith(\"\\n\"):\n try:\n read = stream.readline()\n if len(read) == 0:\n if empty < 3:\n time.sleep(0.01)\n else:\n break\n empty += 1\n nxt += read\n except IOError as error:\n if error.errno in (11, 35):\n # Resource temporarily unavailable\n if empty < 3:\n time.sleep(0.01)\n else:\n break\n empty += 1\n else:\n raise\n\n if nxt:\n yield nxt\n else:\n break",
"def generate_from_queue(self):\n while True:\n yield self.input_queue.get()",
"def collect(stream, min_time, max_time):\n arr = []\n start = time.time()\n min_end, max_end = start + min_time, start + max_time\n while time.time() < min_end:\n if (item := next(stream)) is not None:\n arr.append(item)\n if len(arr) > 0:\n return arr\n\n while time.time() < max_end:\n if (item := next(stream)) is not None:\n return [item]",
"async def queue_consumer(q):\n while True:\n try:\n e = await q.get()\n yield e\n except:\n continue",
"def yield_forever(self, stream: IO) -> Iterator[str]:\n while True:\n if name := stream.readline().strip():\n yield name\n else:\n log.debug(f'Waiting on data ({self.source_path})')\n time.sleep(FILE_SLEEP_PERIOD)",
"def collect_data(self):\n while(self.is_streaming):\n self.skipped_bytes = 0\n self.read_serial_binary()",
"def put(self, src):\n while True:\n # print(f\"{self.rank=} start putting 1 {self.buf.idx=} {self.buf.max=} {self.buf.len=}\", flush=True)\n self.buf.lock()\n # print(f\"{self.rank=} start putting 2\", flush=True)\n self.buf.sync()\n # print(f\"{self.rank=} start putting 3\", flush=True)\n\n # Check if there is space in the buffer for new elements. If the\n # buffer is full, spin and watch for space\n # print(f\"putting {self.buf.idx=} {self.buf.max=} {self.buf.len=}\")\n if self.buf.max - self.buf.idx >= self.buf.n_buf:\n self.buf.unlock()\n # print(f\"PUT {self.buf.max=} {self.buf.idx=} {self.buf.n_buf=}\", flush=True)\n self.schedule()\n continue\n\n self.buf.put(src)\n self.buf.unlock()\n return",
"def make_new_batch(in_queue, out_queue, batch_size):\n batches, num_samples = [], 0\n while True:\n batch_samples = in_queue.get()\n in_queue.task_done()\n if not isinstance(batch_samples, EndSignal):\n cur_num_samples = list(batch_samples.values())[0].shape[0]\n if num_samples + cur_num_samples < batch_size:\n batches.append(batch_samples)\n num_samples += cur_num_samples\n elif num_samples + cur_num_samples == batch_size:\n batches.append(batch_samples)\n out_queue.put(concat_batches(batches))\n batches, num_samples = [], 0\n else:\n num_splited = batch_size - num_samples\n first, second = split_batch(batch_samples, num_splited)\n batches.append(first)\n out_queue.put(concat_batches(batches))\n num_left = cur_num_samples - num_splited\n while num_left > batch_size:\n first, second = split_batch(second, batch_size)\n out_queue.put(first)\n num_left -= batch_size\n\n if num_left == batch_size:\n out_queue.put(second)\n batches, num_samples = [], 0\n else:\n batches, num_samples = [second], num_left\n else:\n if len(batches) > 0:\n out_queue.put(concat_batches(batches))\n out_queue.put(EndSignal())\n break",
"def run_stream(self, stream, handler):\n for item in stream:\n if item is None:\n break\n handler(item)",
"def read_in_chunks(buffer, chunk_size=1024 * 1024.0 * 4):\n\n while True:\n data = buffer.read1(chunk_size)\n if not data:\n break\n yield data",
"def fill_bucket_into_queue(self):\n while True:\n inputs = []\n queue_size = self.input_queue.qsize()\n for _ in range(queue_size):\n model_input = self.input_queue.get()\n inputs.append(model_input)\n\n # whether use bucket\n if self.model_config.bucketing:\n inputs = sorted(inputs, key=lambda inp: inp.enc_len)\n\n # split total batch by batch size\n batches = []\n for i in range(len(inputs), self.model_config.batch_size):\n batches.append(inputs[i:i+self.model_config.batch_size])\n\n # put batch into bucket queue\n shuffle(batches)\n for b in batches:\n self.bucket_input_queue.put(b)\n\n if len(batches) != 0:\n self.bucket_input_success_flag = True",
"def _add_unbuffered(self, qs, elem):\n qs.unbuffered_elements.append(elem)\n if len(qs.unbuffered_elements) == qs.buffer_size:\n qs.unbuffered_elements.sort(key=self._key, reverse=self._reverse)\n heapq.heappush(\n qs.buffers, _QuantileBuffer(elements=qs.unbuffered_elements))\n qs.unbuffered_elements = []\n self._collapse_if_needed(qs)",
"def read_in_chunks(f, size):\n while True:\n data = f.read(size)\n if not data:\n break\n yield data",
"def _iterqueue(queue):\n while 1:\n item = queue.get()\n\n if item is StopIteration:\n queue.put(StopIteration)\n break\n\n yield item",
"def chunk_queue(dir_in=\"../audio/chunk_queue\",\n dir_out=\"../audio/wav_chunked\",\n chunk_len=5,\n sr=22050,\n log=True\n ):\n \n for root, dirs, files in os.walk(dir_in):\n for fname in files:\n if not re.match(r'^\\.', fname):\n rel_fpath = os.path.join(root, fname)\n chunk_song(rel_fpath, chunk_len=chunk_len, sr=sr, log=log)",
"async def read_stream(loop, file, sinks, cleanup=None, timeout=None):\n stream_reader = asyncio.StreamReader(loop=loop)\n transport, _ = await loop.connect_read_pipe(\n lambda: asyncio.StreamReaderProtocol(stream_reader), file)\n while True:\n try:\n product = await asyncio.wait_for(read_product(stream_reader), timeout)\n for sink in sinks:\n await sink.put(product)\n except (EOFError, asyncio.TimeoutError):\n break\n # If we get an EOF, flush out the queues top down, then save remaining\n # chunks to disk for reloading later.\n logger.info('Closing out processing.')\n for sink in sinks:\n logger.debug('Flushing product sinks.')\n await sink.join()\n if cleanup:\n await cleanup()\n await asyncio.sleep(0.01) # Just enough to let other things close out\n transport.close()"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.