content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
#!/usr/bin/env python # Filename: raster_statistic """ introduction: conduct statistic based on vectos, similar to https://github.com/perrygeo/python-rasterstats, # but allow image tiles (multi-raster). authors: Huang Lingcao email:huanglingcao@gmail.com add time: 02 March, 2021 """ import os,sys import vector_gpd from shapely.geometry import mapping # transform to GeJSON format import raster_io import basic_src.io_function as io_function import basic_src.map_projection as map_projection import basic_src.basic as basic import numpy as np from multiprocessing import Pool def zonal_stats_multiRasters(in_shp, raster_file_or_files, nodata=None, band = 1, stats = None, prefix='', range=None,all_touched=True, process_num=1): ''' zonal statistic based on vectors, along multiple rasters (image tiles) Args: in_shp: input vector file raster_file_or_files: a raster file or multiple rasters nodata: band: band stats: like [mean, std, max, min] range: interested values [min, max], None means infinity all_touched: process_num: process number for calculation Returns: ''' io_function.is_file_exist(in_shp) if stats is None: basic.outputlogMessage('warning, No input stats, set to ["mean"])') stats = ['mean'] if isinstance(raster_file_or_files,str): io_function.is_file_exist(raster_file_or_files) image_tiles = [raster_file_or_files] elif isinstance(raster_file_or_files,list): image_tiles = raster_file_or_files else: raise ValueError('unsupport type for %s'%str(raster_file_or_files)) # check projection (assume we have the same projection), check them outside this function # get image box img_tile_boxes = [raster_io.get_image_bound_box(tile) for tile in image_tiles] img_tile_polygons = [vector_gpd.convert_image_bound_to_shapely_polygon(box) for box in img_tile_boxes] polygons = vector_gpd.read_polygons_gpd(in_shp) if len(polygons) < 1: basic.outputlogMessage('No polygons in %s'%in_shp) return False # polygons_json = [mapping(item) for item in polygons] # no need when use new verion of rasterio # process polygons one by one polygons and the corresponding image tiles (parallel and save memory) # also to avoid error: daemonic processes are not allowed to have children if process_num == 1: stats_res_list = [] for idx, polygon in enumerate(polygons): out_stats = zonal_stats_one_polygon(idx, polygon, image_tiles, img_tile_polygons, stats, nodata=nodata, range=range, band=band, all_touched=all_touched) stats_res_list.append(out_stats) elif process_num > 1: threadpool = Pool(process_num) para_list = [ (idx, polygon, image_tiles, img_tile_polygons, stats, nodata, range,band, all_touched) for idx, polygon in enumerate(polygons)] stats_res_list = threadpool.starmap(zonal_stats_one_polygon,para_list) else: raise ValueError('Wrong process number: %s '%str(process_num)) # save to shapefile add_attributes = {} new_key_list = [ prefix + '_' + key for key in stats_res_list[0].keys()] for new_ley in new_key_list: add_attributes[new_ley] = [] for stats_result in stats_res_list: for key in stats_result.keys(): add_attributes[prefix + '_' + key].append(stats_result[key]) vector_gpd.add_attributes_to_shp(in_shp,add_attributes) pass if __name__=='__main__': basic.setlogfile('raster_statistic.log') main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 7066, 12453, 25, 374, 1603, 62, 14269, 2569, 220, 198, 37811, 198, 27427, 596, 25, 3189, 24696, 1912, 319, 1569, 310, 418, 11, 2092, 284, 3740, 1378, 12567, 13, 785, 14, 525, 563,...
2.436675
1,516
# Defutils.py -- Contains parsing functions for definition files. # Produces an organized list of tokens in the file.
[ 2, 2896, 26791, 13, 9078, 1377, 49850, 32096, 5499, 329, 6770, 3696, 13, 198, 198, 2, 21522, 728, 281, 8389, 1351, 286, 16326, 287, 262, 2393, 13, 628 ]
4.285714
28
#!/usr/bin/env python3 import json import sys import clize if __name__ == '__main__': clize.run(main)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 201, 198, 201, 198, 11748, 33918, 201, 198, 11748, 25064, 201, 198, 201, 198, 11748, 537, 1096, 201, 198, 201, 198, 201, 198, 201, 198, 201, 198, 361, 11593, 3672, 834, 6624, 705, 834...
2.066667
60
""" TutorialMirror A simple mirror object to experiment with. """ from evennia import DefaultObject from evennia.utils import make_iter, is_iter from evennia import logger
[ 37811, 198, 51, 44917, 27453, 1472, 198, 198, 32, 2829, 10162, 2134, 284, 6306, 351, 13, 198, 198, 37811, 198, 198, 6738, 772, 18142, 1330, 15161, 10267, 198, 6738, 772, 18142, 13, 26791, 1330, 787, 62, 2676, 11, 318, 62, 2676, 198, ...
3.666667
48
from tkinter import Tk from turtle import ScrolledCanvas, TurtleScreen, RawTurtle DIGIT2POS = dict(zip( "123456789", ((100 * (j - 1), 100 * (-i + 1)) for i in range(3) for j in range(3)) )) if __name__ == "__main__": main("61834927")
[ 6738, 256, 74, 3849, 1330, 309, 74, 198, 6738, 28699, 1330, 1446, 8375, 6090, 11017, 11, 33137, 23901, 11, 16089, 51, 17964, 198, 198, 35, 3528, 2043, 17, 37997, 796, 8633, 7, 13344, 7, 198, 220, 220, 220, 366, 10163, 2231, 3134, 45...
2.431373
102
#!/usr/bin/env python # test code for PyPortMidi # a port of a subset of test.c provided with PortMidi # John Harrison # harrison [at] media [dot] mit [dot] edu # March 15, 2005: accommodate for SysEx messages and preferred list formats # SysEx test code contributed by Markus Pfaff # February 27, 2005: initial release import pypm import array import time NUM_MSGS = 100 # number of MIDI messages for input before closing INPUT=0 OUTPUT=1 # main code begins here pypm.Initialize() # always call this first, or OS may crash when you try to open a stream x=0 while (x<1) | (x>2): print """ enter your choice... 1: test input 2: test output """ x=int(raw_input()) if x==1: TestInput() else: TestOutput() pypm.Terminate()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 1332, 2438, 329, 9485, 13924, 44, 19830, 198, 2, 257, 2493, 286, 257, 24637, 286, 1332, 13, 66, 2810, 351, 4347, 44, 19830, 198, 2, 1757, 17281, 198, 2, 289, 22472, 685, 265, 60...
2.854478
268
#coding=utf-8 import pandas as pd if __name__ == "__main__": correct_rate,error_index = get_labels("../processed_data/dev_processed_data_split.csv","./result/result_predict.txt") print("correct_rate : "+str(correct_rate)) print("error_email : "+str(error_index))
[ 2, 66, 7656, 28, 40477, 12, 23, 198, 11748, 19798, 292, 355, 279, 67, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 628, 220, 220, 220, 3376, 62, 4873, 11, 18224, 62, 9630, 796, 651, 62, 23912, 1424, 7203, 407...
2.641509
106
from ex01.funcoes import *
[ 6738, 409, 486, 13, 12543, 1073, 274, 1330, 1635, 628, 628, 628 ]
2.666667
12
# -*- coding: utf-8 -*- """ :author @Icrons cron: 20 10 * * * new Env(''); """ import json import re import traceback import requests import urllib3 from notify_mtr import send from utils import get_data urllib3.disable_warnings() if __name__ == "__main__": data = get_data() _check_items = data.get("AIRPORT", []) res = SspanelQd(check_items=_check_items).main() send("", res)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 25, 9800, 2488, 40, 6098, 684, 198, 66, 1313, 25, 1160, 838, 1635, 1635, 1635, 198, 3605, 2039, 85, 7, 7061, 1776, 198, 37811, 198, 198, 11748, 33918, 198,...
2.445122
164
# ----------------------------------------------------------------------- # Author: Marcelo Villa-Pieros # # Purpose: Determines the fire season for each window. The fire season is # defined as the minimum number of consecutive months that contain more # than 80% of the burned area (Archibald ett al 2013; Abatzoglou et al. # 2018). # # References: # * Archibald, S., Lehmann, C. E. R., Gmez-Dans, J. L., & Bradstock, # R. A. (2013). Defining pyromes and global syndromes of fire regimes. # Proceedings of the National Academy of Sciences of the United States # of America, 110(16), 64426447. # # * Abatzoglou, J. T., Williams, A. P., Boschetti, L., Zubkova, M., & # Kolden, C. A. (2018). Global patterns of interannual climatefire # relationships. Global Change Biology, 24(11), 51645175. # ----------------------------------------------------------------------- import os from calendar import month_abbr import pandas as pd from src.utils.constants import REGIONS, BURNED_AREA_THRESHOLD if __name__ == "__main__": # Project's root os.chdir("../..") output_folder = "results/csv" if not os.path.exists(output_folder): os.makedirs(output_folder) df = pd.DataFrame(columns=["window", "months"]) for region in REGIONS: month_groups = pd.read_excel( f"results/xlsx/{region['name']}/fire_groups.xlsx", sheet_name="Month" ) # Compute 80% threshold. threshold = month_groups["area"].sum() * BURNED_AREA_THRESHOLD # Sort months from larger to smallest burned area and compute the # cumulative sum. sorted_groups = month_groups.sort_values(by="area", ascending=False) sorted_groups = sorted_groups.reset_index(drop=True) sorted_groups["cumulative_area"] = sorted_groups["area"].cumsum() # Get the months with the largest burned area that compose more # than 80% of the total burned area and change from month int to # month abbreviation. above_threshold = sorted_groups["cumulative_area"] >= threshold fire_season_months = sorted_groups["month"].loc[:above_threshold.idxmax()] fire_season_months = fire_season_months.sort_values() fire_season_months = fire_season_months.apply(lambda x: month_abbr[x]) months = fire_season_months.str.cat(sep="-") df = df.append({"window": region["name"], "months": months}, ignore_index=True) save_to = os.path.join(output_folder, "fire_season_months.csv") df.to_csv(save_to, index=False)
[ 2, 16529, 26866, 198, 2, 6434, 25, 36547, 78, 25018, 12, 47, 959, 418, 198, 2, 198, 2, 32039, 25, 360, 13221, 274, 262, 2046, 1622, 329, 1123, 4324, 13, 383, 2046, 1622, 318, 198, 2, 5447, 355, 262, 5288, 1271, 286, 12785, 1933, ...
2.796031
907
import bpy import json from bpy.types import SpaceView3D from bpy.app.handlers import persistent from mathutils import Quaternion, Matrix, Vector from holo.gestures import prediction_from_camera def duplicate_window(window_type: str = 'INVOKE_DEFAULT') -> None: """Duplicates a new window into bpy.data.screens from current active window.""" context_window = bpy.context.copy() context_window['area'] = [area for area in bpy.context.screen.areas if area.type == 'VIEW_3D'][0] bpy.ops.screen.area_dupli(context_window, window_type) def convert_quadview(area: SpaceView3D) -> None: """Converts a given window into quad-view.""" region = [region for region in RENDER_AREA.regions if region.type == 'WINDOW'][0] override = {'area': RENDER_AREA, 'region': region, 'edit_object': bpy.context.edit_object} bpy.ops.screen.region_quadview(override) def configure_scene(screen_data: SpaceView3D) -> None: """Removes all overlay elements from the 3D viewport.""" screen_data.shading.background_type = 'VIEWPORT' screen_data.shading.background_color = (0, 0, 0) screen_data.overlay.show_overlays = False for attribute in 'show_gizmo', 'show_region_toolbar', 'show_region_tool_header': setattr(screen_data, attribute, False) def initial_config(values: list) -> None: """Sets the camera position and rotation values during initialization of new frame.""" for index, window in enumerate(values): for key, attribute in window.items(): if key not in {'perspective_matrix', 'window_matrix'}: # BUG These values are read only and need a setter setattr(QUAD_VIEWS[index], key, attribute) def transform_rotate(direction: 'str', confidence: int) -> None: """Given a direction and confidence value (Out of 100%), rotate the object by its corresponding vector.""" magnitude = confidence / 100 if direction not in {'retract', 'expand'}: bpy.ops.transform.rotate( value=magnitude, orient_axis='Z', orient_type='VIEW', orient_matrix=((0.85153, 0.277963, -0.44456), (0.15535, 0.676067, 0.720278), (0.500763, -0.6824, 0.53251)), orient_matrix_type='VIEW', mirror=True, use_proportional_edit=False, proportional_edit_falloff='SMOOTH', proportional_size=1, use_proportional_connected=False, use_proportional_projected=False) else: for window in QUAD_VIEWS: window.view_distance += magnitude if direction == 'expand' else magnitude * -1 def get_gestures() -> None: """Retrieves gestures from camera and applies the corresponding tranformation to the object.""" rotation_mapping = { 'Fist' : 'X', 'L' : 'Y', 'Okay' : 'Z', } for gesture in prediction_from_camera(): transform_rotate(direction=rotation_mapping(gesture.gesture), magnitude=gesture.confidence) def initial_config_values() -> list: """Returns initial config values as a convenience utility.""" return [ { "view_distance": 4.183098793029785, "view_location": Vector((-0.8385156989097595, 0.05902576446533203, 0.48941677808761597)), "view_perspective": "PERSP", "view_rotation": Quaternion((0.6414357423782349, -0.6326250433921814, 0.3170725703239441, 0.2963286340236664)) }, { "view_distance": 4.183099269866943, "view_location": Vector((-0.4491613209247589, 1.5609432458877563, 0.014791678637266159)), "view_perspective": "PERSP", "view_rotation": Quaternion((0.4915403723716736, 0.6154682636260986, -0.25714513659477234, -0.559877872467041)), }, { "view_distance": 5.019718647003174, "view_location": Vector((-0.9179283380508423, -0.46830159425735474, 0.334771990776062)), "view_perspective": "PERSP", "view_rotation": Quaternion((-0.22622741758823395, 0.6814441084861755, -0.1789524108171463, 0.6726300716400146)) }, { "view_distance": 5.019718647003174, "view_location": Vector((0.797123372554779, 0.7804675102233887, 0.635741114616394)), "view_perspective": "PERSP", "view_rotation": Quaternion((0.687656581401825, 0.6367506384849548, -0.2974682152271271, 0.1821804791688919)) } ] if __name__ == '__main__': duplicate_window() RENDER_AREA = bpy.data.window_managers[0].windows[-1].screen.areas[0] MAIN_VIEW = [area for area in bpy.data.window_managers[0].windows[0].screen.areas if area.type == 'VIEW_3D'][0].spaces[0].region_3d QUAD_VIEWS = RENDER_AREA.spaces[0].region_quadviews convert_quadview(area=RENDER_AREA) configure_scene(screen_data=RENDER_AREA.spaces[0]) initial_config(initial_config_values()) get_gestures() # bpy.data.window_managers[0].windows[1].screen.areas[0].spaces[0].region_3d.view_rotation.rotate(Euler((1, 10, .1))) for window in bpy.data.window_managers[0].windows: # let's find what's what for area in window.screen.areas: if area.type == 'VIEW_3D': if len(area.spaces[0].region_quadviews) > 0: #if quadviews are active quad_views = area.spaces[0].region_quadviews else: main_view = area.spaces[0].region_3d bpy.app.handlers.frame_change_post.append(update_handler)
[ 11748, 275, 9078, 198, 11748, 33918, 198, 6738, 275, 9078, 13, 19199, 1330, 4687, 7680, 18, 35, 198, 6738, 275, 9078, 13, 1324, 13, 4993, 8116, 1330, 16218, 198, 6738, 10688, 26791, 1330, 2264, 9205, 295, 11, 24936, 11, 20650, 198, 67...
2.287145
2,396
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from tensorflow_probability import distributions as tfd import tensorflow.compat.v1 as tf tf.disable_v2_behavior() from ncp import tools
[ 2, 15069, 2864, 3012, 11419, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921, 743, 7330...
3.690722
194
""" DB operations for Targets """ from api.models.base import DBModel
[ 37811, 198, 11012, 4560, 329, 31089, 1039, 198, 37811, 198, 198, 6738, 40391, 13, 27530, 13, 8692, 1330, 20137, 17633, 628 ]
3.428571
21
# myTeam.py # --------- # Licensing Infoesmation: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to http://ai.berkeley.edu. # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel (pabbeel@cs.berkeley.edu). # TO DISCUSS: # Walkthru # Replay Func # Agent state vs position # Normalizing state values # Actions vs. Legal Actions # Reward Func import random import time import math import json import os from util import nearestPoint from collections import deque import numpy as np from keras.models import Sequential from keras.layers import Dense from keras.optimizers import Adam from game import Directions from captureAgents import CaptureAgent ################# # Team creation # ################# def createTeam(firstIndex, secondIndex, isRed, first='OffDQNAgent', second='DefDQNAgent'): """ This function should return a list of two agents that will form the team, initialized using firstIndex and secondIndex as their agent index numbers. isRed is True if the red team is being created, and will be False if the blue team is being created. As a potentially helpful development aid, this function can take additional string-valued keyword arguments ("first" and "second" are such arguments in the case of this function), which will come from the --redOpts and --blueOpts command-line arguments to capture.py. For the nightly contest, however, your team will be created without any extra arguments, so you should make sure that the default behavior is what you want for the nightly contest. """ # The following line is an example only; feel free to change it. return [eval(first)(firstIndex), eval(second)(secondIndex)] ########## # Agents # ##########
[ 2, 616, 15592, 13, 9078, 198, 2, 45337, 198, 2, 10483, 26426, 4806, 3028, 76, 341, 25, 220, 921, 389, 1479, 284, 779, 393, 9117, 777, 4493, 329, 198, 2, 9856, 4959, 2810, 326, 357, 16, 8, 345, 466, 407, 14983, 393, 7715, 198, 2,...
3.55935
615
from setuptools import setup, find_packages setup( name='SBIExperiments', version='0.0.1', url='https://github.com/astrodeepnet/sbi_experiments', author='Justine Zeghal and friends', description='Package for numerical experiments of SBI tools', packages=find_packages(), install_requires=[ 'numpy>=1.19.2', 'jax>=0.2.0', 'tensorflow_probability>=0.14.1', 'scikit-learn>=0.21', 'jaxopt>=0.2' ], )
[ 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 198, 40406, 7, 198, 220, 1438, 11639, 50, 3483, 20468, 6800, 3256, 198, 220, 2196, 11639, 15, 13, 15, 13, 16, 3256, 198, 220, 19016, 11639, 5450, 1378, 12567, 13, 785, 1...
2.432584
178
import datetime import libcloud from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver from pprint import pprint Engine = get_driver(Provider.ELASTICHOSTS) driver = Engine("733b7dc7-7498-4db4-9dc4-74d3fee8abed", secret="6w6CDAqL6JyXFj3xNkWW2zpUjYfv9dYaLVdaaR4Y", secure=False) images = driver.list_images() sizes = driver.list_sizes() IMAGE_ID = '38df09864d854b76b5023878ffc80161' image = [i for i in images if i.id == IMAGE_ID][0] pprint(images) pprint(sizes) node = driver.deploy_node( name="astricon-{}".format(datetime.datetime.now().strftime('%Y-%m-%dt%H%M%S')), image=image, size=sizes[3], script='deploy-script.sh', enable_root=True, vnc_password="myStr0ngr00tpa55wo7d") print("Waiting for Node") driver.wait_until_running([node], 10, 1000) print("Node is now running")
[ 11748, 4818, 8079, 198, 198, 11748, 9195, 17721, 198, 6738, 9195, 17721, 13, 5589, 1133, 13, 19199, 1330, 32549, 198, 6738, 9195, 17721, 13, 5589, 1133, 13, 15234, 4157, 1330, 651, 62, 26230, 198, 6738, 279, 4798, 1330, 279, 4798, 198, ...
2.233503
394
from django.contrib import admin from .models import TodoModel admin.site.register(TodoModel)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 764, 27530, 1330, 309, 24313, 17633, 198, 198, 28482, 13, 15654, 13, 30238, 7, 51, 24313, 17633, 8, 198 ]
3.275862
29
#!/usr/bin/env python3 """ Author : antoniog1 Date : 2019-02-21 Purpose: Rock the Casbah """ import argparse import sys import os # -------------------------------------------------- def get_args(): """get command-line arguments""" parser = argparse.ArgumentParser( description='Argparse Python script', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('positional', metavar='DIR', type = str, help='A positional argument', nargs="+") parser.add_argument('-w', '--width', help='A named integer argument', metavar='int', type=int, default=50) return parser.parse_args() # -------------------------------------------------- def warn(msg): """Print a message to STDERR""" print(msg, file=sys.stderr) # -------------------------------------------------- def die(msg='Something bad happened'): """warn() and exit with error""" warn(msg) sys.exit(1) # -------------------------------------------------- def main(): """Make a jazz noise here""" args = get_args() width = args.width directory = args.positional for dir_name in directory: dir_dict = {} if not os.path.isdir(dir_name): warn('"{}" is not a directory'.format(dir_name)) continue print(dir_name) for filename in os.listdir(dir_name): path = os.path.join(dir_name,filename) with open(path) as f: first_line = f.readline().rstrip() dir_dict[first_line] = filename for line, file in sorted(dir_dict.items()): num_per = width - len(line) - len(file) ellipses = "." * num_per print('{} {} {}'.format(line,ellipses,file)) # -------------------------------------------------- if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 37811, 198, 13838, 1058, 281, 1122, 72, 519, 16, 198, 10430, 220, 220, 1058, 13130, 12, 2999, 12, 2481, 198, 30026, 3455, 25, 4631, 262, 11294, 47041, 198, 37811, 198, 198, 11748, ...
2.620934
707
#!/usr/bin/env python # encoding: utf-8 # # @Author: Jos Snchez-Gallego # @Date: Oct 10, 2017 # @Filename: target.py # @License: BSD 3-Clause # @Copyright: Jos Snchez-Gallego from __future__ import division from __future__ import print_function from __future__ import absolute_import import os import pathlib import yaml from . import regions from .. import config
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 21004, 25, 3384, 69, 12, 23, 198, 2, 198, 2, 2488, 13838, 25, 22568, 5489, 2395, 89, 12, 26552, 1455, 78, 198, 2, 2488, 10430, 25, 2556, 838, 11, 2177, 198, 2, 2488, 35063, 25...
3.032787
122
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import uuid import google.auth from google.cloud import bigquery import pytest import export_to_bigquery GCLOUD_TESTS_PREFIX = "python_samples_tests" def test_export_data_to_bigquery(capsys, project_id, bigquery_resources): dataset_id, table_id = bigquery_resources export_to_bigquery.export_to_bigquery(project_id, project_id, dataset_id, table_id) out, err = capsys.readouterr() assert "Exported data to BigQuery" in out
[ 2, 15069, 33448, 3012, 11419, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921, 743, 733...
3.264331
314
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import * # Register your models here. set_active.short_description = 'Set Account Status: Active' deactivate.short_description = 'Set Account Status: Inactive' # admin.site.unregister(User) admin.site.register(Author, AuthorAdmin) admin.site.register(Inbox) admin.site.register(Like) admin.site.register(Liked) admin.site.register(FriendRequest) admin.site.register(Followers)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 28482, 1330, 11787, 46787, 198, 6738, 764, 27530, 1330, 1635, 198, 198, 2, 17296, 534, 4981, 994, 13, 198, 198, 2617, 62, 5275, 13,...
3.321678
143
# -*- coding: utf-8 -*- """task module.""" from __future__ import unicode_literals import sys import os import pydoc import time import json import logging import collections import pkg_resources import subprocess import webbrowser import websocket from pyloco.parse import TaskArgParser, PylocoArgParser from pyloco.proxy import ParentProxy from pyloco.util import (load_pymod, type_check, pyloco_print, OS, urlparse, teval, split_assert_expr, get_port, pack_websocket_message, is_ipv6, pyloco_import, PylocoPickle, import_modulepath) from pyloco.error import TestError, InternalError, UsageError from pyloco.base import Object, Global, pyloco_builtins
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 35943, 8265, 526, 15931, 198, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 11748, 25064, 198, 11748, 28686, 198, 11748, 279, 5173, 420...
2.724138
261
"""Azure IoT Device Library - Asynchronous This library provides asynchronous clients for communicating with Azure IoT services from an IoT device. """ from azure.iot.device.iothub.aio import * from azure.iot.device.provisioning.aio import * from . import patch_documentation # Dynamically patch the clients to add shim implementations for all the inherited methods. # This is necessary to generate accurate online docs. # It SHOULD not impact the functionality of the methods themselves in any way. # NOTE In the event of addition of new methods and generation of accurate documentation # for those methods we have to append content to "patch_documentation.py" file. # In order to do so please uncomment the "patch.add_shims" lines below, # enable logging with level "DEBUG" in a python terminal and do # "import azure.iot.device". The delta between the newly generated output # and the existing content of "patch_documentation.py" should be appended to # the function "execute_patch_for_sync" in "patch_documentation.py". # Once done please again omment out the "patch.add_shims" lines below. # patch.add_shims_for_inherited_methods(IoTHubDeviceClient) # noqa: F405 # patch.add_shims_for_inherited_methods(IoTHubModuleClient) # noqa: F405 # patch.add_shims_for_inherited_methods(ProvisioningDeviceClient) # noqa: F405 patch_documentation.execute_patch_for_async()
[ 37811, 26903, 495, 38488, 16232, 10074, 532, 1081, 31301, 198, 198, 1212, 5888, 3769, 39354, 7534, 329, 22889, 351, 22134, 38488, 2594, 198, 6738, 281, 38488, 3335, 13, 198, 37811, 198, 198, 6738, 35560, 495, 13, 5151, 13, 25202, 13, 72...
3.546392
388
# -*- coding: UTF-8 -*- # Copyright 2013-2016 Luc Saffre # # License: BSD (see file COPYING for details) """This module is for managing a reception desk and a waiting queue: register clients into a waiting queue as they present themselves at a reception desk (Empfangsschalter), and unregister them when they leave again. It depends on :mod:`lino_xl.lib.cal`. It does not add any model, but adds some workflow states, actions and tables. Extended by :mod:`lino_welfare.modlib.reception`. .. autosummary:: :toctree: models workflows """ from lino.api import ad, _
[ 2, 532, 9, 12, 19617, 25, 41002, 12, 23, 532, 9, 12, 198, 2, 15069, 2211, 12, 5304, 7598, 311, 2001, 260, 198, 2, 198, 2, 13789, 25, 347, 10305, 357, 3826, 2393, 27975, 45761, 329, 3307, 8, 198, 198, 37811, 1212, 8265, 318, 329,...
3.073684
190
from accent_analyser.rules.EngRule import EngRule
[ 6738, 18702, 62, 272, 26266, 263, 13, 38785, 13, 7936, 31929, 1330, 1985, 31929, 628 ]
3.4
15
# -*- coding:utf-8 -*-
[ 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 628 ]
1.846154
13
session.forget() def vars(): """the running controller function!""" title = '.'.join(request.args) attributes = {} if not request.args: (doc, keys, t, c, d, value) = ('Global variables', globals(), None, None, [], None) elif len(request.args) < 3: obj = get(request.args) if obj: doc = getattr(obj, '__doc__', 'no documentation') keys = dir(obj) t = type(obj) c = getattr(obj, '__class__', None) d = getattr(obj, '__bases__', None) for key in keys: a = getattr(obj, key, None) if a and not isinstance(a, DAL): doc1 = getattr(a, '__doc__', '') t1 = type(a) c1 = getattr(a, '__class__', None) d1 = getattr(a, '__bases__', None) key = '.'.join(request.args) + '.' + key attributes[key] = (doc1, t1, c1, d1) else: doc = 'Unkown' keys = [] t = c = d = None else: raise HTTP(400) return dict( title=title, args=request.args, t=t, c=c, d=d, doc=doc, attributes=attributes, )
[ 29891, 13, 1640, 1136, 3419, 628, 198, 198, 4299, 410, 945, 33529, 198, 220, 220, 220, 37227, 1169, 2491, 10444, 2163, 2474, 15931, 198, 220, 220, 220, 3670, 796, 705, 2637, 13, 22179, 7, 25927, 13, 22046, 8, 198, 220, 220, 220, 126...
1.769663
712
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #223. Rectangle Area #Find the total area covered by two rectilinear rectangles in a 2D plane. #Each rectangle is defined by its bottom left corner and top right corner as shown in the figure. #Assume that the total area is never beyond the maximum possible value of int. #Credits: #Special thanks to @mithmatt for adding this problem, creating the above image and all test cases. #class Solution: # def computeArea(self, A, B, C, D, E, F, G, H): # """ # :type A: int # :type B: int # :type C: int # :type D: int # :type E: int # :type F: int # :type G: int # :type H: int # :rtype: int # """ # Time Is Money
[ 2, 10560, 4944, 42, 54, 23261, 309, 3620, 6489, 6158, 7, 2860, 6764, 290, 32338, 8, 198, 2, 18233, 11851, 290, 12489, 319, 443, 316, 8189, 13, 785, 198, 2, 15553, 24720, 290, 15553, 5038, 13567, 319, 443, 316, 8189, 13, 785, 198, ...
2.669782
321
import serial import RPi.GPIO as GPIO import time ser=serial.Serial("/dev/ttyACM0",9600) start_time = time.time() imu = open("IMU.txt","w") while time.time() - start_time <= 1: ser.readline() while time.time() - start_time <= 8: read_ser=ser.readline() if float(read_ser) == 0.00: pass else: read = read_ser.strip('\n') imu.write(read) imu.write('\n') imu.close()
[ 11748, 11389, 201, 198, 11748, 25812, 72, 13, 16960, 9399, 355, 50143, 201, 198, 11748, 640, 201, 198, 201, 198, 2655, 28, 46911, 13, 32634, 7203, 14, 7959, 14, 42852, 2246, 44, 15, 1600, 4846, 405, 8, 201, 198, 9688, 62, 2435, 796,...
2.032558
215
from pyg_base._types import is_iterable from pyg_base._loop import len0 __all__ = ['zipper', 'lens'] def lens(*values): """ measures (and enforces) a common length across all values :Parameters: ---------------- *values : lists Raises ------ ValueError if you have values with multi lengths. :Returns: ------- int common length. :Example: -------------- >>> assert lens() == 0 >>> assert lens([1,2,3], [2,4,5]) == 3 >>> assert lens([1,2,3], [2,4,5], [6]) == 3 """ if len0(values) == 0: return 0 all_lens = [len0(value) for value in values] lens = set(all_lens) - {1} if len(lens)>1: raise ValueError('found multiple lengths %s '%lens) return list(lens)[0] if lens else 1 def zipper(*values): """ a safer version of zip :Examples: zipper works with single values as well as full list: --------------- >>> assert list(zipper([1,2,3], 4)) == [(1, 4), (2, 4), (3, 4)] >>> assert list(zipper([1,2,3], [4,5,6])) == [(1, 4), (2, 5), (3, 6)] >>> assert list(zipper([1,2,3], [4,5,6], [7])) == [(1, 4, 7), (2, 5, 7), (3, 6, 7)] >>> assert list(zipper([1,2,3], [4,5,6], None)) == [(1, 4, None), (2, 5, None), (3, 6, None)] >>> assert list(zipper((1,2,3), np.array([4,5,6]), None)) == [(1, 4, None), (2, 5, None), (3, 6, None)] :Examples: zipper rejects multi-length lists --------------- >>> import pytest >>> with pytest.raises(ValueError): >>> zipper([1,2,3], [4,5]) :Parameters: ---------------- *values : lists values to be zipped :Returns: ------- zipped values """ values = [list(value) if isinstance(value, zip) else value if is_iterable(value) else [value] for value in values] n = lens(*values) values = [value * n if len(value) == 1 else value for value in values] return zip(*values)
[ 6738, 12972, 70, 62, 8692, 13557, 19199, 1330, 318, 62, 2676, 540, 198, 6738, 12972, 70, 62, 8692, 13557, 26268, 1330, 18896, 15, 198, 198, 834, 439, 834, 796, 37250, 89, 14710, 3256, 705, 75, 641, 20520, 198, 198, 4299, 10317, 46491,...
2.349398
830
import json from typing import List import requests from pawls.preprocessors.model import Page def process_grobid( pdf_file: str, grobid_host: str = "http://localhost:8070" ): """ Integration for importing annotations from grobid. Depends on a grobid API built from our fork https://github.com/allenai/grobid. Fetches a PDF by sha, sends it to the Grobid API and returns them. pdf_file: str The path to the pdf file to process. grobid_host: str (optional, default="http://localhost:8070") The forked grobid API which we use to produce the annotations. """ grobid_structure = fetch_grobid_structure(pdf_file, grobid_host) annotations = parse_annotations(grobid_structure) return annotations
[ 11748, 33918, 198, 6738, 19720, 1330, 7343, 198, 11748, 7007, 198, 198, 6738, 41827, 7278, 13, 3866, 14681, 669, 13, 19849, 1330, 7873, 628, 198, 198, 4299, 1429, 62, 27333, 14065, 7, 198, 220, 220, 220, 37124, 62, 7753, 25, 965, 11, ...
2.957198
257
# coding: utf-8 # # Copyright 2020 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Script for running tests for custom eslint checks.""" from __future__ import absolute_import from __future__ import unicode_literals import os import re import subprocess import sys from core import python_utils from scripts import common def main(): """Run the tests.""" node_path = os.path.join(common.NODE_PATH, 'bin', 'node') nyc_path = os.path.join('node_modules', 'nyc', 'bin', 'nyc.js') mocha_path = os.path.join('node_modules', 'mocha', 'bin', 'mocha') filepath = 'scripts/linters/custom_eslint_checks/rules/' proc_args = [node_path, nyc_path, mocha_path, filepath] proc = subprocess.Popen( proc_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) encoded_tests_stdout, encoded_tests_stderr = proc.communicate() # Standard and error output is in bytes, we need to decode the line to # print it. tests_stdout = encoded_tests_stdout.decode('utf-8') tests_stderr = encoded_tests_stderr.decode('utf-8') if tests_stderr: python_utils.PRINT(tests_stderr) sys.exit(1) python_utils.PRINT(tests_stdout) if 'failing' in tests_stdout: python_utils.PRINT('---------------------------') python_utils.PRINT('Tests not passed') python_utils.PRINT('---------------------------') sys.exit(1) else: python_utils.PRINT('---------------------------') python_utils.PRINT('All tests passed') python_utils.PRINT('---------------------------') coverage_result = re.search = re.search( r'All files\s*\|\s*(?P<stmts>\S+)\s*\|\s*(?P<branch>\S+)\s*\|\s*' r'(?P<funcs>\S+)\s*\|\s*(?P<lines>\S+)\s*\|\s*', tests_stdout) if (coverage_result.group('stmts') != '100' or coverage_result.group('branch') != '100' or coverage_result.group('funcs') != '100' or coverage_result.group('lines') != '100'): raise Exception('Eslint test coverage is not 100%') if __name__ == '__main__': main()
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 2, 198, 2, 15069, 12131, 383, 9385, 544, 46665, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 74...
2.59841
1,006
from __future__ import print_function from pyomo.environ import * from pyomo.core.base import Constraint, Objective, Suffix, minimize from pyomo.opt import ProblemFormat, SolverFactory from nmpc_mhe.dync.NMPCGenv2 import NmpcGen from nmpc_mhe.mods.bfb.nob5_hi_t import bfb_dae from snap_shot import snap import sys, os import itertools, sys from numpy.random import normal as npm # SWITCH TO JUST ONE COLLOCATION POINT AND FINITE ELEMENT states = ["Hgc", "Nsc", "Hsc", "Hge", "Nse", "Hse"] # x_noisy = ["Ngb", "Hgb", "Ngc", "Hgc", "Nsc", "Hsc", "Nge", "Hge", "Nse", "Hse", "mom"] # x_noisy = ["Hse"] x_noisy = ["Hgc", "Nsc", "Hsc", "Hge", "Nse", "Hse"] u = ["u1"] u_bounds = {"u1":(162.183495794 * 0.0005, 162.183495794 * 10000)} ref_state = {("c_capture", ((),)): 0.63} # Known targets 0.38, 0.4, 0.5 nfe_mhe = 10 y = ["Tgb", "vg"] nfet = 10 ncpx = 3 nfex = 5 tfe = [i for i in range(1, nfe_mhe + 1)] lfe = [i for i in range(1, nfex + 1)] lcp = [i for i in range(1, ncpx + 1)] lc = ['c', 'h', 'n'] y_vars = { "Tgb": [i for i in itertools.product(lfe, lcp)], "vg": [i for i in itertools.product(lfe, lcp)] } # x_vars = dict() x_vars = { # "Nge": [i for i in itertools.product(lfe, lcp, lc)], # "Hge": [i for i in itertools.product(lfe, lcp)], "Nsc": [i for i in itertools.product(lfe, lcp, lc)], "Hsc": [i for i in itertools.product(lfe, lcp)], "Nse": [i for i in itertools.product(lfe, lcp, lc)], "Hse": [i for i in itertools.product(lfe, lcp)], "Hgc": [i for i in itertools.product(lfe, lcp)], "Hge": [i for i in itertools.product(lfe, lcp)], # "mom": [i for i in itertools.product(lfe, lcp)] } # States -- (5 * 3 + 6) * fe_x * cp_x. # For fe_x = 5 and cp_x = 3 we will have 315 differential-states. e = NmpcGen(bfb_dae, 400/nfe_mhe, states, u, ref_state=ref_state, u_bounds=u_bounds, nfe_tnmpc=nfe_mhe, ncp_tnmpc=1, nfe_t=5, ncp_t=1) # 10 fe & _t=1000 definitely degenerate # 10 fe & _t=900 definitely degenerate # 10 fe & _t=120 sort-of degenerate # 10 fe & _t=50 sort-of degenerate # 10 fe & _t=50 eventually sort-of degenerate # 10 fe & _t=1 eventually sort-of degenerate e.SteadyRef.dref = snap e.load_iguess_steady() e.SteadyRef.create_bounds() e.solve_steady_ref() e.SteadyRef.report_zL(filename="mult_ss") e.load_d_s(e.PlantSample) e.PlantSample.create_bounds() e.solve_dyn(e.PlantSample) q_cov = {} for i in tfe: for j in itertools.product(lfe, lcp, lc): q_cov[("Nse", j), ("Nse", j), i] = 7525.81478168 * 0.005 q_cov[("Nsc", j), ("Nsc", j), i] = 117.650089456 * 0.005 # q_cov[("Nse", j), ("Nse", j), i] = 735.706082714 * 0.005 for i in tfe: for j in itertools.product(lfe, lcp): # q_cov[("Hge", j), ("Hge", j), i] = 2194.25390583 * 0.005 q_cov[("Hse", j), ("Hse", j), i] = 731143.716603 * 0.005 q_cov[("Hsc", j), ("Hsc", j), i] = 16668.3312216 * 0.005 q_cov[("Hge", j), ("Hge", j), i] = 2166.86838591 * 0.005 q_cov[("Hgc", j), ("Hgc", j), i] = 47.7911012193 * 0.005 # q_cov[("mom", j), ("mom", j), i] = 1.14042251669 * 0.005 # for i in lfe: # for j in [(1,1, 'c'), (5,3, 'c')]: # m_cov[("yb", j), ("yb", j), i] = 1e-04 u_cov = {} for i in [i for i in range(1, nfe_mhe+1)]: u_cov["u1", i] = 162.183495794 * 0.005 m_cov = {} for i in tfe: for j in itertools.product(lfe, lcp): m_cov[("Tgb", j), ("Tgb", j), i] = 40 * 0.005 m_cov[("vg", j), ("vg", j), i] = 0.902649386907 * 0.005 e.find_target_ss() #: Compute target-steady state (beforehand) #: Create NMPC e.create_nmpc() e.update_targets_nmpc() e.compute_QR_nmpc(n=-1) e.new_weights_olnmpc(10000, 1e+08) e.solve_dyn(e.PlantSample, stop_if_nopt=True) ipsr = SolverFactory('ipopt', executable="/home/dav0/Apps/IpoptSR/Ipopt/build/bin/ipoptSR") ref_state = {("c_capture", ((),)): 0.50} e.find_target_ss(ref_state=ref_state) #: Compute target-steady state (beforehand) e.update_targets_nmpc() e.compute_QR_nmpc(n=-1) e.new_weights_olnmpc(10000, 1e+08) for i in range(1, 1000): ps = e.solve_dyn(e.PlantSample, stop_if_nopt=False) e.PlantSample.write_nl(name="baddie.nl") e.PlantSample.pprint(filename="baddie.txt") e.PlantSample.snap_shot(filename="baddie.py") e.PlantSample.report_zL(filename="bad_bounds") if ps != 0: e.PlantSample.write_nl(name="baddie.nl") e.PlantSample.pprint(filename="baddie.txt") e.PlantSample.snap_shot(filename="baddie.py") e.PlantSample.report_zL(filename="bad_bounds") e.solve_dyn(e.PlantSample, stop_if_nopt=True) e.update_state_real() # update the current state e.update_soi_sp_nmpc() # e.initialize_olnmpc(e.PlantSample, "real") e.load_init_state_nmpc(src_kind="state_dict", state_dict="real") stat_nmpc = e.solve_dyn(e.olnmpc, skip_update=False, max_cpu_time=300) # if stat_nmpc != 0: # stat_nmpc = e.solve_dyn(e.olnmpc, # stop_if_nopt=True, # skip_update=False, # iter_max=300, ma57_pivtol=1e-12) if stat_nmpc != 0: strategy = 1 if strategy == 1: if e.nfe_tnmpc == 1: pass else: e.create_nmpc(newnfe=e.ncp_tnmpc-1, newncp=1) e.update_targets_nmpc() e.compute_QR_nmpc(n=-1) e.new_weights_olnmpc(10000, 1e+02) e.initialize_olnmpc(e.PlantSample, "real") e.load_init_state_nmpc(src_kind="state_dict", state_dict="real") stat_nmpc = e.solve_dyn(e.olnmpc, skip_update=False, max_cpu_time=300) else: e.olnmpc.write_nl(name="bad.nl") # e.olnmpc.pprint(filename="bad_" + str(i)) with open("ipopt.opt", "w") as f: f.write("linear_solver ma57\n" "ma57_dep_tol 1e-8\nbig_M 1e30\n") f.close() ipsr.solve(e.olnmpc, tee=True) e.update_u(e.olnmpc) e.print_r_nmpc() e.cycleSamPlant(plant_step=True) e.plant_uinject(e.PlantSample, src_kind="dict", nsteps=10, skip_homotopy=True) # e.plant_input_gen(e.PlantSample, "mod", src=e.ss2)
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 12972, 17902, 13, 268, 2268, 1330, 1635, 198, 6738, 12972, 17902, 13, 7295, 13, 8692, 1330, 1482, 2536, 2913, 11, 37092, 11, 24974, 844, 11, 17775, 198, 6738, 12972, 17902, 13, ...
1.888053
3,323
from urllib.parse import urlparse from quart import current_app as app, request, jsonify
[ 6738, 2956, 297, 571, 13, 29572, 1330, 19016, 29572, 198, 198, 6738, 28176, 1330, 1459, 62, 1324, 355, 598, 11, 2581, 11, 33918, 1958, 628 ]
3.64
25
from django.db import models from filer.fields.file import FilerFileField
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 1226, 263, 13, 25747, 13, 7753, 1330, 376, 5329, 8979, 15878, 628 ]
3.571429
21
from __future__ import print_function import atexit import errno import logging import os import select import signal import sys import time from process_tests import setup_coverage TIMEOUT = int(os.getenv('MANHOLE_TEST_TIMEOUT', 10)) SOCKET_PATH = '/tmp/manhole-socket' OUTPUT = sys.__stdout__ # Handling sigterm ensure that atexit functions are called, and we do not leave # leftover /tmp/manhole-pid sockets. signal.signal(signal.SIGTERM, handle_sigterm) if __name__ == '__main__': logging.basicConfig( level=logging.DEBUG, format='[pid=%(process)d - %(asctime)s]: %(name)s - %(levelname)s - %(message)s', ) test_name = sys.argv[1] try: setup_coverage() if os.getenv('PATCH_THREAD', False): import manhole setup_greenthreads(True) else: setup_greenthreads(True) import manhole if test_name == 'test_activate_on_usr2': manhole.install(activate_on='USR2') for i in range(TIMEOUT * 100): time.sleep(0.1) elif test_name == 'test_install_once': manhole.install() try: manhole.install() except manhole.AlreadyInstalled: print('ALREADY_INSTALLED') else: raise AssertionError("Did not raise AlreadyInstalled") elif test_name == 'test_stderr_doesnt_deadlock': import subprocess manhole.install() for i in range(50): print('running iteration', i) p = subprocess.Popen(['true']) print('waiting for process', p.pid) p.wait() print('process ended') path = '/tmp/manhole-%d' % p.pid if os.path.exists(path): os.unlink(path) raise AssertionError(path + ' exists !') print('SUCCESS') elif test_name == 'test_fork_exec': manhole.install(reinstall_delay=5) print("Installed.") time.sleep(0.2) pid = os.fork() print("Forked, pid =", pid) if pid: os.waitpid(pid, 0) path = '/tmp/manhole-%d' % pid if os.path.exists(path): os.unlink(path) raise AssertionError(path + ' exists !') else: try: time.sleep(1) print("Exec-ing `true`") os.execvp('true', ['true']) finally: os._exit(1) print('SUCCESS') elif test_name == 'test_activate_on_with_oneshot_on': manhole.install(activate_on='USR2', oneshot_on='USR2') for i in range(TIMEOUT * 100): time.sleep(0.1) elif test_name == 'test_interrupt_on_accept': signal.signal(signal.SIGUSR2, handle_usr2) import ctypes import ctypes.util libpthread_path = ctypes.util.find_library("pthread") if not libpthread_path: raise ImportError libpthread = ctypes.CDLL(libpthread_path) if not hasattr(libpthread, "pthread_setname_np"): raise ImportError pthread_kill = libpthread.pthread_kill pthread_kill.argtypes = [ctypes.c_void_p, ctypes.c_int] pthread_kill.restype = ctypes.c_int manhole.install(sigmask=None) for i in range(15): time.sleep(0.1) print("Sending signal to manhole thread ...") pthread_kill(manhole._INST.ident, signal.SIGUSR2) for i in range(TIMEOUT * 100): time.sleep(0.1) elif test_name == 'test_oneshot_on_usr2': manhole.install(oneshot_on='USR2') for i in range(TIMEOUT * 100): time.sleep(0.1) elif test_name.startswith('test_signalfd_weirdness'): if 'negative' in test_name: manhole.install(sigmask=None) else: manhole.install(sigmask=[signal.SIGCHLD]) time.sleep(0.3) # give the manhole a bit enough time to start print('Starting ...') import signalfd signalfd.sigprocmask(signalfd.SIG_BLOCK, [signal.SIGCHLD]) fd = signalfd.signalfd(0, [signal.SIGCHLD], signalfd.SFD_NONBLOCK|signalfd.SFD_CLOEXEC) for i in range(200): print('Forking %s:' % i) pid = os.fork() print(' - [%s/%s] forked' % (i, pid)) if pid: while 1: print(' - [%s/%s] selecting on: %s' % (i, pid, [fd])) read_ready, _, errors = select.select([fd], [], [fd], 1) if read_ready: try: print(' - [%s/%s] reading from signalfd ...' % (i, pid)) print(' - [%s] read from signalfd: %r ' % (i, os.read(fd, 128))) break except OSError as exc: print(' - [%s/%s] reading from signalfd failed with errno %s' % (i, pid, exc.errno)) else: print(' - [%s/%s] reading from signalfd failed - not ready !' % (i, pid)) if 'negative' in test_name: time.sleep(1) if errors: raise RuntimeError("fd has error") else: print(' - [%s/%s] exiting' % (i, pid)) os._exit(0) time.sleep(TIMEOUT * 10) elif test_name == 'test_auth_fail': manhole.get_peercred = lambda _: (-1, -1, -1) manhole.install() time.sleep(TIMEOUT * 10) elif test_name == 'test_socket_path': manhole.install(socket_path=SOCKET_PATH) time.sleep(TIMEOUT * 10) elif test_name == 'test_daemon_connection': manhole.install(daemon_connection=True) time.sleep(TIMEOUT) elif test_name == 'test_socket_path_with_fork': manhole.install(socket_path=SOCKET_PATH) time.sleep(TIMEOUT) do_fork() elif test_name == 'test_locals': manhole.install(socket_path=SOCKET_PATH, locals={'k1': 'v1', 'k2': 'v2'}) time.sleep(TIMEOUT) elif test_name == 'test_locals_after_fork': manhole.install(locals={'k1': 'v1', 'k2': 'v2'}) do_fork() elif test_name == 'test_redirect_stderr_default': manhole.install(socket_path=SOCKET_PATH) time.sleep(TIMEOUT) elif test_name == 'test_redirect_stderr_disabled': manhole.install(socket_path=SOCKET_PATH, redirect_stderr=False) time.sleep(TIMEOUT) elif test_name == 'test_sigmask': manhole.install(socket_path=SOCKET_PATH, sigmask=[signal.SIGUSR1]) time.sleep(TIMEOUT) else: manhole.install() time.sleep(0.3) # give the manhole a bit enough time to start if test_name == 'test_simple': time.sleep(TIMEOUT * 10) elif test_name == 'test_with_forkpty': time.sleep(1) pid, masterfd = os.forkpty() if pid: while not os.waitpid(pid, os.WNOHANG)[0]: try: os.write(2, os.read(masterfd, 1024)) except OSError as e: print("Error while reading from masterfd:", e) else: time.sleep(TIMEOUT * 10) elif test_name == 'test_with_fork': time.sleep(1) do_fork() else: raise RuntimeError('Invalid test spec.') except: # pylint: disable=W0702 print('Died with %s.' % sys.exc_info()[0].__name__, file=OUTPUT) import traceback traceback.print_exc(file=OUTPUT) print('DIED.', file=OUTPUT)
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 379, 37023, 198, 11748, 11454, 3919, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 2922, 198, 11748, 6737, 198, 11748, 25064, 198, 11748, 640, 198, 198, 6738, 1429, 62, ...
1.785637
4,637
from django.contrib import admin from django.conf import settings from django.core.exceptions import ImproperlyConfigured from . import models if settings.HAS_ADDITIONAL_USER_DATA: try: except (Exception, KeyError) as e: raise ImproperlyConfigured("User/admin.py:: Multi Vendor is turned on.") admin.site.register(models.User, UserAdmin) admin.site.register(models.IpAddress) admin.site.register(models.CityFromIpAddress) admin.site.register(models.Marketing)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 7295, 13, 1069, 11755, 1330, 12205, 525, 306, 16934, 1522, 198, 198, 6738, 764, 1330, 4981, 628, 198, 361, 6460...
3.096774
155
from client import exception, embed_creator, console_interface, discord_manager, file_manager, ini_manager, json_manager, origin, permissions, server_timer from client.config import config as c, language as l from discord.ext import commands, tasks from client.external.hiscores import hiscores_xp from PIL import Image, ImageDraw, ImageFont import discord, locale
[ 6738, 5456, 1330, 6631, 11, 11525, 62, 45382, 11, 8624, 62, 39994, 11, 36446, 62, 37153, 11, 2393, 62, 37153, 11, 287, 72, 62, 37153, 11, 33918, 62, 37153, 11, 8159, 11, 21627, 11, 4382, 62, 45016, 198, 6738, 5456, 13, 11250, 1330, ...
4
91
from __future__ import annotations import os import collections BASE_PATH = os.path.dirname(__file__) INPUT_PATH = os.path.join(BASE_PATH, "input.txt") OUTPUT_PATH = os.path.join(BASE_PATH, "output.txt") if __name__ == "__main__": raise SystemExit(main())
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 11748, 28686, 198, 11748, 17268, 628, 198, 33, 11159, 62, 34219, 796, 220, 28686, 13, 6978, 13, 15908, 3672, 7, 834, 7753, 834, 8, 220, 198, 1268, 30076, 62, 34219, 796, 28686, 13, 6978, 13, ...
2.653465
101
"""Agents for neural net bandit problems. We implement three main types of agent: - epsilon-greedy (fixed epsilon, annealing epsilon) - dropout (arXiv:1506.02142) - ensemble sampling All code is specialized to the setting of 2-layer fully connected MLPs. """ import numpy as np import numpy.random as rd from base.agent import Agent from ensemble_nn.env_nn import TwoLayerNNBandit
[ 37811, 10262, 658, 329, 17019, 2010, 4097, 270, 2761, 13, 198, 198, 1135, 3494, 1115, 1388, 3858, 286, 5797, 25, 198, 220, 532, 304, 862, 33576, 12, 16694, 4716, 357, 34021, 304, 862, 33576, 11, 281, 710, 4272, 304, 862, 33576, 8, 1...
3.177419
124
import io import os from django.core.management.base import BaseCommand from django.conf import settings from django.contrib.staticfiles import finders from django.template.loader import render_to_string from django.utils.translation import to_locale
[ 11748, 33245, 198, 11748, 28686, 198, 198, 6738, 42625, 14208, 13, 7295, 13, 27604, 13, 8692, 1330, 7308, 21575, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 12708, 16624, 1330, 1064, 364, ...
3.720588
68
# Copyright 2019. Allen Institute. All rights reserved. import numpy as np import pandas as pd from collections import OrderedDict import math import warnings from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA from sklearn.neighbors import NearestNeighbors from sklearn.metrics import silhouette_score from scipy.spatial.distance import cdist from scipy.stats import chi2 from scipy.ndimage.filters import gaussian_filter1d from .utils import Epoch from .utils import printProgressBar, get_spike_positions def calculate_metrics(spike_times, spike_clusters, amplitudes, pc_features, pc_feature_ind, params, duration, channel_locations=None, cluster_ids=None, epochs=None, seed=None, verbose=True): """ Calculate metrics for all units on one probe Inputs: ------ spike_times : numpy.ndarray (num_spikes x 0) Spike times in seconds (same timebase as epochs) spike_clusters : numpy.ndarray (num_spikes x 0) Cluster IDs for each spike time pc_features : numpy.ndarray (num_spikes x num_pcs x num_channels) Pre-computed PCs for blocks of channels around each spike pc_feature_ind : numpy.ndarray (num_units x num_channels) Channel indices of PCs for each unit epochs : list of Epoch objects contains information on Epoch start and stop times duration : length of recording (seconds) channel_locations : numpy.ndarray (num_channels x 2) Channel locations (if None, a linear geometry is assumed) params : dict of parameters 'isi_threshold' : minimum time for isi violations 'min_isi' 'num_channels_to_compare' 'max_spikes_for_unit' 'max_spikes_for_nn' 'n_neighbors' 'drift_metrics_interval_s' 'drift_metrics_min_spikes_per_interval' Outputs: -------- metrics : pandas.DataFrame one column for each metric one row per unit per epoch """ metrics = pd.DataFrame() if epochs is None: epochs = [Epoch('complete_session', 0, np.inf)] total_units = np.max(spike_clusters) + 1 total_epochs = len(epochs) for epoch in epochs: in_epoch = np.logical_and(spike_times >= epoch.start_time, spike_times < epoch.end_time) spikes_in_epoch = np.sum(in_epoch) spikes_for_nn = min(spikes_in_epoch, params['max_spikes_for_nn']) spikes_for_silhouette = min(spikes_in_epoch, params['n_silhouette']) print("Calculating isi violations") isi_viol = calculate_isi_violations(spike_times=spike_times[in_epoch], spike_clusters=spike_clusters[in_epoch], total_units=total_units, isi_threshold=params['isi_threshold'], min_isi=params['min_isi'], duration=duration, verbose=verbose) print("Calculating presence ratio") presence_ratio = calculate_presence_ratio(spike_times=spike_times[in_epoch], spike_clusters=spike_clusters[in_epoch], total_units=total_units, duration=duration, verbose=verbose) print("Calculating firing rate") firing_rate = calculate_firing_rates(spike_times=spike_times[in_epoch], spike_clusters=spike_clusters[in_epoch], total_units=total_units, duration=duration, verbose=verbose) print("Calculating amplitude cutoff") amplitude_cutoff = calculate_amplitude_cutoff(spike_clusters=spike_clusters[in_epoch], amplitudes=amplitudes[in_epoch], total_units=total_units, verbose=verbose) print("Calculating PC-based metrics") isolation_distance, l_ratio, d_prime, nn_hit_rate, nn_miss_rate = \ calculate_pc_metrics(spike_clusters=spike_clusters[in_epoch], total_units=total_units, pc_features=pc_features[in_epoch, :, :], pc_feature_ind=pc_feature_ind, num_channels_to_compare=params['num_channels_to_compare'], max_spikes_for_cluster=params['max_spikes_for_unit'], spikes_for_nn=spikes_for_nn, n_neighbors=params['n_neighbors'], channel_locations= channel_locations, seed=seed, verbose=verbose) print("Calculating silhouette score") silhouette_score = calculate_silhouette_score(spike_clusters=spike_clusters[in_epoch], total_units=total_units, pc_features=pc_features[in_epoch, :, :], pc_feature_ind=pc_feature_ind, spikes_for_silhouette=spikes_for_silhouette, seed=seed, verbose=verbose) print("Calculating drift metrics") max_drift, cumulative_drift = calculate_drift_metrics(spike_times=spike_times[in_epoch], spike_clusters=spike_clusters[in_epoch], total_units=total_units, pc_features=pc_features[in_epoch, :, :], pc_feature_ind=pc_feature_ind, interval_length=params['drift_metrics_interval_s'], min_spikes_per_interval= params['drift_metrics_min_spikes_per_interval'], channel_locations= channel_locations, verbose=verbose) if cluster_ids is None: cluster_ids_out = np.arange(total_units) else: cluster_ids_out = cluster_ids epoch_name = [epoch.name] * len(cluster_ids_out) metrics = pd.concat((metrics, pd.DataFrame(data=OrderedDict((('cluster_id', cluster_ids_out), ('firing_rate', firing_rate), ('presence_ratio', presence_ratio), ('isi_violation', isi_viol), ('amplitude_cutoff', amplitude_cutoff), ('isolation_distance', isolation_distance), ('l_ratio', l_ratio), ('d_prime', d_prime), ('nn_hit_rate', nn_hit_rate), ('nn_miss_rate', nn_miss_rate), ('silhouette_score', silhouette_score), ('max_drift', max_drift), ('cumulative_drift', cumulative_drift), ('epoch_name', epoch_name), ))))) return metrics # =============================================================== # HELPER FUNCTIONS TO LOOP THROUGH CLUSTERS: # =============================================================== def calculate_pc_metrics(spike_clusters, total_units, pc_features, pc_feature_ind, num_channels_to_compare, max_spikes_for_cluster, spikes_for_nn, n_neighbors, channel_locations, min_num_pcs=10, metric_names=None, seed=None, spike_cluster_subset=None, verbose=True): """ Computes metrics from projection of waveforms to principal components including: isolation distance, l ratio, d prime, nn hit rate, nn miss rate Parameters ---------- spike_clusters: numpy.ndarray (num_spikes,) Unit ID for each spike time total_units: int Total number of units pc_features: numpy.ndarray (num_spikes, num_pcs, num_channels) Pre-computed PCs for blocks of channels around each spike pc_feature_ind: numpy.ndarray (num_units, num_channels) Channel indices of PCs for each unit num_channels_to_compare: int Number of channels around the max channel over which to compute the metrics (e.g. only units from these channels will be considered for the nearest neighbor metrics) max_spikes_for_cluster: int Total number of spikes to use for computing the metrics spikes_for_nn: int Number of spikes in a unit to use for computing nearest neighbor metrics (nn_hit_rate, nn_miss_rate) n_neighbors: int Number of nearest neighbor spikes to compare membership channel_locations: array, (channels, 2) (x,y) location of channels; used to identify neighboring channels min_num_pcs: int, default=10 Minimum number of spikes a unit must have to compute these metrics metric_names: list of str, default=None List of metrics to compute seed: int, default=None Random seed for subsampling spikes from the unit spike_cluster_subset: numpy.array (units,), default=None If specified compute metrics for only these units verbose: bool, default=True Prints out progress bar if True Returns (all 1d numpy.arrays) ------- isolation_distances l_ratios d_primes nn_hit_rates nn_miss_rates """ if metric_names is None: metric_names = ['isolation_distance', 'l_ratio', 'd_prime', 'nearest_neighbor'] if num_channels_to_compare > channel_locations.shape[0]: num_channels_to_compare = channel_locations.shape[0] all_cluster_ids = np.unique(spike_clusters) if spike_cluster_subset is not None: cluster_ids = spike_cluster_subset else: cluster_ids = all_cluster_ids peak_channels = np.zeros((total_units,), dtype='uint16') neighboring_channels = np.zeros((total_units, num_channels_to_compare)) isolation_distances = np.zeros((total_units,)) l_ratios = np.zeros((total_units,)) d_primes = np.zeros((total_units,)) nn_hit_rates = np.zeros((total_units,)) nn_miss_rates = np.zeros((total_units,)) for idx, cluster_id in enumerate(all_cluster_ids): for_unit = np.squeeze(spike_clusters == cluster_id) pc_max = np.argmax(np.mean(pc_features[for_unit, 0, :], 0)) peak_channels[idx] = pc_feature_ind[idx, pc_max] # find neighboring channels neighboring_channels[idx] = find_neighboring_channels(pc_feature_ind[idx, pc_max], pc_feature_ind[idx, :], num_channels_to_compare, channel_locations) for idx, cluster_id in enumerate(cluster_ids): if verbose: printProgressBar(idx + 1, total_units) peak_channel = peak_channels[idx] # units_for_channel: index (not ID) of units defined at the target unit's peak channel units_for_channel, channel_index = np.unravel_index(np.where(pc_feature_ind.flatten() == peak_channel)[0], pc_feature_ind.shape) # units_in_range: list of bool, True for units whose peak channels are in the neighborhood of target unit units_in_range = [channel in neighboring_channels[idx] for channel in peak_channels[units_for_channel]] channels_to_use = neighboring_channels[idx] # only get index of units who are in the neighborhood of target unit units_for_channel = units_for_channel[units_in_range] spike_counts = np.zeros(units_for_channel.shape) for idx2, cluster_id2 in enumerate(units_for_channel): spike_counts[idx2] = np.sum(spike_clusters == all_cluster_ids[cluster_id2]) # index of target unit within the subset of units in its neighborhood (including itself) this_unit_idx = np.where(units_for_channel == idx)[0] if spike_counts[this_unit_idx] > max_spikes_for_cluster: relative_counts = spike_counts / spike_counts[this_unit_idx] * max_spikes_for_cluster else: relative_counts = spike_counts all_pcs = np.zeros((0, pc_features.shape[1], channels_to_use.size)) all_labels = np.zeros((0,)) for idx2, cluster_id2 in enumerate(units_for_channel): try: channel_mask = make_channel_mask(cluster_id2, pc_feature_ind, channels_to_use) except IndexError: # Occurs when pc_feature_ind does not contain all channels of interest # In that case, we will exclude this unit for the calculation print('Unit outside the range set by channel_to_use, skipping...') pass else: subsample = int(relative_counts[idx2]) index_mask = make_index_mask(spike_clusters, all_cluster_ids[cluster_id2], min_num=0, max_num=subsample, seed=seed) pcs = get_unit_pcs(pc_features, index_mask, channel_mask) labels = np.ones((pcs.shape[0],)) * all_cluster_ids[cluster_id2] all_pcs = np.concatenate((all_pcs, pcs), 0) all_labels = np.concatenate((all_labels, labels), 0) all_pcs = np.reshape(all_pcs, (all_pcs.shape[0], pc_features.shape[1] * channels_to_use.size)) if all_pcs.shape[0] > min_num_pcs: if 'isolation_distance' in metric_names or 'l_ratio' in metric_names: isolation_distances[idx], l_ratios[idx] = mahalanobis_metrics(all_pcs, all_labels, cluster_id) else: isolation_distances[idx] = np.nan l_ratios[idx] = np.nan if 'd_prime' in metric_names: d_primes[idx] = lda_metrics(all_pcs, all_labels, cluster_id) else: d_primes[idx] = np.nan if 'nearest_neighbor' in metric_names: nn_hit_rates[idx], nn_miss_rates[idx] = nearest_neighbors_metrics(all_pcs, all_labels, cluster_id, spikes_for_nn, n_neighbors) else: nn_hit_rates[idx] = np.nan nn_miss_rates[idx] = np.nan else: print(f'Unit {str(cluster_id)} only has ' + str( all_pcs.shape[0]) + ' spikes, which is not enough to compute metric; assigning nan...') isolation_distances[idx] = np.nan l_ratios[idx] = np.nan d_primes[idx] = np.nan nn_hit_rates[idx] = np.nan nn_miss_rates[idx] = np.nan return isolation_distances, l_ratios, d_primes, nn_hit_rates, nn_miss_rates # ========================================================== # IMPLEMENTATION OF ACTUAL METRICS: # ========================================================== def isi_violations(spike_train, duration, isi_threshold, min_isi=0): """Calculate Inter-Spike Interval (ISI) violations for a spike train. Based on metric described in Hill et al. (2011) J Neurosci 31: 8699-8705 Originally written in Matlab by Nick Steinmetz (https://github.com/cortex-lab/sortingQuality) Converted to Python by Daniel Denman Inputs: ------- spike_train : array of monotonically increasing spike times (in seconds) [t1, t2, t3, ...] duration : length of recording (seconds) isi_threshold : threshold for classifying adjacent spikes as an ISI violation - this is the biophysical refractory period min_isi : minimum possible inter-spike interval (default = 0) - this is the artificial refractory period enforced by the data acquisition system or post-processing algorithms Outputs: -------- fpRate : rate of contaminating spikes as a fraction of overall rate - higher values indicate more contamination num_violations : total number of violations detected """ isis_initial = np.diff(spike_train) if min_isi > 0: duplicate_spikes = np.where(isis_initial <= min_isi)[0] spike_train = np.delete(spike_train, duplicate_spikes + 1) isis = np.diff(spike_train) num_spikes = len(spike_train) num_violations = sum(isis < isi_threshold) violation_time = 2 * num_spikes * (isi_threshold - min_isi) total_rate = firing_rate(spike_train, duration) violation_rate = num_violations / violation_time fpRate = violation_rate / total_rate return fpRate, num_violations def presence_ratio(spike_train, duration, num_bin_edges=101): """Calculate fraction of time the unit is present within an epoch. Inputs: ------- spike_train : array of spike times duration : length of recording (seconds) num_bin_edges : number of bin edges for histogram - total bins = num_bin_edges - 1 Outputs: -------- presence_ratio : fraction of time bins in which this unit is spiking """ h, b = np.histogram(spike_train, np.linspace(0, duration, num_bin_edges)) return np.sum(h > 0) / (num_bin_edges - 1) def firing_rate(spike_train, duration): """Calculate firing rate for a spike train. If either temporal bound is not specified, the first and last spike time are used by default. Inputs: ------- spike_train : array of spike times (in seconds) duration : length of recording (in seconds) Outputs: -------- fr : float Firing rate in Hz """ fr = spike_train.size / duration return fr def amplitude_cutoff(amplitudes, num_histogram_bins=500, histogram_smoothing_value=3): """ Calculate approximate fraction of spikes missing from a distribution of amplitudes Assumes the amplitude histogram is symmetric (not valid in the presence of drift) Inspired by metric described in Hill et al. (2011) J Neurosci 31: 8699-8705 Input: ------ amplitudes : numpy.ndarray Array of amplitudes (don't need to be in physical units) num_histogram_bins : int Number of bins for calculating amplitude histogram histogram_smoothing_value : float Gaussian filter window for smoothing amplitude histogram Output: ------- fraction_missing : float Fraction of missing spikes (ranges between 0 and 0.5) If more than 50% of spikes are missing, an accurate estimate isn't possible """ h, b = np.histogram(amplitudes, num_histogram_bins, density=True) pdf = gaussian_filter1d(h, histogram_smoothing_value) support = b[:-1] peak_index = np.argmax(pdf) G = np.argmin(np.abs(pdf[peak_index:] - pdf[0])) + peak_index bin_size = np.mean(np.diff(support)) fraction_missing = np.sum(pdf[G:]) * bin_size fraction_missing = np.min([fraction_missing, 0.5]) return fraction_missing def mahalanobis_metrics(all_pcs, all_labels, this_unit_id): """ Calculates isolation distance and L-ratio (metrics computed from Mahalanobis distance) Based on metrics described in Schmitzer-Torbert et al. (2005) Neurosci 131: 1-11 Inputs: ------- all_pcs : numpy.ndarray (num_spikes x PCs) 2D array of PCs for all spikes all_labels : numpy.ndarray (num_spikes x 0) 1D array of cluster labels for all spikes this_unit_id : Int number corresponding to unit for which these metrics will be calculated Outputs: -------- isolation_distance : float Isolation distance of this unit l_ratio : float L-ratio for this unit """ pcs_for_this_unit = all_pcs[all_labels == this_unit_id, :] pcs_for_other_units = all_pcs[all_labels != this_unit_id, :] mean_value = np.expand_dims(np.mean(pcs_for_this_unit, 0), 0) try: VI = np.linalg.inv(np.cov(pcs_for_this_unit.T)) except np.linalg.linalg.LinAlgError: # case of singular matrix return np.nan, np.nan mahalanobis_other = np.sort(cdist(mean_value, pcs_for_other_units, 'mahalanobis', VI=VI)[0]) mahalanobis_self = np.sort(cdist(mean_value, pcs_for_this_unit, 'mahalanobis', VI=VI)[0]) n = np.min([pcs_for_this_unit.shape[0], pcs_for_other_units.shape[0]]) # number of spikes if n >= 2: dof = pcs_for_this_unit.shape[1] # number of features l_ratio = np.sum(1 - chi2.cdf(pow(mahalanobis_other, 2), dof)) / mahalanobis_self.shape[0] isolation_distance = pow(mahalanobis_other[n - 1], 2) # if math.isnan(l_ratio): # print("NaN detected", mahalanobis_other, VI) else: l_ratio = np.nan isolation_distance = np.nan return isolation_distance, l_ratio def lda_metrics(all_pcs, all_labels, this_unit_id): """ Calculates d-prime based on Linear Discriminant Analysis Based on metric described in Hill et al. (2011) J Neurosci 31: 8699-8705 Inputs: ------- all_pcs : numpy.ndarray (num_spikes x PCs) 2D array of PCs for all spikes all_labels : numpy.ndarray (num_spikes x 0) 1D array of cluster labels for all spikes this_unit_id : Int number corresponding to unit for which these metrics will be calculated Outputs: -------- d_prime : float Isolation distance of this unit l_ratio : float L-ratio for this unit """ X = all_pcs y = np.zeros((X.shape[0],), dtype='bool') y[all_labels == this_unit_id] = True lda = LDA(n_components=1) X_flda = lda.fit_transform(X, y) flda_this_cluster = X_flda[np.where(y)[0]] flda_other_cluster = X_flda[np.where(np.invert(y))[0]] d_prime = (np.mean(flda_this_cluster) - np.mean(flda_other_cluster)) / np.sqrt( 0.5 * (np.std(flda_this_cluster) ** 2 + np.std(flda_other_cluster) ** 2)) return d_prime def nearest_neighbors_metrics(all_pcs, all_labels, this_unit_id, spikes_for_nn, n_neighbors): """ Calculates unit contamination based on NearestNeighbors search in PCA space Based on metrics described in Chung, Magland et al. (2017) Neuron 95: 1381-1394 A is a (hopefully) representative subset of cluster X NN_hit(X) = 1/k \sum_i=1^k |{x in A such that ith closest neighbor is in X}| / |A| Inputs: ------- all_pcs : numpy.ndarray (num_spikes x PCs) 2D array of PCs for all spikes all_labels : numpy.ndarray (num_spikes x 0) 1D array of cluster labels for all spikes this_unit_id : Int number corresponding to unit for which these metrics will be calculated spikes_for_nn : Int number of spikes to use (calculation can be very slow when this number is >20000) n_neighbors : Int number of neighbors to use Outputs: -------- hit_rate : float Fraction of neighbors for target cluster that are also in target cluster miss_rate : float Fraction of neighbors outside target cluster that are in target cluster """ total_spikes = all_pcs.shape[0] ratio = spikes_for_nn / total_spikes this_unit = all_labels == this_unit_id X = np.concatenate((all_pcs[this_unit, :], all_pcs[np.invert(this_unit), :]), 0) n = np.sum(this_unit) if ratio < 1: inds = np.arange(0, X.shape[0] - 1, 1 / ratio).astype('int') X = X[inds, :] n = int(n * ratio) nbrs = NearestNeighbors(n_neighbors=n_neighbors, algorithm='ball_tree').fit(X) distances, indices = nbrs.kneighbors(X) this_cluster_inds = np.arange(n) this_cluster_nearest = indices[:n, 1:].flatten() other_cluster_nearest = indices[n:, 1:].flatten() hit_rate = np.mean(this_cluster_nearest < n) miss_rate = np.mean(other_cluster_nearest < n) return hit_rate, miss_rate # ========================================================== # HELPER FUNCTIONS: # ========================================================== def make_index_mask(spike_clusters, unit_id, min_num, max_num, seed=None): """ Create a mask for the spike index dimensions of the pc_features array Inputs: ------- spike_clusters : numpy.ndarray (num_spikes x 0) Contains cluster IDs for all spikes in pc_features array unit_id : Int ID for this unit min_num : Int Minimum number of spikes to return; if there are not enough spikes for this unit, return all False max_num : Int Maximum number of spikes to return; if too many spikes for this unit, return a random subsample seed: int Random seed for reproducibility Output: ------- index_mask : numpy.ndarray (boolean) Mask of spike indices for pc_features array """ index_mask = spike_clusters == unit_id inds = np.where(index_mask)[0] if len(inds) < min_num: index_mask = np.zeros((spike_clusters.size,), dtype='bool') else: index_mask = np.zeros((spike_clusters.size,), dtype='bool') order = np.random.RandomState(seed=seed).permutation(inds.size) index_mask[inds[order[:max_num]]] = True return index_mask def make_channel_mask(unit_id, pc_feature_ind, channels_to_use): """ Create a mask for the channel dimension of the pc_features array Inputs: ------- unit_id : Int ID for this unit pc_feature_ind : np.ndarray Channels used for PC calculation for each unit channels_to_use : np.ndarray Channels to use for calculating metrics Output: ------- channel_mask : numpy.ndarray Channel indices to extract from pc_features array """ these_inds = pc_feature_ind[unit_id, :] channel_mask = [np.argwhere(these_inds == i)[0][0] for i in channels_to_use] return np.array(channel_mask) def get_unit_pcs(these_pc_features, index_mask, channel_mask): """ Use the index_mask and channel_mask to return PC features for one unit Inputs: ------- these_pc_features : numpy.ndarray (float) Array of pre-computed PC features (num_spikes x num_PCs x num_channels) index_mask : numpy.ndarray (boolean) Mask for spike index dimension of pc_features array channel_mask : numpy.ndarray (boolean) Mask for channel index dimension of pc_features array Output: ------- unit_PCs : numpy.ndarray (float) PCs for one unit (num_spikes x num_PCs x num_channels) """ unit_PCs = these_pc_features[index_mask, :, :] unit_PCs = unit_PCs[:, :, channel_mask] return unit_PCs def find_neighboring_channels(peak_channel, channel_list, num_channels_to_compare, channel_locations): """ Finds k nearest channels to the peak channel of a unit Parameters ---------- peak_channel: int ID of channel with largest waveform amplitude channel_list: numpy.ndarray IDs of channels being considered num_channels_to_compare: int Number of nearest channels to return channel_locations: numpy.ndarray, (n_channels, 2) x,y coordinates of the channels in channel_list Returns ------- neighboring_channels: array_like id of k channels that neighbor peak channel (including the peak channel itself) """ # get peak channel location channel_idx = list(channel_list).index(peak_channel) peak_channel_location = channel_locations[channel_idx] # compute pairwise distance distances = [np.linalg.norm(peak_channel_location - loc) for loc in channel_locations] # get k closest channels (+1 because distance 0 is peak_channel) neighboring_channels_inds = np.argsort(distances)[:num_channels_to_compare] neighboring_channels = channel_list[neighboring_channels_inds] return neighboring_channels
[ 2, 15069, 220, 13130, 13, 9659, 5136, 13, 220, 1439, 2489, 10395, 13, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 198, 11748, 10688, 198, 11748, 14601, 1...
2.124649
13,871
import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec import copy from .pdp_calc_utils import _sample_data, _find_onehot_actual, _find_closest from sklearn.cluster import MiniBatchKMeans, KMeans def _pdp_plot_title(n_grids, feature_name, ax, multi_flag, which_class, plot_params): """ Draw pdp plot title :param n_grids: number of grids :param feature_name: name of the feature :param ax: axes to plot on :param multi_flag: whether it is a subplot of a multi-classes plot :param which_class: which class to plot :param plot_params: values of plot parameters """ font_family = 'Arial' title = 'PDP for %s' % feature_name subtitle = "Number of unique grid points: %d" % n_grids title_fontsize = 15 subtitle_fontsize = 12 if plot_params is not None: if 'font_family' in plot_params.keys(): font_family = plot_params['font_family'] if 'title' in plot_params.keys(): title = plot_params['title'] if 'title_fontsize' in plot_params.keys(): title_fontsize = plot_params['title_fontsize'] if 'subtitle_fontsize' in plot_params.keys(): subtitle_fontsize = plot_params['subtitle_fontsize'] ax.set_facecolor('white') if multi_flag: ax.text(0, 0.7, title, va="top", ha="left", fontsize=title_fontsize, fontname=font_family) ax.text(0, 0.45, "For Class %d" % which_class, va="top", ha="left", fontsize=subtitle_fontsize, fontname=font_family) ax.text(0, 0.25, subtitle, va="top", ha="left", fontsize=subtitle_fontsize, fontname=font_family, color='grey') else: ax.text(0, 0.7, title, va="top", ha="left", fontsize=title_fontsize, fontname=font_family) ax.text(0, 0.4, subtitle, va="top", ha="left", fontsize=subtitle_fontsize, fontname=font_family, color='grey') ax.axis('off') def _pdp_plot(pdp_isolate_out, feature_name, center, plot_org_pts, plot_lines, frac_to_plot, cluster, n_cluster_centers, cluster_method, x_quantile, ax, plot_params): """ Plot partial dependent plot :param pdp_isolate_out: instance of pdp_isolate_obj a calculated pdp_isolate_obj instance :param feature_name: string name of the feature, not necessary the same as the column name :param center: boolean, default=True whether to center the plot :param plot_org_pts: boolean, default=False whether to plot out the original points :param plot_lines: boolean, default=False whether to plot out the individual lines :param frac_to_plot: float or integer, default=1 how many points or lines to plot, can be a integer or a float :param cluster: boolean, default=False whether to cluster the individual lines and only plot out the cluster centers :param n_cluster_centers: integer, default=None number of cluster centers :param cluster_method: string, default=None cluster method to use, default is KMeans, if 'approx' is passed, MiniBatchKMeans is used :param x_quantile: boolean, default=False whether to construct x axis ticks using quantiles :param ax: axes to plot on :param plot_params: dict, default=None values of plot parameters """ font_family = 'Arial' xticks_rotation = 0 if plot_params is not None: if 'font_family' in plot_params.keys(): font_family = plot_params['font_family'] if 'xticks_rotation' in plot_params.keys(): xticks_rotation = plot_params['xticks_rotation'] # modify axes _axes_modify(font_family, ax) ax.set_xlabel(feature_name, fontsize=10) feature_type = pdp_isolate_out.feature_type feature_grids = pdp_isolate_out.feature_grids display_columns = pdp_isolate_out.display_columns actual_columns = pdp_isolate_out.actual_columns if feature_type == 'binary' or feature_type == 'onehot' or x_quantile: x = range(len(feature_grids)) ax.set_xticks(x) ax.set_xticklabels(display_columns, rotation=xticks_rotation) else: # for numeric feature x = feature_grids ice_lines = copy.deepcopy(pdp_isolate_out.ice_lines) pdp_y = copy.deepcopy(pdp_isolate_out.pdp) # whether to fill between std upper and lower # whether to highlight pdp line std_fill = True pdp_hl = False # whether to center the plot if center: pdp_y -= pdp_y[0] for col in feature_grids[1:]: ice_lines[col] -= ice_lines[feature_grids[0]] ice_lines['actual_preds'] -= ice_lines[feature_grids[0]] ice_lines[feature_grids[0]] = 0 if cluster or plot_lines: std_fill = False pdp_hl = True if cluster: _ice_cluster_plot(x=x, ice_lines=ice_lines, feature_grids=feature_grids, n_cluster_centers=n_cluster_centers, cluster_method=cluster_method, ax=ax, plot_params=plot_params) else: ice_plot_data = _sample_data(ice_lines=ice_lines, frac_to_plot=frac_to_plot) _ice_line_plot(x=x, ice_plot_data=ice_plot_data, feature_grids=feature_grids, ax=ax, plot_params=plot_params) if plot_org_pts: ice_lines_temp = ice_lines.copy() if feature_type == 'onehot': ice_lines_temp['x'] = ice_lines_temp[actual_columns].apply(lambda x: _find_onehot_actual(x), axis=1) ice_lines_temp = ice_lines_temp[~ice_lines_temp['x'].isnull()].reset_index(drop=True) elif feature_type == 'numeric': feature_grids = pdp_isolate_out.feature_grids ice_lines_temp = ice_lines_temp[(ice_lines_temp[actual_columns[0]] >= feature_grids[0]) & (ice_lines_temp[actual_columns[0]] <= feature_grids[-1])] if x_quantile: ice_lines_temp['x'] = ice_lines_temp[actual_columns[0]].apply(lambda x: _find_closest(x, feature_grids)) else: ice_lines_temp['x'] = ice_lines_temp[actual_columns[0]] else: ice_lines_temp['x'] = ice_lines_temp[actual_columns[0]] ice_plot_data_pts = _sample_data(ice_lines=ice_lines_temp, frac_to_plot=frac_to_plot) _ice_plot_pts(ice_plot_data_pts=ice_plot_data_pts, ax=ax, plot_params=plot_params) std = ice_lines[feature_grids].std().values _pdp_std_plot(x=x, y=pdp_y, std=std, std_fill=std_fill, pdp_hl=pdp_hl, ax=ax, plot_params=plot_params) def _pdp_std_plot(x, y, std, std_fill, pdp_hl, ax, plot_params): """ PDP basic plot :param x: x axis values :param y: pdp values :param std: std values :param std_fill: whether to fill between std upper and lower :param pdp_hl: whether to highlight pdp line :param ax: axes to plot on :param plot_params: dictionary of plot config """ upper = y + std lower = y - std pdp_color = '#1A4E5D' pdp_hl_color = '#FEDC00' pdp_linewidth = 2 zero_color = '#E75438' zero_linewidth = 1.5 fill_color = '#66C2D7' fill_alpha = 0.2 markersize = 5 if plot_params is not None: if 'pdp_color' in plot_params.keys(): pdp_color = plot_params['pdp_color'] if 'pdp_hl_color' in plot_params.keys(): pdp_hl_color = plot_params['pdp_hl_color'] if 'pdp_linewidth' in plot_params.keys(): pdp_linewidth = plot_params['pdp_linewidth'] if 'zero_color' in plot_params.keys(): zero_color = plot_params['zero_color'] if 'zero_linewidth' in plot_params.keys(): zero_linewidth = plot_params['zero_linewidth'] if 'fill_color' in plot_params.keys(): fill_color = plot_params['fill_color'] if 'fill_alpha' in plot_params.keys(): fill_alpha = plot_params['fill_alpha'] if 'markersize' in plot_params.keys(): markersize = plot_params['markersize'] if pdp_hl: ax.plot(x, y, color=pdp_hl_color, linewidth=pdp_linewidth * 3, alpha=0.8) ax.plot(x, y, color=pdp_color, linewidth=pdp_linewidth, marker='o', markersize=markersize) ax.plot(x, [0] * y, linestyle='--', linewidth=zero_linewidth, color=zero_color) if std_fill: ax.fill_between(x, upper, lower, alpha=fill_alpha, color=fill_color) ax.set_ylim(np.min([np.min(lower) * 2, 0]), np.max([np.max(upper) * 2, 0])) def _ice_plot_pts(ice_plot_data_pts, ax, plot_params): """ Plot the real data points :param ice_plot_data_pts: data points to plot :param ax: axes to plot on :param plot_params: dictionary of plot config """ point_size = 50 point_pos_color = '#5BB573' point_neg_color = '#E75438' if plot_params is not None: if 'point_size' in plot_params.keys(): point_size = plot_params['point_size'] if 'point_pos_color' in plot_params.keys(): point_pos_color = plot_params['point_pos_color'] if 'point_neg_color' in plot_params.keys(): point_neg_color = plot_params['point_neg_color'] ice_plot_data_pts['color'] = ice_plot_data_pts['actual_preds'].apply(lambda x: point_pos_color if x >= 0 else point_neg_color) ax.scatter(ice_plot_data_pts['x'], ice_plot_data_pts['actual_preds'], s=point_size, marker="+", linewidth=1, color=ice_plot_data_pts['color']) def _ice_line_plot(x, ice_plot_data, feature_grids, ax, plot_params): """ Plot the ice lines :param x: x axis values :param ice_plot_data: ice lines to plot :param ax: axes to plot on :param plot_params: dictionary of plot config """ linewidth = np.max([1.0 / np.log10(ice_plot_data.shape[0]), 0.3]) linealpha = np.max([1.0 / np.log10(ice_plot_data.shape[0]), 0.3]) line_cmap = 'Blues' if plot_params is not None: if 'line_cmap' in plot_params.keys(): line_cmap = plot_params['line_cmap'] colors = plt.get_cmap(line_cmap)(np.linspace(0, 1, 20))[5:15] for i in range(len(ice_plot_data)): y = list(ice_plot_data[feature_grids].iloc[i].values) ax.plot(x, y, linewidth=linewidth, c=colors[i % 10], alpha=linealpha) def _ice_cluster_plot(x, ice_lines, feature_grids, n_cluster_centers, cluster_method, ax, plot_params): """ Cluster the ice lines and plot out the cluster centers :param x: x axis values :param ice_lines: ice lines :param n_cluster_centers: number of cluster centers :param cluster_method: cluster method :param ax: axes to plot on :param plot_params: dictionary of plot config """ if cluster_method == 'approx': kmeans = MiniBatchKMeans(n_clusters=n_cluster_centers, random_state=0, verbose=0) else: kmeans = KMeans(n_clusters=n_cluster_centers, random_state=0, n_jobs=1) kmeans.fit(ice_lines[feature_grids]) cluster_plot_data = pd.DataFrame(kmeans.cluster_centers_, columns=feature_grids) cluster_cmap = 'Blues' if plot_params is not None: if 'cluster_cmap' in plot_params.keys(): cluster_cmap = plot_params['cluster_cmap'] colors = plt.get_cmap(cluster_cmap)(np.linspace(0, 1, 20))[5:15] for i in range(len(cluster_plot_data)): y = list(cluster_plot_data[feature_grids].iloc[i].values) ax.plot(x, y, linewidth=1, c=colors[i % 10]) def _pdp_interact_plot_title(pdp_interact_out, feature_names, ax, multi_flag, which_class, only_inter, plot_params): """ Draw pdp interaction plot title :param pdp_interact_out: instance of pdp_interact_obj :param feature_name: name of the features :param ax: axes to plot on :param figsize: figure size :param multi_flag: whether it is a subplot of a multi-classes plot :param which_class: which class to plot :param only_inter: whether only draw interaction plot :param plot_params: values of plot parameters """ font_family = 'Arial' title = 'Interaction PDP between %s and %s' % (feature_names[0], feature_names[1]) title_fontsize = 14 subtitle_fontsize = 12 if type(pdp_interact_out) == dict: subtitle1 = 'Number of unique grid points of %s: %d' % ( feature_names[0], len(pdp_interact_out['class_0'].feature_grids[0])) subtitle2 = 'Number of unique grid points of %s: %d' % ( feature_names[1], len(pdp_interact_out['class_0'].feature_grids[1])) else: subtitle1 = 'Number of unique grid points of %s: %d' % ( feature_names[0], len(pdp_interact_out.feature_grids[0])) subtitle2 = 'Number of unique grid points of %s: %d' % ( feature_names[1], len(pdp_interact_out.feature_grids[1])) if plot_params is not None: if 'pdp_inter' in plot_params.keys(): if 'font_family' in plot_params.keys(): font_family = plot_params['font_family'] if 'title' in plot_params.keys(): title = plot_params['title'] if 'title_fontsize' in plot_params.keys(): title_fontsize = plot_params['title_fontsize'] if 'subtitle_fontsize' in plot_params.keys(): subtitle_fontsize = plot_params['subtitle_fontsize'] ax.set_facecolor('white') if only_inter: ax.text(0, 0.8, title, va="top", ha="left", fontsize=title_fontsize, fontname=font_family) if multi_flag: ax.text(0, 0.62, "For Class %d" % which_class, va="top", ha="left", fontsize=title_fontsize, fontname=font_family) ax.text(0, 0.45, subtitle1, va="top", ha="left", fontsize=subtitle_fontsize, fontname=font_family, color='grey') ax.text(0, 0.3, subtitle2, va="top", ha="left", fontsize=subtitle_fontsize, fontname=font_family, color='grey') else: ax.text(0, 0.55, subtitle1, va="top", ha="left", fontsize=subtitle_fontsize, fontname=font_family, color='grey') ax.text(0, 0.4, subtitle2, va="top", ha="left", fontsize=subtitle_fontsize, fontname=font_family, color='grey') else: ax.text(0, 0.6, title, va="top", ha="left", fontsize=title_fontsize, fontname=font_family) if multi_flag: ax.text(0, 0.53, "For Class %d" % which_class, va="top", ha="left", fontsize=title_fontsize, fontname=font_family) ax.text(0, 0.4, subtitle1, va="top", ha="left", fontsize=subtitle_fontsize, fontname=font_family, color='grey') ax.text(0, 0.35, subtitle2, va="top", ha="left", fontsize=subtitle_fontsize, fontname=font_family, color='grey') else: ax.text(0, 0.4, subtitle1, va="top", ha="left", fontsize=subtitle_fontsize, fontname=font_family, color='grey') ax.text(0, 0.35, subtitle2, va="top", ha="left", fontsize=subtitle_fontsize, fontname=font_family, color='grey') ax.axis('off') def _pdp_interact_plot(pdp_interact_out, feature_names, center, plot_org_pts, plot_lines, frac_to_plot, cluster, n_cluster_centers, cluster_method, x_quantile, figsize, plot_params, multi_flag, which_class): """ Plot interaction plot :param pdp_interact_out: instance of pdp_interact_obj a calculated pdp_interact_obj instance :param feature_names: list of feature names :param center: boolean, default=True whether to center the plot :param plot_org_pts: boolean, default=False whether to plot out the original points :param plot_lines: boolean, default=False whether to plot out the individual lines :param frac_to_plot: float or integer, default=1 how many points or lines to plot, can be a integer or a float :param cluster: boolean, default=False whether to cluster the individual lines and only plot out the cluster centers :param n_cluster_centers: integer, default=None number of cluster centers :param cluster_method: string, default=None cluster method to use, default is KMeans, if 'approx' is passed, MiniBatchKMeans is used :param x_quantile: boolean, default=False whether to construct x axis ticks using quantiles :param figsize: figure size :param plot_params: dict, default=None values of plot parameters :param multi_flag: boolean, default=False whether it is a subplot of a multi-class plot :param which_class: integer, default=None must not be None under multi-class mode """ if figsize is None: fig = plt.figure(figsize=(15, 15)) else: fig = plt.figure(figsize=figsize) pdp_plot_params = None if plot_params is not None: if 'pdp' in plot_params.keys(): pdp_plot_params = plot_params['pdp'] gs = GridSpec(2, 2) ax0 = plt.subplot(gs[0, 0]) _pdp_interact_plot_title(pdp_interact_out=pdp_interact_out, feature_names=feature_names, ax=ax0, multi_flag=multi_flag, which_class=which_class, only_inter=False, plot_params=plot_params) ax1 = plt.subplot(gs[0, 1]) _pdp_plot(pdp_isolate_out=pdp_interact_out.pdp_isolate_out1, feature_name=feature_names[0], center=center, plot_org_pts=plot_org_pts, plot_lines=plot_lines, frac_to_plot=frac_to_plot, cluster=cluster, n_cluster_centers=n_cluster_centers, cluster_method=cluster_method, x_quantile=x_quantile, ax=ax1, plot_params=pdp_plot_params) ax2 = plt.subplot(gs[1, 0]) _pdp_plot(pdp_isolate_out=pdp_interact_out.pdp_isolate_out2, feature_name=feature_names[1], center=center, plot_org_pts=plot_org_pts, plot_lines=plot_lines, frac_to_plot=frac_to_plot, cluster=cluster, n_cluster_centers=n_cluster_centers, cluster_method=cluster_method, x_quantile=x_quantile, ax=ax2, plot_params=pdp_plot_params) ax3 = plt.subplot(gs[1, 1]) _pdp_contour_plot(pdp_interact_out=pdp_interact_out, feature_names=feature_names, x_quantile=x_quantile, ax=ax3, fig=fig, plot_params=plot_params) def _pdp_contour_plot(pdp_interact_out, feature_names, x_quantile, ax, fig, plot_params): """ Plot PDP contour :param pdp_interact_out: instance of pdp_interact_obj a calculated pdp_interact_obj instance :param feature_names: list of feature names :param x_quantile: boolean, default=False whether to construct x axis ticks using quantiles :param ax: axes to plot on :param fig: plt figure :param plot_params: dict, default=None values of plot parameters """ font_family = 'Arial' contour_color = 'white' contour_cmap = 'viridis' xticks_rotation = 0 if plot_params is not None: if 'pdp_inter' in plot_params.keys(): if 'contour_color' in plot_params['pdp_inter'].keys(): contour_color = plot_params['pdp_inter']['contour_color'] if 'contour_cmap' in plot_params['pdp_inter'].keys(): contour_cmap = plot_params['pdp_inter']['contour_cmap'] if 'font_family' in plot_params['pdp_inter'].keys(): font_family = plot_params['pdp_inter']['font_family'] if 'xticks_rotation' in plot_params.keys(): xticks_rotation = plot_params['xticks_rotation'] _axes_modify(font_family, ax) feature_types = pdp_interact_out.feature_types pdp = copy.deepcopy(pdp_interact_out.pdp) new_feature_names = [] for i, feature_type in enumerate(feature_types): if feature_type == 'onehot': new_col = 'onehot_%d' % (i) pdp[new_col] = pdp.apply(lambda x: list(x[pdp_interact_out.features[i]]).index(1), axis=1) new_feature_names.append(new_col) else: new_feature_names.append(pdp_interact_out.features[i]) if (feature_types[0] == 'numeric') and x_quantile: pdp[new_feature_names[0]] = pdp[new_feature_names[0]].apply( lambda x: list(pdp_interact_out.feature_grids[0]).index(x)) if (feature_types[1] == 'numeric') and x_quantile: pdp[new_feature_names[1]] = pdp[new_feature_names[1]].apply( lambda x: list(pdp_interact_out.feature_grids[1]).index(x)) X, Y = np.meshgrid(pdp[new_feature_names[0]].unique(), pdp[new_feature_names[1]].unique()) Z = [] for i in range(X.shape[0]): zs = [] for j in range(X.shape[1]): x = X[i, j] y = Y[i, j] z = pdp[(pdp[new_feature_names[0]] == x) & (pdp[new_feature_names[1]] == y)]['preds'].values[0] zs.append(z) Z.append(zs) Z = np.array(Z) if feature_types[0] == 'onehot': ax.set_xticks(range(X.shape[1])) ax.set_xticklabels(pdp_interact_out.pdp_isolate_out1.display_columns, rotation=xticks_rotation) elif feature_types[0] == 'binary': ax.set_xticks([0, 1]) ax.set_xticklabels(pdp_interact_out.pdp_isolate_out1.display_columns, rotation=xticks_rotation) else: if x_quantile: ax.set_xticks(range(len(pdp_interact_out.feature_grids[0]))) ax.set_xticklabels(pdp_interact_out.feature_grids[0], rotation=xticks_rotation) if feature_types[1] == 'onehot': ax.set_yticks(range(Y.shape[0])) ax.set_yticklabels(pdp_interact_out.pdp_isolate_out2.display_columns) elif feature_types[1] == 'binary': ax.set_yticks([0, 1]) ax.set_yticklabels(pdp_interact_out.pdp_isolate_out2.display_columns) else: if x_quantile: ax.set_yticks(range(len(pdp_interact_out.feature_grids[1]))) ax.set_yticklabels(pdp_interact_out.feature_grids[1]) level = np.min([X.shape[0], X.shape[1]]) c1 = ax.contourf(X, Y, Z, N=level, origin='lower', cmap=contour_cmap) c2 = ax.contour(c1, levels=c1.levels, colors=contour_color, origin='lower') ax.clabel(c2, contour_label_fontsize=9, inline=1) ax.set_xlabel(feature_names[0], fontsize=10) ax.set_ylabel(feature_names[1], fontsize=10) ax.get_yaxis().tick_right() if fig is not None: cax = fig.add_axes([0, 0, 0, 0], axes_locator=ColorBarLocator(ax)) fig.colorbar(c1, cax=cax, orientation='horizontal')
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 2603, 29487, 8019, 13, 2164, 2340, 43106, 1330, 24846, 22882, 198, 198, 11748, 4866, 198,...
2.240806
9,979
import os import pytest from kodexa import Document, Pipeline, PipelineContext, TagsToKeyValuePairExtractor, RollupTransformer
[ 11748, 28686, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 479, 375, 1069, 64, 1330, 16854, 11, 37709, 11, 37709, 21947, 11, 44789, 2514, 9218, 11395, 47, 958, 11627, 40450, 11, 8299, 929, 8291, 16354, 628, 628, 628 ]
3.526316
38
"""Make containers available here.""" from .report import Report from .threat_intelligence import ThreatIntelligence from .stackdriver import StackdriverLogs
[ 37811, 12050, 16472, 1695, 994, 526, 15931, 198, 6738, 764, 13116, 1330, 6358, 198, 6738, 764, 19971, 62, 32683, 1330, 25238, 5317, 3480, 198, 6738, 764, 25558, 26230, 1330, 23881, 26230, 11187, 82, 198 ]
4.647059
34
#!/usr/bin/env python3 """Script for simulating IOT measurement stream to ModelConductor experiment.""" import pandas as pd import numpy as np import sqlalchemy as sqla from datetime import datetime as dt from time import sleep, time import logging import sys, os, asyncio from hbmqtt.client import MQTTClient, ConnectException from hbmqtt.version import get_version from docopt import docopt from hbmqtt.utils import read_yaml_config from hbmqtt.mqtt.constants import QOS_0, QOS_1, QOS_2 logger = logging.getLogger(__name__) formatter = "[%(asctime)s] :: %(levelname)s - %(message)s" logging.basicConfig(level=logging.DEBUG, format=formatter) csv_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'experiment_2019-10-03_20-37-36.csv') data = np.random.rand(100, 4) data = np.insert(data, 0, np.arange(100), axis=1) data = pd.DataFrame(data, columns =['time', 'A', 'B', 'C', 'D']) BROKER_URL = "mqtt://localhost:1883" if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 37811, 7391, 329, 985, 8306, 314, 2394, 15558, 4269, 284, 9104, 25559, 33029, 6306, 526, 15931, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, ...
2.665761
368
import sys import math L = [] f = open(sys.argv[1],"r") for item in f: L.append(item.strip()) ids = [] max_id = 0 for sequence in L: id = find_id(sequence) ids.append(id) if id > max_id: max_id = id ids.sort() old = 35 for id in ids: print(id) old = id
[ 11748, 25064, 198, 11748, 10688, 198, 198, 43, 796, 17635, 198, 69, 796, 1280, 7, 17597, 13, 853, 85, 58, 16, 17241, 81, 4943, 198, 198, 1640, 2378, 287, 277, 25, 198, 197, 43, 13, 33295, 7, 9186, 13, 36311, 28955, 198, 198, 2340,...
2.172131
122
# -*- coding: utf-8 -*- """ Injector. A partir de um arquivo binario, de uma tabela binaria gerada com o Finder, e um arquivo de substituio, o Injector capaz de injetar um texto no binario trocando o texto in-game O Injector faz automaticamente a adequao do tamanho do texto ao tamanho da caixa, truncando se maior e colocando corretamente as quebras de linha @author Yan Uehara """ from __future__ import print_function import os import sys import binascii import pickle if __name__ == '__main__': if len(sys.argv) != 4: print("Use: python extractor.py [sfc] [tbl] [substituto]") sys.exit(1) sfc = sys.argv[1] tbl = sys.argv[2] substituto = sys.argv[3] if os.path.exists(sfc) and os.path.isfile(tbl): inj = Injector(sfc, tbl, substituto) inj.run()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 37811, 201, 198, 818, 752, 273, 13, 201, 198, 201, 198, 32, 636, 343, 390, 23781, 610, 421, 23593, 9874, 4982, 11, 390, 334, 2611, 7400, 10304, 9874, 10312, 27602...
2.165816
392
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import os from spack import *
[ 2, 15069, 2211, 12, 42334, 13914, 45036, 3549, 2351, 4765, 11, 11419, 290, 584, 198, 2, 1338, 441, 4935, 34152, 13, 4091, 262, 1353, 12, 5715, 27975, 38162, 9947, 2393, 329, 3307, 13, 198, 2, 198, 2, 30628, 55, 12, 34156, 12, 33234,...
3.469697
66
import numpy as np import argparse import os.path import plots as plot from sklearn.preprocessing import StandardScaler from sklearn.grid_search import GridSearchCV import time from sklearn import svm from sklearn.metrics import classification_report from sklearn.metrics import accuracy_score from sklearn.externals import joblib from sklearn.cross_validation import StratifiedKFold # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-x", "--xTrain", required = True, help = "path to training feature set") ap.add_argument("-y", "--yTrain", required = True, help = "path to training target set") ap.add_argument("-X", "--xTest", required = True, help = "path to testing feature set") ap.add_argument("-Y", "--yTest", required = True, help = "path to testing target set") ap.add_argument("-o", "--optimize", type = int, default = 0, help = "optomization mode: 0 use default, 1 optomize, 2 use pkl model if possible") ap.add_argument("-m", "--multiClass", type = int, default=1, help = "exclusive multi class or regression") ap.add_argument("-p", "--pickle", default="models/svmModel.pkl", help = "pickle dump of model (output if optomize = 1, input if optomize = 0)") ap.add_argument("-v", "--visualize", type=int, default=0, help = "whether or not to show visualizations after a run") args = vars(ap.parse_args()) (trainX, trainY) = loadData(args["xTrain"], args["yTrain"]) (testX, testY) = loadData(args["xTest"], args["yTest"]) # required scaling for SVM trainX = standardize(trainX) testX = standardize(testX) if (args["multiClass"] == 1): trainY = convertToClasses(trainY) testY = convertToClasses(testY) # check to see if a grid search should be done if args["optimize"] == 1: #configure stratified k-fold cross validation cv = StratifiedKFold(y=trainY, n_folds=4, shuffle=True) # perform a grid search on the 'C' and 'gamma' parameter # of SVM print "SEARCHING SVM" C_range = 2. ** np.arange(-15, 15, step=1) gamma_range = 2. ** np.arange(-15, 15, step=1) param_grid = dict(gamma=gamma_range, C=C_range) start = time.time() gs = GridSearchCV(svm.SVC(), param_grid=param_grid, cv=cv, n_jobs = -1, verbose = 2) gs.fit(trainX, trainY) # print diagnostic information to the user and grab the # best model print "done in %0.3fs" % (time.time() - start) print "best score: %0.3f" % (gs.best_score_) print "SVM PARAMETERS" bestParams = gs.best_estimator_.get_params() # loop over the parameters and print each of them out # so they can be manually set print("Best Estimator: %s" % gs.best_estimator_) #for p in sorted(params.keys()): # print "\t %s: %f" % (p, bestParams[p]) print("Accuracy Score On Validation Set: %s\n" % accuracy_score(testY, gs.predict(testX))) # show a reminder message print "\nIMPORTANT" print "Now that your parameters have been searched, manually set" print "them and re-run this script with --optomize 0" joblib.dump(gs.best_estimator_, args["pickle"]) # otherwise, use the manually specified parameters else: # evaluate using SVM if (os.path.isfile(args["pickle"]) and args["optimize"] == 2): clf = joblib.load(args["pickle"]) else: clf = svm.SVC() clf.fit(trainX, trainY) print "SVM PERFORMANCE" pred = clf.predict(testX) print classification_report(testY, pred) print("Accuracy Score: %s\n" % accuracy_score(testY, pred)) if (args["visualize"] == 1): plot.accuracy(testY, pred, "SVM")
[ 11748, 299, 32152, 355, 45941, 198, 11748, 1822, 29572, 198, 11748, 28686, 13, 6978, 198, 11748, 21528, 355, 7110, 198, 6738, 1341, 35720, 13, 3866, 36948, 1330, 8997, 3351, 36213, 198, 6738, 1341, 35720, 13, 25928, 62, 12947, 1330, 24846...
2.618638
1,395
import abc import json import logging import socket import sys import time import aio_logstash import traceback from aio_logstash import constants from datetime import datetime, date class V1Formatter(BaseFormatter):
[ 11748, 450, 66, 198, 11748, 33918, 198, 11748, 18931, 198, 11748, 17802, 198, 11748, 25064, 198, 11748, 640, 198, 11748, 257, 952, 62, 6404, 301, 1077, 198, 11748, 12854, 1891, 198, 6738, 257, 952, 62, 6404, 301, 1077, 1330, 38491, 198,...
3.492063
63
# -*- coding: utf-8 -*- """Graphical monitor of Celery events using curses.""" from __future__ import absolute_import, print_function, unicode_literals import curses import sys import threading from datetime import datetime from itertools import count from textwrap import wrap from time import time from math import ceil from celery import VERSION_BANNER from celery import states from celery.app import app_or_default from celery.five import items, values from celery.utils.text import abbr, abbrtask __all__ = ['CursesMonitor', 'evtop'] BORDER_SPACING = 4 LEFT_BORDER_OFFSET = 3 UUID_WIDTH = 36 STATE_WIDTH = 8 TIMESTAMP_WIDTH = 8 MIN_WORKER_WIDTH = 15 MIN_TASK_WIDTH = 16 # this module is considered experimental # we don't care about coverage. STATUS_SCREEN = """\ events: {s.event_count} tasks:{s.task_count} workers:{w_alive}/{w_all} """ keyalias = {curses.KEY_DOWN: 'J', curses.KEY_UP: 'K', curses.KEY_ENTER: 'I'} def capture_events(app, state, display): # pragma: no cover while 1: print('-> evtop: starting capture...', file=sys.stderr) with app.connection_for_read() as conn: try: conn.ensure_connection(on_connection_error, app.conf.broker_connection_max_retries) recv = app.events.Receiver(conn, handlers={'*': state.event}) display.resetscreen() display.init_screen() recv.capture() except conn.connection_errors + conn.channel_errors as exc: print('Connection lost: {0!r}'.format(exc), file=sys.stderr) def evtop(app=None): # pragma: no cover """Start curses monitor.""" app = app_or_default(app) state = app.events.State() display = CursesMonitor(state, app) display.init_screen() refresher = DisplayThread(display) refresher.start() try: capture_events(app, state, display) except Exception: refresher.shutdown = True refresher.join() display.resetscreen() raise except (KeyboardInterrupt, SystemExit): refresher.shutdown = True refresher.join() display.resetscreen() if __name__ == '__main__': # pragma: no cover evtop()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 37065, 605, 5671, 286, 15248, 1924, 2995, 1262, 43878, 526, 15931, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 3601, 62, 8818, 11, 28000, 1098, 62, 1...
2.362319
966
"""A feature extractor for patients' utilization.""" from __future__ import absolute_import import logging import pandas as pd from sutter.lib import postgres from sutter.lib.feature_extractor import FeatureExtractor log = logging.getLogger('feature_extraction')
[ 37811, 32, 3895, 7925, 273, 329, 3871, 6, 32121, 526, 15931, 198, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 11748, 18931, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 6738, 264, 10381, 13, 8019, 1330, 1281...
3.635135
74
"""Perform normalization on inputs or rewards. """ import numpy as np import torch from gym.spaces import Box def normalize_angle(x): """Wraps input angle to [-pi, pi]. """ return ((x + np.pi) % (2 * np.pi)) - np.pi
[ 37811, 5990, 687, 3487, 1634, 319, 17311, 393, 11530, 13, 198, 198, 37811, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 198, 6738, 11550, 13, 2777, 2114, 1330, 8315, 628, 198, 4299, 3487, 1096, 62, 9248, 7, 87, 2599, 19...
2.696629
89
#!/usr/bin/python import socket import threading import sys # Support command line args import getopt # Support command line option parsing import os # Kill the application import signal # Catch an interrupt import time # Thread sleeping # Global variables definitions target = "" port = False listen = False command = "" upload = False # This tool should be able to replace netcat # The tool should be able to act as a server and as a client depending on the arguments ############################################################################### # Start menu ############################################################################### # Connect as a client ############################################################################### # Handle the connection from the client. ############################################################################### # This is the listening functionality of the program ############################################################################### # main definition ############################################################################### # Program execution try: main() except KeyboardInterrupt: print "" sys.exit(0)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 11748, 17802, 198, 11748, 4704, 278, 198, 11748, 25064, 220, 197, 197, 197, 2, 7929, 3141, 1627, 26498, 198, 11748, 651, 8738, 220, 197, 197, 2, 7929, 3141, 1627, 3038, 32096, 198, 11748...
5.063025
238
import nest import pylab as pl import pickle from nest import voltage_trace from nest import raster_plot as rplt import numpy as np from params import * seed = [np.random.randint(0, 9999999)] * num_threads calcFI() # checkConninMV()
[ 11748, 16343, 198, 11748, 279, 2645, 397, 355, 458, 198, 11748, 2298, 293, 198, 6738, 16343, 1330, 15004, 62, 40546, 198, 6738, 16343, 1330, 374, 1603, 62, 29487, 355, 374, 489, 83, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, ...
2.879518
83
import os from fastf1.core import Session, Weekend from fastf1.livetiming.data import LiveTimingData
[ 11748, 28686, 198, 198, 6738, 3049, 69, 16, 13, 7295, 1330, 23575, 11, 30537, 198, 6738, 3049, 69, 16, 13, 12583, 16514, 278, 13, 7890, 1330, 7547, 14967, 278, 6601, 628, 628 ]
3.28125
32
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 21 20:09:08 2021 ###################### ##### read h5 ######## ###################### # 1.read h5-file h5_file = h5py.File(files[1],'r') # 2.show all keys in h5-file h5_file.keys() # 3. keys in h5-file for key in h5_file.keys(): onekey = key onekey_name = h5_file[key].name # 4.group key "NN" h5_file["NN"] h5_file["NN"].keys() f_dict = dict(h5_file["NN"]) f_dict.keys() # keyword # 5. group datasets data = f_dict["data"][()] # data = f_dict["data"].value # data numpy ndarray trace = data[0] # # 6. group Int Float baz = f_dict["baz"].value baz = h5_file["NN"]["baz"].value # 7. group # encodeunicodestr2.encode(utf8)unicodestr2utf8 comp = h5_file["NN"]["comp"].value[0].decode('utf-8') # 8. f_dict.close() ###################### ##### write h5 ######## ###################### @author: yf """ #%% import numpy as np import h5py import os import glob #%% 1. set parameter file = "../../data/BJ.081_BJ.084__2020_04_11_00_00_00T2021_04_13_00_00_00__all.jld2" chan = "NN" dt = 0.005 #%% 2. read h5 # open file f = h5py.File(file,'r') # read data data = f[chan]["data"][0] # read parameters azi = f[chan]["azi"][()] baz = f[chan]["baz"][()] maxlag = f[chan]["maxlag"][()] cc_len = f[chan]["cc_len"][()] cc_step = f[chan]["cc_step"][()] corr_type = f[chan]["corr_type"][()] comp = f[chan]["comp"][()] dist = f[chan]["dist"][()] # dist = f[chan]["dist"].value lat = f[chan]["lat"][()] lon = f[chan]["lon"][()] N_glob = f[chan]["N_glob"][()] N_read = f[chan]["N_read"][()] N_good = f[chan]["N_good"][()] name = f[chan]["name"][()][0].decode('utf-8') # close h5-file f.close()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 26223, 2556, 2310, 1160, 25, 2931, 25, 2919, 33448, 198, 198, 14468, 4242, 2235, 198, 4242,...
2.142494
786
from distutils.core import setup setup( name = 'colormate', packages = ['colormate'], version = '0.2214', license='MIT', description = 'A package to theme terminal scripts with custom colors and text formatting', author = 'Rodrigo', author_email = 'roarba011@gmail.com', url = 'https://github.com/mrjakesir/themify', download_url = 'https://github.com/MrJakeSir/themify/archive/refs/tags/v_0.3.1.tar.gz', keywords = ['Colors', 'Scripting', 'Theme', 'Theming'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', ], )
[ 6738, 1233, 26791, 13, 7295, 1330, 9058, 198, 40406, 7, 198, 220, 1438, 796, 705, 4033, 579, 378, 3256, 198, 220, 10392, 796, 37250, 4033, 579, 378, 6, 4357, 198, 220, 2196, 796, 705, 15, 13, 1828, 1415, 3256, 198, 220, 5964, 11639,...
2.986301
292
import data_algebra import data_algebra.test_util from data_algebra.data_ops import * # https://github.com/WinVector/data_algebra import data_algebra.util import data_algebra.SQLite
[ 11748, 1366, 62, 282, 29230, 198, 11748, 1366, 62, 282, 29230, 13, 9288, 62, 22602, 198, 6738, 1366, 62, 282, 29230, 13, 7890, 62, 2840, 1330, 1635, 220, 1303, 3740, 1378, 12567, 13, 785, 14, 16643, 38469, 14, 7890, 62, 282, 29230, ...
3
62
from django.contrib import admin from .models import Student # Register your models here. admin.site.register(Student,StudentAdmin)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 764, 27530, 1330, 13613, 198, 198, 2, 17296, 534, 4981, 994, 13, 198, 198, 28482, 13, 15654, 13, 30238, 7, 38778, 11, 38778, 46787, 8, 628 ]
3.75
36
"""Collection of functions to run Viterbi algorithms on dipoid genotype data, where the data is structured as variants x samples.""" import numba as nb import numpy as np # https://github.com/numba/numba/issues/1269 # def forwards_viterbi_dip_naive(n, m, G, s, e, r): # # Initialise # V = np.zeros((m, n, n)) # P = np.zeros((m, n, n)).astype(np.int64) # c = np.ones(m) # index = ( # 4*np.equal(G[0,:,:], s[0,0]).astype(np.int64) + # 2*(G[0,:,:] == 1).astype(np.int64) + # np.int64(s[0,0] == 1) # ) # V[0,:,:] = 1/(n**2) * e[0,index] # r_n = r/n # for l in range(1,m): # index = ( # 4*np.equal(G[l,:,:], s[0,l]).astype(np.int64) + # 2*(G[l,:,:] == 1).astype(np.int64) + # np.int64(s[0,l] == 1) # ) # for j1 in range(n): # for j2 in range(n): # # Get the vector to maximise over # v = np.zeros((n,n)) # for k1 in range(n): # for k2 in range(n): # v[k1, k2] = V[l-1,k1, k2] # if ((k1 == j1) and (k2 == j2)): # v[k1, k2] *= ((1 - r[l])**2 + 2*(1-r[l]) * r_n[l] + r_n[l]**2) # elif ((k1 == j1) or (k2 == j2)): # v[k1, k2] *= (r_n[l] * (1 - r[l]) + r_n[l]**2) # else: # v[k1, k2] *= r_n[l]**2 # V[l,j1,j2] = np.amax(v) * e[l, index[j1, j2]] # P[l,j1,j2] = np.argmax(v) # c[l] = np.amax(V[l,:,:]) # V[l,:,:] *= 1/c[l] # ll = np.sum(np.log10(c)) # return V, P, ll # def forwards_viterbi_dip_naive_low_mem(n, m, G, s, e, r): # # Initialise # V = np.zeros((n,n)) # P = np.zeros((m,n,n)).astype(np.int64) # c = np.ones(m) # index = ( # 4*np.equal(G[0,:,:], s[0,0]).astype(np.int64) + # 2*(G[0,:,:] == 1).astype(np.int64) + # np.int64(s[0,0] == 1) # ) # V_previous = 1/(n**2) * e[0,index] # r_n = r/n # # Take a look at Haploid Viterbi implementation in Jeromes code and see if we can pinch some ideas. # # Diploid Viterbi, with smaller memory footprint. # for l in range(1,m): # index = ( # 4*np.equal(G[l,:,:], s[0,l]).astype(np.int64) + # 2*(G[l,:,:] == 1).astype(np.int64) + # np.int64(s[0,l] == 1) # ) # for j1 in range(n): # for j2 in range(n): # # Get the vector to maximise over # v = np.zeros((n,n)) # for k1 in range(n): # for k2 in range(n): # v[k1, k2] = V_previous[k1, k2] # if ((k1 == j1) and (k2 == j2)): # v[k1, k2] *= ((1 - r[l])**2 + 2*(1-r[l]) * r_n[l] + r_n[l]**2) # elif ((k1 == j1) or (k2 == j2)): # v[k1, k2] *= (r_n[l] * (1 - r[l]) + r_n[l]**2) # else: # v[k1, k2] *= r_n[l]**2 # V[j1,j2] = np.amax(v) * e[l,index[j1, j2]] # P[l,j1,j2] = np.argmax(v) # c[l] = np.amax(V) # V_previous = np.copy(V) / c[l] # ll = np.sum(np.log10(c)) # return V, P, ll # def forwards_viterbi_dip_low_mem(n, m, G, s, e, r): # # Initialise # V = np.zeros((n, n)) # P = np.zeros((m,n,n)).astype(np.int64) # index = ( # 4*np.equal(G[0,:,:], s[0,0]).astype(np.int64) + # 2*(G[0,:,:] == 1).astype(np.int64) + # np.int64(s[0,0] == 1) # ) # V_previous = 1/(n**2) * e[0,index] # c = np.ones(m) # r_n = r/n # # Diploid Viterbi, with smaller memory footprint, rescaling, and using the structure of the HMM. # for l in range(1,m): # index = ( # 4*np.equal(G[l,:,:], s[0,l]).astype(np.int64) + # 2*(G[l,:,:] == 1).astype(np.int64) + # np.int64(s[0,l] == 1) # ) # c[l] = np.amax(V_previous) # argmax = np.argmax(V_previous) # V_previous *= 1/c[l] # V_rowcol_max = np_amax(V_previous, 0) # arg_rowcol_max = np_argmax(V_previous, 0) # no_switch = (1 - r[l])**2 + 2*(r_n[l]*(1 - r[l])) + r_n[l]**2 # single_switch = r_n[l]*(1 - r[l]) + r_n[l]**2 # double_switch = r_n[l]**2 # j1_j2 = 0 # for j1 in range(n): # for j2 in range(n): # V_single_switch = max(V_rowcol_max[j1], V_rowcol_max[j2]) # P_single_switch = np.argmax(np.array([V_rowcol_max[j1], V_rowcol_max[j2]])) # if P_single_switch == 0: # template_single_switch = j1*n + arg_rowcol_max[j1] # else: # template_single_switch = arg_rowcol_max[j2]*n + j2 # V[j1,j2] = V_previous[j1,j2] * no_switch # No switch in either # P[l, j1, j2] = j1_j2 # # Single or double switch? # single_switch_tmp = single_switch * V_single_switch # if (single_switch_tmp > double_switch): # # Then single switch is the alternative # if (V[j1,j2] < single_switch * V_single_switch): # V[j1,j2] = single_switch * V_single_switch # P[l, j1, j2] = template_single_switch # else: # # Double switch is the alternative # if V[j1, j2] < double_switch: # V[j1, j2] = double_switch # P[l, j1, j2] = argmax # V[j1,j2] *= e[l, index[j1, j2]] # j1_j2 += 1 # V_previous = np.copy(V) # ll = np.sum(np.log10(c)) + np.log10(np.amax(V)) # return V, P, ll # def forwards_viterbi_dip_naive_vec(n, m, G, s, e, r): # # Initialise # V = np.zeros((m,n,n)) # P = np.zeros((m,n,n)).astype(np.int64) # c = np.ones(m) # index = ( # 4*np.equal(G[0,:,:], s[0,0]).astype(np.int64) + # 2*(G[0,:,:] == 1).astype(np.int64) + # np.int64(s[0,0] == 1) # ) # V[0,:,:] = 1/(n**2) * e[0,index] # r_n = r/n # # Jumped the gun - vectorising. # for l in range(1,m): # index = ( # 4*np.equal(G[l,:,:], s[0,l]).astype(np.int64) + # 2*(G[l,:,:] == 1).astype(np.int64) + # np.int64(s[0,l] == 1) # ) # for j1 in range(n): # for j2 in range(n): # v = (r_n[l]**2) * np.ones((n,n)) # v[j1,j2] += (1-r[l])**2 # v[j1, :] += (r_n[l] * (1 - r[l])) # v[:, j2] += (r_n[l] * (1 - r[l])) # v *= V[l-1,:,:] # V[l,j1,j2] = np.amax(v) * e[l,index[j1, j2]] # P[l,j1,j2] = np.argmax(v) # c[l] = np.amax(V[l,:,:]) # V[l,:,:] *= 1/c[l] # ll = np.sum(np.log10(c)) # return V, P, ll def forwards_viterbi_dip_naive_full_vec(n, m, G, s, e, r): """Fully vectorised naive LS diploid Viterbi algorithm using numpy.""" char_both = np.eye(n * n).ravel().reshape((n, n, n, n)) char_col = np.tile(np.sum(np.eye(n * n).reshape((n, n, n, n)), 3), (n, 1, 1, 1)) char_row = np.copy(char_col).T rows, cols = np.ogrid[:n, :n] # Initialise V = np.zeros((m, n, n)) P = np.zeros((m, n, n)).astype(np.int64) c = np.ones(m) index = ( 4 * np.equal(G[0, :, :], s[0, 0]).astype(np.int64) + 2 * (G[0, :, :] == 1).astype(np.int64) + np.int64(s[0, 0] == 1) ) V[0, :, :] = 1 / (n ** 2) * e[0, index] r_n = r / n for l in range(1, m): index = ( 4 * np.equal(G[l, :, :], s[0, l]).astype(np.int64) + 2 * (G[l, :, :] == 1).astype(np.int64) + np.int64(s[0, l] == 1) ) v = ( (r_n[l] ** 2) + (1 - r[l]) ** 2 * char_both + (r_n[l] * (1 - r[l])) * (char_col + char_row) ) v *= V[l - 1, :, :] P[l, :, :] = np.argmax(v.reshape(n, n, -1), 2) # Have to flatten to use argmax V[l, :, :] = v.reshape(n, n, -1)[rows, cols, P[l, :, :]] * e[l, index] c[l] = np.amax(V[l, :, :]) V[l, :, :] *= 1 / c[l] ll = np.sum(np.log10(c)) return V, P, ll def get_phased_path(n, path): """Obtain the phased path.""" return np.unravel_index(path, (n, n))
[ 37811, 36307, 286, 5499, 284, 1057, 569, 2676, 8482, 16113, 319, 19550, 1868, 2429, 8690, 1366, 11, 810, 262, 1366, 318, 20793, 355, 17670, 2124, 8405, 526, 15931, 198, 11748, 997, 7012, 355, 299, 65, 198, 11748, 299, 32152, 355, 45941,...
1.554081
5,501
from alembic_utils.pg_function import PGFunction from alembic_utils.replaceable_entity import register_entities from alembic_utils.testbase import TEST_VERSIONS_ROOT, run_alembic_command TO_UPPER = PGFunction( schema="public", signature="toUpper(some_text text default 'my text!')", definition=""" returns text as $$ begin return upper(some_text) || 'abc'; end; $$ language PLPGSQL; """, )
[ 6738, 31341, 2022, 291, 62, 26791, 13, 6024, 62, 8818, 1330, 350, 21713, 4575, 198, 6738, 31341, 2022, 291, 62, 26791, 13, 33491, 540, 62, 26858, 1330, 7881, 62, 298, 871, 198, 6738, 31341, 2022, 291, 62, 26791, 13, 9288, 8692, 1330, ...
2.625
168
import numpy as np np.random.seed(0) if __name__ == "__main__": main()
[ 11748, 299, 32152, 355, 45941, 198, 37659, 13, 25120, 13, 28826, 7, 15, 8, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1388, 3419, 220 ]
2.30303
33
from setuptools import setup, find_packages setup( name='passgen-py', packages=find_packages(), version='1.1', description='Generate Passwords Deterministically based on a Master Password.', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3' ], python_requires='>=3.6, <4', entry_points={ 'console_scripts': [ 'passgen=src:cli', ], }, install_requires=['click', 'pyperclip'], )
[ 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 198, 40406, 7, 198, 220, 220, 220, 1438, 11639, 6603, 5235, 12, 9078, 3256, 198, 220, 220, 220, 10392, 28, 19796, 62, 43789, 22784, 198, 220, 220, 220, 2196, 11639, 16, ...
2.472973
222
# https://codegolf.stackexchange.com/a/11480 multiplication = [] for i in range(10): multiplication.append(i * (i + 1)) for x in multiplication: print(x)
[ 2, 3740, 1378, 8189, 70, 4024, 13, 301, 330, 365, 87, 3803, 13, 785, 14, 64, 14, 16562, 1795, 198, 198, 47945, 3299, 796, 17635, 198, 1640, 1312, 287, 2837, 7, 940, 2599, 198, 220, 220, 220, 48473, 13, 33295, 7, 72, 1635, 357, 7...
2.587302
63
#!/usr/bin/env python """ Requirements: * Python >= 3.7 * Pysam Copyright (c) 2021 Dietmar Rieder <dietmar.rieder@i-med.ac.at> MIT License <http://opensource.org/licenses/MIT> """ RELEASE = False __version_info__ = ( "0", "1", ) __version__ = ".".join(__version_info__) __version__ += "-dev" if not RELEASE else "" import os import sys import argparse def _file_write(fname): """Returns an open file handle if the given filename exists.""" return open(fname, "w") def _file_read(fname): """Returns an open file handle if the given filename exists.""" return open(fname, "r") if __name__ == "__main__": usage = __doc__.split("\n\n\n") parser = argparse.ArgumentParser(description="Compile sample info sheet") parser.add_argument( "--tmb", required=True, type=_file_read, help="TMB file", ) parser.add_argument( "--tmb_coding", required=True, type=_file_read, help="TMB coding file", ) parser.add_argument( "--csin", required=True, type=_file_read, help="CSiN file", ) parser.add_argument( "--out", required=True, type=_file_write, help="Output file", ) parser.add_argument( "--sample_name", required=True, type=str, help="Sample name", ) parser.add_argument( "--version", action="version", version="%(prog)s " + __version__ ) args = parser.parse_args() tmb = args.tmb tmb_coding = args.tmb_coding csin = args.csin out = args.out sample_name = args.sample_name tmb_info = { "cov_genome": 0, "cov_coding": 0, "variants_tot": 0, "variants_coding": 0, "TMB": 0, "TMB_clonal": 0, "TMB_coding": 0, "TMB_clonal_coding": 0, } csin_info = {"MHCI": 0, "MHCII": 0, "combined": 0} tmb_info = parse_tmb(tmb, tmb_info, "all") tmb_info = parse_tmb(tmb_coding, tmb_info, "coding") csin_info = parse_csin(csin, csin_info) write_output(out, tmb_info, csin_info, sample_name) out.close()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 37811, 198, 42249, 25, 198, 220, 220, 220, 1635, 11361, 18189, 513, 13, 22, 198, 220, 220, 220, 1635, 350, 893, 321, 198, 198, 15269, 357, 66, 8, 33448, 16292, 3876, 371, 798, ...
2.089768
1,036
#!/usr/bin/env python import sys import colorama from pick_db_file import pick_db_file import db_connection import card_repository from review_cards import review_cards from new_card import new_card from new_cards import new_cards import review from user_colors import print_info, print_instruction, print_error from usage_info import print_usage_info if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 25064, 198, 11748, 3124, 1689, 198, 6738, 2298, 62, 9945, 62, 7753, 1330, 2298, 62, 9945, 62, 7753, 198, 11748, 20613, 62, 38659, 198, 11748, 2657, 62, 260, 1930, 37765, 198, 67...
3.285714
119
# Copyright 2021 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ImageNet dataset with pre-processing and augmentation. Deng, et al CVPR 2009 - ImageNet: A large-scale hierarchical image database. https://image-net.org/ """ import enum from typing import Any, Generator, Mapping, Optional, Sequence, Text, Tuple import jax import numpy as np import tensorflow.compat.v2 as tf import tensorflow_datasets as tfds import tensorflow_probability as tfp from perceiver.train import autoaugment Batch = Mapping[Text, np.ndarray] MEAN_RGB = (0.485 * 255, 0.456 * 255, 0.406 * 255) STDDEV_RGB = (0.229 * 255, 0.224 * 255, 0.225 * 255) AUTOTUNE = tf.data.experimental.AUTOTUNE INPUT_DIM = 224 # The number of pixels in the image resize. # cutmix_padding, my_cutmix, my_mixup, and my_mixup_cutmix taken from: # https://github.com/deepmind/deepmind-research/blob/master/nfnets/dataset.py def cutmix_padding(h, w): """Returns image mask for CutMix. Taken from (https://github.com/google/edward2/blob/master/experimental /marginalization_mixup/data_utils.py#L367) Args: h: image height. w: image width. """ r_x = tf.random.uniform([], 0, w, tf.int32) r_y = tf.random.uniform([], 0, h, tf.int32) # Beta dist in paper, but they used Beta(1,1) which is just uniform. image1_proportion = tf.random.uniform([]) patch_length_ratio = tf.math.sqrt(1 - image1_proportion) r_w = tf.cast(patch_length_ratio * tf.cast(w, tf.float32), tf.int32) r_h = tf.cast(patch_length_ratio * tf.cast(h, tf.float32), tf.int32) bbx1 = tf.clip_by_value(tf.cast(r_x - r_w // 2, tf.int32), 0, w) bby1 = tf.clip_by_value(tf.cast(r_y - r_h // 2, tf.int32), 0, h) bbx2 = tf.clip_by_value(tf.cast(r_x + r_w // 2, tf.int32), 0, w) bby2 = tf.clip_by_value(tf.cast(r_y + r_h // 2, tf.int32), 0, h) # Create the binary mask. pad_left = bbx1 pad_top = bby1 pad_right = tf.maximum(w - bbx2, 0) pad_bottom = tf.maximum(h - bby2, 0) r_h = bby2 - bby1 r_w = bbx2 - bbx1 mask = tf.pad( tf.ones((r_h, r_w)), paddings=[[pad_top, pad_bottom], [pad_left, pad_right]], mode='CONSTANT', constant_values=0) mask.set_shape((h, w)) return mask[..., None] # Add channel dim. def my_cutmix(batch): """Apply CutMix: https://arxiv.org/abs/1905.04899.""" batch = dict(**batch) bs = tf.shape(batch['images'])[0] // 2 mask = batch['mask'][:bs] images = (mask * batch['images'][:bs] + (1.0 - mask) * batch['images'][bs:]) mix_labels = batch['labels'][bs:] labels = batch['labels'][:bs] ratio = batch['cutmix_ratio'][:bs] return {'images': images, 'labels': labels, 'mix_labels': mix_labels, 'ratio': ratio} def my_mixup(batch): """Apply mixup: https://arxiv.org/abs/1710.09412.""" batch = dict(**batch) bs = tf.shape(batch['images'])[0] // 2 ratio = batch['mixup_ratio'][:bs, None, None, None] images = (ratio * batch['images'][:bs] + (1.0 - ratio) * batch['images'][bs:]) mix_labels = batch['labels'][bs:] labels = batch['labels'][:bs] ratio = ratio[..., 0, 0, 0] # Unsqueeze return {'images': images, 'labels': labels, 'mix_labels': mix_labels, 'ratio': ratio} def my_mixup_cutmix(batch): """Apply mixup to half the batch, and cutmix to the other.""" batch = dict(**batch) bs = tf.shape(batch['images'])[0] // 4 mixup_ratio = batch['mixup_ratio'][:bs, None, None, None] mixup_images = (mixup_ratio * batch['images'][:bs] + (1.0 - mixup_ratio) * batch['images'][bs:2*bs]) mixup_labels = batch['labels'][:bs] mixup_mix_labels = batch['labels'][bs:2*bs] cutmix_mask = batch['mask'][2*bs:3*bs] cutmix_images = (cutmix_mask * batch['images'][2*bs:3*bs] + (1.0 - cutmix_mask) * batch['images'][-bs:]) cutmix_labels = batch['labels'][2*bs:3*bs] cutmix_mix_labels = batch['labels'][-bs:] cutmix_ratio = batch['cutmix_ratio'][2*bs : 3*bs] return {'images': tf.concat([mixup_images, cutmix_images], axis=0), 'labels': tf.concat([mixup_labels, cutmix_labels], axis=0), 'mix_labels': tf.concat([mixup_mix_labels, cutmix_mix_labels], 0), 'ratio': tf.concat([mixup_ratio[..., 0, 0, 0], cutmix_ratio], axis=0)} def _to_tfds_split(split: Split) -> tfds.Split: """Returns the TFDS split appropriately sharded.""" # NOTE: Imagenet did not release labels for the test split used in the # competition, so it has been typical at DeepMind to consider the VALID # split the TEST split and to reserve 10k images from TRAIN for VALID. if split in ( Split.TRAIN, Split.TRAIN_AND_VALID, Split.VALID): return tfds.Split.TRAIN else: assert split == Split.TEST return tfds.Split.VALIDATION def _shard( split: Split, shard_index: int, num_shards: int) -> Tuple[int, int]: """Returns [start, end) for the given shard index.""" assert shard_index < num_shards arange = np.arange(split.num_examples) shard_range = np.array_split(arange, num_shards)[shard_index] start, end = shard_range[0], (shard_range[-1] + 1) if split == Split.TRAIN: # Note that our TRAIN=TFDS_TRAIN[10000:] and VALID=TFDS_TRAIN[:10000]. offset = Split.VALID.num_examples start += offset end += offset return start, end def _preprocess_image( image_bytes: tf.Tensor, is_training: bool, image_size: Sequence[int], augmentation_settings: Mapping[str, Any], ) -> Tuple[tf.Tensor, tf.Tensor]: """Returns processed and resized images.""" # Get the image crop. if is_training: image, im_shape = _decode_and_random_crop(image_bytes) image = tf.image.random_flip_left_right(image) else: image, im_shape = _decode_and_center_crop(image_bytes) assert image.dtype == tf.uint8 # Optionally apply RandAugment: https://arxiv.org/abs/1909.13719 if is_training: if augmentation_settings['randaugment'] is not None: # Input and output images are dtype uint8. image = autoaugment.distort_image_with_randaugment( image, num_layers=augmentation_settings['randaugment']['num_layers'], magnitude=augmentation_settings['randaugment']['magnitude']) # Resize and normalize the image crop. # NOTE: Bicubic resize (1) casts uint8 to float32 and (2) resizes without # clamping overshoots. This means values returned will be outside the range # [0.0, 255.0] (e.g. we have observed outputs in the range [-51.1, 336.6]). image = tf.image.resize( image, image_size, tf.image.ResizeMethod.BICUBIC) image = _normalize_image(image) return image, im_shape def _normalize_image(image: tf.Tensor) -> tf.Tensor: """Normalize the image to zero mean and unit variance.""" image -= tf.constant(MEAN_RGB, shape=[1, 1, 3], dtype=image.dtype) image /= tf.constant(STDDEV_RGB, shape=[1, 1, 3], dtype=image.dtype) return image def _distorted_bounding_box_crop( image_bytes: tf.Tensor, *, jpeg_shape: tf.Tensor, bbox: tf.Tensor, min_object_covered: float, aspect_ratio_range: Tuple[float, float], area_range: Tuple[float, float], max_attempts: int, ) -> Tuple[tf.Tensor, tf.Tensor]: """Generates cropped_image using one of the bboxes randomly distorted.""" bbox_begin, bbox_size, _ = tf.image.sample_distorted_bounding_box( jpeg_shape, bounding_boxes=bbox, min_object_covered=min_object_covered, aspect_ratio_range=aspect_ratio_range, area_range=area_range, max_attempts=max_attempts, use_image_if_no_bounding_boxes=True) # Crop the image to the specified bounding box. offset_y, offset_x, _ = tf.unstack(bbox_begin) target_height, target_width, _ = tf.unstack(bbox_size) crop_window = [offset_y, offset_x, target_height, target_width] if image_bytes.dtype == tf.dtypes.string: image = tf.image.decode_and_crop_jpeg(image_bytes, tf.stack(crop_window), channels=3) else: image = tf.image.crop_to_bounding_box(image_bytes, *crop_window) im_shape = tf.stack([target_height, target_width]) return image, im_shape def _decode_whole_image(image_bytes: tf.Tensor) -> Tuple[tf.Tensor, tf.Tensor]: image = tf.io.decode_jpeg(image_bytes, channels=3) im_shape = tf.io.extract_jpeg_shape(image_bytes, output_type=tf.int32) return image, im_shape def _decode_and_random_crop( image_bytes: tf.Tensor ) -> Tuple[tf.Tensor, tf.Tensor]: """Make a random crop of INPUT_DIM.""" if image_bytes.dtype == tf.dtypes.string: jpeg_shape = tf.image.extract_jpeg_shape(image_bytes) else: jpeg_shape = tf.shape(image_bytes) bbox = tf.constant([0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4]) image, im_shape = _distorted_bounding_box_crop( image_bytes, jpeg_shape=jpeg_shape, bbox=bbox, min_object_covered=0.1, aspect_ratio_range=(3 / 4, 4 / 3), area_range=(0.08, 1.0), max_attempts=10) if tf.reduce_all(tf.equal(jpeg_shape, tf.shape(image))): # If the random crop failed fall back to center crop. image, im_shape = _decode_and_center_crop(image_bytes, jpeg_shape) return image, im_shape def _center_crop(image, crop_dim): """Center crops an image to a target dimension.""" image_height = image.shape[0] image_width = image.shape[1] offset_height = ((image_height - crop_dim) + 1) // 2 offset_width = ((image_width - crop_dim) + 1) // 2 return tf.image.crop_to_bounding_box( image, offset_height, offset_width, crop_dim, crop_dim) def _decode_and_center_crop( image_bytes: tf.Tensor, jpeg_shape: Optional[tf.Tensor] = None, ) -> Tuple[tf.Tensor, tf.Tensor]: """Crops to center of image with padding then scales.""" if jpeg_shape is None: if image_bytes.dtype == tf.dtypes.string: jpeg_shape = tf.image.extract_jpeg_shape(image_bytes) else: jpeg_shape = tf.shape(image_bytes) image_height = jpeg_shape[0] image_width = jpeg_shape[1] padded_center_crop_size = tf.cast( ((INPUT_DIM / (INPUT_DIM + 32)) * tf.cast(tf.minimum(image_height, image_width), tf.float32)), tf.int32) offset_height = ((image_height - padded_center_crop_size) + 1) // 2 offset_width = ((image_width - padded_center_crop_size) + 1) // 2 crop_window = [offset_height, offset_width, padded_center_crop_size, padded_center_crop_size] if image_bytes.dtype == tf.dtypes.string: image = tf.image.decode_and_crop_jpeg(image_bytes, tf.stack(crop_window), channels=3) else: image = tf.image.crop_to_bounding_box(image_bytes, *crop_window) im_shape = tf.stack([padded_center_crop_size, padded_center_crop_size]) return image, im_shape
[ 2, 15069, 33448, 10766, 28478, 21852, 15302, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, ...
2.431936
4,628
import numpy as np from scipy.special import factorial from pyapprox.indexing import hash_array from pyapprox.indexing import compute_hyperbolic_level_indices def multiply_multivariate_polynomials(indices1,coeffs1,indices2,coeffs2): """ TODO: instead of using dictionary to colect terms consider using unique_indices,repeated_idx=np.unique( indices[active_idx,:],axis=1,return_inverse=True) as is done in multivariate_polynomials.conditional_moments_of_polynomial_chaos_expansion. Choose which one is faster Parameters ---------- index : multidimensional index multidimensional index specifying the polynomial degree in each dimension Returns ------- """ num_vars = indices1.shape[0] num_indices1 = indices1.shape[1] num_indices2 = indices2.shape[1] assert num_indices1==coeffs1.shape[0] assert num_indices2==coeffs2.shape[0] assert num_vars==indices2.shape[0] indices_dict = dict() max_num_indices = num_indices1*num_indices2 indices = np.empty((num_vars,max_num_indices),int) coeffs = np.empty((max_num_indices),float) kk = 0 for ii in range(num_indices1): index1 = indices1[:,ii] coeff1 = coeffs1[ii] for jj in range(num_indices2): index= index1+indices2[:,jj] key = hash_array(index) coeff = coeff1*coeffs2[jj] if key in indices_dict: coeffs[indices_dict[key]]+=coeff else: indices_dict[key]=kk indices[:,kk]=index coeffs[kk]=coeff kk+=1 indices = indices[:,:kk] coeffs = coeffs[:kk] return indices, coeffs def coeffs_of_power_of_nd_linear_polynomial(num_vars, degree, linear_coeffs): """ Compute the polynomial (coefficients and indices) obtained by raising a linear multivariate polynomial (no constant term) to some power. Parameters ---------- num_vars : integer The number of variables degree : integer The power of the linear polynomial linear_coeffs: np.ndarray (num_vars) The coefficients of the linear polynomial Returns ------- coeffs: np.ndarray (num_terms) The coefficients of the new polynomial indices : np.ndarray (num_vars, num_terms) The set of multivariate indices that define the new polynomial """ assert len(linear_coeffs)==num_vars coeffs, indices=multinomial_coeffs_of_power_of_nd_linear_polynomial( num_vars, degree) for ii in range(indices.shape[1]): index = indices[:,ii] for dd in range(num_vars): degree = index[dd] coeffs[ii] *= linear_coeffs[dd]**degree return coeffs, indices def substitute_polynomial_for_variables_in_single_basis_term( indices_in,coeffs_in,basis_index,basis_coeff,var_idx,global_var_idx, num_global_vars): """ var_idx : np.ndarray (nsub_vars) The dimensions in basis_index which will be substituted global_var_idx : [ np.ndarray(nvars[ii]) for ii in num_inputs] The index of the active variables for each input """ num_inputs = var_idx.shape[0] assert num_inputs==len(indices_in) assert num_inputs==len(coeffs_in) assert basis_coeff.shape[0]==1 assert var_idx.max()<basis_index.shape[0] assert basis_index.shape[1]==1 assert len(global_var_idx)==num_inputs # store input indices in global_var_idx temp = [] for ii in range(num_inputs): ind = np.zeros((num_global_vars,indices_in[ii].shape[1])) ind[global_var_idx,:] = indices_in[ii] temp.append(ind) indices_in = temp jj=0 degree = basis_index[var_idx[jj]] c1,ind1 = coeffs_of_power_of_polynomial( indices_in,coeffs_in[:,jj:jj+1],degree) for jj in range(1,var_idx.shape[0]): degree = basis_index[var_idx[jj]] c2,ind2 = coeffs_of_power_of_polynomial( indices_in,coeffs_in[:,jj:jj+1],degree) ind1,c1 = multiply_multivariate_polynomials(ind1,c1,ind2,c2) # this mask may be wrong. I might be confusing global and var idx mask = np.ones(basis_index.shape[0],dtype=bool); mask[var_idx]=False print(ind1.shape,mask.shape) ind1[mask,:] += basis_index[mask] c1*=basis_coeff return ind1, c1 def coeffs_of_power_of_polynomial(indices, coeffs, degree): """ Compute the polynomial (coefficients and indices) obtained by raising a multivariate polynomial to some power. TODO: Deprecate coeffs_of_power_of_nd_linear_polynomial as that function can be obtained as a special case of this function Parameters ---------- indices : np.ndarray (num_vars,num_terms) The indices of the multivariate polynomial coeffs: np.ndarray (num_vars) The coefficients of the polynomial Returns ------- coeffs: np.ndarray (num_terms) The coefficients of the new polynomial indices : np.ndarray (num_vars, num_terms) The set of multivariate indices that define the new polynomial """ num_vars, num_terms = indices.shape assert indices.shape[1]==coeffs.shape[0] multinomial_coeffs, multinomial_indices = \ multinomial_coeffs_of_power_of_nd_linear_polynomial(num_terms, degree) new_indices = np.zeros((num_vars,multinomial_indices.shape[1])) new_coeffs = np.tile(multinomial_coeffs[:,np.newaxis],coeffs.shape[1]) for ii in range(multinomial_indices.shape[1]): multinomial_index = multinomial_indices[:,ii] for dd in range(num_terms): deg = multinomial_index[dd] new_coeffs[ii] *= coeffs[dd]**deg new_indices[:,ii] += indices[:,dd]*deg return new_coeffs, new_indices def multinomial_coefficient(index): """Compute the multinomial coefficient of an index [i1,i2,...,id]. Parameters ---------- index : multidimensional index multidimensional index specifying the polynomial degree in each dimension Returns ------- coeff : double the multinomial coefficient """ level = index.sum() denom = np.prod(factorial(index)) coeff = factorial(level)/denom return coeff def multinomial_coeffs_of_power_of_nd_linear_polynomial(num_vars,degree): """ Compute the multinomial coefficients of the individual terms obtained when taking the power of a linear polynomial (without constant term). Given a linear multivariate polynomial e.g. e.g. (x1+x2+x3)**2 = x1**2+2*x1*x2+2*x1*x3+2*x2**2+x2*x3+x3**2 return the coefficients of each quadratic term, i.e. [1,2,2,1,2,1] Parameters ---------- num_vars : integer the dimension of the multivariate polynomial degree : integer the power of the linear polynomial Returns ------- coeffs: np.ndarray (num_terms) the multinomial coefficients of the polynomial obtained when raising the linear multivariate polynomial to the power=degree indices: np.ndarray (num_terms) the indices of the polynomial obtained when raising the linear multivariate polynomial to the power=degree """ indices = compute_hyperbolic_level_indices(num_vars,degree,1.0) coeffs = multinomial_coefficients(indices) return coeffs, indices def add_polynomials(indices_list, coeffs_list): """ Add many polynomials together. Example: p1 = x1**2+x2+x3, p2 = x2**2+2*x3 p3 = p1+p2 return the degrees of each term in the the polynomial p3 = x1**2+x2+3*x3+x2**2 [2, 1, 1, 2] and the coefficients of each of these terms [1., 1., 3., 1.] Parameters ---------- indices_list : list [np.ndarray (num_vars,num_indices_i)] List of polynomial indices. indices_i may be different for each polynomial coeffs_list : list [np.ndarray (num_indices_i,num_qoi)] List of polynomial coefficients. indices_i may be different for each polynomial. num_qoi must be the same for each list element. Returns ------- indices: np.ndarray (num_vars,num_terms) the polynomial indices of the polynomial obtained from summing the polynomials. This will be the union of the indices of the input polynomials coeffs: np.ndarray (num_terms,num_qoi) the polynomial coefficients of the polynomial obtained from summing the polynomials """ num_polynomials = len(indices_list) assert num_polynomials==len(coeffs_list) indices_dict = dict() indices = [] coeff = [] ii=0; kk=0 for jj in range(indices_list[ii].shape[1]): assert coeffs_list[ii].ndim==2 assert coeffs_list[ii].shape[0]==indices_list[ii].shape[1] index=indices_list[ii][:,jj] indices_dict[hash_array(index)]=kk indices.append(index) coeff.append(coeffs_list[ii][jj,:].copy()) kk+=1 for ii in range(1,num_polynomials): #print indices_list[ii].T,num_polynomials assert coeffs_list[ii].ndim==2 assert coeffs_list[ii].shape[0]==indices_list[ii].shape[1] for jj in range(indices_list[ii].shape[1]): index=indices_list[ii][:,jj] key = hash_array(index) if key in indices_dict: nn = indices_dict[key] coeff[nn]+=coeffs_list[ii][jj,:] else: indices_dict[key]=kk indices.append(index) coeff.append(coeffs_list[ii][jj,:].copy()) kk+=1 indices = np.asarray(indices).T coeff = np.asarray(coeff) return indices, coeff def get_indices_double_set(indices): """ Given muultivariate indices [i1,i2,...,] Compute its double set by [i1*i1,i1*i2,...,i2*i2,i2*i3...] The double set will only contain unique indices Parameters ---------- indices : np.ndarray (num_vars,num_indices) The initial indices Returns ------- double_set_indices : np.ndarray (num_vars,num_indices) The double set of indices """ dummy_coeffs = np.zeros(indices.shape[1]) double_set_indices = multiply_multivariate_polynomials( indices,dummy_coeffs,indices,dummy_coeffs)[0] return double_set_indices #Some of these functions can be replaced by numpy functions described at #https://docs.scipy.org/doc/numpy/reference/routines.polynomials.polynomial.html
[ 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 13, 20887, 1330, 1109, 5132, 198, 6738, 12972, 1324, 13907, 13, 9630, 278, 1330, 12234, 62, 18747, 198, 6738, 12972, 1324, 13907, 13, 9630, 278, 1330, 24061, 62, 49229, 65, 4160, ...
2.270166
4,649
# -------------------------------------------------------- # mcan-vqa (Deep Modular Co-Attention Networks) # Licensed under The MIT License [see LICENSE for details] # Written by Yuhao Cui https://github.com/cuiyuhao1996 # -------------------------------------------------------- import h5py import pickle import random import numpy as np from numpy.random import default_rng import pandas as pd import glob, json, torch, time from torch.utils.data import Dataset, DataLoader from core.data.data_utils import img_feat_path_load, img_feat_load, ques_load, tokenize, ans_stat from core.data.data_utils import pad_img_feat, proc_ques, proc_ans, proc_mimic_ans
[ 2, 20368, 22369, 198, 2, 285, 5171, 12, 85, 20402, 357, 29744, 3401, 934, 1766, 12, 8086, 1463, 27862, 8, 198, 2, 49962, 739, 383, 17168, 13789, 685, 3826, 38559, 24290, 329, 3307, 60, 198, 2, 22503, 416, 10605, 23778, 327, 9019, 37...
3.55914
186
from .database import Db from .initiatives import InitiativeBase, Platform, ImportBatch, InitiativeImport, BatchImportState, InitiativeGroup
[ 6738, 764, 48806, 1330, 360, 65, 198, 6738, 764, 259, 8846, 2929, 1330, 18362, 14881, 11, 19193, 11, 17267, 33, 963, 11, 18362, 20939, 11, 347, 963, 20939, 9012, 11, 18362, 13247 ]
4.375
32
# -*- coding: utf-8 -*- # # Copyright Spyder Project Contributors # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) """ Widget that handles communications between a console in debugging mode and Spyder """ import ast from qtpy.QtCore import Qt from qtconsole.rich_jupyter_widget import RichJupyterWidget
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 220, 23688, 1082, 4935, 25767, 669, 198, 2, 49962, 739, 262, 2846, 286, 262, 17168, 13789, 198, 2, 357, 3826, 13997, 1082, 14, 834, 15003, 834, 13, ...
3.194444
108
from .string import <caret>
[ 6738, 764, 8841, 1330, 1279, 6651, 83, 29 ]
3.375
8
import numpy as np import sklearn.metrics from dataset_chunking_fxns import subsample_df_by_groups import sklearn import sklearn.linear_model from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler import time # learning function: logistic regression multi-class # learning function: logistic regression
[ 11748, 299, 32152, 355, 45941, 198, 11748, 1341, 35720, 13, 4164, 10466, 198, 6738, 27039, 62, 354, 2954, 278, 62, 21373, 5907, 1330, 6352, 1403, 62, 7568, 62, 1525, 62, 24432, 198, 11748, 1341, 35720, 198, 11748, 1341, 35720, 13, 29127...
3.790909
110
""" PSET-7 Part 2: Triggers (PhraseTriggers) At this point, you have no way of writing a trigger that matches on "New York City" -- the only triggers you know how to write would be a trigger that would fire on "New" AND "York" AND "City" -- which also fires on the phrase "New students at York University love the city". It's time to fix this. Since here you're asking for an exact match, we will require that the cases match, but we'll be a little more flexible on word matching. So, "New York City" will match: * New York City sees movie premiere * In the heart of New York City's famous cafe * New York Cityrandomtexttoproveapointhere but will not match: * I love new york city * I love New York City!!!!!!!!!!!!!! PROBLEM 9 Implement a phrase trigger (PhraseTrigger) that fires when a given phrase is in any of the story's subject, title, or summary. The phrase should be an argument to the class's constructor. """ # Enter your code for WordTrigger, TitleTrigger, # SubjectTrigger, SummaryTrigger, and PhraseTrigger in this box
[ 37811, 198, 3705, 2767, 12, 22, 198, 7841, 362, 25, 833, 328, 5355, 357, 2725, 22789, 2898, 328, 5355, 8, 198, 198, 2953, 428, 966, 11, 345, 423, 645, 835, 286, 3597, 257, 7616, 326, 7466, 319, 220, 198, 1, 3791, 1971, 2254, 1, ...
3.304878
328
# -*- coding: utf-8 -*- from unittest import TestCase from mock import Mock, patch from vault.tests.fakes import fake_request from vault.views import SetProjectView from django.utils.translation import ugettext as _
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 555, 715, 395, 1330, 6208, 20448, 198, 6738, 15290, 1330, 44123, 11, 8529, 198, 198, 6738, 22563, 13, 41989, 13, 69, 1124, 1330, 8390, 62, 25927, 198, 6738, ...
3.318182
66
from tasks.cephfs.cephfs_test_case import CephFSTestCase import random import os
[ 6738, 8861, 13, 344, 746, 9501, 13, 344, 746, 9501, 62, 9288, 62, 7442, 1330, 327, 27446, 37, 2257, 395, 20448, 198, 11748, 4738, 198, 11748, 28686, 198 ]
2.892857
28
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BOARD) control_pins = [7,11,13,15] for pin in control_pins: GPIO.setup(pin, GPIO.OUT) GPIO.output(pin, 0) halfstep_seq = [ [1,0,0,0], [1,1,0,0], [0,1,0,0], [0,1,1,0], [0,0,1,0], [0,0,1,1], [0,0,0,1], [1,0,0,1] ] # speed from 0 to 1 (one being the fastest) # steps 50 steps = one rotation for k in range(1,10,1): move_forward(50,0.1) time.sleep(0.5) #move_forward(50,0.25) time.sleep(1) #move_backward(500,0.5) GPIO.cleanup()
[ 198, 198, 11748, 25812, 72, 13, 16960, 9399, 355, 50143, 198, 11748, 640, 198, 198, 16960, 9399, 13, 2617, 14171, 7, 16960, 9399, 13, 8202, 9795, 8, 198, 13716, 62, 49556, 796, 685, 22, 11, 1157, 11, 1485, 11, 1314, 60, 198, 198, ...
1.903346
269
import numpy as np import cv2 import os import math os.system("fswebcam -r 507x456 --no-banner image11.jpg") img = cv2.imread('image11.jpg',-1) height, width, channel = img.shape topy= height topx = width hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) lower_color = np.array([0,255,255]) upper_color = np.array([0,255,255]) mask = cv2.inRange(hsv, lower_color, upper_color) res = cv2.bitwise_and(img,img, mask=mask) '''def draw_circle(event, x, y, flags, param): if event == cv2.EVENT_LBUTTONDBLCLK: cv2.circle(img, (x,y), 100, (255,255,255), -1)''' '''cap = cv2.VideoCapture(-1) while(True): ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow('hjhj', gray) if cv2.waitKey(0) & 0xFF -- ord('q'): break cap.release() cv2.destroyAllWindows()''' propx = (topx/512) propy = (topy/512) '''lineX1 = int(0*propx) lineY2 = int(0*propy) lineX2 = int(511*propx) lineY1 = int(511*propy) img = cv2.line(img, (lineX1,lineY1), (lineX2, lineY2), (255,255,255), 5)''' w = 100*(propx+propy)/2 x1 = int(topx/2 - w/2) x2 = int(topx/2 + w/2) y1 = int(topy/2 + w/2) y2 = int(topy/2 - w/2) img = cv2.rectangle(res, (x1,y1), (x2,y2), (0,255,0),3) img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) showImage(img) ret, thresh = cv2.threshold(img, 15, 250, 0) showImage(thresh) image, contours, heirarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) #showImage(image) cv2.drawContours(img, contours, 0, (0,255,0), 3) showImage(img) print('Num of Contours ', len(contours)) cnt = contours[0] M = cv2.moments(cnt) print (M) cx = int(M['m10']/M['m00']) cy = int(M['m01']/M['m00']) area = cv2.contourArea(cnt) print (cx) print (cy) print (area) '''xCircle = 40*propx xCircle = int(xCircle) yCircle = xCircle radCircle = xCircle img = cv2.circle(img, (xCircle, yCircle), radCircle, (0,0,255),-1) x3 = int(topx - 60*propx) y3 = int(topy - 110*propy) minAx = int(50*propx) majAx = int(100*propy) img = cv2.ellipse(img, (x3, y3), (minAx,majAx), 0, 0, 360, (0,150,255), -1)''' '''pt1X = int(70*propx) pt1Y = int(60*propy) pt2X = int(154*propx) pt2Y = int(23*propy) pt3X = int(500*propx) pt3Y = int(3*propy)''' #pts = np.array([[pt1X, pt1Y], [pt2X, pt2Y], [pt3X, pt3Y]], np.int32) #pts = pts.reshape((-1,1,2)) #img = cv2.polylines(img, [pts], True, (100,100,234)) #font = cv2.FONT_HERSHEY_SIMPLEX #startPtX = int(240*propx) #startPtY = int(240*propy) #scale = 2*(propx + propy)/2 #cv2.putText(img, 'Apurva', (startPtX, startPtY), font, scale, (210, 80, 150), 4, cv2.LINE_AA) #cv2.imshow("kl", img) '''cv2.setMouseCallback('kl', draw_circle)''' '''''' #cv2.imshow('frame', img) #cv2.imshow('mask',mask) cv2.imshow('res',res) '''sd = img[130:200, 175:245] img[20:90, 140:210]=sd cv2.imshow("kl", img)''' cv2.waitKey(0) cv2.destroyAllWindows()
[ 11748, 299, 32152, 355, 45941, 198, 11748, 269, 85, 17, 198, 11748, 28686, 198, 11748, 10688, 198, 418, 13, 10057, 7203, 9501, 12384, 20991, 532, 81, 2026, 22, 87, 29228, 1377, 3919, 12, 3820, 1008, 2939, 1157, 13, 9479, 4943, 198, 19...
1.965877
1,436
from django.conf.urls import include from django.http import HttpResponseRedirect from django.urls import re_path from Poem.poem_super_admin.admin import mysuperadmin urlpatterns = [ re_path(r'^$', lambda x: HttpResponseRedirect('/poem/superadmin/')), re_path(r'^superadmin/', mysuperadmin.urls), re_path(r'^saml2/', include(('djangosaml2.urls', 'poem'), namespace='saml2')), ]
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 2291, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 31077, 7738, 1060, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 302, 62, 6978, 198, 198, 6738, 7695, 368, 13, 7501, 368, 62,...
2.291892
185
import json from optimism.JaxConfig import * from optimism import Mesh
[ 11748, 33918, 198, 198, 6738, 24323, 13, 41, 897, 16934, 1330, 1635, 198, 6738, 24323, 1330, 47529, 628 ]
4.055556
18
# -*- coding: utf-8 -*- """ Ramsey numbers. """ # Copyright (C) 2011 by # Nicholas Mancuso <nick.mancuso@gmail.com> # All rights reserved. # BSD license. import networkx as nx from ...utils import arbitrary_element __all__ = ["ramsey_R2"] __author__ = """Nicholas Mancuso (nick.mancuso@gmail.com)""" def ramsey_R2(G): r"""Approximately computes the Ramsey number `R(2;s,t)` for graph. Parameters ---------- G : NetworkX graph Undirected graph Returns ------- max_pair : (set, set) tuple Maximum clique, Maximum independent set. """ if not G: return set(), set() node = arbitrary_element(G) nbrs = nx.all_neighbors(G, node) nnbrs = nx.non_neighbors(G, node) c_1, i_1 = ramsey_R2(G.subgraph(nbrs).copy()) c_2, i_2 = ramsey_R2(G.subgraph(nnbrs).copy()) c_1.add(node) i_2.add(node) # Choose the larger of the two cliques and the larger of the two # independent sets, according to cardinality. return max(c_1, c_2, key=len), max(i_1, i_2, key=len)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 33754, 4397, 3146, 13, 198, 37811, 198, 2, 220, 220, 15069, 357, 34, 8, 2813, 416, 198, 2, 220, 220, 20320, 337, 1192, 385, 78, 1279, 17172, 13, 805, 904...
2.310044
458
"""Linux-specific code""" from pysyte.types import paths def xdg_home(): """path to $XDG_CONFIG_HOME >>> assert xdg_home() == paths.path('~/.config').expand() """ return paths.environ_path("XDG_CONFIG_HOME", "~/.config") def xdg_home_config(filename): """path to that file in $XDG_CONFIG_HOME >>> assert xdg_home_config('fred') == paths.path('~/.config/fred').expand() """ return xdg_home() / filename def xdg_dirs(): """paths in $XDG_CONFIG_DIRS""" return paths.environ_paths("XDG_CONFIG_DIRS") bash_paste = "xclip -selection clipboard" bash_copy = "xclip -selection clipboard -o"
[ 37811, 19314, 12, 11423, 2438, 37811, 628, 198, 6738, 279, 893, 88, 660, 13, 19199, 1330, 13532, 628, 198, 4299, 2124, 67, 70, 62, 11195, 33529, 198, 220, 220, 220, 37227, 6978, 284, 720, 55, 35, 38, 62, 10943, 16254, 62, 39069, 628...
2.46124
258
import mpv import keyboard import time p = mpv.MPV() p.play("song_name.mp4") keyboard.add_hotkey("e", play_pause) keyboard.add_hotkey("2", full) keyboard.add_hotkey("1", go_to_start) while 1: time.sleep(40)
[ 11748, 29034, 85, 201, 198, 11748, 10586, 201, 198, 11748, 640, 201, 198, 201, 198, 79, 796, 29034, 85, 13, 7378, 53, 3419, 201, 198, 201, 198, 79, 13, 1759, 7203, 34050, 62, 3672, 13, 3149, 19, 4943, 201, 198, 201, 198, 201, 198,...
1.975806
124
# Copyright (c) 2010-2011 OpenStack, LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. """ Tests for swift.common.db """ from __future__ import with_statement import hashlib import os import unittest from shutil import rmtree, copy from StringIO import StringIO from time import sleep, time from uuid import uuid4 import simplejson import sqlite3 import swift.common.db from swift.common.db import AccountBroker, chexor, ContainerBroker, \ DatabaseBroker, DatabaseConnectionError, dict_factory, get_db_connection from swift.common.utils import normalize_timestamp from swift.common.exceptions import LockTimeout def premetadata_create_container_stat_table(self, conn, put_timestamp=None): """ Copied from swift.common.db.ContainerBroker before the metadata column was added; used for testing with TestContainerBrokerBeforeMetadata. Create the container_stat table which is specifc to the container DB. :param conn: DB connection object :param put_timestamp: put timestamp """ if put_timestamp is None: put_timestamp = normalize_timestamp(0) conn.executescript(""" CREATE TABLE container_stat ( account TEXT, container TEXT, created_at TEXT, put_timestamp TEXT DEFAULT '0', delete_timestamp TEXT DEFAULT '0', object_count INTEGER, bytes_used INTEGER, reported_put_timestamp TEXT DEFAULT '0', reported_delete_timestamp TEXT DEFAULT '0', reported_object_count INTEGER DEFAULT 0, reported_bytes_used INTEGER DEFAULT 0, hash TEXT default '00000000000000000000000000000000', id TEXT, status TEXT DEFAULT '', status_changed_at TEXT DEFAULT '0' ); INSERT INTO container_stat (object_count, bytes_used) VALUES (0, 0); """) conn.execute(''' UPDATE container_stat SET account = ?, container = ?, created_at = ?, id = ?, put_timestamp = ? ''', (self.account, self.container, normalize_timestamp(time()), str(uuid4()), put_timestamp)) def prexsync_create_container_stat_table(self, conn, put_timestamp=None): """ Copied from swift.common.db.ContainerBroker before the x_container_sync_point[12] columns were added; used for testing with TestContainerBrokerBeforeXSync. Create the container_stat table which is specifc to the container DB. :param conn: DB connection object :param put_timestamp: put timestamp """ if put_timestamp is None: put_timestamp = normalize_timestamp(0) conn.executescript(""" CREATE TABLE container_stat ( account TEXT, container TEXT, created_at TEXT, put_timestamp TEXT DEFAULT '0', delete_timestamp TEXT DEFAULT '0', object_count INTEGER, bytes_used INTEGER, reported_put_timestamp TEXT DEFAULT '0', reported_delete_timestamp TEXT DEFAULT '0', reported_object_count INTEGER DEFAULT 0, reported_bytes_used INTEGER DEFAULT 0, hash TEXT default '00000000000000000000000000000000', id TEXT, status TEXT DEFAULT '', status_changed_at TEXT DEFAULT '0', metadata TEXT DEFAULT '' ); INSERT INTO container_stat (object_count, bytes_used) VALUES (0, 0); """) conn.execute(''' UPDATE container_stat SET account = ?, container = ?, created_at = ?, id = ?, put_timestamp = ? ''', (self.account, self.container, normalize_timestamp(time()), str(uuid4()), put_timestamp)) def premetadata_create_account_stat_table(self, conn, put_timestamp): """ Copied from swift.common.db.AccountBroker before the metadata column was added; used for testing with TestAccountBrokerBeforeMetadata. Create account_stat table which is specific to the account DB. :param conn: DB connection object :param put_timestamp: put timestamp """ conn.executescript(""" CREATE TABLE account_stat ( account TEXT, created_at TEXT, put_timestamp TEXT DEFAULT '0', delete_timestamp TEXT DEFAULT '0', container_count INTEGER, object_count INTEGER DEFAULT 0, bytes_used INTEGER DEFAULT 0, hash TEXT default '00000000000000000000000000000000', id TEXT, status TEXT DEFAULT '', status_changed_at TEXT DEFAULT '0' ); INSERT INTO account_stat (container_count) VALUES (0); """) conn.execute(''' UPDATE account_stat SET account = ?, created_at = ?, id = ?, put_timestamp = ? ''', (self.account, normalize_timestamp(time()), str(uuid4()), put_timestamp)) if __name__ == '__main__': unittest.main()
[ 2, 15069, 357, 66, 8, 3050, 12, 9804, 4946, 25896, 11, 11419, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, ...
2.539461
2,154
import os import pytest from robocorp_ls_core.protocols import IConfigProvider from robocorp_ls_core.robotframework_log import get_logger from robocorp_ls_core.unittest_tools.cases_fixture import CasesFixture from robocorp_code.protocols import IRcc, ActionResult import sys from typing import Any from pathlib import Path from robocorp_code_tests.protocols import IRobocorpLanguageServerClient log = get_logger(__name__) IMAGE_IN_BASE64 = "iVBORw0KGgoAAAANSUhEUgAAAb8AAAAiCAYAAADPnNdbAAAAAXNSR0IArs4c6QAAAJ1JREFUeJzt1TEBACAMwDDAv+fhAo4mCvp1z8wsAAg5vwMA4DXzAyDH/ADIMT8AcswPgBzzAyDH/ADIMT8AcswPgBzzAyDH/ADIMT8AcswPgBzzAyDH/ADIMT8AcswPgBzzAyDH/ADIMT8AcswPgBzzAyDH/ADIMT8AcswPgBzzAyDH/ADIMT8AcswPgBzzAyDH/ADIMT8AcswPgJwLXQ0EQMJRx4AAAAAASUVORK5CYII=" _WS_INFO = ( { "id": "workspace_id_1", "name": "CI workspace", "orgId": "affd282c8f9fe", "orgName": "My Org Name", "orgShortName": "654321", "shortName": "123456", # Can be some generated number or something provided by the user. "state": "active", "url": "http://url1", }, { "id": "workspace_id_2", "name": "My Other workspace", "orgId": "affd282c8f9fe", "orgName": "My Org Name", "orgShortName": "1234567", "shortName": "7654321", "state": "active", "url": "http://url2", }, ) _PACKAGE_INFO_WS_2: dict = {} _PACKAGE_INFO_WS_1: dict = { "activities": [ {"id": "452", "name": "Package Name 1"}, {"id": "453", "name": "Package Name 2"}, ] }
[ 11748, 28686, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 3857, 420, 16300, 62, 7278, 62, 7295, 13, 11235, 4668, 82, 1330, 314, 16934, 29495, 198, 6738, 3857, 420, 16300, 62, 7278, 62, 7295, 13, 305, 13645, 30604, 62, 6404, 1330, 65...
2.061278
767
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Abstract Base Class for quantize emulation in custom keras layers.""" import abc import six
[ 2, 15069, 2864, 383, 309, 22854, 37535, 46665, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, ...
4.248649
185
import os import re import string import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from GEN_Utils import FileHandling from loguru import logger logger.info("Import OK") # Set sample-specific variables input_path = 'examples/python/gauss_models/' output_path = 'examples/python/phase_plotting/' plate_sample = ['TPE only', '1', '1.5', '2', '3', '4']*4 plate_cords = [f'{x}{y}' for x in string.ascii_uppercase[0:4] for y in range(1, 7)] sample_map = dict(zip(plate_cords, plate_sample)) if not os.path.exists(output_path): os.mkdir(output_path) # Read in summary df and preview summary = pd.read_excel(f'{input_path}summary.xlsx') # Assign sample-specific descriptors to summary table summary['plate'] = summary['sample'].str[0] summary['well'] = summary['sample'].str[1:] summary['sample'] = summary['well'].map(sample_map) phase_name = ['G', 'S', 'M'] phase_num = [1, 2, 3] phase_map = dict(zip(phase_name, phase_num)) # Generate line-plot fig = plt.subplots() for phase in phase_name: sns.lineplot(summary['sample'], summary[phase], label=phase, ci='sd') plt.ylabel("Proportion of cells in phase") plt.xlabel(r'Density(x 10$^ 5$)') plt.title('Phase distribution') plt.legend(bbox_to_anchor=(1.1, 1.0), title='Phase') plt.tight_layout() plt.autoscale() plt.savefig(f'{output_path}line_plot.png')
[ 11748, 28686, 198, 11748, 302, 198, 11748, 4731, 198, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 384, 397, 1211, 355, 3013, 82, 1...
2.542593
540
# -------------------------------------------------------------------------------------------------- # Copyright (c) 2018 Microsoft Corporation # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and # associated documentation files (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, publish, distribute, # sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all copies or # substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT # NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -------------------------------------------------------------------------------------------------- """Module containing explorer classes""" from numpy import random as np_random from .summaries import ScalarSummary from .triggers import each_step from .abc import Explorer, EpsilonFunction, Visualizable
[ 2, 16529, 3880, 438, 198, 2, 220, 15069, 357, 66, 8, 2864, 5413, 10501, 198, 2, 198, 2, 220, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 286, 428, 3788, 290, 198, 2, 220, 3917, 10314, ...
4.318182
352
# Standard imports import sys # Project imports from icecreamscrape.cli import cli from icecreamscrape.webdriver import driver_factory from icecreamscrape import composites as comps from icecreamscrape.composites import create_timestamped_dir def main(args=sys.argv[1:]): """ Main function. :param: args is used for testing """ user_inputs = cli(args) url = user_inputs.params.url active_features = user_inputs.active_features if len(active_features) > 0: time_dir = create_timestamped_dir() with driver_factory(url) as driver: for feature in active_features: getattr(sys.modules[comps.__name__], feature)(driver, time_dir) def init(): """ Init construction allows for testing """ if __name__ == "__main__": sys.exit(main()) init()
[ 2, 8997, 17944, 198, 11748, 25064, 198, 198, 2, 4935, 17944, 198, 6738, 4771, 36277, 1416, 13484, 13, 44506, 1330, 537, 72, 198, 6738, 4771, 36277, 1416, 13484, 13, 12384, 26230, 1330, 4639, 62, 69, 9548, 198, 6738, 4771, 36277, 1416, ...
2.931034
261
# pylint: skip-file # type: ignore # -*- coding: utf-8 -*- # # tests.controllers.mission.mission_unit_test.py is part of The # RAMSTK Project # # All rights reserved. # Copyright since 2007 Doyle "weibullguy" Rowland doyle.rowland <AT> reliaqual <DOT> com """Test class for testing Mission module algorithms and models.""" # Third Party Imports import pytest from pubsub import pub from treelib import Tree # RAMSTK Package Imports from ramstk.models.dbrecords import RAMSTKMissionRecord from ramstk.models.dbtables import RAMSTKMissionTable from tests import ( MockDAO, UnitTestDeleteMethods, UnitTestGetterSetterMethods, UnitTestInsertMethods, UnitTestSelectMethods, )
[ 2, 279, 2645, 600, 25, 14267, 12, 7753, 198, 2, 2099, 25, 8856, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 220, 220, 220, 220, 220, 220, 5254, 13, 3642, 36667, 13, 3411, 13, 3411, 62, 20850,...
2.921811
243
#!/usr/bin/env python from .error import FLVError from .compat import is_py2 from .tag import Header, Tag __all__ = ["FLV"]
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 764, 18224, 1330, 9977, 6089, 81, 1472, 198, 6738, 764, 5589, 265, 1330, 318, 62, 9078, 17, 198, 6738, 764, 12985, 1330, 48900, 11, 17467, 628, 198, 198, 834, 439, 834, 79...
2.666667
48
from pheasant.renderers.jupyter.jupyter import Jupyter jupyter = Jupyter() jupyter.findall("{{3}}3{{5}}") jupyter.page
[ 6738, 279, 258, 8775, 13, 10920, 19288, 13, 73, 929, 88, 353, 13, 73, 929, 88, 353, 1330, 449, 929, 88, 353, 198, 198, 73, 929, 88, 353, 796, 449, 929, 88, 353, 3419, 198, 73, 929, 88, 353, 13, 19796, 439, 7203, 27007, 18, 117...
2.033898
59
#!/usr/bin/env python3 import json from http.server import HTTPServer, BaseHTTPRequestHandler num_requests = 0 if __name__ == "__main__": http_service = HTTPServer(("0.0.0.0", 8000), Handler) print(f"Starting http service on 0.0.0.0:8000") http_service.serve_forever()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 33918, 198, 6738, 2638, 13, 15388, 1330, 38288, 18497, 11, 7308, 40717, 18453, 25060, 198, 198, 22510, 62, 8897, 3558, 796, 657, 628, 198, 361, 11593, 3672, 834, 6624, 366, ...
2.679245
106
from app.app import create_app from config import BaseConfig app = create_app(BaseConfig)
[ 6738, 598, 13, 1324, 1330, 2251, 62, 1324, 198, 6738, 4566, 1330, 7308, 16934, 198, 198, 1324, 796, 2251, 62, 1324, 7, 14881, 16934, 8, 198 ]
3.5
26
""" Create data for simulations (c) 2019 - EggdraSyl """ import json # from mockup import Blockchain, Block from minersimulator import MinerSimulator from math import sin, pi SPECIAL_MIN_TIME = 5 * 60 if __name__ == "__main__": init_stable( 0, 1000, block_time=3600, target="0000000000000028acfa28a803d2000000000000000000000000000000000000", file="stable_3600_14.json", ) init_stable( 0, 1000, block_time=60 * 5, target="000000ffffffffff28acfa28a803d20000000000000000000000000000000000", file="stable_300_6.json", ) init_stable( 0, 1000, block_time=60 * 5, target="00000ffffffffff28acfa28a803d200000000000000000000000000000000000", file="stable_300_5.json", ) init_stable( 0, 1000, block_time=60 * 5, target="0000ffffffffff28acfa28a803d2000000000000000000000000000000000000", file="stable_300_4.json", ) init_stable( 0, 1000, block_time=60 * 5, target="000ffffffffff28acfa28a803d2000000000000000000000000000000000000", file="stable_300_3.json", ) hash_stable(10000, 167, file="stable_167.json") hash_stable(10000, 1670, file="stable_1670.json") hash_stable(10000, 16700, file="stable_16700.json") hash_arithmetic(10000, 167, 16, file="arithmetic_167_16.json") hash_step(10000, 167, 500, file="step_up_167_500.json") hash_step(10000, 500, 167, file="step_down_500_167.json") hash_sinus(10000, 300, 150, 60*12, file="sinus_300_150_720.json") hash_sinus(10000, 300, 100, 1440, file="sinus_300_100_1440.json") hash_sinus(10000, 300, 100, 2880, file="sinus_300_100_2880.json")
[ 37811, 198, 16447, 1366, 329, 27785, 198, 7, 66, 8, 13130, 532, 14562, 32491, 50, 2645, 198, 37811, 198, 198, 11748, 33918, 198, 198, 2, 422, 15290, 929, 1330, 29724, 11, 9726, 198, 6738, 18295, 320, 8927, 1330, 29295, 8890, 8927, 198...
2.271907
776
# This file is part of Pynguin. # # Pynguin is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Pynguin is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Pynguin. If not, see <https://www.gnu.org/licenses/>. from unittest import mock from unittest.mock import MagicMock import pytest import pynguin.configuration as config import pynguin.testcase.defaulttestcase as dtc import pynguin.testcase.statements.primitivestatements as prim import pynguin.testcase.testcase as tc import pynguin.testcase.variable.variablereferenceimpl as vri def test_none_statement_equals_clone(): test_case = MagicMock(tc.TestCase) statement = prim.NoneStatement(test_case, type(None)) test_case.statements = [statement] test_case2 = MagicMock(tc.TestCase) clone = statement.clone(test_case2) test_case2.statements = [clone] assert statement.__eq__(clone)
[ 2, 770, 2393, 318, 636, 286, 9485, 782, 48441, 13, 198, 2, 198, 2, 9485, 782, 48441, 318, 1479, 3788, 25, 345, 460, 17678, 4163, 340, 290, 14, 273, 13096, 198, 2, 340, 739, 262, 2846, 286, 262, 22961, 12892, 263, 3611, 5094, 13789...
3.216981
424
from pathlib import Path from src import constants from src.data.download.utils.download_dataset_zip import download_dataset_zip def download_tencent_test( tmp_dir: Path = None, tqdm_name: str = None, tqdm_idx: int = None, ): """Download the test set of the Tencent Corpus and extract it to the appropriate directory.""" download_dataset_zip( name="tencent_test", data_url=constants.TENCENT_TEST_URL, output_dir=constants.TENCENT_TEST_DIR, extracted_name=constants.TENCENT_TEST_ZIP_FOLDER, tmp_dir=tmp_dir, tqdm_name=tqdm_name, tqdm_idx=tqdm_idx, ) if __name__ == "__main__": download_tencent_test(tqdm_name="tencent", tqdm_idx=0)
[ 6738, 3108, 8019, 1330, 10644, 198, 198, 6738, 12351, 1330, 38491, 198, 6738, 12351, 13, 7890, 13, 15002, 13, 26791, 13, 15002, 62, 19608, 292, 316, 62, 13344, 1330, 4321, 62, 19608, 292, 316, 62, 13344, 628, 198, 4299, 4321, 62, 1452...
2.230769
325
import tensorflow as tf from ..fastspeech.model import ( TFFastSpeechEncoder, TFTacotronPostnet, TFFastSpeechLayer, ) from ..speechsplit.model import InterpLnr import numpy as np import copy
[ 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 11485, 7217, 45862, 13, 19849, 1330, 357, 198, 220, 220, 220, 309, 5777, 459, 5248, 3055, 27195, 12342, 11, 198, 220, 220, 220, 309, 9792, 330, 313, 1313, 6307, 3262, 11, 198, 220, 220,...
2.727273
77