code
stringlengths
22
1.05M
apis
listlengths
1
3.31k
extract_api
stringlengths
75
3.25M
#!/usr/bin/env python import numpy import itertools from pymatgen.core.lattice import Lattice from pymatgen.core.operations import SymmOp from pymatgen.core.structure import Structure from crystal import fillcell, tikz_atoms def dfh(single = True, defect = False): if defect: single = False a = 5.43 fcc = Lattice([[a/2,a/2,0],[a/2,0,a/2],[0,a/2,a/2]]) dfh = Structure(fcc,['Si']*2,[[0.00,0.00,0.00],[0.25,0.25,0.25]]) # Make the orthogonal cubic dfh.make_supercell([[0,0,1],[1,-1,0],[1,1,-1]]) # Rotate the cell rt = 0.70710678118654746 symmop = SymmOp.from_rotation_and_translation([[0,rt,rt],[0,rt,-rt],[1,0,0]]) dfh.apply_operation(symmop) # Make supercell if single == True: dfh.make_supercell([1,1,8]) else: dfh.make_supercell([2,2,8]) # Insert Mn atoms for i,atom in enumerate(dfh): if abs(atom.frac_coords[2] - 0.5) < 0.01 and atom.specie.symbol == 'Si': dfh.append('Mn',atom.frac_coords) del dfh[i] # Do defects if defect == 1: defectMn = numpy.array([0,0,0.5]) for i,atom in enumerate(dfh): if numpy.linalg.norm(atom.frac_coords - defectMn) < 0.01 and atom.specie.symbol == 'Mn': dfh.append('Si',defectMn) del dfh[i] if defect == 2: defectMn = numpy.array([0.5,0.5,0.5]) for i,atom in enumerate(dfh): if numpy.linalg.norm(atom.frac_coords - defectMn) < 0.01 and atom.specie.symbol == 'Mn': del dfh[i] if defect == 3: defectMn = numpy.array([0.5,0.25,0.5-1./32]) for i,atom in enumerate(dfh): if numpy.linalg.norm(atom.frac_coords - defectMn) < 0.01 and atom.specie.symbol == 'Si': dfh.append('Mn',defectMn) del dfh[i] return dfh atoms = dfh(single = True) atoms_full = fillcell(atoms) bondatoms = [] snsite = numpy.array([0.625,0.625,0.625]) for sitei,sitej in itertools.combinations(atoms_full,2): radius = sitei.specie.atomic_radius + sitej.specie.atomic_radius bondlength = sitei.distance_from_point(sitej.coords) if bondlength <= 1.25 * radius: bondatoms.append((sitei,sitej)) tikz = tikz_atoms(atoms_full, bondatoms, drawcell = True)
[ "pymatgen.core.structure.Structure", "itertools.combinations", "crystal.fillcell", "numpy.array", "pymatgen.core.lattice.Lattice", "numpy.linalg.norm", "pymatgen.core.operations.SymmOp.from_rotation_and_translation", "crystal.tikz_atoms" ]
[((1909, 1924), 'crystal.fillcell', 'fillcell', (['atoms'], {}), '(atoms)\n', (1917, 1924), False, 'from crystal import fillcell, tikz_atoms\n'), ((1949, 1983), 'numpy.array', 'numpy.array', (['[0.625, 0.625, 0.625]'], {}), '([0.625, 0.625, 0.625])\n', (1960, 1983), False, 'import numpy\n'), ((2001, 2038), 'itertools.combinations', 'itertools.combinations', (['atoms_full', '(2)'], {}), '(atoms_full, 2)\n', (2023, 2038), False, 'import itertools\n'), ((2261, 2309), 'crystal.tikz_atoms', 'tikz_atoms', (['atoms_full', 'bondatoms'], {'drawcell': '(True)'}), '(atoms_full, bondatoms, drawcell=True)\n', (2271, 2309), False, 'from crystal import fillcell, tikz_atoms\n'), ((329, 395), 'pymatgen.core.lattice.Lattice', 'Lattice', (['[[a / 2, a / 2, 0], [a / 2, 0, a / 2], [0, a / 2, a / 2]]'], {}), '([[a / 2, a / 2, 0], [a / 2, 0, a / 2], [0, a / 2, a / 2]])\n', (336, 395), False, 'from pymatgen.core.lattice import Lattice\n'), ((386, 451), 'pymatgen.core.structure.Structure', 'Structure', (['fcc', "(['Si'] * 2)", '[[0.0, 0.0, 0.0], [0.25, 0.25, 0.25]]'], {}), "(fcc, ['Si'] * 2, [[0.0, 0.0, 0.0], [0.25, 0.25, 0.25]])\n", (395, 451), False, 'from pymatgen.core.structure import Structure\n'), ((604, 680), 'pymatgen.core.operations.SymmOp.from_rotation_and_translation', 'SymmOp.from_rotation_and_translation', (['[[0, rt, rt], [0, rt, -rt], [1, 0, 0]]'], {}), '([[0, rt, rt], [0, rt, -rt], [1, 0, 0]])\n', (640, 680), False, 'from pymatgen.core.operations import SymmOp\n'), ((1108, 1132), 'numpy.array', 'numpy.array', (['[0, 0, 0.5]'], {}), '([0, 0, 0.5])\n', (1119, 1132), False, 'import numpy\n'), ((1378, 1406), 'numpy.array', 'numpy.array', (['[0.5, 0.5, 0.5]'], {}), '([0.5, 0.5, 0.5])\n', (1389, 1406), False, 'import numpy\n'), ((1610, 1650), 'numpy.array', 'numpy.array', (['[0.5, 0.25, 0.5 - 1.0 / 32]'], {}), '([0.5, 0.25, 0.5 - 1.0 / 32])\n', (1621, 1650), False, 'import numpy\n'), ((1184, 1230), 'numpy.linalg.norm', 'numpy.linalg.norm', (['(atom.frac_coords - defectMn)'], {}), '(atom.frac_coords - defectMn)\n', (1201, 1230), False, 'import numpy\n'), ((1458, 1504), 'numpy.linalg.norm', 'numpy.linalg.norm', (['(atom.frac_coords - defectMn)'], {}), '(atom.frac_coords - defectMn)\n', (1475, 1504), False, 'import numpy\n'), ((1697, 1743), 'numpy.linalg.norm', 'numpy.linalg.norm', (['(atom.frac_coords - defectMn)'], {}), '(atom.frac_coords - defectMn)\n', (1714, 1743), False, 'import numpy\n')]
import logging def create_app(config=None, testing=False): from airflow.www_rbac import app as airflow_app app, appbuilder = airflow_app.create_app(config=config, testing=testing) # only now we can load view.. # this import might causes circular dependency if placed above from dbnd_airflow.airflow_override.dbnd_aiflow_webserver import ( use_databand_airflow_dagbag, ) use_databand_airflow_dagbag() logging.info("Airflow applications has been created") return app, appbuilder def cached_appbuilder(config=None, testing=False): _, appbuilder = create_app(config, testing) return appbuilder
[ "dbnd_airflow.airflow_override.dbnd_aiflow_webserver.use_databand_airflow_dagbag", "airflow.www_rbac.app.create_app", "logging.info" ]
[((136, 190), 'airflow.www_rbac.app.create_app', 'airflow_app.create_app', ([], {'config': 'config', 'testing': 'testing'}), '(config=config, testing=testing)\n', (158, 190), True, 'from airflow.www_rbac import app as airflow_app\n'), ((411, 440), 'dbnd_airflow.airflow_override.dbnd_aiflow_webserver.use_databand_airflow_dagbag', 'use_databand_airflow_dagbag', ([], {}), '()\n', (438, 440), False, 'from dbnd_airflow.airflow_override.dbnd_aiflow_webserver import use_databand_airflow_dagbag\n'), ((445, 498), 'logging.info', 'logging.info', (['"""Airflow applications has been created"""'], {}), "('Airflow applications has been created')\n", (457, 498), False, 'import logging\n')]
# coding: utf-8 """ @brief test log(time=1s) """ import unittest import pandas import numpy from scipy.sparse.linalg import lsqr as sparse_lsqr from pyquickhelper.pycode import ExtTestCase, ignore_warnings from pandas_streaming.df import pandas_groupby_nan, numpy_types class TestPandasHelper(ExtTestCase): def test_pandas_groupbynan(self): self.assertTrue(sparse_lsqr is not None) types = [(int, -10), (float, -20.2), (str, "e"), (bytes, bytes("a", "ascii"))] skip = (numpy.bool_, numpy.complex64, numpy.complex128) types += [(_, _(5)) for _ in numpy_types() if _ not in skip] for ty in types: data = [{"this": "cst", "type": "tt1=" + str(ty[0]), "value": ty[1]}, {"this": "cst", "type": "tt2=" + str(ty[0]), "value": ty[1]}, {"this": "cst", "type": "row_for_nan"}] df = pandas.DataFrame(data) gr = pandas_groupby_nan(df, "value") co = gr.sum() li = list(co["value"]) try: self.assertIsInstance(li[-1], float) except AssertionError as e: raise AssertionError("Issue with {0}".format(ty)) from e try: self.assertTrue(numpy.isnan(li[-1])) except AssertionError as e: raise AssertionError( "Issue with value {}\n--df--\n{}\n--gr--\n{}\n--co--\n{}".format( li, df, gr.count(), co)) from e for ty in types: data = [{"this": "cst", "type": "tt1=" + str(ty[0]), "value": ty[1]}, {"this": "cst", "type": "tt2=" + str(ty[0]), "value": ty[1]}, {"this": "cst", "type": "row_for_nan"}] df = pandas.DataFrame(data) try: gr = pandas_groupby_nan(df, ("value", "this")) t = True raise Exception("---") except TypeError: t = False if t: co = gr.sum() li = list(co["value"]) self.assertIsInstance(li[-1], float) self.assertTrue(numpy.isnan(li[-1])) try: gr = pandas_groupby_nan(df, ["value", "this"]) t = True except (TypeError, NotImplementedError): t = False if t: co = gr.sum() li = list(co["value"]) self.assertEqual(len(li), 2) def test_pandas_groupbynan_tuple(self): data = [dict(a="a", b="b", c="c", n=1), dict( b="b", n=2), dict(a="a", n=3), dict(c="c", n=4)] df = pandas.DataFrame(data) gr = df.groupby(["a", "b", "c"]).sum() self.assertEqual(gr.shape, (1, 1)) for nanback in [True, False]: try: gr2_ = pandas_groupby_nan( df, ["a", "b", "c"], nanback=nanback, suffix="NAN") except NotImplementedError: continue gr2 = gr2_.sum().sort_values("n") self.assertEqual(gr2.shape, (4, 4)) d = gr2.to_dict("records") self.assertEqual(d[0]["a"], "a") self.assertEqual(d[0]["b"], "b") self.assertEqual(d[0]["c"], "c") self.assertEqual(d[0]["n"], 1) self.assertEqual(d[1]["a"], "NAN") def test_pandas_groupbynan_regular(self): df = pandas.DataFrame([dict(a="a", b=1), dict(a="a", b=2)]) gr = df.groupby(["a"]).sum() gr2_ = pandas_groupby_nan(df, ["a"]).sum() self.assertEqualDataFrame(gr, gr2_) def test_pandas_groupbynan_regular_nanback(self): df = pandas.DataFrame([dict(a="a", b=1, cc=0), dict(a="a", b=2)]) gr = df.groupby(["a", "cc"]).sum() self.assertEqual(len(gr), 1) self.assertRaise( lambda: pandas_groupby_nan(df, ["a", "cc"], nanback=True).sum(), NotImplementedError) def test_pandas_groupbynan_doc(self): data = [dict(a=2, ind="a", n=1), dict(a=2, ind="a"), dict(a=3, ind="b"), dict(a=30)] df = pandas.DataFrame(data) gr2 = pandas_groupby_nan(df, ["ind"]).sum() ind = list(gr2['ind']) self.assertTrue(numpy.isnan(ind[-1])) val = list(gr2['a']) self.assertEqual(val[-1], 30) @ignore_warnings(UserWarning) def test_pandas_groupbynan_doc2(self): data = [dict(a=2, ind="a", n=1), dict(a=2, ind="a"), dict(a=3, ind="b"), dict(a=30)] df = pandas.DataFrame(data) gr2 = pandas_groupby_nan(df, ["ind", "a"], nanback=False).sum() ind = list(gr2['ind']) self.assertEqual(ind[-1], "²nan") def test_pandas_groupbynan_doc3(self): data = [dict(a=2, ind="a", n=1), dict(a=2, ind="a"), dict(a=3, ind="b"), dict(a=30)] df = pandas.DataFrame(data) self.assertRaise(lambda: pandas_groupby_nan(df, ["ind", "n"]).sum(), NotImplementedError) # ind = list(gr2['ind']) # self.assertTrue(numpy.isnan(ind[-1])) if __name__ == "__main__": unittest.main()
[ "pandas.DataFrame", "numpy.isnan", "pandas_streaming.df.numpy_types", "unittest.main", "pyquickhelper.pycode.ignore_warnings", "pandas_streaming.df.pandas_groupby_nan" ]
[((4454, 4482), 'pyquickhelper.pycode.ignore_warnings', 'ignore_warnings', (['UserWarning'], {}), '(UserWarning)\n', (4469, 4482), False, 'from pyquickhelper.pycode import ExtTestCase, ignore_warnings\n'), ((5306, 5321), 'unittest.main', 'unittest.main', ([], {}), '()\n', (5319, 5321), False, 'import unittest\n'), ((2733, 2755), 'pandas.DataFrame', 'pandas.DataFrame', (['data'], {}), '(data)\n', (2749, 2755), False, 'import pandas\n'), ((4229, 4251), 'pandas.DataFrame', 'pandas.DataFrame', (['data'], {}), '(data)\n', (4245, 4251), False, 'import pandas\n'), ((4680, 4702), 'pandas.DataFrame', 'pandas.DataFrame', (['data'], {}), '(data)\n', (4696, 4702), False, 'import pandas\n'), ((5046, 5068), 'pandas.DataFrame', 'pandas.DataFrame', (['data'], {}), '(data)\n', (5062, 5068), False, 'import pandas\n'), ((930, 952), 'pandas.DataFrame', 'pandas.DataFrame', (['data'], {}), '(data)\n', (946, 952), False, 'import pandas\n'), ((970, 1001), 'pandas_streaming.df.pandas_groupby_nan', 'pandas_groupby_nan', (['df', '"""value"""'], {}), "(df, 'value')\n", (988, 1001), False, 'from pandas_streaming.df import pandas_groupby_nan, numpy_types\n'), ((1827, 1849), 'pandas.DataFrame', 'pandas.DataFrame', (['data'], {}), '(data)\n', (1843, 1849), False, 'import pandas\n'), ((4359, 4379), 'numpy.isnan', 'numpy.isnan', (['ind[-1]'], {}), '(ind[-1])\n', (4370, 4379), False, 'import numpy\n'), ((607, 620), 'pandas_streaming.df.numpy_types', 'numpy_types', ([], {}), '()\n', (618, 620), False, 'from pandas_streaming.df import pandas_groupby_nan, numpy_types\n'), ((1888, 1929), 'pandas_streaming.df.pandas_groupby_nan', 'pandas_groupby_nan', (['df', "('value', 'this')"], {}), "(df, ('value', 'this'))\n", (1906, 1929), False, 'from pandas_streaming.df import pandas_groupby_nan, numpy_types\n'), ((2281, 2322), 'pandas_streaming.df.pandas_groupby_nan', 'pandas_groupby_nan', (['df', "['value', 'this']"], {}), "(df, ['value', 'this'])\n", (2299, 2322), False, 'from pandas_streaming.df import pandas_groupby_nan, numpy_types\n'), ((2925, 2995), 'pandas_streaming.df.pandas_groupby_nan', 'pandas_groupby_nan', (['df', "['a', 'b', 'c']"], {'nanback': 'nanback', 'suffix': '"""NAN"""'}), "(df, ['a', 'b', 'c'], nanback=nanback, suffix='NAN')\n", (2943, 2995), False, 'from pandas_streaming.df import pandas_groupby_nan, numpy_types\n'), ((3607, 3636), 'pandas_streaming.df.pandas_groupby_nan', 'pandas_groupby_nan', (['df', "['a']"], {}), "(df, ['a'])\n", (3625, 3636), False, 'from pandas_streaming.df import pandas_groupby_nan, numpy_types\n'), ((4266, 4297), 'pandas_streaming.df.pandas_groupby_nan', 'pandas_groupby_nan', (['df', "['ind']"], {}), "(df, ['ind'])\n", (4284, 4297), False, 'from pandas_streaming.df import pandas_groupby_nan, numpy_types\n'), ((4717, 4768), 'pandas_streaming.df.pandas_groupby_nan', 'pandas_groupby_nan', (['df', "['ind', 'a']"], {'nanback': '(False)'}), "(df, ['ind', 'a'], nanback=False)\n", (4735, 4768), False, 'from pandas_streaming.df import pandas_groupby_nan, numpy_types\n'), ((1295, 1314), 'numpy.isnan', 'numpy.isnan', (['li[-1]'], {}), '(li[-1])\n', (1306, 1314), False, 'import numpy\n'), ((2222, 2241), 'numpy.isnan', 'numpy.isnan', (['li[-1]'], {}), '(li[-1])\n', (2233, 2241), False, 'import numpy\n'), ((3942, 3991), 'pandas_streaming.df.pandas_groupby_nan', 'pandas_groupby_nan', (['df', "['a', 'cc']"], {'nanback': '(True)'}), "(df, ['a', 'cc'], nanback=True)\n", (3960, 3991), False, 'from pandas_streaming.df import pandas_groupby_nan, numpy_types\n'), ((5102, 5138), 'pandas_streaming.df.pandas_groupby_nan', 'pandas_groupby_nan', (['df', "['ind', 'n']"], {}), "(df, ['ind', 'n'])\n", (5120, 5138), False, 'from pandas_streaming.df import pandas_groupby_nan, numpy_types\n')]
#!/usr/bin/env python import rospy from std_msgs.msg import Int32 from geometry_msgs.msg import PoseStamped, Pose from styx_msgs.msg import TrafficLightArray, TrafficLight from styx_msgs.msg import Lane from sensor_msgs.msg import Image from cv_bridge import CvBridge from light_classification.tl_classifier import TLClassifier from scipy.spatial import KDTree import tf import cv2 import yaml STATE_COUNT_THRESHOLD = 3 class TLDetector(object): def __init__(self): rospy.init_node('tl_detector') self.pose = None self.waypoints = None self.waypoint_tree = None self.camera_image = None self.lights = [] sub1 = rospy.Subscriber('/current_pose', PoseStamped, self.pose_cb) sub2 = rospy.Subscriber('/base_waypoints', Lane, self.waypoints_cb) ''' /vehicle/traffic_lights provides you with the location of the traffic light in 3D map space and helps you acquire an accurate ground truth data source for the traffic light classifier by sending the current color state of all traffic lights in the simulator. When testing on the vehicle, the color state will not be available. You'll need to rely on the position of the light and the camera image to predict it. ''' sub3 = rospy.Subscriber('/vehicle/traffic_lights', TrafficLightArray, self.traffic_cb) sub6 = rospy.Subscriber('/image_color', Image, self.image_cb) config_string = rospy.get_param("/traffic_light_config") self.config = yaml.load(config_string) self.upcoming_red_light_pub = rospy.Publisher('/traffic_waypoint', Int32, queue_size=1) self.bridge = CvBridge() self.light_classifier = TLClassifier() self.listener = tf.TransformListener() self.state = TrafficLight.UNKNOWN self.last_state = TrafficLight.UNKNOWN self.last_wp = -1 self.state_count = 0 rospy.spin() def pose_cb(self, msg): self.pose = msg def waypoints_cb(self, waypoints): self.waypoints = waypoints if not self.waypoint_tree: self.waypoint_tree = KDTree([ [w.pose.pose.position.x, w.pose.pose.position.y] for w in waypoints.waypoints]) def traffic_cb(self, msg): self.lights = msg.lights def image_cb(self, msg): """Identifies red lights in the incoming camera image and publishes the index of the waypoint closest to the red light's stop line to /traffic_waypoint Args: msg (Image): image from car-mounted camera """ self.has_image = True self.camera_image = msg light_wp, state = self.process_traffic_lights() # Publish upcoming red lights at camera frequency. # Each predicted state has to occur `STATE_COUNT_THRESHOLD` number # of times till we start using it. Otherwise the previous stable state is # used. if self.state != state: self.state_count = 0 self.state = state elif self.state_count >= STATE_COUNT_THRESHOLD: self.last_state = self.state light_wp = light_wp if state == TrafficLight.RED else -1 self.last_wp = light_wp self.upcoming_red_light_pub.publish(Int32(light_wp)) else: self.upcoming_red_light_pub.publish(Int32(self.last_wp)) if (state == TrafficLight.RED): rospy.logwarn("Detected RED light! Count: %i" % self.state_count) if (state == TrafficLight.GREEN): rospy.logwarn("Detected GREEN light! Count: %i" % self.state_count) self.state_count += 1 def get_closest_waypoint(self, x, y): """Identifies the closest path waypoint to the given position https://en.wikipedia.org/wiki/Closest_pair_of_points_problem Args: pose (Pose): position to match a waypoint to Returns: int: index of the closest waypoint in self.waypoints """ return self.waypoint_tree.query([x, y], 1)[1] def get_light_state(self, light): """Determines the current color of the traffic light Args: light (TrafficLight): light to classify Returns: int: ID of traffic light color (specified in styx_msgs/TrafficLight) """ # For testing, just return the light state. return light.state #if (not self.has_image): # self.prev_light_loc = None # return False #cv_image = self.bridge.imgmsg_to_cv2(self.camera_image, "bgr8") #return self.light_classifier.get_classification(cv_image) def process_traffic_lights(self): """Finds closest visible traffic light, if one exists, and determines its location and color Returns: int: index of waypoint closest to the upcoming stop line for a traffic light (-1 if none exists) int: ID of traffic light color (specified in styx_msgs/TrafficLight) """ closest_light = None closest_stop_line_idx = -1 stop_line_positions = self.config['stop_line_positions'] if (self.pose): car_waypoint_idx = self.get_closest_waypoint(self.pose.pose.position.x, self.pose.pose.position.y) # Find the closest visible traffic light. # Since the list of lights is short (~8), there isn't much benefit in using KD trees. min_distance_to_stop_line = len(self.waypoints.waypoints) for light, stop_line in zip(self.lights, stop_line_positions): stop_line_idx = self.get_closest_waypoint(stop_line[0], stop_line[1]) distance_to_stop_line = stop_line_idx - car_waypoint_idx # -10 is key to getting the simualtor to work (at least on my not-so-powerful machine). # The simulator is laggy and reports the position further ahead that it displays it. # Often, when the car is in front of a red traffic light, it doesn't stop because it # thinks it's past it. if -10 <= distance_to_stop_line <= min_distance_to_stop_line: min_distance_to_stop_line = distance_to_stop_line closest_light = light closest_stop_line_idx = stop_line_idx light_state = self.get_light_state(closest_light) if closest_light else TrafficLight.UNKNOWN return closest_stop_line_idx, light_state if __name__ == '__main__': try: TLDetector() except rospy.ROSInterruptException: rospy.logerr('Could not start traffic node.')
[ "rospy.logerr", "rospy.Subscriber", "rospy.logwarn", "rospy.init_node", "rospy.get_param", "scipy.spatial.KDTree", "std_msgs.msg.Int32", "yaml.load", "cv_bridge.CvBridge", "light_classification.tl_classifier.TLClassifier", "tf.TransformListener", "rospy.spin", "rospy.Publisher" ]
[((480, 510), 'rospy.init_node', 'rospy.init_node', (['"""tl_detector"""'], {}), "('tl_detector')\n", (495, 510), False, 'import rospy\n'), ((675, 735), 'rospy.Subscriber', 'rospy.Subscriber', (['"""/current_pose"""', 'PoseStamped', 'self.pose_cb'], {}), "('/current_pose', PoseStamped, self.pose_cb)\n", (691, 735), False, 'import rospy\n'), ((751, 811), 'rospy.Subscriber', 'rospy.Subscriber', (['"""/base_waypoints"""', 'Lane', 'self.waypoints_cb'], {}), "('/base_waypoints', Lane, self.waypoints_cb)\n", (767, 811), False, 'import rospy\n'), ((1304, 1383), 'rospy.Subscriber', 'rospy.Subscriber', (['"""/vehicle/traffic_lights"""', 'TrafficLightArray', 'self.traffic_cb'], {}), "('/vehicle/traffic_lights', TrafficLightArray, self.traffic_cb)\n", (1320, 1383), False, 'import rospy\n'), ((1399, 1453), 'rospy.Subscriber', 'rospy.Subscriber', (['"""/image_color"""', 'Image', 'self.image_cb'], {}), "('/image_color', Image, self.image_cb)\n", (1415, 1453), False, 'import rospy\n'), ((1479, 1519), 'rospy.get_param', 'rospy.get_param', (['"""/traffic_light_config"""'], {}), "('/traffic_light_config')\n", (1494, 1519), False, 'import rospy\n'), ((1542, 1566), 'yaml.load', 'yaml.load', (['config_string'], {}), '(config_string)\n', (1551, 1566), False, 'import yaml\n'), ((1606, 1663), 'rospy.Publisher', 'rospy.Publisher', (['"""/traffic_waypoint"""', 'Int32'], {'queue_size': '(1)'}), "('/traffic_waypoint', Int32, queue_size=1)\n", (1621, 1663), False, 'import rospy\n'), ((1687, 1697), 'cv_bridge.CvBridge', 'CvBridge', ([], {}), '()\n', (1695, 1697), False, 'from cv_bridge import CvBridge\n'), ((1730, 1744), 'light_classification.tl_classifier.TLClassifier', 'TLClassifier', ([], {}), '()\n', (1742, 1744), False, 'from light_classification.tl_classifier import TLClassifier\n'), ((1769, 1791), 'tf.TransformListener', 'tf.TransformListener', ([], {}), '()\n', (1789, 1791), False, 'import tf\n'), ((1946, 1958), 'rospy.spin', 'rospy.spin', ([], {}), '()\n', (1956, 1958), False, 'import rospy\n'), ((2157, 2249), 'scipy.spatial.KDTree', 'KDTree', (['[[w.pose.pose.position.x, w.pose.pose.position.y] for w in waypoints.waypoints]'], {}), '([[w.pose.pose.position.x, w.pose.pose.position.y] for w in waypoints\n .waypoints])\n', (2163, 2249), False, 'from scipy.spatial import KDTree\n'), ((3480, 3545), 'rospy.logwarn', 'rospy.logwarn', (["('Detected RED light! Count: %i' % self.state_count)"], {}), "('Detected RED light! Count: %i' % self.state_count)\n", (3493, 3545), False, 'import rospy\n'), ((3599, 3666), 'rospy.logwarn', 'rospy.logwarn', (["('Detected GREEN light! Count: %i' % self.state_count)"], {}), "('Detected GREEN light! Count: %i' % self.state_count)\n", (3612, 3666), False, 'import rospy\n'), ((6723, 6768), 'rospy.logerr', 'rospy.logerr', (['"""Could not start traffic node."""'], {}), "('Could not start traffic node.')\n", (6735, 6768), False, 'import rospy\n'), ((3327, 3342), 'std_msgs.msg.Int32', 'Int32', (['light_wp'], {}), '(light_wp)\n', (3332, 3342), False, 'from std_msgs.msg import Int32\n'), ((3406, 3425), 'std_msgs.msg.Int32', 'Int32', (['self.last_wp'], {}), '(self.last_wp)\n', (3411, 3425), False, 'from std_msgs.msg import Int32\n')]
#Import required Modules: import pygame import constants from paddle import Paddle from ball import Ball from score import Score from text import Text from screenState import ScreenState #This function basically executes everything in the "screenState" module's class def init(): #Initialize all the constants: screen = constants.initialize() #Making the FPS clock: clock = pygame.time.Clock() FPS = 60 #Creating paddle 1 score: paddle1Score = Score(screen) paddle1Score.x = 100 #Creating paddle 2 score: paddle2Score = Score(screen) paddle2Score.color = constants.colors["RED"] #Making 2 paddles: paddle1 = Paddle() paddle1.x = 10 paddle1.color = constants.colors["BLUE"] paddle2 = Paddle() paddle2.x = 780 paddle2.color = constants.colors["RED"] # Making the ball: ball = Ball() ball.dx = ball.speed ball.dy = ball.speed #The ball starts at the center: ball.x = constants.cx ball.y = constants.cy #The ball's intital color is blue ball.color = constants.colors["PURPLE"] #Creating the title screen's text: title_text = Text(screen) title_text.text = "Welcome to Saabit Pong Game. Difficulty keys: Easy: 1, Medium: 2, Hard: 3" #Creating the end game screen's text endScreen_text = Text(screen) endScreen_text.text = "Game Over. Press 'P' to play again" return ScreenState(screen, title_text, endScreen_text, paddle1, paddle2, ball, paddle1Score, paddle2Score, clock, FPS)
[ "score.Score", "screenState.ScreenState", "text.Text", "ball.Ball", "pygame.time.Clock", "constants.initialize", "paddle.Paddle" ]
[((344, 366), 'constants.initialize', 'constants.initialize', ([], {}), '()\n', (364, 366), False, 'import constants\n'), ((412, 431), 'pygame.time.Clock', 'pygame.time.Clock', ([], {}), '()\n', (429, 431), False, 'import pygame\n'), ((499, 512), 'score.Score', 'Score', (['screen'], {}), '(screen)\n', (504, 512), False, 'from score import Score\n'), ((594, 607), 'score.Score', 'Score', (['screen'], {}), '(screen)\n', (599, 607), False, 'from score import Score\n'), ((701, 709), 'paddle.Paddle', 'Paddle', ([], {}), '()\n', (707, 709), False, 'from paddle import Paddle\n'), ((793, 801), 'paddle.Paddle', 'Paddle', ([], {}), '()\n', (799, 801), False, 'from paddle import Paddle\n'), ((908, 914), 'ball.Ball', 'Ball', ([], {}), '()\n', (912, 914), False, 'from ball import Ball\n'), ((1217, 1229), 'text.Text', 'Text', (['screen'], {}), '(screen)\n', (1221, 1229), False, 'from text import Text\n'), ((1395, 1407), 'text.Text', 'Text', (['screen'], {}), '(screen)\n', (1399, 1407), False, 'from text import Text\n'), ((1488, 1603), 'screenState.ScreenState', 'ScreenState', (['screen', 'title_text', 'endScreen_text', 'paddle1', 'paddle2', 'ball', 'paddle1Score', 'paddle2Score', 'clock', 'FPS'], {}), '(screen, title_text, endScreen_text, paddle1, paddle2, ball,\n paddle1Score, paddle2Score, clock, FPS)\n', (1499, 1603), False, 'from screenState import ScreenState\n')]
import tensorflow as tf from typing import List from ..utils.tf_utils import gen_CNN from ...utils import MODEL from ..utils.pointnet import pointnet2_utils class Pointnet2MSG(tf.keras.layers.Layer): def __init__( self, in_channels=6, use_xyz=True, SA_config={ "npoints": [128, 32, -1], "radius": [0.2, 0.4, 100], "nsample": [64, 64, 64], "mlps": [[128, 128, 128], [128, 128, 256], [256, 256, 512]] }, fp_mlps=[]): super().__init__() self.SA_modules = [] skip_channel_list = [in_channels] for i in range(len(SA_config["npoints"])): mlps = SA_config["mlps"][i].copy() out_channels = 0 for idx in range(len(mlps)): mlps[idx] = [in_channels] + mlps[idx] out_channels += mlps[idx][-1] self.SA_modules.append( PointnetSAModuleMSG(npoint=SA_config["npoints"][i], radii=SA_config["radius"][i], nsamples=SA_config["nsample"][i], mlps=mlps, use_xyz=use_xyz, batch_norm=True)) in_channels = out_channels skip_channel_list.append(out_channels) self.FP_modules = [] for i in range(len(fp_mlps)): pre_channel = fp_mlps[ i + 1][-1] if i + 1 < len(fp_mlps) else out_channels self.FP_modules.append( PointnetFPModule(mlp=[pre_channel + skip_channel_list[i]] + fp_mlps[i], batch_norm=True)) def _break_up_pc(self, pc): xyz = pc[..., 0:3] features = pc[..., 3:] if pc.shape[-1] > 3 else None return xyz, features def call(self, pointcloud, training=True): xyz, features = self._break_up_pc(pointcloud) l_xyz, l_features = [xyz], [features] for i in range(len(self.SA_modules)): li_xyz, li_features = self.SA_modules[i](l_xyz[i], l_features[i], training=training) l_xyz.append(li_xyz) l_features.append(li_features) for i in range(-1, -(len(self.FP_modules) + 1), -1): l_features[i - 1] = self.FP_modules[i](l_xyz[i - 1], l_xyz[i], l_features[i - 1], l_features[i], training=training) return l_xyz[0], l_features[0] MODEL._register_module(Pointnet2MSG, 'tf') class _PointnetSAModuleBase(tf.keras.layers.Layer): def __init__(self): super().__init__() self.npoint = None self.groupers = None self.mlps = None self.pool_method = 'max_pool' def call(self, xyz, features=None, new_xyz=None, training=True): """ :param xyz: (B, N, 3) tensor of the xyz coordinates of the features :param features: (B, N, C) tensor of the descriptors of the the features :param new_xyz: :return: new_xyz: (B, npoint, 3) tensor of the new features' xyz new_features: (B, npoint, \sum_k(mlps[k][-1])) tensor of the new_features descriptors """ new_features_list = [] if new_xyz is None and self.npoint is not None: sampling = tf.expand_dims(pointnet2_utils.furthest_point_sample( xyz, self.npoint), axis=-1) new_xyz = tf.gather_nd(xyz, sampling, batch_dims=1) for i in range(len(self.groupers)): new_features = self.groupers[i](xyz, new_xyz, features) # (B, C, npoint, nsample) new_features = self.mlps[i]( new_features, training=training) # (B, mlp[-1], npoint, nsample) if self.pool_method == 'max_pool': new_features = tf.reduce_max(new_features, axis=-1) # (B, mlp[-1], npoint) elif self.pool_method == 'avg_pool': new_features = tf.reduce_mean(new_features, axis=-1) # (B, mlp[-1], npoint) else: raise NotImplementedError new_features_list.append(new_features) return new_xyz, tf.concat(new_features_list, axis=1) class PointnetSAModuleMSG(_PointnetSAModuleBase): """Pointnet set abstraction layer with multiscale grouping""" def __init__(self, *, npoint: int, radii: List[float], nsamples: List[int], mlps: List[List[int]], batch_norm=False, use_xyz: bool = True, pool_method='max_pool', use_bias=False): """ :param npoint: int :param radii: list of float, list of radii to group with :param nsamples: list of int, number of samples in each ball query :param mlps: list of list of int, spec of the pointnet before the global pooling for each scale :param bn: whether to use batchnorm :param use_xyz: :param pool_method: max_pool / avg_pool """ super().__init__() assert len(radii) == len(nsamples) == len(mlps) self.npoint = npoint self.groupers = [] self.mlps = [] for i in range(len(radii)): radius = radii[i] nsample = nsamples[i] self.groupers.append( pointnet2_utils.QueryAndGroup(radius, nsample, use_xyz=use_xyz) if npoint is not None else pointnet2_utils.GroupAll(use_xyz)) mlp_spec = mlps[i] if use_xyz: mlp_spec[0] += 3 self.mlps.append( gen_CNN(mlp_spec, conv=tf.keras.layers.Conv2D, batch_norm=batch_norm, use_bias=use_bias)) self.pool_method = pool_method class PointnetSAModule(PointnetSAModuleMSG): """Pointnet set abstraction layer""" def __init__(self, *, mlp: List[int], npoint: int = None, radius: float = None, nsample: int = None, batch_norm=False, use_xyz: bool = True, pool_method='max_pool', use_bias=False): """ :param mlp: list of int, spec of the pointnet before the global max_pool :param npoint: int, number of features :param radius: float, radius of ball :param nsample: int, number of samples in the ball query :param bn: whether to use batchnorm :param use_xyz: :param pool_method: max_pool / avg_pool """ super().__init__(mlps=[mlp], npoint=npoint, radii=[radius], nsamples=[nsample], batch_norm=batch_norm, use_xyz=use_xyz, pool_method=pool_method, use_bias=use_bias) MODEL._register_module(PointnetSAModule, 'tf') class PointnetFPModule(tf.keras.layers.Layer): r"""Propigates the features of one set to another""" def __init__(self, *, mlp: List[int], batch_norm=False, use_bias=False): """ :param mlp: list of int :param bn: whether to use batchnorm """ super().__init__() self.mlp = gen_CNN(mlp, conv=tf.keras.layers.Conv2D, batch_norm=batch_norm, use_bias=use_bias) def call(self, unknown, known, unknow_feats, known_feats, training=True): """ :param unknown: (B, n, 3) tensor of the xyz positions of the unknown features :param known: (B, m, 3) tensor of the xyz positions of the known features :param unknow_feats: (B, C1, n) tensor of the features to be propigated to :param known_feats: (B, C2, m) tensor of features to be propigated :return: new_features: (B, mlp[-1], n) tensor of the features of the unknown features """ if known is not None: dist, idx = pointnet2_utils.three_nn_gpu(unknown, known) dist_recip = 1.0 / (dist + 1e-8) norm = tf.reduce_sum(dist_recip, axis=2, keepdims=True) weight = dist_recip / norm interpolated_feats = pointnet2_utils.three_interpolate_gpu( known_feats, idx, weight) else: interpolated_feats = known_feats.expand(*known_feats.shape[0:2], unknown.shape[1]) if unknow_feats is not None: new_features = tf.concat([interpolated_feats, unknow_feats], axis=1) # (B, C2 + C1, n) else: new_features = interpolated_feats new_features = tf.expand_dims(new_features, axis=-1) new_features = self.mlp(new_features, training=training) return tf.squeeze(new_features, axis=-1) MODEL._register_module(PointnetFPModule, 'tf') if __name__ == "__main__": pass
[ "tensorflow.reduce_sum", "tensorflow.reduce_max", "tensorflow.concat", "tensorflow.reduce_mean", "tensorflow.expand_dims", "tensorflow.gather_nd", "tensorflow.squeeze" ]
[((9439, 9476), 'tensorflow.expand_dims', 'tf.expand_dims', (['new_features'], {'axis': '(-1)'}), '(new_features, axis=-1)\n', (9453, 9476), True, 'import tensorflow as tf\n'), ((9558, 9591), 'tensorflow.squeeze', 'tf.squeeze', (['new_features'], {'axis': '(-1)'}), '(new_features, axis=-1)\n', (9568, 9591), True, 'import tensorflow as tf\n'), ((3849, 3890), 'tensorflow.gather_nd', 'tf.gather_nd', (['xyz', 'sampling'], {'batch_dims': '(1)'}), '(xyz, sampling, batch_dims=1)\n', (3861, 3890), True, 'import tensorflow as tf\n'), ((4724, 4760), 'tensorflow.concat', 'tf.concat', (['new_features_list'], {'axis': '(1)'}), '(new_features_list, axis=1)\n', (4733, 4760), True, 'import tensorflow as tf\n'), ((8816, 8864), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['dist_recip'], {'axis': '(2)', 'keepdims': '(True)'}), '(dist_recip, axis=2, keepdims=True)\n', (8829, 8864), True, 'import tensorflow as tf\n'), ((9245, 9298), 'tensorflow.concat', 'tf.concat', (['[interpolated_feats, unknow_feats]'], {'axis': '(1)'}), '([interpolated_feats, unknow_feats], axis=1)\n', (9254, 9298), True, 'import tensorflow as tf\n'), ((4293, 4329), 'tensorflow.reduce_max', 'tf.reduce_max', (['new_features'], {'axis': '(-1)'}), '(new_features, axis=-1)\n', (4306, 4329), True, 'import tensorflow as tf\n'), ((4479, 4516), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['new_features'], {'axis': '(-1)'}), '(new_features, axis=-1)\n', (4493, 4516), True, 'import tensorflow as tf\n')]
import argparse import json from easydict import EasyDict def get_args(): argparser = argparse.ArgumentParser(description=__doc__) argparser.add_argument( '-c', '--config', metavar='C', default=None, help='The Configuration file') argparser.add_argument( '-i', '--id', metavar='I', default='', help='The commit id)') argparser.add_argument( '-t', '--ts', metavar='T', default='', help='The time stamp)') argparser.add_argument( '-d', '--dir', metavar='D', default='', help='The output directory)') args = argparser.parse_args() return args def get_config_from_json(json_file): # parse the configurations from the configs json file provided with open(json_file, 'r') as config_file: config_dict = json.load(config_file) # convert the dictionary to a namespace using bunch lib config = EasyDict(config_dict) return config def process_config(args): config = get_config_from_json(args.config) config.commit_id = args.id config.time_stamp = args.ts config.directory = args.dir return config if __name__ == '__main__': config = get_config_from_json('../configs/MUTAG.json') sub_configurations = config.configurations print(sub_configurations['pooling'])
[ "json.load", "easydict.EasyDict", "argparse.ArgumentParser" ]
[((92, 136), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '__doc__'}), '(description=__doc__)\n', (115, 136), False, 'import argparse\n'), ((969, 990), 'easydict.EasyDict', 'EasyDict', (['config_dict'], {}), '(config_dict)\n', (977, 990), False, 'from easydict import EasyDict\n'), ((872, 894), 'json.load', 'json.load', (['config_file'], {}), '(config_file)\n', (881, 894), False, 'import json\n')]
import shutil import numpy as np ALL_SYNTHS_LIST = 'synth_imgs.txt' TRAIN_IMAGES_LIST = 'train_imgs.txt' VAL_IMAGES_LIST = 'val_imgs.txt' TEST_IMAGES_LIST = 'test_imgs.txt' TRAIN_STOP = 342000 VAL_STOP = TRAIN_STOP + 38000 ''' 390000 examples : 342000 train and 38000 val (90/10 splits on 380000), 10000 test ''' with open(ALL_SYNTHS_LIST,'r') as img_list: files = np.array(img_list.read().splitlines()) files = files[np.random.permutation(files.shape[0])] with open(TRAIN_IMAGES_LIST,"w") as list_file: for i in range(TRAIN_STOP): shutil.copy(files[i],'./train_imgs/') shutil.copy(files[i][:-4] + "_r.jpg",'./train_imgs/') shutil.copy(files[i][:-4] + "_b.jpg",'./train_imgs/') fname = files[i].split('/') fname = fname[len(fname) - 1] list_file.write('./train_imgs/' + fname) list_file.write('\n') print("Copying training examples ..." + str(i) + "/342000") with open(VAL_IMAGES_LIST,"w") as list_file: for i in range(TRAIN_STOP,VAL_STOP): shutil.copy(files[i],'./val_imgs/') shutil.copy(files[i][:-4] + "_r.jpg",'./val_imgs/') shutil.copy(files[i][:-4] + "_b.jpg",'./val_imgs/') fname = files[i].split('/') fname = fname[len(fname) - 1] list_file.write('./val_imgs/' + fname) list_file.write('\n') print("Copying validation examples ..." + str(i) + "/38000") with open(TEST_IMAGES_LIST,"w") as list_file: for i in range(VAL_STOP,files.shape[0]): shutil.copy(files[i],'./test_imgs/') shutil.copy(files[i][:-4] + "_r.jpg",'./test_imgs/') shutil.copy(files[i][:-4] + "_b.jpg",'./test_imgs/') fname = files[i].split('/') fname = fname[len(fname) - 1] list_file.write('./test_imgs/' + fname) list_file.write('\n') print("Copying testing examples ..." + str(i) + "/10000")
[ "shutil.copy", "numpy.random.permutation" ]
[((428, 465), 'numpy.random.permutation', 'np.random.permutation', (['files.shape[0]'], {}), '(files.shape[0])\n', (449, 465), True, 'import numpy as np\n'), ((556, 594), 'shutil.copy', 'shutil.copy', (['files[i]', '"""./train_imgs/"""'], {}), "(files[i], './train_imgs/')\n", (567, 594), False, 'import shutil\n'), ((602, 656), 'shutil.copy', 'shutil.copy', (["(files[i][:-4] + '_r.jpg')", '"""./train_imgs/"""'], {}), "(files[i][:-4] + '_r.jpg', './train_imgs/')\n", (613, 656), False, 'import shutil\n'), ((664, 718), 'shutil.copy', 'shutil.copy', (["(files[i][:-4] + '_b.jpg')", '"""./train_imgs/"""'], {}), "(files[i][:-4] + '_b.jpg', './train_imgs/')\n", (675, 718), False, 'import shutil\n'), ((1034, 1070), 'shutil.copy', 'shutil.copy', (['files[i]', '"""./val_imgs/"""'], {}), "(files[i], './val_imgs/')\n", (1045, 1070), False, 'import shutil\n'), ((1078, 1130), 'shutil.copy', 'shutil.copy', (["(files[i][:-4] + '_r.jpg')", '"""./val_imgs/"""'], {}), "(files[i][:-4] + '_r.jpg', './val_imgs/')\n", (1089, 1130), False, 'import shutil\n'), ((1138, 1190), 'shutil.copy', 'shutil.copy', (["(files[i][:-4] + '_b.jpg')", '"""./val_imgs/"""'], {}), "(files[i][:-4] + '_b.jpg', './val_imgs/')\n", (1149, 1190), False, 'import shutil\n'), ((1510, 1547), 'shutil.copy', 'shutil.copy', (['files[i]', '"""./test_imgs/"""'], {}), "(files[i], './test_imgs/')\n", (1521, 1547), False, 'import shutil\n'), ((1555, 1608), 'shutil.copy', 'shutil.copy', (["(files[i][:-4] + '_r.jpg')", '"""./test_imgs/"""'], {}), "(files[i][:-4] + '_r.jpg', './test_imgs/')\n", (1566, 1608), False, 'import shutil\n'), ((1616, 1669), 'shutil.copy', 'shutil.copy', (["(files[i][:-4] + '_b.jpg')", '"""./test_imgs/"""'], {}), "(files[i][:-4] + '_b.jpg', './test_imgs/')\n", (1627, 1669), False, 'import shutil\n')]
import importlib import json import os import pdb import sys import fnet import pandas as pd import tifffile import numpy as np from fnet.transforms import normalize def pearson_loss(x, y): #x = output #y = target vx = x - torch.mean(x) vy = y - torch.mean(y) cost = torch.sum(vx * vy) / (torch.sqrt(torch.sum(vx ** 2)) * torch.sqrt(torch.sum(vy ** 2))) return cost # code retrieved on 21.05.21 from: https://github.com/pytorch/pytorch/issues/1254 def pearsonr(x, y): """ Mimics `scipy.stats.pearsonr` Arguments --------- x : 1D torch.Tensor y : 1D torch.Tensor Returns ------- r_val : float pearsonr correlation coefficient between x and y Scipy docs ref: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html Scipy code ref: https://github.com/scipy/scipy/blob/v0.19.0/scipy/stats/stats.py#L2975-L3033 Example: >>> x = np.random.randn(100) >>> y = np.random.randn(100) >>> sp_corr = scipy.stats.pearsonr(x, y)[0] >>> th_corr = pearsonr(torch.from_numpy(x), torch.from_numpy(y)) >>> np.allclose(sp_corr, th_corr) """ x = x.detach().cpu().numpy().flatten() #pred y = y.detach().cpu().numpy().flatten() #target pearson_img = np.corrcoef(x,y) r_val = pearson_img[0,1] return r_val def load_model(path_model, gpu_ids=0, module='fnet_model', in_channels=1, out_channels=1): module_fnet_model = importlib.import_module('fnet.' + module) if os.path.isdir(path_model): path_model = os.path.join(path_model, 'model.p') model = module_fnet_model.Model(in_channels=in_channels, out_channels=out_channels) model.load_state(path_model, gpu_ids=gpu_ids) return model def load_model_from_dir(path_model_dir, gpu_ids=0, in_channels=1, out_channels=1): assert os.path.isdir(path_model_dir) path_model_state = os.path.join(path_model_dir, 'model.p') model = fnet.fnet_model.Model(in_channels=in_channels, out_channels=out_channels) model.load_state(path_model_state, gpu_ids=gpu_ids) return model def compute_dataset_min_max_ranges(train_path, val_path=None, norm=False): df_train = pd.read_csv(train_path) if val_path is not None: df_val = pd.read_csv(val_path) df=pd.concat([df_train, df_val]) else: df=df_train min_bright=[] max_bright =[] min_inf = [] max_inf = [] min_dapi = [] max_dapi = [] if df.iloc[0,:]['target_channel'] is None: no_target = True else: no_target = False if df.iloc[0,:]['dapi_channel'] is None: no_dapi = True else: no_dapi = False for index in range(len(df)): element=df.iloc[index, :] image = tifffile.imread(element['file']) if not no_target: image_infection = image[element['target_channel'],:,:] min_inf.append(np.min(image_infection)) max_inf.append(np.max(image_infection)) if not no_dapi: image_dapi = image[element['dapi_channel'],:,:] min_dapi.append(np.min(image_dapi)) max_dapi.append(np.max(image_dapi)) image_bright = image[element['signal_channel'],:,:] if norm: image_bright = normalize(image_bright) min_bright.append(np.min(image_bright)) max_bright.append(np.max(image_bright)) min_inf = np.min(np.array(min_inf)) if not no_target else None max_inf = np.max(np.array(max_inf)) if not no_target else None min_dapi = np.min(np.array(min_dapi)) if not no_dapi else None max_dapi = np.max(np.array(max_dapi)) if not no_dapi else None min_bright = np.min(np.array(min_bright)) max_bright = np.max(np.array(max_bright)) return [min_bright, max_bright], [min_inf, max_inf], [min_dapi, max_dapi]
[ "fnet.fnet_model.Model", "importlib.import_module", "pandas.read_csv", "numpy.corrcoef", "tifffile.imread", "os.path.join", "numpy.max", "numpy.array", "os.path.isdir", "numpy.min", "pandas.concat", "fnet.transforms.normalize" ]
[((1322, 1339), 'numpy.corrcoef', 'np.corrcoef', (['x', 'y'], {}), '(x, y)\n', (1333, 1339), True, 'import numpy as np\n'), ((1503, 1544), 'importlib.import_module', 'importlib.import_module', (["('fnet.' + module)"], {}), "('fnet.' + module)\n", (1526, 1544), False, 'import importlib\n'), ((1552, 1577), 'os.path.isdir', 'os.path.isdir', (['path_model'], {}), '(path_model)\n', (1565, 1577), False, 'import os\n'), ((1886, 1915), 'os.path.isdir', 'os.path.isdir', (['path_model_dir'], {}), '(path_model_dir)\n', (1899, 1915), False, 'import os\n'), ((1939, 1978), 'os.path.join', 'os.path.join', (['path_model_dir', '"""model.p"""'], {}), "(path_model_dir, 'model.p')\n", (1951, 1978), False, 'import os\n'), ((1991, 2064), 'fnet.fnet_model.Model', 'fnet.fnet_model.Model', ([], {'in_channels': 'in_channels', 'out_channels': 'out_channels'}), '(in_channels=in_channels, out_channels=out_channels)\n', (2012, 2064), False, 'import fnet\n'), ((2234, 2257), 'pandas.read_csv', 'pd.read_csv', (['train_path'], {}), '(train_path)\n', (2245, 2257), True, 'import pandas as pd\n'), ((1600, 1635), 'os.path.join', 'os.path.join', (['path_model', '"""model.p"""'], {}), "(path_model, 'model.p')\n", (1612, 1635), False, 'import os\n'), ((2304, 2325), 'pandas.read_csv', 'pd.read_csv', (['val_path'], {}), '(val_path)\n', (2315, 2325), True, 'import pandas as pd\n'), ((2337, 2366), 'pandas.concat', 'pd.concat', (['[df_train, df_val]'], {}), '([df_train, df_val])\n', (2346, 2366), True, 'import pandas as pd\n'), ((2825, 2857), 'tifffile.imread', 'tifffile.imread', (["element['file']"], {}), "(element['file'])\n", (2840, 2857), False, 'import tifffile\n'), ((3794, 3814), 'numpy.array', 'np.array', (['min_bright'], {}), '(min_bright)\n', (3802, 3814), True, 'import numpy as np\n'), ((3840, 3860), 'numpy.array', 'np.array', (['max_bright'], {}), '(max_bright)\n', (3848, 3860), True, 'import numpy as np\n'), ((3371, 3394), 'fnet.transforms.normalize', 'normalize', (['image_bright'], {}), '(image_bright)\n', (3380, 3394), False, 'from fnet.transforms import normalize\n'), ((3421, 3441), 'numpy.min', 'np.min', (['image_bright'], {}), '(image_bright)\n', (3427, 3441), True, 'import numpy as np\n'), ((3469, 3489), 'numpy.max', 'np.max', (['image_bright'], {}), '(image_bright)\n', (3475, 3489), True, 'import numpy as np\n'), ((3517, 3534), 'numpy.array', 'np.array', (['min_inf'], {}), '(min_inf)\n', (3525, 3534), True, 'import numpy as np\n'), ((3584, 3601), 'numpy.array', 'np.array', (['max_inf'], {}), '(max_inf)\n', (3592, 3601), True, 'import numpy as np\n'), ((3653, 3671), 'numpy.array', 'np.array', (['min_dapi'], {}), '(min_dapi)\n', (3661, 3671), True, 'import numpy as np\n'), ((3720, 3738), 'numpy.array', 'np.array', (['max_dapi'], {}), '(max_dapi)\n', (3728, 3738), True, 'import numpy as np\n'), ((2987, 3010), 'numpy.min', 'np.min', (['image_infection'], {}), '(image_infection)\n', (2993, 3010), True, 'import numpy as np\n'), ((3039, 3062), 'numpy.max', 'np.max', (['image_infection'], {}), '(image_infection)\n', (3045, 3062), True, 'import numpy as np\n'), ((3185, 3203), 'numpy.min', 'np.min', (['image_dapi'], {}), '(image_dapi)\n', (3191, 3203), True, 'import numpy as np\n'), ((3233, 3251), 'numpy.max', 'np.max', (['image_dapi'], {}), '(image_dapi)\n', (3239, 3251), True, 'import numpy as np\n')]
import os import pandas as pd import pymongo import requests import time from splinter import Browser from bs4 import BeautifulSoup from selenium import webdriver print(os.path.abspath("chromedriver.exe")) def init_browser(): executable_path = {"executable_path": os.path.abspath("chromedriver.exe")} return Browser("chrome", **executable_path, headless=False) def scrape(): browser = init_browser() url = "https://mars.nasa.gov/news/" browser.visit(url) html = browser.html soup = BeautifulSoup(html, "html.parser") mars_title = soup.find("div", class_="content_title").text mars_p = soup.find("div", class_="article_teaser_body").text img_url = "https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars" browser.visit(img_url) browser.click_link_by_partial_text('FULL IMAGE') time.sleep(3) browser.click_link_by_partial_text('more info') img_html = browser.html soup = BeautifulSoup(img_html, "html.parser") img_path = soup.find('figure', class_='lede').a['href'] feat_img_url = "https://www.jpl.nasa.gov" + img_path weather_url = "https://twitter.com/marswxreport?lang=en" browser.visit(weather_url) weather_html = browser.html soup = BeautifulSoup(weather_html, 'html.parser') mars_weather = soup.find('p', class_="TweetTextSize TweetTextSize--normal js-tweet-text tweet-text").text facts_url = "https://space-facts.com/mars/" browser.visit(facts_url) facts_html = browser.html soup = BeautifulSoup(facts_html, 'html.parser') table_data = soup.find('table', class_="tablepress tablepress-id-mars") table_all = table_data.find_all('tr') labels = [] values = [] for tr in table_all: td_elements = tr.find_all('td') labels.append(td_elements[0].text) values.append(td_elements[1].text) mars_df = pd.DataFrame({ "Label": labels, "Values": values }) facts_table = mars_df.to_html(header=False, index=False) facts_table usgs_url = "https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars" browser.visit(usgs_url) usgs_html = browser.html soup = BeautifulSoup(usgs_html, "html.parser") mars_hemi = [] results = soup.find("div", class_="collapsible results" ) hemis = results.find_all("div", class_="item") for hemi in hemis: title = hemi.find("h3").text img_link = hemi.find("a")["href"] usgs_img_link = "https://astrogeology.usgs.gov" + img_link browser.visit(usgs_img_link) html = browser.html soup = BeautifulSoup(html, "html.parser") downloads = soup.find("div", class_="downloads") usgs_img_url = downloads.find("a")["href"] mars_hemi.append({"title": title, "img_url": usgs_img_url}) mars_dict = { "mars_title": mars_title, "mars_p": mars_p, "feat_img_url": feat_img_url, "mars_weather": mars_weather, "facts_table": facts_table, "hemi_images": mars_hemi } return mars_dict if __name__ == "__main__": print(scrape())
[ "pandas.DataFrame", "splinter.Browser", "time.sleep", "bs4.BeautifulSoup", "os.path.abspath" ]
[((170, 205), 'os.path.abspath', 'os.path.abspath', (['"""chromedriver.exe"""'], {}), "('chromedriver.exe')\n", (185, 205), False, 'import os\n'), ((319, 371), 'splinter.Browser', 'Browser', (['"""chrome"""'], {'headless': '(False)'}), "('chrome', **executable_path, headless=False)\n", (326, 371), False, 'from splinter import Browser\n'), ((519, 553), 'bs4.BeautifulSoup', 'BeautifulSoup', (['html', '"""html.parser"""'], {}), "(html, 'html.parser')\n", (532, 553), False, 'from bs4 import BeautifulSoup\n'), ((844, 857), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (854, 857), False, 'import time\n'), ((950, 988), 'bs4.BeautifulSoup', 'BeautifulSoup', (['img_html', '"""html.parser"""'], {}), "(img_html, 'html.parser')\n", (963, 988), False, 'from bs4 import BeautifulSoup\n'), ((1242, 1284), 'bs4.BeautifulSoup', 'BeautifulSoup', (['weather_html', '"""html.parser"""'], {}), "(weather_html, 'html.parser')\n", (1255, 1284), False, 'from bs4 import BeautifulSoup\n'), ((1518, 1558), 'bs4.BeautifulSoup', 'BeautifulSoup', (['facts_html', '"""html.parser"""'], {}), "(facts_html, 'html.parser')\n", (1531, 1558), False, 'from bs4 import BeautifulSoup\n'), ((2213, 2252), 'bs4.BeautifulSoup', 'BeautifulSoup', (['usgs_html', '"""html.parser"""'], {}), "(usgs_html, 'html.parser')\n", (2226, 2252), False, 'from bs4 import BeautifulSoup\n'), ((270, 305), 'os.path.abspath', 'os.path.abspath', (['"""chromedriver.exe"""'], {}), "('chromedriver.exe')\n", (285, 305), False, 'import os\n'), ((1880, 1929), 'pandas.DataFrame', 'pd.DataFrame', (["{'Label': labels, 'Values': values}"], {}), "({'Label': labels, 'Values': values})\n", (1892, 1929), True, 'import pandas as pd\n'), ((2640, 2674), 'bs4.BeautifulSoup', 'BeautifulSoup', (['html', '"""html.parser"""'], {}), "(html, 'html.parser')\n", (2653, 2674), False, 'from bs4 import BeautifulSoup\n')]
import lyricsgenius geniustoken = "<KEY>" genius = lyricsgenius.Genius(geniustoken) songname = input("") def lysearch(songname): import lyricsgenius geniustoken = "<KEY>" genius = lyricsgenius.Genius(geniustoken) songname = songname.split("/") if len(songname) == 1: song = genius.search_song(songname[0]) elif len(songname) > 1: song = genius.search_song(songname[0], songname[1]) ly = song.lyrics return ly #print(song.lyrics)
[ "lyricsgenius.Genius" ]
[((53, 85), 'lyricsgenius.Genius', 'lyricsgenius.Genius', (['geniustoken'], {}), '(geniustoken)\n', (72, 85), False, 'import lyricsgenius\n'), ((199, 231), 'lyricsgenius.Genius', 'lyricsgenius.Genius', (['geniustoken'], {}), '(geniustoken)\n', (218, 231), False, 'import lyricsgenius\n')]
import numpy as np import numpy.random as rand from functools import reduce class Network: def __init__(self, layer_sizes): # layer_sizes: list of numbers representing number of neurons per layer # Create a numpy array of biases for each layer except the (first) input layer self.biases = [rand.randn(l, 1) for l in layer_sizes[1:]] # The weights are an array of matrices. 'Between' each two layers is one matrix. # Every row contains a set of weights for each node self.weights = [rand.randn(y, x) for x, y in zip(layer_sizes[:-1], layer_sizes[1:])] def feed_forward(self, input): # Perform a left fold return reduce(lambda input, b_w: np.dot(b_w[1], input)+b_w[0], zip(self.biases, self.weights), input) def sigmoid(z): # The sigmoid function return 1.0 / (1.0 + np.exp(-z)) def sigmoid_deriv(z): # First-order derivative of the sigmoid function return sigmoid(z) * (1 - sigmoid(z))
[ "numpy.exp", "numpy.dot", "numpy.random.randn" ]
[((322, 338), 'numpy.random.randn', 'rand.randn', (['l', '(1)'], {}), '(l, 1)\n', (332, 338), True, 'import numpy.random as rand\n'), ((539, 555), 'numpy.random.randn', 'rand.randn', (['y', 'x'], {}), '(y, x)\n', (549, 555), True, 'import numpy.random as rand\n'), ((857, 867), 'numpy.exp', 'np.exp', (['(-z)'], {}), '(-z)\n', (863, 867), True, 'import numpy as np\n'), ((715, 736), 'numpy.dot', 'np.dot', (['b_w[1]', 'input'], {}), '(b_w[1], input)\n', (721, 736), True, 'import numpy as np\n')]
import sys sys.path.append('../') # 新加入的 sys.path.append('.') # 新加入的 from flasgger import Swagger from flask import Flask from v1.sum_ab_controller import demo_sum app = Flask(__name__) # API 文档的配置 template = { "swagger": "2.0", "info": { "title": "XXX 在线API", "description": "在线API 调用测试", "contact": { "responsibleOrganization": "AturX", "responsibleDeveloper": "AturX", "email": "<EMAIL>", "url": "www.me.com", }, "termsOfService": "http://me.com/terms", "version": "0.0.1" }, "host": "localhost:5000", # overrides localhost:5000 "basePath": "/", # base bash for blueprint registration "schemes": [ "http", "https" ], "operationId": "getmyData" } Swagger(app, template=template) # 注册蓝图,并指定其对应的前缀(url_prefix) app.register_blueprint(demo_sum, url_prefix="/sumAB") if __name__ == '__main__': # 访问API 接口地址 : http://localhost:5000/apidocs/ app.run(host='0.0.0.0', port='5000')
[ "flasgger.Swagger", "sys.path.append", "flask.Flask" ]
[((11, 33), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (26, 33), False, 'import sys\n'), ((42, 62), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (57, 62), False, 'import sys\n'), ((173, 188), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (178, 188), False, 'from flask import Flask\n'), ((727, 758), 'flasgger.Swagger', 'Swagger', (['app'], {'template': 'template'}), '(app, template=template)\n', (734, 758), False, 'from flasgger import Swagger\n')]
from django.conf.urls import patterns, include, url from .views import (show_job_submitted, dynamic_input, dynamic_finished, ogusa_results, dynamic_landing, dynamic_behavioral, behavior_results, edit_dynamic_behavioral, elastic_results, dynamic_elasticities, edit_dynamic_elastic) urlpatterns = patterns('', url(r'^results/(?P<pk>\d+)/', ogusa_results, name='ogusa_results'), url(r'^(?P<pk>\d+)/', dynamic_landing, name='dynamic_landing'), url(r'^ogusa/(?P<pk>\d+)/', dynamic_input, name='dynamic_input'), url(r'^behavioral/(?P<pk>\d+)/', dynamic_behavioral, name='dynamic_behavioral'), url(r'^behavioral/edit/(?P<pk>\d+)/', edit_dynamic_behavioral, name='edit_dynamic_behavioral'), url(r'^macro/edit/(?P<pk>\d+)/', edit_dynamic_elastic, name='edit_dynamic_elastic'), url(r'^macro/(?P<pk>\d+)/', dynamic_elasticities, name='dynamic_elasticities'), url(r'^submitted/(?P<pk>\d+)/', show_job_submitted, name='show_job_submitted'), url(r'^macro_results/(?P<pk>\d+)/', elastic_results, name='elastic_results'), url(r'^behavior_results/(?P<pk>\d+)/', behavior_results, name='behavior_results'), url(r'^dynamic_finished/', dynamic_finished, name='dynamic_finished'), )
[ "django.conf.urls.url" ]
[((375, 441), 'django.conf.urls.url', 'url', (['"""^results/(?P<pk>\\\\d+)/"""', 'ogusa_results'], {'name': '"""ogusa_results"""'}), "('^results/(?P<pk>\\\\d+)/', ogusa_results, name='ogusa_results')\n", (378, 441), False, 'from django.conf.urls import patterns, include, url\n'), ((447, 509), 'django.conf.urls.url', 'url', (['"""^(?P<pk>\\\\d+)/"""', 'dynamic_landing'], {'name': '"""dynamic_landing"""'}), "('^(?P<pk>\\\\d+)/', dynamic_landing, name='dynamic_landing')\n", (450, 509), False, 'from django.conf.urls import patterns, include, url\n'), ((515, 579), 'django.conf.urls.url', 'url', (['"""^ogusa/(?P<pk>\\\\d+)/"""', 'dynamic_input'], {'name': '"""dynamic_input"""'}), "('^ogusa/(?P<pk>\\\\d+)/', dynamic_input, name='dynamic_input')\n", (518, 579), False, 'from django.conf.urls import patterns, include, url\n'), ((585, 664), 'django.conf.urls.url', 'url', (['"""^behavioral/(?P<pk>\\\\d+)/"""', 'dynamic_behavioral'], {'name': '"""dynamic_behavioral"""'}), "('^behavioral/(?P<pk>\\\\d+)/', dynamic_behavioral, name='dynamic_behavioral')\n", (588, 664), False, 'from django.conf.urls import patterns, include, url\n'), ((670, 769), 'django.conf.urls.url', 'url', (['"""^behavioral/edit/(?P<pk>\\\\d+)/"""', 'edit_dynamic_behavioral'], {'name': '"""edit_dynamic_behavioral"""'}), "('^behavioral/edit/(?P<pk>\\\\d+)/', edit_dynamic_behavioral, name=\n 'edit_dynamic_behavioral')\n", (673, 769), False, 'from django.conf.urls import patterns, include, url\n'), ((770, 858), 'django.conf.urls.url', 'url', (['"""^macro/edit/(?P<pk>\\\\d+)/"""', 'edit_dynamic_elastic'], {'name': '"""edit_dynamic_elastic"""'}), "('^macro/edit/(?P<pk>\\\\d+)/', edit_dynamic_elastic, name=\n 'edit_dynamic_elastic')\n", (773, 858), False, 'from django.conf.urls import patterns, include, url\n'), ((859, 937), 'django.conf.urls.url', 'url', (['"""^macro/(?P<pk>\\\\d+)/"""', 'dynamic_elasticities'], {'name': '"""dynamic_elasticities"""'}), "('^macro/(?P<pk>\\\\d+)/', dynamic_elasticities, name='dynamic_elasticities')\n", (862, 937), False, 'from django.conf.urls import patterns, include, url\n'), ((943, 1021), 'django.conf.urls.url', 'url', (['"""^submitted/(?P<pk>\\\\d+)/"""', 'show_job_submitted'], {'name': '"""show_job_submitted"""'}), "('^submitted/(?P<pk>\\\\d+)/', show_job_submitted, name='show_job_submitted')\n", (946, 1021), False, 'from django.conf.urls import patterns, include, url\n'), ((1027, 1103), 'django.conf.urls.url', 'url', (['"""^macro_results/(?P<pk>\\\\d+)/"""', 'elastic_results'], {'name': '"""elastic_results"""'}), "('^macro_results/(?P<pk>\\\\d+)/', elastic_results, name='elastic_results')\n", (1030, 1103), False, 'from django.conf.urls import patterns, include, url\n'), ((1109, 1195), 'django.conf.urls.url', 'url', (['"""^behavior_results/(?P<pk>\\\\d+)/"""', 'behavior_results'], {'name': '"""behavior_results"""'}), "('^behavior_results/(?P<pk>\\\\d+)/', behavior_results, name=\n 'behavior_results')\n", (1112, 1195), False, 'from django.conf.urls import patterns, include, url\n'), ((1196, 1264), 'django.conf.urls.url', 'url', (['"""^dynamic_finished/"""', 'dynamic_finished'], {'name': '"""dynamic_finished"""'}), "('^dynamic_finished/', dynamic_finished, name='dynamic_finished')\n", (1199, 1264), False, 'from django.conf.urls import patterns, include, url\n')]
import collections import torch import einops import cached_property import padertorch as pt # loss: torch.Tenso r =None, # losses: dict =None, # scalars: dict =None, # histograms: dict =None, # audios: dict =None, # images: dict =None, class ReviewSummary(collections.abc.Mapping): """ >>> review_summary = ReviewSummary() >>> review_summary ReviewSummary(prefix='', _data={}) """ _keys = set(pt.train.hooks.SummaryHook.empty_summary_dict().keys()) | { 'loss', 'losses' } def __init__(self, prefix='', _data=None, sampling_rate=None, visible_dB=60): if _data is None: _data = {} self.data = _data self.prefix = prefix self.sampling_rate = sampling_rate self.visible_dB = visible_dB def add_to_loss(self, value): assert torch.isfinite(value), value if 'loss' in self.data: self.data['loss'] = self.data['loss'] + value else: self.data['loss'] = value def add_scalar(self, name, *value): # Save the mean of all added values value = pt.data.batch.example_to_numpy(value, detach=True) self.data.setdefault( 'scalars', {} ).setdefault( f'{self.prefix}{name}', [] ).extend(value) def add_audio(self, name, signal, sampling_rate=None, batch_first=None, normalize=True): if sampling_rate is None: sampling_rate = self.sampling_rate assert sampling_rate is not None, sampling_rate audio = pt.summary.audio( signal=signal, sampling_rate=sampling_rate, batch_first=batch_first, normalize=normalize ) self.data.setdefault( 'audios', {} )[f'{self.prefix}{name}'] = audio def add_text(self, name, text): assert isinstance(text, str), (type(text), text) self.data.setdefault( 'texts', {} )[f'{self.prefix}{name}'] = text def _rearrange(self, array, rearrange): if rearrange is not None: return einops.rearrange(array, rearrange) else: return array def add_image(self, name, image): # Save the last added value image = pt.utils.to_numpy(image, detach=True) if image.ndim != 3: raise AssertionError( 'Did you forgot to call "pt.summary.*_to_image"?\n' f'Expect ndim == 3, got shape {image.shape}.' ) self.data.setdefault( 'images', {} )[f'{self.prefix}{name}'] = image def add_stft_image( self, name, signal, *, batch_first=None, color='viridis', rearrange=None): signal = self._rearrange(signal, rearrange) image = pt.summary.stft_to_image(signal, batch_first=batch_first, color=color, visible_dB=self.visible_dB) self.add_image(name, image) def add_spectrogram_image( self, name, signal, *, batch_first=None, color='viridis', rearrange=None): signal = self._rearrange(signal, rearrange) image = pt.summary.spectrogram_to_image(signal, batch_first=batch_first, color=color, visible_dB=self.visible_dB) self.add_image(name, image) def add_mask_image(self, name, mask, *, batch_first=None, color='viridis', rearrange=None): mask = self._rearrange(mask, rearrange) image = pt.summary.mask_to_image(mask, batch_first=batch_first, color=color) self.add_image(name, image) def add_histogram(self, name, values): value = pt.utils.to_numpy(values, detach=True) self.data.setdefault( 'histograms', {} ).setdefault( f'{self.prefix}{name}', [] ).append(value) def __contains__(self, item): return item in self.data def __getitem__(self, key): assert key in self._keys, (key, self._keys) return self.data[key] def __setitem__(self, key, value): assert key in self._keys, (key, self._keys) self.data[key] = value def get(self, item, default): if item in self: return self.data[item] else: return default def pop(self, *args, **kwargs): """pop(key[, default])""" return self.data.pop(*args, **kwargs) def setdefault(self, key, default): self.data.setdefault(key, default) def __iter__(self): return iter(self.data) def __len__(self): return len(self.data) def __repr__(self): return f'{self.__class__.__name__}(prefix={self.prefix!r}, _data={dict(self)!r})' def _repr_pretty_(self, p, cycle): """ >>> review_summary = ReviewSummary() >>> review_summary.add_to_loss(1) >>> review_summary.add_scalar('abc', 2) >>> review_summary ReviewSummary(prefix='', _data={'loss': 1, 'scalars': {'abc': [2]}}) >>> from IPython.lib.pretty import pprint >>> pprint(review_summary) ReviewSummary(prefix='', _data={'loss': 1, 'scalars': {'abc': [2]}}) >>> pprint(review_summary, max_width=79-18) ReviewSummary( prefix='', _data={'loss': 1, 'scalars': {'abc': [2]}} ) >>> pprint(review_summary, max_width=79-40) ReviewSummary( prefix='', _data={'loss': 1, 'scalars': {'abc': [2]}} ) """ if cycle: p.text(f'{self.__class__.__name__}(...)') else: txt = f'{self.__class__.__name__}(' with p.group(4, txt, ''): p.breakable(sep='') p.text('prefix=') p.pretty(self.prefix) p.text(',') p.breakable() txt = '_data=' with p.group(len(txt), txt, ''): p.pretty(dict(self)) p.breakable('') p.text(')') class _Plotter: def __init__(self, review: 'ReviewSummary'): self.review = review def image( self, key, origin='lower', **kwargs ): import numpy as np import matplotlib.pyplot as plt kwargs = { 'origin': origin, **kwargs, } if key not in self.review['images']: from paderbox.utils.mapping import DispatchError raise DispatchError(key, self.review['images'].keys()) X = np.einsum('chw->hwc', self.review['images'][key]) if origin == 'lower': X = X[::-1] else: assert origin == 'upper' # ToDo: Where is AxesImage defined? ax: 'plt.AxesImage' = plt.imshow( X, **kwargs, ) # ax.set_title(key) plt.title(key) plt.grid(False) return ax def images( self, columns=1, font_scale=1.0, line_width=3, figure_size=(8.0, 6.0), ): from paderbox.visualization import axes_context from paderbox.visualization.context_manager import _AxesHandler with axes_context( columns=columns, font_scale=font_scale, line_width=line_width, figure_size=figure_size, ) as axes: axes: _AxesHandler for k in self.review['images']: axes.new.grid(False) # set gca self.image(k) @cached_property.cached_property def plot(self): return self._Plotter(self) def play(self, key=None): if key is None: for k in self['audios'].keys(): self.play(k) elif key in self['audios']: from paderbox.io.play import play data, sample_rate = self['audios'][key] play(data, sample_rate=sample_rate, name=key) else: from paderbox.utils.mapping import DispatchError raise DispatchError(key, self['audios'].keys())
[ "matplotlib.pyplot.imshow", "padertorch.summary.spectrogram_to_image", "matplotlib.pyplot.grid", "padertorch.data.batch.example_to_numpy", "padertorch.summary.mask_to_image", "torch.isfinite", "einops.rearrange", "paderbox.visualization.axes_context", "paderbox.io.play.play", "numpy.einsum", "pa...
[((834, 855), 'torch.isfinite', 'torch.isfinite', (['value'], {}), '(value)\n', (848, 855), False, 'import torch\n'), ((1106, 1156), 'padertorch.data.batch.example_to_numpy', 'pt.data.batch.example_to_numpy', (['value'], {'detach': '(True)'}), '(value, detach=True)\n', (1136, 1156), True, 'import padertorch as pt\n'), ((1587, 1698), 'padertorch.summary.audio', 'pt.summary.audio', ([], {'signal': 'signal', 'sampling_rate': 'sampling_rate', 'batch_first': 'batch_first', 'normalize': 'normalize'}), '(signal=signal, sampling_rate=sampling_rate, batch_first=\n batch_first, normalize=normalize)\n', (1603, 1698), True, 'import padertorch as pt\n'), ((2309, 2346), 'padertorch.utils.to_numpy', 'pt.utils.to_numpy', (['image'], {'detach': '(True)'}), '(image, detach=True)\n', (2326, 2346), True, 'import padertorch as pt\n'), ((2854, 2956), 'padertorch.summary.stft_to_image', 'pt.summary.stft_to_image', (['signal'], {'batch_first': 'batch_first', 'color': 'color', 'visible_dB': 'self.visible_dB'}), '(signal, batch_first=batch_first, color=color,\n visible_dB=self.visible_dB)\n', (2878, 2956), True, 'import padertorch as pt\n'), ((3188, 3298), 'padertorch.summary.spectrogram_to_image', 'pt.summary.spectrogram_to_image', (['signal'], {'batch_first': 'batch_first', 'color': 'color', 'visible_dB': 'self.visible_dB'}), '(signal, batch_first=batch_first, color=\n color, visible_dB=self.visible_dB)\n', (3219, 3298), True, 'import padertorch as pt\n'), ((3491, 3559), 'padertorch.summary.mask_to_image', 'pt.summary.mask_to_image', (['mask'], {'batch_first': 'batch_first', 'color': 'color'}), '(mask, batch_first=batch_first, color=color)\n', (3515, 3559), True, 'import padertorch as pt\n'), ((3656, 3694), 'padertorch.utils.to_numpy', 'pt.utils.to_numpy', (['values'], {'detach': '(True)'}), '(values, detach=True)\n', (3673, 3694), True, 'import padertorch as pt\n'), ((2144, 2178), 'einops.rearrange', 'einops.rearrange', (['array', 'rearrange'], {}), '(array, rearrange)\n', (2160, 2178), False, 'import einops\n'), ((6616, 6665), 'numpy.einsum', 'np.einsum', (['"""chw->hwc"""', "self.review['images'][key]"], {}), "('chw->hwc', self.review['images'][key])\n", (6625, 6665), True, 'import numpy as np\n'), ((6871, 6894), 'matplotlib.pyplot.imshow', 'plt.imshow', (['X'], {}), '(X, **kwargs)\n', (6881, 6894), True, 'import matplotlib.pyplot as plt\n'), ((6986, 7000), 'matplotlib.pyplot.title', 'plt.title', (['key'], {}), '(key)\n', (6995, 7000), True, 'import matplotlib.pyplot as plt\n'), ((7013, 7028), 'matplotlib.pyplot.grid', 'plt.grid', (['(False)'], {}), '(False)\n', (7021, 7028), True, 'import matplotlib.pyplot as plt\n'), ((7387, 7491), 'paderbox.visualization.axes_context', 'axes_context', ([], {'columns': 'columns', 'font_scale': 'font_scale', 'line_width': 'line_width', 'figure_size': 'figure_size'}), '(columns=columns, font_scale=font_scale, line_width=line_width,\n figure_size=figure_size)\n', (7399, 7491), False, 'from paderbox.visualization import axes_context\n'), ((8129, 8174), 'paderbox.io.play.play', 'play', (['data'], {'sample_rate': 'sample_rate', 'name': 'key'}), '(data, sample_rate=sample_rate, name=key)\n', (8133, 8174), False, 'from paderbox.io.play import play\n'), ((426, 473), 'padertorch.train.hooks.SummaryHook.empty_summary_dict', 'pt.train.hooks.SummaryHook.empty_summary_dict', ([], {}), '()\n', (471, 473), True, 'import padertorch as pt\n')]
# Generated by Django 2.1.4 on 2019-01-21 03:56 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Image', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=200)), ('slug', models.CharField(blank=True, max_length=200)), ('image', models.ImageField(upload_to='image/%Y')), ('url', models.URLField()), ('description', models.TextField(blank=True)), ('created', models.DateField(auto_now_add=True, db_index=True)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='images_created', to=settings.AUTH_USER_MODEL)), ('user_like', models.ManyToManyField(blank=True, related_name='image_liked', to=settings.AUTH_USER_MODEL)), ], options={ 'db_table': 'images', }, ), ]
[ "django.db.models.DateField", "django.db.models.TextField", "django.db.models.ForeignKey", "django.db.models.ManyToManyField", "django.db.models.AutoField", "django.db.models.ImageField", "django.db.migrations.swappable_dependency", "django.db.models.URLField", "django.db.models.CharField" ]
[((247, 304), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (278, 304), False, 'from django.db import migrations, models\n'), ((434, 527), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (450, 527), False, 'from django.db import migrations, models\n'), ((552, 584), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)'}), '(max_length=200)\n', (568, 584), False, 'from django.db import migrations, models\n'), ((612, 656), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(200)'}), '(blank=True, max_length=200)\n', (628, 656), False, 'from django.db import migrations, models\n'), ((685, 724), 'django.db.models.ImageField', 'models.ImageField', ([], {'upload_to': '"""image/%Y"""'}), "(upload_to='image/%Y')\n", (702, 724), False, 'from django.db import migrations, models\n'), ((751, 768), 'django.db.models.URLField', 'models.URLField', ([], {}), '()\n', (766, 768), False, 'from django.db import migrations, models\n'), ((803, 831), 'django.db.models.TextField', 'models.TextField', ([], {'blank': '(True)'}), '(blank=True)\n', (819, 831), False, 'from django.db import migrations, models\n'), ((862, 912), 'django.db.models.DateField', 'models.DateField', ([], {'auto_now_add': '(True)', 'db_index': '(True)'}), '(auto_now_add=True, db_index=True)\n', (878, 912), False, 'from django.db import migrations, models\n'), ((940, 1067), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.CASCADE', 'related_name': '"""images_created"""', 'to': 'settings.AUTH_USER_MODEL'}), "(on_delete=django.db.models.deletion.CASCADE, related_name\n ='images_created', to=settings.AUTH_USER_MODEL)\n", (957, 1067), False, 'from django.db import migrations, models\n'), ((1095, 1191), 'django.db.models.ManyToManyField', 'models.ManyToManyField', ([], {'blank': '(True)', 'related_name': '"""image_liked"""', 'to': 'settings.AUTH_USER_MODEL'}), "(blank=True, related_name='image_liked', to=settings.\n AUTH_USER_MODEL)\n", (1117, 1191), False, 'from django.db import migrations, models\n')]
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 # {fact rule=os-command-injection@v1.0 defects=1} def exec_command_noncompliant(): from paramiko import client from flask import request address = request.args.get("address") cmd = "ping -c 1 %s" % address client = client.SSHClient() client.connect("ssh.samplehost.com") # Noncompliant: address argument is not sanitized. client.exec_command(cmd) # {/fact} # {fact rule=os-command-injection@v1.0 defects=0} def exec_command_compliant(): from paramiko import client from flask import request address = request.args.get("address") # Compliant: address argument is sanitized (shell-escaped). address = shlex.quote(request.args.get("address")) cmd = "ping -c 1 %s" % address client = client.SSHClient() client.connect("ssh.samplehost.com") client.exec_command(cmd) # {/fact}
[ "flask.request.args.get", "paramiko.client.connect", "paramiko.client.exec_command", "paramiko.client.SSHClient" ]
[((269, 296), 'flask.request.args.get', 'request.args.get', (['"""address"""'], {}), "('address')\n", (285, 296), False, 'from flask import request\n'), ((345, 363), 'paramiko.client.SSHClient', 'client.SSHClient', ([], {}), '()\n', (361, 363), False, 'from paramiko import client\n'), ((368, 404), 'paramiko.client.connect', 'client.connect', (['"""ssh.samplehost.com"""'], {}), "('ssh.samplehost.com')\n", (382, 404), False, 'from paramiko import client\n'), ((464, 488), 'paramiko.client.exec_command', 'client.exec_command', (['cmd'], {}), '(cmd)\n', (483, 488), False, 'from paramiko import client\n'), ((657, 684), 'flask.request.args.get', 'request.args.get', (['"""address"""'], {}), "('address')\n", (673, 684), False, 'from flask import request\n'), ((852, 870), 'paramiko.client.SSHClient', 'client.SSHClient', ([], {}), '()\n', (868, 870), False, 'from paramiko import client\n'), ((875, 911), 'paramiko.client.connect', 'client.connect', (['"""ssh.samplehost.com"""'], {}), "('ssh.samplehost.com')\n", (889, 911), False, 'from paramiko import client\n'), ((916, 940), 'paramiko.client.exec_command', 'client.exec_command', (['cmd'], {}), '(cmd)\n', (935, 940), False, 'from paramiko import client\n'), ((775, 802), 'flask.request.args.get', 'request.args.get', (['"""address"""'], {}), "('address')\n", (791, 802), False, 'from flask import request\n')]
#!/usr/bin/python # encoding: utf-8 """ adobeutils.py Utilities to enable munki to install/uninstall Adobe CS3/CS4/CS5 products using the CS3/CS4/CS5 Deployment Toolkits. """ # Copyright 2009-2014 <NAME>. # # 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 sys import os import re import subprocess import time import tempfile import sqlite3 from xml.dom import minidom from glob import glob import FoundationPlist import munkicommon import munkistatus import utils # we use lots of camelCase-style names. Deal with it. # pylint: disable=C0103 class AdobeInstallProgressMonitor(object): """A class to monitor installs/removals of Adobe products. Finds the currently active installation log and scrapes data out of it. Installations that install a product and updates may actually create multiple logs.""" def __init__(self, kind='CS5', operation='install'): '''Provide some hints as to what type of installer is running and whether we are installing or removing''' self.kind = kind self.operation = operation self.payload_count = {} def get_current_log(self): '''Returns the current Adobe install log''' logpath = '/Library/Logs/Adobe/Installers' # find the most recently-modified log file proc = subprocess.Popen(['/bin/ls', '-t1', logpath], bufsize=-1, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (output, dummy_err) = proc.communicate() if output: firstitem = str(output).splitlines()[0] if firstitem.endswith(".log"): # return path of most recently modified log file return os.path.join(logpath, firstitem) return None def info(self): '''Returns the number of completed Adobe payloads, and the AdobeCode of the most recently completed payload.''' last_adobecode = "" logfile = self.get_current_log() if logfile: if self.kind in ['CS6', 'CS5']: regex = r'END TIMER :: \[Payload Operation :\{' elif self.kind in ['CS3', 'CS4']: if self.operation == 'install': regex = r'Closed PCD cache session payload with ID' else: regex = r'Closed CAPS session for removal of payload' else: if self.operation == 'install': regex = r'Completing installation for payload at ' else: regex = r'Physical payload uninstall result ' cmd = ['/usr/bin/grep', '-E', regex, logfile] proc = subprocess.Popen(cmd, bufsize=-1, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (output, dummy_err) = proc.communicate() if output: lines = str(output).splitlines() completed_payloads = len(lines) if (not logfile in self.payload_count or completed_payloads > self.payload_count[logfile]): # record number of completed payloads self.payload_count[logfile] = completed_payloads # now try to get the AdobeCode of the most recently # completed payload. # this isn't 100% accurate, but it's mostly for show # anyway... regex = re.compile(r'[^{]*(\{[A-Fa-f0-9-]+\})') lines.reverse() for line in lines: m = regex.match(line) try: last_adobecode = m.group(1) break except (IndexError, AttributeError): pass total_completed_payloads = 0 for key in self.payload_count.keys(): total_completed_payloads += self.payload_count[key] return (total_completed_payloads, last_adobecode) # dmg helper # we need this instead of the one in munkicommon because the Adobe stuff # needs the dmgs mounted under /Volumes. We can merge this later (or not). def mountAdobeDmg(dmgpath): """ Attempts to mount the dmg at dmgpath and returns a list of mountpoints """ mountpoints = [] dmgname = os.path.basename(dmgpath) proc = subprocess.Popen(['/usr/bin/hdiutil', 'attach', dmgpath, '-nobrowse', '-noverify', '-plist'], bufsize=-1, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (pliststr, err) = proc.communicate() if err: munkicommon.display_error('Error %s mounting %s.' % (err, dmgname)) if pliststr: plist = FoundationPlist.readPlistFromString(pliststr) for entity in plist['system-entities']: if 'mount-point' in entity: mountpoints.append(entity['mount-point']) return mountpoints def getCS5uninstallXML(optionXMLfile): '''Gets the uninstall deployment data from a CS5 installer''' xml = '' dom = minidom.parse(optionXMLfile) DeploymentInfo = dom.getElementsByTagName('DeploymentInfo') if DeploymentInfo: for info_item in DeploymentInfo: DeploymentUninstall = info_item.getElementsByTagName( 'DeploymentUninstall') if DeploymentUninstall: deploymentData = DeploymentUninstall[0].getElementsByTagName( 'Deployment') if deploymentData: Deployment = deploymentData[0] xml += Deployment.toxml('UTF-8') return xml def getCS5mediaSignature(dirpath): '''Returns the CS5 mediaSignature for an AAMEE CS5 install. dirpath is typically the root of a mounted dmg''' payloads_dir = "" # look for a payloads folder for (path, dummy_dirs, dummy_files) in os.walk(dirpath): if path.endswith('/payloads'): payloads_dir = path # return empty-handed if we didn't find a payloads folder if not payloads_dir: return '' # now look for setup.xml setupxml = os.path.join(payloads_dir, 'Setup.xml') if os.path.exists(setupxml) and os.path.isfile(setupxml): # parse the XML dom = minidom.parse(setupxml) setupElements = dom.getElementsByTagName('Setup') if setupElements: mediaSignatureElements = \ setupElements[0].getElementsByTagName('mediaSignature') if mediaSignatureElements: element = mediaSignatureElements[0] elementvalue = '' for node in element.childNodes: elementvalue += node.nodeValue return elementvalue return "" def getPayloadInfo(dirpath): '''Parses Adobe payloads, pulling out info useful to munki. .proxy.xml files are used if available, or for CC-era updates which do not contain one, the Media_db.db file, which contains identical XML, is instead used. CS3/CS4: contain only .proxy.xml CS5/CS5.5/CS6: contain both CC: contain only Media_db.db''' payloadinfo = {} # look for .proxy.xml file dir if os.path.isdir(dirpath): proxy_paths = glob(os.path.join(dirpath, '*.proxy.xml')) if proxy_paths: xmlpath = proxy_paths[0] dom = minidom.parse(xmlpath) # if there's no .proxy.xml we should hope there's a Media_db.db else: db_path = os.path.join(dirpath, 'Media_db.db') if os.path.exists(db_path): conn = sqlite3.connect(db_path) cur = conn.cursor() cur.execute("SELECT value FROM PayloadData WHERE " "PayloadData.key = 'PayloadInfo'") result = cur.fetchone() cur.close() if result: info_xml = result[0].encode('UTF-8') dom = minidom.parseString(info_xml) else: # no xml, no db, no payload info! return payloadinfo payload_info = dom.getElementsByTagName('PayloadInfo') if payload_info: installer_properties = payload_info[0].getElementsByTagName( 'InstallerProperties') if installer_properties: properties = installer_properties[0].getElementsByTagName( 'Property') for prop in properties: if 'name' in prop.attributes.keys(): propname = prop.attributes['name'].value.encode('UTF-8') propvalue = '' for node in prop.childNodes: propvalue += node.nodeValue if propname == 'AdobeCode': payloadinfo['AdobeCode'] = propvalue if propname == 'ProductName': payloadinfo['display_name'] = propvalue if propname == 'ProductVersion': payloadinfo['version'] = propvalue installmetadata = payload_info[0].getElementsByTagName( 'InstallDestinationMetadata') if installmetadata: totalsizes = installmetadata[0].getElementsByTagName( 'TotalSize') if totalsizes: installsize = '' for node in totalsizes[0].childNodes: installsize += node.nodeValue payloadinfo['installed_size'] = int(installsize)/1024 return payloadinfo def getAdobeSetupInfo(installroot): '''Given the root of mounted Adobe DMG, look for info about the installer or updater''' info = {} payloads = [] # look for all the payloads folders for (path, dummy_dirs, dummy_files) in os.walk(installroot): if path.endswith('/payloads'): driverfolder = '' mediaSignature = '' setupxml = os.path.join(path, 'setup.xml') if os.path.exists(setupxml): dom = minidom.parse(setupxml) drivers = dom.getElementsByTagName('Driver') if drivers: driver = drivers[0] if 'folder' in driver.attributes.keys(): driverfolder = driver.attributes[ 'folder'].value.encode('UTF-8') if driverfolder == '': # look for mediaSignature (CS5 AAMEE install) setupElements = dom.getElementsByTagName('Setup') if setupElements: mediaSignatureElements = setupElements[ 0].getElementsByTagName('mediaSignature') if mediaSignatureElements: element = mediaSignatureElements[0] for node in element.childNodes: mediaSignature += node.nodeValue for item in munkicommon.listdir(path): payloadpath = os.path.join(path, item) payloadinfo = getPayloadInfo(payloadpath) if payloadinfo: payloads.append(payloadinfo) if ((driverfolder and item == driverfolder) or (mediaSignature and payloadinfo['AdobeCode'] == mediaSignature)): info['display_name'] = payloadinfo['display_name'] info['version'] = payloadinfo['version'] info['AdobeSetupType'] = 'ProductInstall' if not payloads: # look for an extensions folder; almost certainly this is an Updater for (path, dummy_dirs, dummy_files) in os.walk(installroot): if path.endswith("/extensions"): for item in munkicommon.listdir(path): #skip LanguagePacks if item.find("LanguagePack") == -1: itempath = os.path.join(path, item) payloadinfo = getPayloadInfo(itempath) if payloadinfo: payloads.append(payloadinfo) # we found an extensions dir, # so no need to keep walking the install root break if payloads: if len(payloads) == 1: info['display_name'] = payloads[0]['display_name'] info['version'] = payloads[0]['version'] else: if not 'display_name' in info: info['display_name'] = "ADMIN: choose from payloads" if not 'version' in info: info['version'] = "ADMIN please set me" info['payloads'] = payloads installed_size = 0 for payload in payloads: installed_size = installed_size + payload.get('installed_size', 0) info['installed_size'] = installed_size return info def getAdobePackageInfo(installroot): '''Gets the package name from the AdobeUberInstaller.xml file; other info from the payloads folder''' info = getAdobeSetupInfo(installroot) info['description'] = "" installerxml = os.path.join(installroot, "AdobeUberInstaller.xml") if os.path.exists(installerxml): description = '' dom = minidom.parse(installerxml) installinfo = dom.getElementsByTagName("InstallInfo") if installinfo: packagedescriptions = \ installinfo[0].getElementsByTagName("PackageDescription") if packagedescriptions: prop = packagedescriptions[0] for node in prop.childNodes: description += node.nodeValue if description: description_parts = description.split(' : ', 1) info['display_name'] = description_parts[0] if len(description_parts) > 1: info['description'] = description_parts[1] else: info['description'] = "" return info else: installerxml = os.path.join(installroot, "optionXML.xml") if os.path.exists(installerxml): dom = minidom.parse(installerxml) installinfo = dom.getElementsByTagName("InstallInfo") if installinfo: pkgname_elems = installinfo[0].getElementsByTagName( "PackageName") if pkgname_elems: prop = pkgname_elems[0] pkgname = "" for node in prop.childNodes: pkgname += node.nodeValue info['display_name'] = pkgname if not info.get('display_name'): info['display_name'] = os.path.basename(installroot) return info def getXMLtextElement(dom_node, name): '''Returns the text value of the first item found with the given tagname''' value = None subelements = dom_node.getElementsByTagName(name) if subelements: value = '' for node in subelements[0].childNodes: value += node.nodeValue return value def parseOptionXML(option_xml_file): '''Parses an optionXML.xml file and pulls ot items of interest, returning them in a dictionary''' info = {} dom = minidom.parse(option_xml_file) installinfo = dom.getElementsByTagName('InstallInfo') if installinfo: if 'id' in installinfo[0].attributes.keys(): info['packager_id'] = installinfo[0].attributes['id'].value if 'version' in installinfo[0].attributes.keys(): info['packager_version'] = installinfo[ 0].attributes['version'].value info['package_name'] = getXMLtextElement(installinfo[0], 'PackageName') info['package_id'] = getXMLtextElement(installinfo[0], 'PackageID') info['products'] = [] medias_elements = installinfo[0].getElementsByTagName('Medias') if medias_elements: media_elements = medias_elements[0].getElementsByTagName('Media') if media_elements: for media in media_elements: product = {} product['prodName'] = getXMLtextElement(media, 'prodName') product['prodVersion'] = getXMLtextElement( media, 'prodVersion') setup_elements = media.getElementsByTagName('Setup') if setup_elements: mediaSignatureElements = setup_elements[ 0].getElementsByTagName('mediaSignature') if mediaSignatureElements: product['mediaSignature'] = '' element = mediaSignatureElements[0] for node in element.childNodes: product['mediaSignature'] += node.nodeValue info['products'].append(product) return info def countPayloads(dirpath): '''Attempts to count the payloads in the Adobe installation item''' count = 0 for (path, dummy_dirs, dummy_files) in os.walk(dirpath): if path.endswith("/payloads"): for subitem in munkicommon.listdir(path): subitempath = os.path.join(path, subitem) if os.path.isdir(subitempath): count = count + 1 return count def getPercent(current, maximum): '''Returns a value useful with MunkiStatus to use when displaying precent-done stauts''' if maximum == 0: percentdone = -1 elif current < 0: percentdone = -1 elif current > maximum: percentdone = -1 elif current == maximum: percentdone = 100 else: percentdone = int(float(current)/float(maximum)*100) return percentdone def findSetupApp(dirpath): '''Search dirpath and enclosed directories for Setup.app. Returns the path to the actual executable.''' for (path, dummy_dirs, dummy_files) in os.walk(dirpath): if path.endswith("Setup.app"): setup_path = os.path.join(path, "Contents", "MacOS", "Setup") if os.path.exists(setup_path): return setup_path return '' def findInstallApp(dirpath): '''Searches dirpath and enclosed directories for Install.app. Returns the path to the actual executable.''' for (path, dummy_dirs, dummy_files) in os.walk(dirpath): if path.endswith("Install.app"): setup_path = os.path.join(path, "Contents", "MacOS", "Install") if os.path.exists(setup_path): return setup_path return '' def findAdobePatchInstallerApp(dirpath): '''Searches dirpath and enclosed directories for AdobePatchInstaller.app. Returns the path to the actual executable.''' for (path, dummy_dirs, dummy_files) in os.walk(dirpath): if path.endswith("AdobePatchInstaller.app"): setup_path = os.path.join( path, "Contents", "MacOS", "AdobePatchInstaller") if os.path.exists(setup_path): return setup_path return '' def findAdobeDeploymentManager(dirpath): '''Searches dirpath and enclosed directories for AdobeDeploymentManager. Returns path to the executable.''' for (path, dummy_dirs, dummy_files) in os.walk(dirpath): if path.endswith("pkg/Contents/Resources"): dm_path = os.path.join(path, "AdobeDeploymentManager") if os.path.exists(dm_path): return dm_path return '' secondsToLive = {} def killStupidProcesses(): '''A nasty bit of hackery to get Adobe CS5 AAMEE packages to install when at the loginwindow.''' stupid_processes = ["Adobe AIR Installer", "Adobe AIR Application Installer", "InstallAdobeHelp", "open -a /Library/Application Support/Adobe/" "SwitchBoard/SwitchBoard.app", "/bin/bash /Library/Application Support/Adobe/" "SwitchBoard/SwitchBoard.app/Contents/MacOS/" "switchboard.sh"] for procname in stupid_processes: pid = utils.getPIDforProcessName(procname) if pid: if not pid in secondsToLive: secondsToLive[pid] = 30 else: secondsToLive[pid] = secondsToLive[pid] - 1 if secondsToLive[pid] == 0: # it's been running too long; kill it munkicommon.log("Killing PID %s: %s" % (pid, procname)) try: os.kill(int(pid), 9) except OSError: pass # remove this PID from our list del secondsToLive[pid] # only kill one process per invocation return def runAdobeInstallTool( cmd, number_of_payloads=0, killAdobeAIR=False, payloads=None, kind="CS5", operation="install"): '''An abstraction of the tasks for running Adobe Setup, AdobeUberInstaller, AdobeUberUninstaller, AdobeDeploymentManager, etc''' # initialize an AdobeInstallProgressMonitor object. progress_monitor = AdobeInstallProgressMonitor( kind=kind, operation=operation) if munkicommon.munkistatusoutput and not number_of_payloads: # indeterminate progress bar munkistatus.percent(-1) proc = subprocess.Popen(cmd, shell=False, bufsize=1, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) old_payload_completed_count = 0 payloadname = "" while proc.poll() == None: time.sleep(1) (payload_completed_count, adobe_code) = progress_monitor.info() if payload_completed_count > old_payload_completed_count: old_payload_completed_count = payload_completed_count if adobe_code and payloads: matched_payloads = [payload for payload in payloads if payload.get('AdobeCode') == adobe_code] if matched_payloads: payloadname = matched_payloads[0].get('display_name') else: payloadname = adobe_code payloadinfo = " - " + payloadname else: payloadinfo = "" if number_of_payloads: munkicommon.display_status_minor( 'Completed payload %s of %s%s' % (payload_completed_count, number_of_payloads, payloadinfo)) else: munkicommon.display_status_minor( 'Completed payload %s%s', payload_completed_count, payloadinfo) if munkicommon.munkistatusoutput: munkistatus.percent( getPercent(payload_completed_count, number_of_payloads)) # Adobe AIR Installer workaround/hack # CSx installs at the loginwindow hang when Adobe AIR is installed. # So we check for this and kill the process. Ugly. # Hopefully we can disable this in the future. if killAdobeAIR: if (not munkicommon.getconsoleuser() or munkicommon.getconsoleuser() == u"loginwindow"): # we're at the loginwindow. killStupidProcesses() # run of tool completed retcode = proc.poll() #check output for errors output = proc.stdout.readlines() for line in output: line = line.rstrip("\n") if line.startswith("Error"): munkicommon.display_error(line) if line.startswith("Exit Code:"): if retcode == 0: try: retcode = int(line[11:]) except (ValueError, TypeError): retcode = -1 if retcode != 0 and retcode != 8: munkicommon.display_error( 'Adobe Setup error: %s: %s', retcode, adobeSetupError(retcode)) else: if munkicommon.munkistatusoutput: munkistatus.percent(100) munkicommon.display_status_minor('Done.') return retcode def runAdobeSetup(dmgpath, uninstalling=False, payloads=None): '''Runs the Adobe setup tool in silent mode from an Adobe update DMG or an Adobe CS3 install DMG''' munkicommon.display_status_minor( 'Mounting disk image %s' % os.path.basename(dmgpath)) mountpoints = mountAdobeDmg(dmgpath) if mountpoints: setup_path = findSetupApp(mountpoints[0]) if setup_path: # look for install.xml or uninstall.xml at root deploymentfile = None installxml = os.path.join(mountpoints[0], "install.xml") uninstallxml = os.path.join(mountpoints[0], "uninstall.xml") if uninstalling: operation = 'uninstall' if os.path.exists(uninstallxml): deploymentfile = uninstallxml else: # we've been asked to uninstall, # but found no uninstall.xml # so we need to bail munkicommon.unmountdmg(mountpoints[0]) munkicommon.display_error( '%s doesn\'t appear to contain uninstall info.', os.path.basename(dmgpath)) return -1 else: operation = 'install' if os.path.exists(installxml): deploymentfile = installxml # try to find and count the number of payloads # so we can give a rough progress indicator number_of_payloads = countPayloads(mountpoints[0]) munkicommon.display_status_minor('Running Adobe Setup') adobe_setup = [setup_path, '--mode=silent', '--skipProcessCheck=1'] if deploymentfile: adobe_setup.append('--deploymentFile=%s' % deploymentfile) retcode = runAdobeInstallTool( adobe_setup, number_of_payloads, payloads=payloads, kind='CS3', operation=operation) else: munkicommon.display_error( '%s doesn\'t appear to contain Adobe Setup.' % os.path.basename(dmgpath)) retcode = -1 munkicommon.unmountdmg(mountpoints[0]) return retcode else: munkicommon.display_error('No mountable filesystems on %s' % dmgpath) return -1 def writefile(stringdata, path): '''Writes string data to path. Returns the path on success, empty string on failure.''' try: fileobject = open(path, mode='w', buffering=1) print >> fileobject, stringdata.encode('UTF-8') fileobject.close() return path except (OSError, IOError): munkicommon.display_error("Couldn't write %s" % stringdata) return "" def doAdobeCS5Uninstall(adobeInstallInfo, payloads=None): '''Runs the locally-installed Adobe CS5 tools to remove CS5 products. We need the uninstallxml and the CS5 Setup.app.''' uninstallxml = adobeInstallInfo.get('uninstallxml') if not uninstallxml: munkicommon.display_error("No uninstall.xml in adobe_install_info") return -1 payloadcount = adobeInstallInfo.get('payload_count', 0) path = os.path.join(munkicommon.tmpdir(), "uninstall.xml") deploymentFile = writefile(uninstallxml, path) if not deploymentFile: return -1 setupapp = "/Library/Application Support/Adobe/OOBE/PDApp/DWA/Setup.app" setup = os.path.join(setupapp, "Contents/MacOS/Setup") if not os.path.exists(setup): munkicommon.display_error("%s is not installed." % setupapp) return -1 uninstall_cmd = [setup, '--mode=silent', '--action=uninstall', '--skipProcessCheck=1', '--deploymentFile=%s' % deploymentFile] munkicommon.display_status_minor('Running Adobe Uninstall') return runAdobeInstallTool(uninstall_cmd, payloadcount, payloads=payloads, kind='CS5', operation='uninstall') def runAdobeCCPpkgScript(dmgpath, payloads=None, operation='install'): '''Installs or removes an Adobe product packaged via Creative Cloud Packager''' munkicommon.display_status_minor( 'Mounting disk image %s' % os.path.basename(dmgpath)) mountpoints = mountAdobeDmg(dmgpath) if not mountpoints: munkicommon.display_error("No mountable filesystems on %s" % dmgpath) return -1 deploymentmanager = findAdobeDeploymentManager(mountpoints[0]) if not deploymentmanager: munkicommon.display_error( '%s doesn\'t appear to contain AdobeDeploymentManager', os.path.basename(dmgpath)) munkicommon.unmountdmg(mountpoints[0]) return -1 # big hack to convince the Adobe tools to install off a mounted # disk image. # # For some reason, some versions of the Adobe install tools refuse to # install when the payloads are on a "removable" disk, # which includes mounted disk images. # # we create a temporary directory on the local disk and then symlink # some resources from the mounted disk image to the temporary # directory. When we pass this temporary directory to the Adobe # installation tools, they are now happy. basepath = os.path.dirname(deploymentmanager) preinstall_script = os.path.join(basepath, "preinstall") if not os.path.exists(preinstall_script): if operation == 'install': munkicommon.display_error( "No Adobe install script found on %s" % dmgpath) else: munkicommon.display_error( "No Adobe uninstall script found on %s" % dmgpath) munkicommon.unmountdmg(mountpoints[0]) return -1 number_of_payloads = countPayloads(basepath) tmpdir = tempfile.mkdtemp(prefix='munki-', dir='/tmp') # make our symlinks for dir_name in ['ASU' 'ASU2', 'ProvisioningTool', 'uninstallinfo']: if os.path.isdir(os.path.join(basepath, dir_name)): os.symlink(os.path.join(basepath, dir_name), os.path.join(tmpdir, dir_name)) for dir_name in ['Patches', 'Setup']: realdir = os.path.join(basepath, dir_name) if os.path.isdir(realdir): tmpsubdir = os.path.join(tmpdir, dir_name) os.mkdir(tmpsubdir) for item in munkicommon.listdir(realdir): os.symlink(os.path.join(realdir, item), os.path.join(tmpsubdir, item)) os_version_tuple = munkicommon.getOsVersion(as_tuple=True) if (os_version_tuple < (10, 11) and (not munkicommon.getconsoleuser() or munkicommon.getconsoleuser() == u"loginwindow")): # we're at the loginwindow, so we need to run the deployment # manager in the loginwindow context using launchctl bsexec # launchctl bsexec doesn't work for this in El Cap, so do it # only if we're running Yosemite or earlier loginwindowPID = utils.getPIDforProcessName("loginwindow") cmd = ['/bin/launchctl', 'bsexec', loginwindowPID] else: cmd = [] # preinstall script is in pkg/Contents/Resources, so calculate # path to pkg pkg_dir = os.path.dirname(os.path.dirname(basepath)) cmd.extend([preinstall_script, pkg_dir, '/', '/']) if operation == 'install': munkicommon.display_status_minor('Starting Adobe installer...') retcode = runAdobeInstallTool( cmd, number_of_payloads, killAdobeAIR=True, payloads=payloads, kind='CS6', operation=operation) # now clean up and return dummy_result = subprocess.call(["/bin/rm", "-rf", tmpdir]) munkicommon.unmountdmg(mountpoints[0]) return retcode def runAdobeCS5AAMEEInstall(dmgpath, payloads=None): '''Installs a CS5 product using an AAMEE-generated package on a disk image.''' munkicommon.display_status_minor( 'Mounting disk image %s' % os.path.basename(dmgpath)) mountpoints = mountAdobeDmg(dmgpath) if not mountpoints: munkicommon.display_error("No mountable filesystems on %s" % dmgpath) return -1 deploymentmanager = findAdobeDeploymentManager(mountpoints[0]) if deploymentmanager: # big hack to convince the Adobe tools to install off a mounted # disk image. # # For some reason, some versions of the Adobe install tools refuse to # install when the payloads are on a "removable" disk, # which includes mounted disk images. # # we create a temporary directory on the local disk and then symlink # some resources from the mounted disk image to the temporary # directory. When we pass this temporary directory to the Adobe # installation tools, they are now happy. basepath = os.path.dirname(deploymentmanager) number_of_payloads = countPayloads(basepath) tmpdir = tempfile.mkdtemp(prefix='munki-', dir='/tmp') # make our symlinks os.symlink(os.path.join(basepath, "ASU"), os.path.join(tmpdir, "ASU")) os.symlink(os.path.join(basepath, "ProvisioningTool"), os.path.join(tmpdir, "ProvisioningTool")) for dir_name in ['Patches', 'Setup']: realdir = os.path.join(basepath, dir_name) if os.path.isdir(realdir): tmpsubdir = os.path.join(tmpdir, dir_name) os.mkdir(tmpsubdir) for item in munkicommon.listdir(realdir): os.symlink( os.path.join(realdir, item), os.path.join(tmpsubdir, item)) optionXMLfile = os.path.join(basepath, "optionXML.xml") os_version_tuple = munkicommon.getOsVersion(as_tuple=True) if (os_version_tuple < (10, 11) and (not munkicommon.getconsoleuser() or munkicommon.getconsoleuser() == u"loginwindow")): # we're at the loginwindow, so we need to run the deployment # manager in the loginwindow context using launchctl bsexec # launchctl bsexec doesn't work for this in El Cap, so do it # only if we're running Yosemite or earlier loginwindowPID = utils.getPIDforProcessName("loginwindow") cmd = ['/bin/launchctl', 'bsexec', loginwindowPID] else: cmd = [] cmd.extend([deploymentmanager, '--optXMLPath=%s' % optionXMLfile, '--setupBasePath=%s' % basepath, '--installDirPath=/', '--mode=install']) munkicommon.display_status_minor('Starting Adobe installer...') retcode = runAdobeInstallTool( cmd, number_of_payloads, killAdobeAIR=True, payloads=payloads, kind='CS5', operation='install') # now clean up our symlink hackfest dummy_result = subprocess.call(["/bin/rm", "-rf", tmpdir]) else: munkicommon.display_error( '%s doesn\'t appear to contain AdobeDeploymentManager', os.path.basename(dmgpath)) retcode = -1 munkicommon.unmountdmg(mountpoints[0]) return retcode def runAdobeCS5PatchInstaller(dmgpath, copylocal=False, payloads=None): '''Runs the AdobePatchInstaller for CS5. Optionally can copy the DMG contents to the local disk to work around issues with the patcher.''' munkicommon.display_status_minor( 'Mounting disk image %s' % os.path.basename(dmgpath)) mountpoints = mountAdobeDmg(dmgpath) if mountpoints: if copylocal: # copy the update to the local disk before installing updatedir = tempfile.mkdtemp(prefix='munki-', dir='/tmp') retcode = subprocess.call( ["/bin/cp", "-r", mountpoints[0], updatedir]) # unmount diskimage munkicommon.unmountdmg(mountpoints[0]) if retcode: munkicommon.display_error( 'Error copying items from %s' % dmgpath) return -1 # remove the dmg file to free up space, since we don't need it # any longer dummy_result = subprocess.call(["/bin/rm", dmgpath]) else: updatedir = mountpoints[0] patchinstaller = findAdobePatchInstallerApp(updatedir) if patchinstaller: # try to find and count the number of payloads # so we can give a rough progress indicator number_of_payloads = countPayloads(updatedir) munkicommon.display_status_minor('Running Adobe Patch Installer') install_cmd = [patchinstaller, '--mode=silent', '--skipProcessCheck=1'] retcode = runAdobeInstallTool(install_cmd, number_of_payloads, payloads=payloads, kind='CS5', operation='install') else: munkicommon.display_error( "%s doesn't appear to contain AdobePatchInstaller.app.", os.path.basename(dmgpath)) retcode = -1 if copylocal: # clean up our mess dummy_result = subprocess.call(["/bin/rm", "-rf", updatedir]) else: munkicommon.unmountdmg(mountpoints[0]) return retcode else: munkicommon.display_error('No mountable filesystems on %s' % dmgpath) return -1 def runAdobeUberTool(dmgpath, pkgname='', uninstalling=False, payloads=None): '''Runs either AdobeUberInstaller or AdobeUberUninstaller from a disk image and provides progress feedback. pkgname is the name of a directory at the top level of the dmg containing the AdobeUber tools and their XML files.''' munkicommon.display_status_minor( 'Mounting disk image %s' % os.path.basename(dmgpath)) mountpoints = mountAdobeDmg(dmgpath) if mountpoints: installroot = mountpoints[0] if uninstalling: ubertool = os.path.join(installroot, pkgname, "AdobeUberUninstaller") else: ubertool = os.path.join(installroot, pkgname, "AdobeUberInstaller") if os.path.exists(ubertool): info = getAdobePackageInfo(installroot) packagename = info['display_name'] action = "Installing" operation = "install" if uninstalling: action = "Uninstalling" operation = "uninstall" munkicommon.display_status_major('%s %s' % (action, packagename)) if munkicommon.munkistatusoutput: munkistatus.detail('Starting %s' % os.path.basename(ubertool)) # try to find and count the number of payloads # so we can give a rough progress indicator number_of_payloads = countPayloads(installroot) retcode = runAdobeInstallTool( [ubertool], number_of_payloads, killAdobeAIR=True, payloads=payloads, kind='CS4', operation=operation) else: munkicommon.display_error("No %s found" % ubertool) retcode = -1 munkicommon.unmountdmg(installroot) return retcode else: munkicommon.display_error("No mountable filesystems on %s" % dmgpath) return -1 def findAcrobatPatchApp(dirpath): '''Attempts to find an AcrobatPro patching application in dirpath. If found, returns the path to the bundled patching script.''' for (path, dummy_dirs, dummy_files) in os.walk(dirpath): if path.endswith(".app"): # look for Adobe's patching script patch_script_path = os.path.join( path, 'Contents', 'Resources', 'ApplyOperation.py') if os.path.exists(patch_script_path): return path return '' def updateAcrobatPro(dmgpath): """Uses the scripts and Resources inside the Acrobat Patch application bundle to silently update Acrobat Pro and related apps Why oh why does this use a different mechanism than the other Adobe apps?""" if munkicommon.munkistatusoutput: munkistatus.percent(-1) #first mount the dmg munkicommon.display_status_minor( 'Mounting disk image %s' % os.path.basename(dmgpath)) mountpoints = mountAdobeDmg(dmgpath) if mountpoints: installroot = mountpoints[0] pathToAcrobatPatchApp = findAcrobatPatchApp(installroot) else: munkicommon.display_error("No mountable filesystems on %s" % dmgpath) return -1 if not pathToAcrobatPatchApp: munkicommon.display_error( 'No Acrobat Patch app at %s', pathToAcrobatPatchApp) munkicommon.unmountdmg(installroot) return -1 # some values needed by the patching script resourcesDir = os.path.join( pathToAcrobatPatchApp, 'Contents', 'Resources') ApplyOperation = os.path.join(resourcesDir, 'ApplyOperation.py') callingScriptPath = os.path.join(resourcesDir, 'InstallUpdates.sh') appList = [] appListFile = os.path.join(resourcesDir, 'app_list.txt') if os.path.exists(appListFile): fileobj = open(appListFile, mode='r', buffering=-1) if fileobj: for line in fileobj.readlines(): appList.append(line) fileobj.close() if not appList: munkicommon.display_error('Did not find a list of apps to update.') munkicommon.unmountdmg(installroot) return -1 payloadNum = -1 for line in appList: payloadNum = payloadNum + 1 if munkicommon.munkistatusoutput: munkistatus.percent(getPercent(payloadNum + 1, len(appList) + 1)) (appname, status) = line.split("\t") munkicommon.display_status_minor('Searching for %s' % appname) # first look in the obvious place pathname = os.path.join("/Applications/Adobe Acrobat 9 Pro", appname) if os.path.exists(pathname): item = {} item['path'] = pathname candidates = [item] else: # use system_profiler to search for the app candidates = [item for item in munkicommon.getAppData() if item['path'].endswith('/' + appname)] # hope there's only one! if len(candidates) == 0: if status == "optional": continue else: munkicommon.display_error("Cannot patch %s because it " "was not found on the startup " "disk." % appname) munkicommon.unmountdmg(installroot) return -1 if len(candidates) > 1: munkicommon.display_error("Cannot patch %s because we found " "more than one copy on the " "startup disk." % appname) munkicommon.unmountdmg(installroot) return -1 munkicommon.display_status_minor('Updating %s' % appname) apppath = os.path.dirname(candidates[0]["path"]) cmd = [ApplyOperation, apppath, appname, resourcesDir, callingScriptPath, str(payloadNum)] proc = subprocess.Popen(cmd, shell=False, bufsize=-1, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while proc.poll() == None: time.sleep(1) # run of patch tool completed retcode = proc.poll() if retcode != 0: munkicommon.display_error( 'Error patching %s: %s', appname, retcode) break else: munkicommon.display_status_minor('Patching %s complete.', appname) munkicommon.display_status_minor('Done.') if munkicommon.munkistatusoutput: munkistatus.percent(100) munkicommon.unmountdmg(installroot) return retcode def getBundleInfo(path): """ Returns Info.plist data if available for bundle at path """ infopath = os.path.join(path, "Contents", "Info.plist") if not os.path.exists(infopath): infopath = os.path.join(path, "Resources", "Info.plist") if os.path.exists(infopath): try: plist = FoundationPlist.readPlist(infopath) return plist except FoundationPlist.NSPropertyListSerializationException: pass return None def getAdobeInstallInfo(installdir): '''Encapsulates info used by the Adobe Setup/Install app.''' adobeInstallInfo = {} if installdir: adobeInstallInfo['media_signature'] = getCS5mediaSignature(installdir) adobeInstallInfo['payload_count'] = countPayloads(installdir) optionXMLfile = os.path.join(installdir, "optionXML.xml") if os.path.exists(optionXMLfile): adobeInstallInfo['uninstallxml'] = \ getCS5uninstallXML(optionXMLfile) return adobeInstallInfo def getAdobeCatalogInfo(mountpoint, pkgname=""): '''Used by makepkginfo to build pkginfo data for Adobe installers/updaters''' # look for AdobeDeploymentManager (AAMEE installer) deploymentmanager = findAdobeDeploymentManager(mountpoint) if deploymentmanager: dirpath = os.path.dirname(deploymentmanager) option_xml_file = os.path.join(dirpath, 'optionXML.xml') option_xml_info = {} if os.path.exists(option_xml_file): option_xml_info = parseOptionXML(option_xml_file) cataloginfo = getAdobePackageInfo(dirpath) if cataloginfo: # add some more data if option_xml_info.get('packager_id') == u'CloudPackager': # CCP package cataloginfo['display_name'] = option_xml_info.get( 'package_name', 'unknown') cataloginfo['name'] = cataloginfo['display_name'].replace( ' ', '') cataloginfo['uninstallable'] = True cataloginfo['uninstall_method'] = "AdobeCCPUninstaller" cataloginfo['installer_type'] = "AdobeCCPInstaller" cataloginfo['minimum_os_version'] = "10.6.8" mediasignatures = [ item['mediaSignature'] for item in option_xml_info.get('products', []) if 'mediaSignature' in item] else: # AAMEE package cataloginfo['name'] = cataloginfo['display_name'].replace( ' ', '') cataloginfo['uninstallable'] = True cataloginfo['uninstall_method'] = "AdobeCS5AAMEEPackage" cataloginfo['installer_type'] = "AdobeCS5AAMEEPackage" cataloginfo['minimum_os_version'] = "10.5.0" cataloginfo['adobe_install_info'] = getAdobeInstallInfo( installdir=dirpath) mediasignature = cataloginfo['adobe_install_info'].get( "media_signature") mediasignatures = [mediasignature] if mediasignatures: # make a default <key>installs</key> array uninstalldir = "/Library/Application Support/Adobe/Uninstall" installs = [] for mediasignature in mediasignatures: signaturefile = mediasignature + ".db" filepath = os.path.join(uninstalldir, signaturefile) installitem = {} installitem['path'] = filepath installitem['type'] = 'file' installs.append(installitem) cataloginfo['installs'] = installs return cataloginfo # Look for Install.app (Bare metal CS5 install) # we don't handle this type, but we'll report it # back so makepkginfo can provide an error message installapp = findInstallApp(mountpoint) if installapp: cataloginfo = {} cataloginfo['installer_type'] = "AdobeCS5Installer" return cataloginfo # Look for AdobePatchInstaller.app (CS5 updater) installapp = findAdobePatchInstallerApp(mountpoint) if os.path.exists(installapp): # this is a CS5 updater disk image cataloginfo = getAdobePackageInfo(mountpoint) if cataloginfo: # add some more data cataloginfo['name'] = cataloginfo['display_name'].replace(' ', '') cataloginfo['uninstallable'] = False cataloginfo['installer_type'] = "AdobeCS5PatchInstaller" if pkgname: cataloginfo['package_path'] = pkgname # make some (hopfully functional) installs items from the payloads installs = [] uninstalldir = "/Library/Application Support/Adobe/Uninstall" # first look for a payload with a display_name matching the # overall display_name for payload in cataloginfo.get('payloads', []): if (payload.get('display_name', '') == cataloginfo['display_name']): if 'AdobeCode' in payload: dbfile = payload['AdobeCode'] + ".db" filepath = os.path.join(uninstalldir, dbfile) installitem = {} installitem['path'] = filepath installitem['type'] = 'file' installs.append(installitem) break if installs == []: # didn't find a payload with matching name # just add all of the non-LangPack payloads # to the installs list. for payload in cataloginfo.get('payloads', []): if 'AdobeCode' in payload: if ("LangPack" in payload.get("display_name") or "Language Files" in payload.get( "display_name")): # skip Language Packs continue dbfile = payload['AdobeCode'] + ".db" filepath = os.path.join(uninstalldir, dbfile) installitem = {} installitem['path'] = filepath installitem['type'] = 'file' installs.append(installitem) cataloginfo['installs'] = installs return cataloginfo # Look for AdobeUberInstaller items (CS4 install) pkgroot = os.path.join(mountpoint, pkgname) adobeinstallxml = os.path.join(pkgroot, "AdobeUberInstaller.xml") if os.path.exists(adobeinstallxml): # this is a CS4 Enterprise Deployment package cataloginfo = getAdobePackageInfo(pkgroot) if cataloginfo: # add some more data cataloginfo['name'] = cataloginfo['display_name'].replace(' ', '') cataloginfo['uninstallable'] = True cataloginfo['uninstall_method'] = "AdobeUberUninstaller" cataloginfo['installer_type'] = "AdobeUberInstaller" if pkgname: cataloginfo['package_path'] = pkgname return cataloginfo # maybe this is an Adobe update DMG or CS3 installer # look for Adobe Setup.app setuppath = findSetupApp(mountpoint) if setuppath: cataloginfo = getAdobeSetupInfo(mountpoint) if cataloginfo: # add some more data cataloginfo['name'] = cataloginfo['display_name'].replace(' ', '') cataloginfo['installer_type'] = "AdobeSetup" if cataloginfo.get('AdobeSetupType') == "ProductInstall": cataloginfo['uninstallable'] = True cataloginfo['uninstall_method'] = "AdobeSetup" else: cataloginfo['description'] = "Adobe updater" cataloginfo['uninstallable'] = False cataloginfo['update_for'] = ["PleaseEditMe-1.0.0.0.0"] return cataloginfo # maybe this is an Adobe Acrobat 9 Pro patcher? acrobatpatcherapp = findAcrobatPatchApp(mountpoint) if acrobatpatcherapp: cataloginfo = {} cataloginfo['installer_type'] = "AdobeAcrobatUpdater" cataloginfo['uninstallable'] = False plist = getBundleInfo(acrobatpatcherapp) cataloginfo['version'] = munkicommon.getVersionString(plist) cataloginfo['name'] = "AcrobatPro9Update" cataloginfo['display_name'] = "Adobe Acrobat Pro Update" cataloginfo['update_for'] = ["AcrobatPro9"] cataloginfo['RestartAction'] = 'RequireLogout' cataloginfo['requires'] = [] cataloginfo['installs'] = [ {'CFBundleIdentifier': 'com.adobe.Acrobat.Pro', 'CFBundleName': 'Acrobat', 'CFBundleShortVersionString': cataloginfo['version'], 'path': '/Applications/Adobe Acrobat 9 Pro/Adobe Acrobat Pro.app', 'type': 'application'} ] return cataloginfo # didn't find any Adobe installers/updaters we understand return None def adobeSetupError(errorcode): '''Returns text description for numeric error code Reference: http://www.adobe.com/devnet/creativesuite/pdfs/DeployGuide.pdf''' errormessage = { 0: "Application installed successfully", 1: "Unable to parse command line", 2: "Unknown user interface mode specified", 3: "Unable to initialize ExtendScript", 4: "User interface workflow failed", 5: "Unable to initialize user interface workflow", 6: "Silent workflow completed with errors", 7: "Unable to complete the silent workflow", 8: "Exit and restart", 9: "Unsupported operating system version", 10: "Unsupported file system", 11: "Another instance of Adobe Setup is running", 12: "CAPS integrity error", 13: "Media optimization failed", 14: "Failed due to insufficient privileges", 15: "Media DB Sync Failed", 16: "Failed to laod the Deployment file", 17: "EULA Acceptance Failed", 18: "C3PO Bootstrap Failed", 19: "Conflicting processes running", 20: "Install source path not specified or does not exist", 21: "Version of payloads is not supported by this version of RIB", 22: "Install Directory check failed", 23: "System Requirements Check failed", 24: "Exit User Canceled Workflow", 25: "A binary path Name exceeded Operating System's MAX PATH limit", 26: "Media Swap Required in Silent Mode", 27: "Keyed files detected in target", 28: "Base product is not installed", 29: "Base product has been moved", 30: "Insufficient disk space to install the payload + Done with errors", 31: "Insufficient disk space to install the payload + Failed", 32: "The patch is already applied", 9999: "Catastrophic error", -1: "AdobeUberInstaller failed before launching Setup"} return errormessage.get(errorcode, "Unknown error") def doAdobeRemoval(item): '''Wrapper for all the Adobe removal methods''' uninstallmethod = item['uninstall_method'] payloads = item.get("payloads") itempath = "" if "uninstaller_item" in item: managedinstallbase = munkicommon.pref('ManagedInstallDir') itempath = os.path.join(managedinstallbase, 'Cache', item["uninstaller_item"]) if not os.path.exists(itempath): munkicommon.display_error("%s package for %s was " "missing from the cache." % (uninstallmethod, item['name'])) return -1 if uninstallmethod == "AdobeSetup": # CS3 uninstall retcode = runAdobeSetup(itempath, uninstalling=True, payloads=payloads) elif uninstallmethod == "AdobeUberUninstaller": # CS4 uninstall pkgname = item.get("adobe_package_name") or item.get("package_path", "") retcode = runAdobeUberTool( itempath, pkgname, uninstalling=True, payloads=payloads) elif uninstallmethod == "AdobeCS5AAMEEPackage": # CS5 uninstall. Sheesh. Three releases, three methods. adobeInstallInfo = item.get('adobe_install_info') retcode = doAdobeCS5Uninstall(adobeInstallInfo, payloads=payloads) elif uninstallmethod == "AdobeCCPUninstaller": # Adobe Creative Cloud Packager packages retcode = runAdobeCCPpkgScript( itempath, payloads=payloads, operation="uninstall") if retcode: munkicommon.display_error("Uninstall of %s failed.", item['name']) return retcode def doAdobeInstall(item): '''Wrapper to handle all the Adobe installer methods. First get the path to the installer dmg. We know it exists because installer.py already checked.''' managedinstallbase = munkicommon.pref('ManagedInstallDir') itempath = os.path.join( managedinstallbase, 'Cache', item['installer_item']) installer_type = item.get("installer_type", "") payloads = item.get("payloads") if installer_type == "AdobeSetup": # Adobe CS3/CS4 updater or Adobe CS3 installer retcode = runAdobeSetup(itempath, payloads=payloads) elif installer_type == "AdobeUberInstaller": # Adobe CS4 installer pkgname = item.get("adobe_package_name") or item.get("package_path", "") retcode = runAdobeUberTool(itempath, pkgname, payloads=payloads) elif installer_type == "AdobeAcrobatUpdater": # Acrobat Pro 9 updater retcode = updateAcrobatPro(itempath) elif installer_type == "AdobeCS5AAMEEPackage": # Adobe CS5 AAMEE package retcode = runAdobeCS5AAMEEInstall(itempath, payloads=payloads) elif installer_type == "AdobeCS5PatchInstaller": # Adobe CS5 updater retcode = runAdobeCS5PatchInstaller( itempath, copylocal=item.get("copy_local"), payloads=payloads) elif installer_type == "AdobeCCPInstaller": # Adobe Creative Cloud Packager packages retcode = runAdobeCCPpkgScript(itempath, payloads=payloads) return retcode def main(): '''Placeholder''' pass if __name__ == '__main__': main()
[ "re.compile", "time.sleep", "munkicommon.log", "utils.getPIDforProcessName", "munkicommon.getconsoleuser", "munkistatus.percent", "os.walk", "munkicommon.pref", "os.path.exists", "xml.dom.minidom.parse", "munkicommon.getOsVersion", "subprocess.Popen", "munkicommon.getVersionString", "munki...
[((4930, 4955), 'os.path.basename', 'os.path.basename', (['dmgpath'], {}), '(dmgpath)\n', (4946, 4955), False, 'import os\n'), ((4967, 5129), 'subprocess.Popen', 'subprocess.Popen', (["['/usr/bin/hdiutil', 'attach', dmgpath, '-nobrowse', '-noverify', '-plist']"], {'bufsize': '(-1)', 'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.PIPE'}), "(['/usr/bin/hdiutil', 'attach', dmgpath, '-nobrowse',\n '-noverify', '-plist'], bufsize=-1, stdout=subprocess.PIPE, stderr=\n subprocess.PIPE)\n", (4983, 5129), False, 'import subprocess\n'), ((5714, 5742), 'xml.dom.minidom.parse', 'minidom.parse', (['optionXMLfile'], {}), '(optionXMLfile)\n', (5727, 5742), False, 'from xml.dom import minidom\n'), ((6532, 6548), 'os.walk', 'os.walk', (['dirpath'], {}), '(dirpath)\n', (6539, 6548), False, 'import os\n'), ((6772, 6811), 'os.path.join', 'os.path.join', (['payloads_dir', '"""Setup.xml"""'], {}), "(payloads_dir, 'Setup.xml')\n", (6784, 6811), False, 'import os\n'), ((7860, 7882), 'os.path.isdir', 'os.path.isdir', (['dirpath'], {}), '(dirpath)\n', (7873, 7882), False, 'import os\n'), ((10570, 10590), 'os.walk', 'os.walk', (['installroot'], {}), '(installroot)\n', (10577, 10590), False, 'import os\n'), ((13952, 14003), 'os.path.join', 'os.path.join', (['installroot', '"""AdobeUberInstaller.xml"""'], {}), "(installroot, 'AdobeUberInstaller.xml')\n", (13964, 14003), False, 'import os\n'), ((14011, 14039), 'os.path.exists', 'os.path.exists', (['installerxml'], {}), '(installerxml)\n', (14025, 14039), False, 'import os\n'), ((16104, 16134), 'xml.dom.minidom.parse', 'minidom.parse', (['option_xml_file'], {}), '(option_xml_file)\n', (16117, 16134), False, 'from xml.dom import minidom\n'), ((17943, 17959), 'os.walk', 'os.walk', (['dirpath'], {}), '(dirpath)\n', (17950, 17959), False, 'import os\n'), ((18826, 18842), 'os.walk', 'os.walk', (['dirpath'], {}), '(dirpath)\n', (18833, 18842), False, 'import os\n'), ((19238, 19254), 'os.walk', 'os.walk', (['dirpath'], {}), '(dirpath)\n', (19245, 19254), False, 'import os\n'), ((19678, 19694), 'os.walk', 'os.walk', (['dirpath'], {}), '(dirpath)\n', (19685, 19694), False, 'import os\n'), ((20147, 20163), 'os.walk', 'os.walk', (['dirpath'], {}), '(dirpath)\n', (20154, 20163), False, 'import os\n'), ((22312, 22435), 'subprocess.Popen', 'subprocess.Popen', (['cmd'], {'shell': '(False)', 'bufsize': '(1)', 'stdin': 'subprocess.PIPE', 'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.STDOUT'}), '(cmd, shell=False, bufsize=1, stdin=subprocess.PIPE, stdout\n =subprocess.PIPE, stderr=subprocess.STDOUT)\n', (22328, 22435), False, 'import subprocess\n'), ((28521, 28567), 'os.path.join', 'os.path.join', (['setupapp', '"""Contents/MacOS/Setup"""'], {}), "(setupapp, 'Contents/MacOS/Setup')\n", (28533, 28567), False, 'import os\n'), ((28908, 28967), 'munkicommon.display_status_minor', 'munkicommon.display_status_minor', (['"""Running Adobe Uninstall"""'], {}), "('Running Adobe Uninstall')\n", (28940, 28967), False, 'import munkicommon\n'), ((30383, 30417), 'os.path.dirname', 'os.path.dirname', (['deploymentmanager'], {}), '(deploymentmanager)\n', (30398, 30417), False, 'import os\n'), ((30442, 30478), 'os.path.join', 'os.path.join', (['basepath', '"""preinstall"""'], {}), "(basepath, 'preinstall')\n", (30454, 30478), False, 'import os\n'), ((30911, 30956), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {'prefix': '"""munki-"""', 'dir': '"""/tmp"""'}), "(prefix='munki-', dir='/tmp')\n", (30927, 30956), False, 'import tempfile\n'), ((31635, 31674), 'munkicommon.getOsVersion', 'munkicommon.getOsVersion', ([], {'as_tuple': '(True)'}), '(as_tuple=True)\n', (31659, 31674), False, 'import munkicommon\n'), ((32737, 32780), 'subprocess.call', 'subprocess.call', (["['/bin/rm', '-rf', tmpdir]"], {}), "(['/bin/rm', '-rf', tmpdir])\n", (32752, 32780), False, 'import subprocess\n'), ((32785, 32823), 'munkicommon.unmountdmg', 'munkicommon.unmountdmg', (['mountpoints[0]'], {}), '(mountpoints[0])\n', (32807, 32823), False, 'import munkicommon\n'), ((36196, 36234), 'munkicommon.unmountdmg', 'munkicommon.unmountdmg', (['mountpoints[0]'], {}), '(mountpoints[0])\n', (36218, 36234), False, 'import munkicommon\n'), ((40726, 40742), 'os.walk', 'os.walk', (['dirpath'], {}), '(dirpath)\n', (40733, 40742), False, 'import os\n'), ((42014, 42074), 'os.path.join', 'os.path.join', (['pathToAcrobatPatchApp', '"""Contents"""', '"""Resources"""'], {}), "(pathToAcrobatPatchApp, 'Contents', 'Resources')\n", (42026, 42074), False, 'import os\n'), ((42105, 42152), 'os.path.join', 'os.path.join', (['resourcesDir', '"""ApplyOperation.py"""'], {}), "(resourcesDir, 'ApplyOperation.py')\n", (42117, 42152), False, 'import os\n'), ((42177, 42224), 'os.path.join', 'os.path.join', (['resourcesDir', '"""InstallUpdates.sh"""'], {}), "(resourcesDir, 'InstallUpdates.sh')\n", (42189, 42224), False, 'import os\n'), ((42261, 42303), 'os.path.join', 'os.path.join', (['resourcesDir', '"""app_list.txt"""'], {}), "(resourcesDir, 'app_list.txt')\n", (42273, 42303), False, 'import os\n'), ((42311, 42338), 'os.path.exists', 'os.path.exists', (['appListFile'], {}), '(appListFile)\n', (42325, 42338), False, 'import os\n'), ((45040, 45081), 'munkicommon.display_status_minor', 'munkicommon.display_status_minor', (['"""Done."""'], {}), "('Done.')\n", (45072, 45081), False, 'import munkicommon\n'), ((45158, 45193), 'munkicommon.unmountdmg', 'munkicommon.unmountdmg', (['installroot'], {}), '(installroot)\n', (45180, 45193), False, 'import munkicommon\n'), ((45335, 45379), 'os.path.join', 'os.path.join', (['path', '"""Contents"""', '"""Info.plist"""'], {}), "(path, 'Contents', 'Info.plist')\n", (45347, 45379), False, 'import os\n'), ((45490, 45514), 'os.path.exists', 'os.path.exists', (['infopath'], {}), '(infopath)\n', (45504, 45514), False, 'import os\n'), ((49481, 49507), 'os.path.exists', 'os.path.exists', (['installapp'], {}), '(installapp)\n', (49495, 49507), False, 'import os\n'), ((51868, 51901), 'os.path.join', 'os.path.join', (['mountpoint', 'pkgname'], {}), '(mountpoint, pkgname)\n', (51880, 51901), False, 'import os\n'), ((51924, 51971), 'os.path.join', 'os.path.join', (['pkgroot', '"""AdobeUberInstaller.xml"""'], {}), "(pkgroot, 'AdobeUberInstaller.xml')\n", (51936, 51971), False, 'import os\n'), ((51979, 52010), 'os.path.exists', 'os.path.exists', (['adobeinstallxml'], {}), '(adobeinstallxml)\n', (51993, 52010), False, 'import os\n'), ((58298, 58335), 'munkicommon.pref', 'munkicommon.pref', (['"""ManagedInstallDir"""'], {}), "('ManagedInstallDir')\n", (58314, 58335), False, 'import munkicommon\n'), ((58351, 58416), 'os.path.join', 'os.path.join', (['managedinstallbase', '"""Cache"""', "item['installer_item']"], {}), "(managedinstallbase, 'Cache', item['installer_item'])\n", (58363, 58416), False, 'import os\n'), ((1806, 1916), 'subprocess.Popen', 'subprocess.Popen', (["['/bin/ls', '-t1', logpath]"], {'bufsize': '(-1)', 'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.PIPE'}), "(['/bin/ls', '-t1', logpath], bufsize=-1, stdout=subprocess\n .PIPE, stderr=subprocess.PIPE)\n", (1822, 1916), False, 'import subprocess\n'), ((5267, 5334), 'munkicommon.display_error', 'munkicommon.display_error', (["('Error %s mounting %s.' % (err, dmgname))"], {}), "('Error %s mounting %s.' % (err, dmgname))\n", (5292, 5334), False, 'import munkicommon\n'), ((5368, 5413), 'FoundationPlist.readPlistFromString', 'FoundationPlist.readPlistFromString', (['pliststr'], {}), '(pliststr)\n', (5403, 5413), False, 'import FoundationPlist\n'), ((6819, 6843), 'os.path.exists', 'os.path.exists', (['setupxml'], {}), '(setupxml)\n', (6833, 6843), False, 'import os\n'), ((6848, 6872), 'os.path.isfile', 'os.path.isfile', (['setupxml'], {}), '(setupxml)\n', (6862, 6872), False, 'import os\n'), ((6912, 6935), 'xml.dom.minidom.parse', 'minidom.parse', (['setupxml'], {}), '(setupxml)\n', (6925, 6935), False, 'from xml.dom import minidom\n'), ((12518, 12538), 'os.walk', 'os.walk', (['installroot'], {}), '(installroot)\n', (12525, 12538), False, 'import os\n'), ((14080, 14107), 'xml.dom.minidom.parse', 'minidom.parse', (['installerxml'], {}), '(installerxml)\n', (14093, 14107), False, 'from xml.dom import minidom\n'), ((15554, 15583), 'os.path.basename', 'os.path.basename', (['installroot'], {}), '(installroot)\n', (15570, 15583), False, 'import os\n'), ((21034, 21070), 'utils.getPIDforProcessName', 'utils.getPIDforProcessName', (['procname'], {}), '(procname)\n', (21060, 21070), False, 'import utils\n'), ((22276, 22299), 'munkistatus.percent', 'munkistatus.percent', (['(-1)'], {}), '(-1)\n', (22295, 22299), False, 'import munkistatus\n'), ((22584, 22597), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (22594, 22597), False, 'import time\n'), ((25029, 25070), 'munkicommon.display_status_minor', 'munkicommon.display_status_minor', (['"""Done."""'], {}), "('Done.')\n", (25061, 25070), False, 'import munkicommon\n'), ((27266, 27304), 'munkicommon.unmountdmg', 'munkicommon.unmountdmg', (['mountpoints[0]'], {}), '(mountpoints[0])\n', (27288, 27304), False, 'import munkicommon\n'), ((27346, 27415), 'munkicommon.display_error', 'munkicommon.display_error', (["('No mountable filesystems on %s' % dmgpath)"], {}), "('No mountable filesystems on %s' % dmgpath)\n", (27371, 27415), False, 'import munkicommon\n'), ((28127, 28194), 'munkicommon.display_error', 'munkicommon.display_error', (['"""No uninstall.xml in adobe_install_info"""'], {}), "('No uninstall.xml in adobe_install_info')\n", (28152, 28194), False, 'import munkicommon\n'), ((28297, 28317), 'munkicommon.tmpdir', 'munkicommon.tmpdir', ([], {}), '()\n', (28315, 28317), False, 'import munkicommon\n'), ((28579, 28600), 'os.path.exists', 'os.path.exists', (['setup'], {}), '(setup)\n', (28593, 28600), False, 'import os\n'), ((28610, 28670), 'munkicommon.display_error', 'munkicommon.display_error', (["('%s is not installed.' % setupapp)"], {}), "('%s is not installed.' % setupapp)\n", (28635, 28670), False, 'import munkicommon\n'), ((29447, 29516), 'munkicommon.display_error', 'munkicommon.display_error', (["('No mountable filesystems on %s' % dmgpath)"], {}), "('No mountable filesystems on %s' % dmgpath)\n", (29472, 29516), False, 'import munkicommon\n'), ((29783, 29821), 'munkicommon.unmountdmg', 'munkicommon.unmountdmg', (['mountpoints[0]'], {}), '(mountpoints[0])\n', (29805, 29821), False, 'import munkicommon\n'), ((30490, 30523), 'os.path.exists', 'os.path.exists', (['preinstall_script'], {}), '(preinstall_script)\n', (30504, 30523), False, 'import os\n'), ((30792, 30830), 'munkicommon.unmountdmg', 'munkicommon.unmountdmg', (['mountpoints[0]'], {}), '(mountpoints[0])\n', (30814, 30830), False, 'import munkicommon\n'), ((31288, 31320), 'os.path.join', 'os.path.join', (['basepath', 'dir_name'], {}), '(basepath, dir_name)\n', (31300, 31320), False, 'import os\n'), ((31332, 31354), 'os.path.isdir', 'os.path.isdir', (['realdir'], {}), '(realdir)\n', (31345, 31354), False, 'import os\n'), ((32110, 32151), 'utils.getPIDforProcessName', 'utils.getPIDforProcessName', (['"""loginwindow"""'], {}), "('loginwindow')\n", (32136, 32151), False, 'import utils\n'), ((32354, 32379), 'os.path.dirname', 'os.path.dirname', (['basepath'], {}), '(basepath)\n', (32369, 32379), False, 'import os\n'), ((32476, 32539), 'munkicommon.display_status_minor', 'munkicommon.display_status_minor', (['"""Starting Adobe installer..."""'], {}), "('Starting Adobe installer...')\n", (32508, 32539), False, 'import munkicommon\n'), ((33158, 33227), 'munkicommon.display_error', 'munkicommon.display_error', (["('No mountable filesystems on %s' % dmgpath)"], {}), "('No mountable filesystems on %s' % dmgpath)\n", (33183, 33227), False, 'import munkicommon\n'), ((33930, 33964), 'os.path.dirname', 'os.path.dirname', (['deploymentmanager'], {}), '(deploymentmanager)\n', (33945, 33964), False, 'import os\n'), ((34035, 34080), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {'prefix': '"""munki-"""', 'dir': '"""/tmp"""'}), "(prefix='munki-', dir='/tmp')\n", (34051, 34080), False, 'import tempfile\n'), ((34772, 34811), 'os.path.join', 'os.path.join', (['basepath', '"""optionXML.xml"""'], {}), "(basepath, 'optionXML.xml')\n", (34784, 34811), False, 'import os\n'), ((34839, 34878), 'munkicommon.getOsVersion', 'munkicommon.getOsVersion', ([], {'as_tuple': '(True)'}), '(as_tuple=True)\n', (34863, 34878), False, 'import munkicommon\n'), ((35684, 35747), 'munkicommon.display_status_minor', 'munkicommon.display_status_minor', (['"""Starting Adobe installer..."""'], {}), "('Starting Adobe installer...')\n", (35716, 35747), False, 'import munkicommon\n'), ((35974, 36017), 'subprocess.call', 'subprocess.call', (["['/bin/rm', '-rf', tmpdir]"], {}), "(['/bin/rm', '-rf', tmpdir])\n", (35989, 36017), False, 'import subprocess\n'), ((38473, 38542), 'munkicommon.display_error', 'munkicommon.display_error', (["('No mountable filesystems on %s' % dmgpath)"], {}), "('No mountable filesystems on %s' % dmgpath)\n", (38498, 38542), False, 'import munkicommon\n'), ((39367, 39391), 'os.path.exists', 'os.path.exists', (['ubertool'], {}), '(ubertool)\n', (39381, 39391), False, 'import os\n'), ((40340, 40375), 'munkicommon.unmountdmg', 'munkicommon.unmountdmg', (['installroot'], {}), '(installroot)\n', (40362, 40375), False, 'import munkicommon\n'), ((40417, 40486), 'munkicommon.display_error', 'munkicommon.display_error', (["('No mountable filesystems on %s' % dmgpath)"], {}), "('No mountable filesystems on %s' % dmgpath)\n", (40442, 40486), False, 'import munkicommon\n'), ((41330, 41353), 'munkistatus.percent', 'munkistatus.percent', (['(-1)'], {}), '(-1)\n', (41349, 41353), False, 'import munkistatus\n'), ((41661, 41730), 'munkicommon.display_error', 'munkicommon.display_error', (["('No mountable filesystems on %s' % dmgpath)"], {}), "('No mountable filesystems on %s' % dmgpath)\n", (41686, 41730), False, 'import munkicommon\n'), ((41792, 41870), 'munkicommon.display_error', 'munkicommon.display_error', (['"""No Acrobat Patch app at %s"""', 'pathToAcrobatPatchApp'], {}), "('No Acrobat Patch app at %s', pathToAcrobatPatchApp)\n", (41817, 41870), False, 'import munkicommon\n'), ((41892, 41927), 'munkicommon.unmountdmg', 'munkicommon.unmountdmg', (['installroot'], {}), '(installroot)\n', (41914, 41927), False, 'import munkicommon\n'), ((42559, 42626), 'munkicommon.display_error', 'munkicommon.display_error', (['"""Did not find a list of apps to update."""'], {}), "('Did not find a list of apps to update.')\n", (42584, 42626), False, 'import munkicommon\n'), ((42635, 42670), 'munkicommon.unmountdmg', 'munkicommon.unmountdmg', (['installroot'], {}), '(installroot)\n', (42657, 42670), False, 'import munkicommon\n'), ((42945, 43007), 'munkicommon.display_status_minor', 'munkicommon.display_status_minor', (["('Searching for %s' % appname)"], {}), "('Searching for %s' % appname)\n", (42977, 43007), False, 'import munkicommon\n'), ((43069, 43127), 'os.path.join', 'os.path.join', (['"""/Applications/Adobe Acrobat 9 Pro"""', 'appname'], {}), "('/Applications/Adobe Acrobat 9 Pro', appname)\n", (43081, 43127), False, 'import os\n'), ((43139, 43163), 'os.path.exists', 'os.path.exists', (['pathname'], {}), '(pathname)\n', (43153, 43163), False, 'import os\n'), ((44210, 44267), 'munkicommon.display_status_minor', 'munkicommon.display_status_minor', (["('Updating %s' % appname)"], {}), "('Updating %s' % appname)\n", (44242, 44267), False, 'import munkicommon\n'), ((44286, 44324), 'os.path.dirname', 'os.path.dirname', (["candidates[0]['path']"], {}), "(candidates[0]['path'])\n", (44301, 44324), False, 'import os\n'), ((44455, 44578), 'subprocess.Popen', 'subprocess.Popen', (['cmd'], {'shell': '(False)', 'bufsize': '(-1)', 'stdin': 'subprocess.PIPE', 'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.STDOUT'}), '(cmd, shell=False, bufsize=-1, stdin=subprocess.PIPE,\n stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n', (44471, 44578), False, 'import subprocess\n'), ((45128, 45152), 'munkistatus.percent', 'munkistatus.percent', (['(100)'], {}), '(100)\n', (45147, 45152), False, 'import munkistatus\n'), ((45391, 45415), 'os.path.exists', 'os.path.exists', (['infopath'], {}), '(infopath)\n', (45405, 45415), False, 'import os\n'), ((45436, 45481), 'os.path.join', 'os.path.join', (['path', '"""Resources"""', '"""Info.plist"""'], {}), "(path, 'Resources', 'Info.plist')\n", (45448, 45481), False, 'import os\n'), ((46035, 46076), 'os.path.join', 'os.path.join', (['installdir', '"""optionXML.xml"""'], {}), "(installdir, 'optionXML.xml')\n", (46047, 46076), False, 'import os\n'), ((46088, 46117), 'os.path.exists', 'os.path.exists', (['optionXMLfile'], {}), '(optionXMLfile)\n', (46102, 46117), False, 'import os\n'), ((46576, 46610), 'os.path.dirname', 'os.path.dirname', (['deploymentmanager'], {}), '(deploymentmanager)\n', (46591, 46610), False, 'import os\n'), ((46637, 46675), 'os.path.join', 'os.path.join', (['dirpath', '"""optionXML.xml"""'], {}), "(dirpath, 'optionXML.xml')\n", (46649, 46675), False, 'import os\n'), ((46716, 46747), 'os.path.exists', 'os.path.exists', (['option_xml_file'], {}), '(option_xml_file)\n', (46730, 46747), False, 'import os\n'), ((53705, 53740), 'munkicommon.getVersionString', 'munkicommon.getVersionString', (['plist'], {}), '(plist)\n', (53733, 53740), False, 'import munkicommon\n'), ((56684, 56721), 'munkicommon.pref', 'munkicommon.pref', (['"""ManagedInstallDir"""'], {}), "('ManagedInstallDir')\n", (56700, 56721), False, 'import munkicommon\n'), ((56741, 56808), 'os.path.join', 'os.path.join', (['managedinstallbase', '"""Cache"""', "item['uninstaller_item']"], {}), "(managedinstallbase, 'Cache', item['uninstaller_item'])\n", (56753, 56808), False, 'import os\n'), ((57992, 58058), 'munkicommon.display_error', 'munkicommon.display_error', (['"""Uninstall of %s failed."""', "item['name']"], {}), "('Uninstall of %s failed.', item['name'])\n", (58017, 58058), False, 'import munkicommon\n'), ((3193, 3279), 'subprocess.Popen', 'subprocess.Popen', (['cmd'], {'bufsize': '(-1)', 'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.PIPE'}), '(cmd, bufsize=-1, stdout=subprocess.PIPE, stderr=subprocess\n .PIPE)\n', (3209, 3279), False, 'import subprocess\n'), ((7911, 7947), 'os.path.join', 'os.path.join', (['dirpath', '"""*.proxy.xml"""'], {}), "(dirpath, '*.proxy.xml')\n", (7923, 7947), False, 'import os\n'), ((8028, 8050), 'xml.dom.minidom.parse', 'minidom.parse', (['xmlpath'], {}), '(xmlpath)\n', (8041, 8050), False, 'from xml.dom import minidom\n'), ((8159, 8195), 'os.path.join', 'os.path.join', (['dirpath', '"""Media_db.db"""'], {}), "(dirpath, 'Media_db.db')\n", (8171, 8195), False, 'import os\n'), ((8211, 8234), 'os.path.exists', 'os.path.exists', (['db_path'], {}), '(db_path)\n', (8225, 8234), False, 'import os\n'), ((10716, 10747), 'os.path.join', 'os.path.join', (['path', '"""setup.xml"""'], {}), "(path, 'setup.xml')\n", (10728, 10747), False, 'import os\n'), ((10763, 10787), 'os.path.exists', 'os.path.exists', (['setupxml'], {}), '(setupxml)\n', (10777, 10787), False, 'import os\n'), ((11755, 11780), 'munkicommon.listdir', 'munkicommon.listdir', (['path'], {}), '(path)\n', (11774, 11780), False, 'import munkicommon\n'), ((14848, 14890), 'os.path.join', 'os.path.join', (['installroot', '"""optionXML.xml"""'], {}), "(installroot, 'optionXML.xml')\n", (14860, 14890), False, 'import os\n'), ((14906, 14934), 'os.path.exists', 'os.path.exists', (['installerxml'], {}), '(installerxml)\n', (14920, 14934), False, 'import os\n'), ((18027, 18052), 'munkicommon.listdir', 'munkicommon.listdir', (['path'], {}), '(path)\n', (18046, 18052), False, 'import munkicommon\n'), ((18908, 18956), 'os.path.join', 'os.path.join', (['path', '"""Contents"""', '"""MacOS"""', '"""Setup"""'], {}), "(path, 'Contents', 'MacOS', 'Setup')\n", (18920, 18956), False, 'import os\n'), ((18972, 18998), 'os.path.exists', 'os.path.exists', (['setup_path'], {}), '(setup_path)\n', (18986, 18998), False, 'import os\n'), ((19322, 19372), 'os.path.join', 'os.path.join', (['path', '"""Contents"""', '"""MacOS"""', '"""Install"""'], {}), "(path, 'Contents', 'MacOS', 'Install')\n", (19334, 19372), False, 'import os\n'), ((19388, 19414), 'os.path.exists', 'os.path.exists', (['setup_path'], {}), '(setup_path)\n', (19402, 19414), False, 'import os\n'), ((19774, 19836), 'os.path.join', 'os.path.join', (['path', '"""Contents"""', '"""MacOS"""', '"""AdobePatchInstaller"""'], {}), "(path, 'Contents', 'MacOS', 'AdobePatchInstaller')\n", (19786, 19836), False, 'import os\n'), ((19869, 19895), 'os.path.exists', 'os.path.exists', (['setup_path'], {}), '(setup_path)\n', (19883, 19895), False, 'import os\n'), ((20239, 20283), 'os.path.join', 'os.path.join', (['path', '"""AdobeDeploymentManager"""'], {}), "(path, 'AdobeDeploymentManager')\n", (20251, 20283), False, 'import os\n'), ((20299, 20322), 'os.path.exists', 'os.path.exists', (['dm_path'], {}), '(dm_path)\n', (20313, 20322), False, 'import os\n'), ((24532, 24563), 'munkicommon.display_error', 'munkicommon.display_error', (['line'], {}), '(line)\n', (24557, 24563), False, 'import munkicommon\n'), ((24996, 25020), 'munkistatus.percent', 'munkistatus.percent', (['(100)'], {}), '(100)\n', (25015, 25020), False, 'import munkistatus\n'), ((25337, 25362), 'os.path.basename', 'os.path.basename', (['dmgpath'], {}), '(dmgpath)\n', (25353, 25362), False, 'import os\n'), ((25617, 25660), 'os.path.join', 'os.path.join', (['mountpoints[0]', '"""install.xml"""'], {}), "(mountpoints[0], 'install.xml')\n", (25629, 25660), False, 'import os\n'), ((25688, 25733), 'os.path.join', 'os.path.join', (['mountpoints[0]', '"""uninstall.xml"""'], {}), "(mountpoints[0], 'uninstall.xml')\n", (25700, 25733), False, 'import os\n'), ((26669, 26724), 'munkicommon.display_status_minor', 'munkicommon.display_status_minor', (['"""Running Adobe Setup"""'], {}), "('Running Adobe Setup')\n", (26701, 26724), False, 'import munkicommon\n'), ((27771, 27830), 'munkicommon.display_error', 'munkicommon.display_error', (['("Couldn\'t write %s" % stringdata)'], {}), '("Couldn\'t write %s" % stringdata)\n', (27796, 27830), False, 'import munkicommon\n'), ((29347, 29372), 'os.path.basename', 'os.path.basename', (['dmgpath'], {}), '(dmgpath)\n', (29363, 29372), False, 'import os\n'), ((29748, 29773), 'os.path.basename', 'os.path.basename', (['dmgpath'], {}), '(dmgpath)\n', (29764, 29773), False, 'import os\n'), ((30572, 30646), 'munkicommon.display_error', 'munkicommon.display_error', (["('No Adobe install script found on %s' % dmgpath)"], {}), "('No Adobe install script found on %s' % dmgpath)\n", (30597, 30646), False, 'import munkicommon\n'), ((30690, 30766), 'munkicommon.display_error', 'munkicommon.display_error', (["('No Adobe uninstall script found on %s' % dmgpath)"], {}), "('No Adobe uninstall script found on %s' % dmgpath)\n", (30715, 30766), False, 'import munkicommon\n'), ((31080, 31112), 'os.path.join', 'os.path.join', (['basepath', 'dir_name'], {}), '(basepath, dir_name)\n', (31092, 31112), False, 'import os\n'), ((31380, 31410), 'os.path.join', 'os.path.join', (['tmpdir', 'dir_name'], {}), '(tmpdir, dir_name)\n', (31392, 31410), False, 'import os\n'), ((31423, 31442), 'os.mkdir', 'os.mkdir', (['tmpsubdir'], {}), '(tmpsubdir)\n', (31431, 31442), False, 'import os\n'), ((31467, 31495), 'munkicommon.listdir', 'munkicommon.listdir', (['realdir'], {}), '(realdir)\n', (31486, 31495), False, 'import munkicommon\n'), ((33058, 33083), 'os.path.basename', 'os.path.basename', (['dmgpath'], {}), '(dmgpath)\n', (33074, 33083), False, 'import os\n'), ((34129, 34158), 'os.path.join', 'os.path.join', (['basepath', '"""ASU"""'], {}), "(basepath, 'ASU')\n", (34141, 34158), False, 'import os\n'), ((34160, 34187), 'os.path.join', 'os.path.join', (['tmpdir', '"""ASU"""'], {}), "(tmpdir, 'ASU')\n", (34172, 34187), False, 'import os\n'), ((34208, 34250), 'os.path.join', 'os.path.join', (['basepath', '"""ProvisioningTool"""'], {}), "(basepath, 'ProvisioningTool')\n", (34220, 34250), False, 'import os\n'), ((34271, 34311), 'os.path.join', 'os.path.join', (['tmpdir', '"""ProvisioningTool"""'], {}), "(tmpdir, 'ProvisioningTool')\n", (34283, 34311), False, 'import os\n'), ((34382, 34414), 'os.path.join', 'os.path.join', (['basepath', 'dir_name'], {}), '(basepath, dir_name)\n', (34394, 34414), False, 'import os\n'), ((34430, 34452), 'os.path.isdir', 'os.path.isdir', (['realdir'], {}), '(realdir)\n', (34443, 34452), False, 'import os\n'), ((35346, 35387), 'utils.getPIDforProcessName', 'utils.getPIDforProcessName', (['"""loginwindow"""'], {}), "('loginwindow')\n", (35372, 35387), False, 'import utils\n'), ((36143, 36168), 'os.path.basename', 'os.path.basename', (['dmgpath'], {}), '(dmgpath)\n', (36159, 36168), False, 'import os\n'), ((36552, 36577), 'os.path.basename', 'os.path.basename', (['dmgpath'], {}), '(dmgpath)\n', (36568, 36577), False, 'import os\n'), ((36752, 36797), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {'prefix': '"""munki-"""', 'dir': '"""/tmp"""'}), "(prefix='munki-', dir='/tmp')\n", (36768, 36797), False, 'import tempfile\n'), ((36820, 36881), 'subprocess.call', 'subprocess.call', (["['/bin/cp', '-r', mountpoints[0], updatedir]"], {}), "(['/bin/cp', '-r', mountpoints[0], updatedir])\n", (36835, 36881), False, 'import subprocess\n'), ((36943, 36981), 'munkicommon.unmountdmg', 'munkicommon.unmountdmg', (['mountpoints[0]'], {}), '(mountpoints[0])\n', (36965, 36981), False, 'import munkicommon\n'), ((37263, 37300), 'subprocess.call', 'subprocess.call', (["['/bin/rm', dmgpath]"], {}), "(['/bin/rm', dmgpath])\n", (37278, 37300), False, 'import subprocess\n'), ((37630, 37695), 'munkicommon.display_status_minor', 'munkicommon.display_status_minor', (['"""Running Adobe Patch Installer"""'], {}), "('Running Adobe Patch Installer')\n", (37662, 37695), False, 'import munkicommon\n'), ((38320, 38366), 'subprocess.call', 'subprocess.call', (["['/bin/rm', '-rf', updatedir]"], {}), "(['/bin/rm', '-rf', updatedir])\n", (38335, 38366), False, 'import subprocess\n'), ((38393, 38431), 'munkicommon.unmountdmg', 'munkicommon.unmountdmg', (['mountpoints[0]'], {}), '(mountpoints[0])\n', (38415, 38431), False, 'import munkicommon\n'), ((38957, 38982), 'os.path.basename', 'os.path.basename', (['dmgpath'], {}), '(dmgpath)\n', (38973, 38982), False, 'import os\n'), ((39130, 39188), 'os.path.join', 'os.path.join', (['installroot', 'pkgname', '"""AdobeUberUninstaller"""'], {}), "(installroot, pkgname, 'AdobeUberUninstaller')\n", (39142, 39188), False, 'import os\n'), ((39262, 39318), 'os.path.join', 'os.path.join', (['installroot', 'pkgname', '"""AdobeUberInstaller"""'], {}), "(installroot, pkgname, 'AdobeUberInstaller')\n", (39274, 39318), False, 'import os\n'), ((39681, 39746), 'munkicommon.display_status_major', 'munkicommon.display_status_major', (["('%s %s' % (action, packagename))"], {}), "('%s %s' % (action, packagename))\n", (39713, 39746), False, 'import munkicommon\n'), ((40254, 40305), 'munkicommon.display_error', 'munkicommon.display_error', (["('No %s found' % ubertool)"], {}), "('No %s found' % ubertool)\n", (40279, 40305), False, 'import munkicommon\n'), ((40857, 40921), 'os.path.join', 'os.path.join', (['path', '"""Contents"""', '"""Resources"""', '"""ApplyOperation.py"""'], {}), "(path, 'Contents', 'Resources', 'ApplyOperation.py')\n", (40869, 40921), False, 'import os\n'), ((40954, 40987), 'os.path.exists', 'os.path.exists', (['patch_script_path'], {}), '(patch_script_path)\n', (40968, 40987), False, 'import os\n'), ((41453, 41478), 'os.path.basename', 'os.path.basename', (['dmgpath'], {}), '(dmgpath)\n', (41469, 41478), False, 'import os\n'), ((43937, 44058), 'munkicommon.display_error', 'munkicommon.display_error', (["('Cannot patch %s because we found more than one copy on the startup disk.' %\n appname)"], {}), "(\n 'Cannot patch %s because we found more than one copy on the startup disk.'\n % appname)\n", (43962, 44058), False, 'import munkicommon\n'), ((44143, 44178), 'munkicommon.unmountdmg', 'munkicommon.unmountdmg', (['installroot'], {}), '(installroot)\n', (44165, 44178), False, 'import munkicommon\n'), ((44718, 44731), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (44728, 44731), False, 'import time\n'), ((44838, 44906), 'munkicommon.display_error', 'munkicommon.display_error', (['"""Error patching %s: %s"""', 'appname', 'retcode'], {}), "('Error patching %s: %s', appname, retcode)\n", (44863, 44906), False, 'import munkicommon\n'), ((44968, 45034), 'munkicommon.display_status_minor', 'munkicommon.display_status_minor', (['"""Patching %s complete."""', 'appname'], {}), "('Patching %s complete.', appname)\n", (45000, 45034), False, 'import munkicommon\n'), ((45549, 45584), 'FoundationPlist.readPlist', 'FoundationPlist.readPlist', (['infopath'], {}), '(infopath)\n', (45574, 45584), False, 'import FoundationPlist\n'), ((56856, 56880), 'os.path.exists', 'os.path.exists', (['itempath'], {}), '(itempath)\n', (56870, 56880), False, 'import os\n'), ((56894, 57006), 'munkicommon.display_error', 'munkicommon.display_error', (["('%s package for %s was missing from the cache.' % (uninstallmethod, item[\n 'name']))"], {}), "('%s package for %s was missing from the cache.' %\n (uninstallmethod, item['name']))\n", (56919, 57006), False, 'import munkicommon\n'), ((2227, 2259), 'os.path.join', 'os.path.join', (['logpath', 'firstitem'], {}), '(logpath, firstitem)\n', (2239, 2259), False, 'import os\n'), ((8259, 8283), 'sqlite3.connect', 'sqlite3.connect', (['db_path'], {}), '(db_path)\n', (8274, 8283), False, 'import sqlite3\n'), ((10811, 10834), 'xml.dom.minidom.parse', 'minidom.parse', (['setupxml'], {}), '(setupxml)\n', (10824, 10834), False, 'from xml.dom import minidom\n'), ((11812, 11836), 'os.path.join', 'os.path.join', (['path', 'item'], {}), '(path, item)\n', (11824, 11836), False, 'import os\n'), ((12613, 12638), 'munkicommon.listdir', 'munkicommon.listdir', (['path'], {}), '(path)\n', (12632, 12638), False, 'import munkicommon\n'), ((14958, 14985), 'xml.dom.minidom.parse', 'minidom.parse', (['installerxml'], {}), '(installerxml)\n', (14971, 14985), False, 'from xml.dom import minidom\n'), ((18084, 18111), 'os.path.join', 'os.path.join', (['path', 'subitem'], {}), '(path, subitem)\n', (18096, 18111), False, 'import os\n'), ((18131, 18157), 'os.path.isdir', 'os.path.isdir', (['subitempath'], {}), '(subitempath)\n', (18144, 18157), False, 'import os\n'), ((23319, 23449), 'munkicommon.display_status_minor', 'munkicommon.display_status_minor', (["('Completed payload %s of %s%s' % (payload_completed_count,\n number_of_payloads, payloadinfo))"], {}), "('Completed payload %s of %s%s' % (\n payload_completed_count, number_of_payloads, payloadinfo))\n", (23351, 23449), False, 'import munkicommon\n'), ((23541, 23641), 'munkicommon.display_status_minor', 'munkicommon.display_status_minor', (['"""Completed payload %s%s"""', 'payload_completed_count', 'payloadinfo'], {}), "('Completed payload %s%s',\n payload_completed_count, payloadinfo)\n", (23573, 23641), False, 'import munkicommon\n'), ((25822, 25850), 'os.path.exists', 'os.path.exists', (['uninstallxml'], {}), '(uninstallxml)\n', (25836, 25850), False, 'import os\n'), ((26402, 26428), 'os.path.exists', 'os.path.exists', (['installxml'], {}), '(installxml)\n', (26416, 26428), False, 'import os\n'), ((31138, 31170), 'os.path.join', 'os.path.join', (['basepath', 'dir_name'], {}), '(basepath, dir_name)\n', (31150, 31170), False, 'import os\n'), ((31195, 31225), 'os.path.join', 'os.path.join', (['tmpdir', 'dir_name'], {}), '(tmpdir, dir_name)\n', (31207, 31225), False, 'import os\n'), ((31732, 31760), 'munkicommon.getconsoleuser', 'munkicommon.getconsoleuser', ([], {}), '()\n', (31758, 31760), False, 'import munkicommon\n'), ((31777, 31805), 'munkicommon.getconsoleuser', 'munkicommon.getconsoleuser', ([], {}), '()\n', (31803, 31805), False, 'import munkicommon\n'), ((34482, 34512), 'os.path.join', 'os.path.join', (['tmpdir', 'dir_name'], {}), '(tmpdir, dir_name)\n', (34494, 34512), False, 'import os\n'), ((34529, 34548), 'os.mkdir', 'os.mkdir', (['tmpsubdir'], {}), '(tmpsubdir)\n', (34537, 34548), False, 'import os\n'), ((34577, 34605), 'munkicommon.listdir', 'munkicommon.listdir', (['realdir'], {}), '(realdir)\n', (34596, 34605), False, 'import munkicommon\n'), ((37022, 37088), 'munkicommon.display_error', 'munkicommon.display_error', (["('Error copying items from %s' % dmgpath)"], {}), "('Error copying items from %s' % dmgpath)\n", (37047, 37088), False, 'import munkicommon\n'), ((38187, 38212), 'os.path.basename', 'os.path.basename', (['dmgpath'], {}), '(dmgpath)\n', (38203, 38212), False, 'import os\n'), ((43623, 43728), 'munkicommon.display_error', 'munkicommon.display_error', (["('Cannot patch %s because it was not found on the startup disk.' % appname)"], {}), "(\n 'Cannot patch %s because it was not found on the startup disk.' % appname)\n", (43648, 43728), False, 'import munkicommon\n'), ((43830, 43865), 'munkicommon.unmountdmg', 'munkicommon.unmountdmg', (['installroot'], {}), '(installroot)\n', (43852, 43865), False, 'import munkicommon\n'), ((4027, 4067), 're.compile', 're.compile', (['"""[^{]*(\\\\{[A-Fa-f0-9-]+\\\\})"""'], {}), "('[^{]*(\\\\{[A-Fa-f0-9-]+\\\\})')\n", (4037, 4067), False, 'import re\n'), ((8628, 8657), 'xml.dom.minidom.parseString', 'minidom.parseString', (['info_xml'], {}), '(info_xml)\n', (8647, 8657), False, 'from xml.dom import minidom\n'), ((21368, 21423), 'munkicommon.log', 'munkicommon.log', (["('Killing PID %s: %s' % (pid, procname))"], {}), "('Killing PID %s: %s' % (pid, procname))\n", (21383, 21423), False, 'import munkicommon\n'), ((24121, 24149), 'munkicommon.getconsoleuser', 'munkicommon.getconsoleuser', ([], {}), '()\n', (24147, 24149), False, 'import munkicommon\n'), ((24173, 24201), 'munkicommon.getconsoleuser', 'munkicommon.getconsoleuser', ([], {}), '()\n', (24199, 24201), False, 'import munkicommon\n'), ((26087, 26125), 'munkicommon.unmountdmg', 'munkicommon.unmountdmg', (['mountpoints[0]'], {}), '(mountpoints[0])\n', (26109, 26125), False, 'import munkicommon\n'), ((27205, 27230), 'os.path.basename', 'os.path.basename', (['dmgpath'], {}), '(dmgpath)\n', (27221, 27230), False, 'import os\n'), ((31524, 31551), 'os.path.join', 'os.path.join', (['realdir', 'item'], {}), '(realdir, item)\n', (31536, 31551), False, 'import os\n'), ((31580, 31609), 'os.path.join', 'os.path.join', (['tmpsubdir', 'item'], {}), '(tmpsubdir, item)\n', (31592, 31609), False, 'import os\n'), ((34944, 34972), 'munkicommon.getconsoleuser', 'munkicommon.getconsoleuser', ([], {}), '()\n', (34970, 34972), False, 'import munkicommon\n'), ((34993, 35021), 'munkicommon.getconsoleuser', 'munkicommon.getconsoleuser', ([], {}), '()\n', (35019, 35021), False, 'import munkicommon\n'), ((43368, 43392), 'munkicommon.getAppData', 'munkicommon.getAppData', ([], {}), '()\n', (43390, 43392), False, 'import munkicommon\n'), ((48717, 48758), 'os.path.join', 'os.path.join', (['uninstalldir', 'signaturefile'], {}), '(uninstalldir, signaturefile)\n', (48729, 48758), False, 'import os\n'), ((12771, 12795), 'os.path.join', 'os.path.join', (['path', 'item'], {}), '(path, item)\n', (12783, 12795), False, 'import os\n'), ((26270, 26295), 'os.path.basename', 'os.path.basename', (['dmgpath'], {}), '(dmgpath)\n', (26286, 26295), False, 'import os\n'), ((34663, 34690), 'os.path.join', 'os.path.join', (['realdir', 'item'], {}), '(realdir, item)\n', (34675, 34690), False, 'import os\n'), ((34716, 34745), 'os.path.join', 'os.path.join', (['tmpsubdir', 'item'], {}), '(tmpsubdir, item)\n', (34728, 34745), False, 'import os\n'), ((39844, 39870), 'os.path.basename', 'os.path.basename', (['ubertool'], {}), '(ubertool)\n', (39860, 39870), False, 'import os\n'), ((50538, 50572), 'os.path.join', 'os.path.join', (['uninstalldir', 'dbfile'], {}), '(uninstalldir, dbfile)\n', (50550, 50572), False, 'import os\n'), ((51483, 51517), 'os.path.join', 'os.path.join', (['uninstalldir', 'dbfile'], {}), '(uninstalldir, dbfile)\n', (51495, 51517), False, 'import os\n')]
import sys, pygame pygame.init() world_size = width, height = 10000, 9000 speed = [2, 2] DX, DY = 0.1, 0.1 position = [width / 2, height / 2] screen_size = int(DX * width), int(DY * height) black = 0, 0, 0 screen = pygame.display.set_mode(screen_size) ball = pygame.image.load("intro_ball.gif") ballrect = ball.get_rect() w, h = ballrect.width / DX, ballrect.height / DY pygame.time.set_timer(pygame.USEREVENT, 10) drag = False while 1: event = pygame.event.wait() if event.type == pygame.QUIT: sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: if position[0] - w/2 < event.pos[0]/DX < position[0] + w/2 and position[1] - h/2 < event.pos[1]/DY < position[1] + h/2: drag = True drg_x, drg_y = event.pos[0] / DX - position[0], event.pos[1] / DY - position[1] if event.type == pygame.MOUSEBUTTONUP: drag = False if event.type == pygame.MOUSEMOTION: if drag: position[0] = event.pos[0] / DX - drg_x position[1] = event.pos[1] / DY - drg_y if event.type == pygame.USEREVENT: if not drag: position[0] += speed[0] position[1] += speed[1] if position[0] - w/2 < 0 or position[0] + w/2 > width: speed[0] = -speed[0] if position[1] - h/2 < 0 or position[1] + h/2 > height: speed[1] = -speed[1] screen.fill(black) screen.blit(ball, (int(DX * (position[0] - w/2)), int(DY * (position[1] - h/2)))) pygame.display.flip()
[ "pygame.init", "pygame.display.set_mode", "pygame.display.flip", "pygame.event.wait", "sys.exit", "pygame.image.load", "pygame.time.set_timer" ]
[((19, 32), 'pygame.init', 'pygame.init', ([], {}), '()\n', (30, 32), False, 'import sys, pygame\n'), ((218, 254), 'pygame.display.set_mode', 'pygame.display.set_mode', (['screen_size'], {}), '(screen_size)\n', (241, 254), False, 'import sys, pygame\n'), ((263, 298), 'pygame.image.load', 'pygame.image.load', (['"""intro_ball.gif"""'], {}), "('intro_ball.gif')\n", (280, 298), False, 'import sys, pygame\n'), ((376, 419), 'pygame.time.set_timer', 'pygame.time.set_timer', (['pygame.USEREVENT', '(10)'], {}), '(pygame.USEREVENT, 10)\n', (397, 419), False, 'import sys, pygame\n'), ((456, 475), 'pygame.event.wait', 'pygame.event.wait', ([], {}), '()\n', (473, 475), False, 'import sys, pygame\n'), ((510, 520), 'sys.exit', 'sys.exit', ([], {}), '()\n', (518, 520), False, 'import sys, pygame\n'), ((1491, 1512), 'pygame.display.flip', 'pygame.display.flip', ([], {}), '()\n', (1510, 1512), False, 'import sys, pygame\n')]
# Generated by Django 3.2.5 on 2021-07-04 19:36 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('activities', '0002_rename_currentactivity_currentactivitie'), ] operations = [ migrations.AlterField( model_name='currentactivitie', name='importance_level', field=models.CharField(choices=[('Optional', 'Optional'), ('Important', 'Important'), ('Very important', 'Very important'), ('Critical', 'Critical')], default='None', max_length=25), ), ]
[ "django.db.models.CharField" ]
[((380, 563), 'django.db.models.CharField', 'models.CharField', ([], {'choices': "[('Optional', 'Optional'), ('Important', 'Important'), ('Very important',\n 'Very important'), ('Critical', 'Critical')]", 'default': '"""None"""', 'max_length': '(25)'}), "(choices=[('Optional', 'Optional'), ('Important',\n 'Important'), ('Very important', 'Very important'), ('Critical',\n 'Critical')], default='None', max_length=25)\n", (396, 563), False, 'from django.db import migrations, models\n')]
#!/usr/bin/python # -*- coding: utf-8 -*- ''' Unit tests for the item() utility function. ''' import unittest from collector.utilities.item import item class TestUtilityItem(unittest.TestCase): ''' Tests for the item() utility function. ''' def test_item_returns_correct_type(self): ''' Tests that the item() utility function returns the right type. ''' result = item('bullet') self.assertIs(type(result), str)
[ "collector.utilities.item.item" ]
[((390, 404), 'collector.utilities.item.item', 'item', (['"""bullet"""'], {}), "('bullet')\n", (394, 404), False, 'from collector.utilities.item import item\n')]
# flake8: noqa import json import time import requests from django.conf import settings from websocket import create_connection from open.core.scripts.swarm_ml_services import get_random_prompt from open.core.writeup.constants import TEXT_GENERATION_URL """ this script's design was to compare performance behind django channels and how much overhead it added versus directly hitting the microservice output: 1.8620352506637574 was the average time in seconds to run. 1.8132854890823364 was the average time in seconds to run directly. amazingly enough, django channels ... has almost zero overhead wow. """ def run(): # dpy runscript writeup_profile_prompt_generate_view url = f"wss://open.senrigan.io/ws/async/writeup/{TEXT_GENERATION_URL}/session/a-cool-test-session/" ws = create_connection(url) start = time.time() intervals = 50 for _ in range(intervals): data = get_random_prompt() ws_msg = json.dumps(data) ws.send(ws_msg) result = ws.recv() end = time.time() websocket_difference = end - start print(f"{websocket_difference/intervals} was the average time in seconds to run.") url = settings.GPT2_MEDUM_API_ENDPOINT token_key = f"Token {settings.ML_SERVICE_ENDPOINT_API_KEY}" headers = {"Authorization": token_key} api_start = time.time() for _ in range(intervals): data = get_random_prompt() response = requests.post(url, json=data, headers=headers) assert response.status_code == 200 api_end = time.time() api_difference = api_end - api_start print( f"{api_difference / intervals} was the average time in seconds to run directly." )
[ "open.core.scripts.swarm_ml_services.get_random_prompt", "requests.post", "json.dumps", "websocket.create_connection", "time.time" ]
[((797, 819), 'websocket.create_connection', 'create_connection', (['url'], {}), '(url)\n', (814, 819), False, 'from websocket import create_connection\n'), ((833, 844), 'time.time', 'time.time', ([], {}), '()\n', (842, 844), False, 'import time\n'), ((1027, 1038), 'time.time', 'time.time', ([], {}), '()\n', (1036, 1038), False, 'import time\n'), ((1334, 1345), 'time.time', 'time.time', ([], {}), '()\n', (1343, 1345), False, 'import time\n'), ((1536, 1547), 'time.time', 'time.time', ([], {}), '()\n', (1545, 1547), False, 'import time\n'), ((911, 930), 'open.core.scripts.swarm_ml_services.get_random_prompt', 'get_random_prompt', ([], {}), '()\n', (928, 930), False, 'from open.core.scripts.swarm_ml_services import get_random_prompt\n'), ((948, 964), 'json.dumps', 'json.dumps', (['data'], {}), '(data)\n', (958, 964), False, 'import json\n'), ((1392, 1411), 'open.core.scripts.swarm_ml_services.get_random_prompt', 'get_random_prompt', ([], {}), '()\n', (1409, 1411), False, 'from open.core.scripts.swarm_ml_services import get_random_prompt\n'), ((1431, 1477), 'requests.post', 'requests.post', (['url'], {'json': 'data', 'headers': 'headers'}), '(url, json=data, headers=headers)\n', (1444, 1477), False, 'import requests\n')]
import http.client, urllib.request, urllib.parse, urllib.error, base64, time, json, ast, datetime, math, keys import logging logging.basicConfig(filename='io.log', level=logging.INFO, format='%(asctime)s %(message)s') headers = { # Request headers 'Ocp-Apim-Subscription-Key': keys.OCP_APIM_SUBSCRIPTION_KEY, } def get_spot_price(): now = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M") # print(now) params = urllib.parse.urlencode({ '$filter': 'PointOfConnectionCode eq \'CML0331\'', '&filter': 'TradingDate eq datetime'+now+'' }) conn = http.client.HTTPSConnection('emi.azure-api.net') conn.request("GET", "/real-time-prices/?%s" % params, "{body}", headers) response = conn.getresponse() data = response.read() json_data = json.loads(data.decode('utf-8')) value = json_data[0]['DollarsPerMegawattHour']/1000 logging.info("SPOT PRICE:$%s" ,value) conn.close() return value while(1): print(get_spot_price()) time.sleep(60)
[ "logging.basicConfig", "datetime.datetime.now", "logging.info", "time.sleep" ]
[((127, 224), 'logging.basicConfig', 'logging.basicConfig', ([], {'filename': '"""io.log"""', 'level': 'logging.INFO', 'format': '"""%(asctime)s %(message)s"""'}), "(filename='io.log', level=logging.INFO, format=\n '%(asctime)s %(message)s')\n", (146, 224), False, 'import logging\n'), ((901, 938), 'logging.info', 'logging.info', (['"""SPOT PRICE:$%s"""', 'value'], {}), "('SPOT PRICE:$%s', value)\n", (913, 938), False, 'import logging\n'), ((1017, 1031), 'time.sleep', 'time.sleep', (['(60)'], {}), '(60)\n', (1027, 1031), False, 'import http.client, urllib.request, urllib.parse, urllib.error, base64, time, json, ast, datetime, math, keys\n'), ((356, 379), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (377, 379), False, 'import http.client, urllib.request, urllib.parse, urllib.error, base64, time, json, ast, datetime, math, keys\n')]
import time import random def main(): print("You are trying to find your way to the centre of a maze where there is a pot of gold!") time.sleep(2) print("What you don't know is that this is a dangerous maze with traps and hazards.") time.sleep(2) start = input ("Do you want to enter the maze? (y/n)") if start == "y" or start == "Y" or start == "Yes" or start == "yes": print ("Welcome to the maze.") print("You enter the maze...") time.sleep(2) print("You reach a opening in the wall and go through it...") time.sleep(2) print("You can go left (L) or right (R)") answer = input("Make your choice ... ") print("You chose",answer,"... what will happen? ") time.sleep(2) print("You turn a corner...") time.sleep(2) print("You take a few steps forward...") time.sleep(2) if answer == "R" or answer == "r" or answer == "right" or answer == "Right": print("...and fall down a trapdoor!") time.sleep(1) print ("After falling down for few seconds, you arrived in a damp room with no light.") A = input ("Do you want to explore the room? (Y/N)") if A == "Y" or A == "y" or A == "Yes" or A == "yes": print ("Exploring. . .") time.sleep(2) print ("You found a torch and two stones!") AN = input ("Ignite the torch? (Y/N)") if AN == "Y": print ("Igniting the torch...") time.sleep(2) items = ["You failed to ignite the torch. After a few hours in the dark, you died due to hypothermia. No one could find your dead body.", "You succeeded! With the torch, you found many pots of gold... But where is the way to escape?"] ri = random.choice (items) print (ri) else: time.sleep(2) print ("After a few hours in dark, you died due to hypothermia. No one could find your dead body.") else: time.sleep(2) print ("You were too afraid to move an inch in the dark, so you stayed... and never saw the sun again.") else: print('''...and see a beautiful grassy patch lined with trees! There is a pot of gold at the end!''') time.sleep(2) print("You run towards the pot of gold, shining under the bright sunshine...") time.sleep(2) print(". . .and find out that the pot of gold was an illusion.") time.sleep(2) print("The beautiful grassy patch was just a grey path covered with mold, and the trees were just tall torches!") time.sleep(3) print("And the bright sunshine was...") time.sleep(2) print("An enormous burning stone falling directly towards you! \n") time.sleep(2) print("Farewell, explorer. You encountered death!") elif start == "n": print ("Well, well, you coward! Come back whenever you feel brave enough to start!") main()
[ "random.choice", "time.sleep" ]
[((146, 159), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (156, 159), False, 'import time\n'), ((254, 267), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (264, 267), False, 'import time\n'), ((486, 499), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (496, 499), False, 'import time\n'), ((586, 599), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (596, 599), False, 'import time\n'), ((773, 786), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (783, 786), False, 'import time\n'), ((841, 854), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (851, 854), False, 'import time\n'), ((920, 933), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (930, 933), False, 'import time\n'), ((1087, 1100), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (1097, 1100), False, 'import time\n'), ((2522, 2535), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (2532, 2535), False, 'import time\n'), ((2639, 2652), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (2649, 2652), False, 'import time\n'), ((2742, 2755), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (2752, 2755), False, 'import time\n'), ((2894, 2907), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (2904, 2907), False, 'import time\n'), ((2972, 2985), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (2982, 2985), False, 'import time\n'), ((3078, 3091), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (3088, 3091), False, 'import time\n'), ((1385, 1398), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (1395, 1398), False, 'import time\n'), ((2248, 2261), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (2258, 2261), False, 'import time\n'), ((1631, 1644), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (1641, 1644), False, 'import time\n'), ((1971, 1991), 'random.choice', 'random.choice', (['items'], {}), '(items)\n', (1984, 1991), False, 'import random\n'), ((2083, 2096), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (2093, 2096), False, 'import time\n')]
import os from PyQt5 import QtWidgets from .qtd import Ui_MainWindow from version import __version__ from utils import SpinBoxFixStyle class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow): """ Main window """ def __init__(self, parent=None): # initialization of the superclass super(MainWindow, self).__init__(parent) self.setupUi(self) # setup the GUI --> function generated by pyuic5 env = os.environ['CONDA_DEFAULT_ENV'] self.setWindowTitle("JCPDSTools ver. " + str(__version__) + " on " + env) # self.build_ui() #self.connect_channel() def build_ui(self): self.pushButton_WriteDioptasJCPDS.setDisabled(True) self.doubleSpinBox_CellParamA.setKeyboardTracking(False) self.doubleSpinBox_CellParamA.setStyle(SpinBoxFixStyle()) self.doubleSpinBox_CellParamB.setKeyboardTracking(False) self.doubleSpinBox_CellParamB.setStyle(SpinBoxFixStyle()) self.doubleSpinBox_CellParamC.setKeyboardTracking(False) self.doubleSpinBox_CellParamC.setStyle(SpinBoxFixStyle()) self.doubleSpinBox_CellParamAlpha.setKeyboardTracking(False) self.doubleSpinBox_CellParamAlpha.setStyle(SpinBoxFixStyle()) self.doubleSpinBox_CellParamBeta.setKeyboardTracking(False) self.doubleSpinBox_CellParamBeta.setStyle(SpinBoxFixStyle()) self.doubleSpinBox_CellParamGamma.setKeyboardTracking(False) self.doubleSpinBox_CellParamGamma.setStyle(SpinBoxFixStyle()) self.doubleSpinBox_K0.setStyle(SpinBoxFixStyle()) self.doubleSpinBox_K0p.setStyle(SpinBoxFixStyle()) self.doubleSpinBox_MinDsp.setStyle(SpinBoxFixStyle()) self.doubleSpinBox_MinInt.setStyle(SpinBoxFixStyle()) self.doubleSpinBox_K0.setKeyboardTracking(False) self.doubleSpinBox_K0p.setKeyboardTracking(False) self.doubleSpinBox_MinDsp.setKeyboardTracking(False) self.doubleSpinBox_MinInt.setKeyboardTracking(False) def closeEvent(self, event): self.deleteLater() event.accept()
[ "utils.SpinBoxFixStyle" ]
[((823, 840), 'utils.SpinBoxFixStyle', 'SpinBoxFixStyle', ([], {}), '()\n', (838, 840), False, 'from utils import SpinBoxFixStyle\n'), ((954, 971), 'utils.SpinBoxFixStyle', 'SpinBoxFixStyle', ([], {}), '()\n', (969, 971), False, 'from utils import SpinBoxFixStyle\n'), ((1085, 1102), 'utils.SpinBoxFixStyle', 'SpinBoxFixStyle', ([], {}), '()\n', (1100, 1102), False, 'from utils import SpinBoxFixStyle\n'), ((1224, 1241), 'utils.SpinBoxFixStyle', 'SpinBoxFixStyle', ([], {}), '()\n', (1239, 1241), False, 'from utils import SpinBoxFixStyle\n'), ((1361, 1378), 'utils.SpinBoxFixStyle', 'SpinBoxFixStyle', ([], {}), '()\n', (1376, 1378), False, 'from utils import SpinBoxFixStyle\n'), ((1500, 1517), 'utils.SpinBoxFixStyle', 'SpinBoxFixStyle', ([], {}), '()\n', (1515, 1517), False, 'from utils import SpinBoxFixStyle\n'), ((1558, 1575), 'utils.SpinBoxFixStyle', 'SpinBoxFixStyle', ([], {}), '()\n', (1573, 1575), False, 'from utils import SpinBoxFixStyle\n'), ((1617, 1634), 'utils.SpinBoxFixStyle', 'SpinBoxFixStyle', ([], {}), '()\n', (1632, 1634), False, 'from utils import SpinBoxFixStyle\n'), ((1679, 1696), 'utils.SpinBoxFixStyle', 'SpinBoxFixStyle', ([], {}), '()\n', (1694, 1696), False, 'from utils import SpinBoxFixStyle\n'), ((1741, 1758), 'utils.SpinBoxFixStyle', 'SpinBoxFixStyle', ([], {}), '()\n', (1756, 1758), False, 'from utils import SpinBoxFixStyle\n')]
# Python3 from solution1 import arrayReplace as f qa = [ ([1, 2, 1], 1, 3, [3, 2, 3]), ([1, 2, 3, 4, 5], 3, 0, [1, 2, 0, 4, 5]), ([1, 1, 1], 1, 10, [10, 10, 10]), ([1, 2, 1, 2, 1], 2, 1, [1, 1, 1, 1, 1]), ([1, 2, 1, 2, 1], 2, 2, [1, 2, 1, 2, 1]), ([3, 1], 3, 9, [9, 1]) ] for *q, a in qa: for i, e in enumerate(q): print('input{0}: {1}'.format(i + 1, e)) ans = f(*q) if ans != a: print(' [failed]') print(' output:', ans) print(' expected:', a) else: print(' [ok]') print(' output:', ans) print()
[ "solution1.arrayReplace" ]
[((434, 439), 'solution1.arrayReplace', 'f', (['*q'], {}), '(*q)\n', (435, 439), True, 'from solution1 import arrayReplace as f\n')]
from avatar2 import * import sys import os import logging import serial import time import argparse import pyudev import struct import ctypes from random import randint # For profiling import pstats logging.basicConfig(filename='/tmp/inception-tests.log', level=logging.INFO) # **************************************************************************** def single_step(target, nb_test): print("[*] Single step target %d times" % nb_test) for i in range(nb_test): pc = target.protocols.execution.read_pc() print(pc) target.step() print('stepped') next_pc = target.protocols.execution.read_pc() print(next_pc) # **************************************************************************** def read_full_mem(target, nb_test, raw=True, summary=True): print(" - Read the full memory") nb_test = 1 average_read = 0 for i in range(nb_test): t0 = time.time() target.read_memory(ram.address, 1, ram.size, raw=raw) t1 = time.time() average_read += t1 - t0 if summary: average_read = average_read / nb_test speed_read = ram.size / average_read / 1024 print(" -> On average raw read of %s bytes takes %.2f sec, speed: %.2f KB/sec" % (ram.size, average_read, speed_read)) # **************************************************************************** def write_full_mem(target, nb_test, raw=True, summary=True): print(" - Write the full memory") nb_test = 1 average_write = 0 buf = ctypes.create_string_buffer(ram.size) for i in range(int(ram.size / 4)): struct.pack_into(">I", buf, i * 4, randint(0, 0xffffffff)) for i in range(nb_test): t0 = time.time() target.write_memory(ram.address, 1, buf, raw=raw) t1 = time.time() average_write += t1 - t0 if summary: average_write = average_write / nb_test speed_write = ram.size / average_write / 1024 print(" -> On average raw write of %s bytes takes %.2f sec, speed: %.2f KB/sec" % (ram.size, average_write, speed_write)) # **************************************************************************** def read_write_full_mem(target, nb_test, raw=True, summary=True): print(" - Read and write the full memory") reads = [] average_read_write = 0 for i in range(nb_test): if raw: t0 = time.time() reads.append(target.read_memory(ram.address, 1, ram.size, raw=raw)) target.write_memory(ram.address, 1, reads[i], raw=raw) t1 = time.time() else: t0 = time.time() reads.append(target.read_memory(ram.address, 1, ram.size, raw=raw)) target.write_memory(ram.address, 1, reads[i], len(reads[i]), raw=raw) t1 = time.time() average_read_write += t1 - t0 if summary: average_read_write = average_read_write / nb_test speed_read_write = ram.size / average_read_write / 1024 print(" -> On average raw read&write of %s bytes takes %.2f sec, speed: %.2f KB/sec" % (ram.size, average_read_write, speed_read_write)) # Verify all reads are identical for i in range(len(reads) - 1): assert(reads[i] == reads[i+1]) #print("[!] Multiple reads produce different values !") # **************************************************************************** def random_read_write(target, nb_test, raw=True): print(" - Random read / writes of random size in the ram") for i in range(0, nb_test): size = randint(0, int(ram.size / 8)) * 8 #size = 2**4 # Reset the board and wait to reach the breakpoint target.reset() target.wait() if raw: m1 = ctypes.create_string_buffer(size) for j in range(int(size / 4)): struct.pack_into(">I", m1, j * 4, randint(0, 0xFFFFFFFF)) target.write_memory(ram.address, 1, m1, raw=True) m2 = target.read_memory(ram.address, 1, size, raw=True) n1, n2 = ([] for i in range(2)) for j in range(int(size / 4)): n1.append(struct.unpack_from(">I", m1, j)[0]) n2.append(struct.unpack_from(">I", m2, j)[0]) assert(n1 == n2) #print("i=%s m1: %s m2: %s" % (i, m1.raw, m2)) #print("[!] Multiple random reads produce different values !") else: m1 = [] for j in range(int(size / 4)): m1.append(randint(0, 0xFFFFFFFF)) target.write_memory(ram.address, 1, m1, size, raw=False) m2 = target.read_memory(ram.address, 1, size, raw=False) for j in range(int(size / 4)): assert(m1[j] == m2[j]) #print("[!] Multiple random reads produce different values !") #print("i=%s j=%s m1[j]: %s m2[j]: %s" % (i, j, m1[j], m2[j])) # **************************************************************************** def random_4bytes_read_write(target, nb_test): print(" - Random read / writes of 4 bytes in the ram") for i in range(nb_test): written_word = randint(0, 0xFFFFFFFF) address = randint(ram.address, ram.address + ram.size - 4) target.write_memory(address, 4, written_word, 1, raw=False) read_word = target.read_memory(address, 4, 1, raw=False) assert(written_word == read_word) # **************************************************************************** def read_write_registers(target, nb_test): print(" - Read / write registers") regs = ['R0', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'R7', 'R8', 'R9', 'R10', 'R11', 'R12', 'SP', 'LR', 'PC', 'CPSR'] for i in range(nb_test): for j in range(17): written_reg = randint(0, 0xFFFFFFFF) saved_reg = target.read_register(regs[j]) target.write_register(regs[j], written_reg) read_reg = target.read_register(regs[j]) ''' if read_reg != written_reg: print(i) print(j) print(hex(read_reg)) print(hex(written_reg)) ''' target.write_register(regs[j], saved_reg) # **************************************************************************** def transfer_state(av, target_from, target_to, nb_test, summary=True): print(" - Transfer state") average = 0 for i in range(nb_test): t0 = time.time() av.transfer_state(target_from, target_to, synced_ranges=[ram]) t1 = time.time() average += t1 - t0 if summary: average = average / nb_test speed = ram.size / average / 1024 print(" -> On average transfer state from %s to %s of %s bytes takes %.2f sec, speed: %.2f KB/sec" % (target_from.name, target_to.name, ram.size, average, speed)) if __name__ == '__main__': # Number each test is repeated n = 2 avatar = Avatar(arch=ARMV7M, output_directory='/tmp/inception-tests') nucleo = avatar.add_target(InceptionTarget, name='nucleo') dum = avatar.add_target(DummyTarget, name='dum') #qemu = avatar.add_target(QemuTarget, gdb_port=1236) # Memory mapping of NUCLEO-L152RE rom = avatar.add_memory_range(0x08000000, 0x1000000, 'rom', file=firmware) ram = avatar.add_memory_range(0x20000000, 0x14000, 'ram') mmio = avatar.add_memory_range(0x40000000, 0x1000000, forwarded=True, forwarded_to=nucleo) ram = avatar.get_memory_range(0x20000000) avatar.init_targets() print("Targets initialized") nucleo.reset() nucleo.cont() nucleo.stop() print("Targets stopped, start tests for n = %s" % n) print("[*] Raw read / writes tests") read_full_mem(nucleo, n) write_full_mem(nucleo, n) read_write_full_mem(nucleo, n) random_read_write(nucleo, n) print("[*] !raw read / writes tests") read_full_mem(nucleo, n, raw=False, summary=False) write_full_mem(nucleo, n, raw=False, summary=False) read_write_full_mem(nucleo, n, raw=False, summary=False) random_read_write(nucleo, n, raw=False) random_4bytes_read_write(nucleo, 100 * n) print("[*] Read / Write registers") read_write_registers(nucleo, n) print("[*] Transfer state to dummy target") transfer_state(avatar, nucleo, dum, n) #Stop all threads for the profiler print("[*] Test completed") avatar.stop()
[ "logging.basicConfig", "ctypes.create_string_buffer", "time.time", "random.randint", "struct.unpack_from" ]
[((203, 279), 'logging.basicConfig', 'logging.basicConfig', ([], {'filename': '"""/tmp/inception-tests.log"""', 'level': 'logging.INFO'}), "(filename='/tmp/inception-tests.log', level=logging.INFO)\n", (222, 279), False, 'import logging\n'), ((1534, 1571), 'ctypes.create_string_buffer', 'ctypes.create_string_buffer', (['ram.size'], {}), '(ram.size)\n', (1561, 1571), False, 'import ctypes\n'), ((931, 942), 'time.time', 'time.time', ([], {}), '()\n', (940, 942), False, 'import time\n'), ((1018, 1029), 'time.time', 'time.time', ([], {}), '()\n', (1027, 1029), False, 'import time\n'), ((1721, 1732), 'time.time', 'time.time', ([], {}), '()\n', (1730, 1732), False, 'import time\n'), ((1804, 1815), 'time.time', 'time.time', ([], {}), '()\n', (1813, 1815), False, 'import time\n'), ((5167, 5189), 'random.randint', 'randint', (['(0)', '(4294967295)'], {}), '(0, 4294967295)\n', (5174, 5189), False, 'from random import randint\n'), ((5208, 5256), 'random.randint', 'randint', (['ram.address', '(ram.address + ram.size - 4)'], {}), '(ram.address, ram.address + ram.size - 4)\n', (5215, 5256), False, 'from random import randint\n'), ((6509, 6520), 'time.time', 'time.time', ([], {}), '()\n', (6518, 6520), False, 'import time\n'), ((6605, 6616), 'time.time', 'time.time', ([], {}), '()\n', (6614, 6616), False, 'import time\n'), ((1654, 1676), 'random.randint', 'randint', (['(0)', '(4294967295)'], {}), '(0, 4294967295)\n', (1661, 1676), False, 'from random import randint\n'), ((2399, 2410), 'time.time', 'time.time', ([], {}), '()\n', (2408, 2410), False, 'import time\n'), ((2575, 2586), 'time.time', 'time.time', ([], {}), '()\n', (2584, 2586), False, 'import time\n'), ((2618, 2629), 'time.time', 'time.time', ([], {}), '()\n', (2627, 2629), False, 'import time\n'), ((2809, 2820), 'time.time', 'time.time', ([], {}), '()\n', (2818, 2820), False, 'import time\n'), ((3762, 3795), 'ctypes.create_string_buffer', 'ctypes.create_string_buffer', (['size'], {}), '(size)\n', (3789, 3795), False, 'import ctypes\n'), ((5814, 5836), 'random.randint', 'randint', (['(0)', '(4294967295)'], {}), '(0, 4294967295)\n', (5821, 5836), False, 'from random import randint\n'), ((3889, 3911), 'random.randint', 'randint', (['(0)', '(4294967295)'], {}), '(0, 4294967295)\n', (3896, 3911), False, 'from random import randint\n'), ((4523, 4545), 'random.randint', 'randint', (['(0)', '(4294967295)'], {}), '(0, 4294967295)\n', (4530, 4545), False, 'from random import randint\n'), ((4158, 4189), 'struct.unpack_from', 'struct.unpack_from', (['""">I"""', 'm1', 'j'], {}), "('>I', m1, j)\n", (4176, 4189), False, 'import struct\n'), ((4220, 4251), 'struct.unpack_from', 'struct.unpack_from', (['""">I"""', 'm2', 'j'], {}), "('>I', m2, j)\n", (4238, 4251), False, 'import struct\n')]
from django.conf.urls import include, url urlpatterns = [ url(r'^admin/(?P<slug>[\w\-]+)/', 'posts.views.post_preview', name='post_preview'), url(r'^tag/(?P<slug>[\w\-]+)/', 'posts.views.posts_view_tag', name='posts_tag'), url(r'^popular/', 'posts.views.posts_view_popular', name='posts_popular'), url(r'^(?P<slug>[\w\-]+)/', 'posts.views.post_view', name='post_view'), ]
[ "django.conf.urls.url" ]
[((63, 151), 'django.conf.urls.url', 'url', (['"""^admin/(?P<slug>[\\\\w\\\\-]+)/"""', '"""posts.views.post_preview"""'], {'name': '"""post_preview"""'}), "('^admin/(?P<slug>[\\\\w\\\\-]+)/', 'posts.views.post_preview', name=\n 'post_preview')\n", (66, 151), False, 'from django.conf.urls import include, url\n'), ((151, 236), 'django.conf.urls.url', 'url', (['"""^tag/(?P<slug>[\\\\w\\\\-]+)/"""', '"""posts.views.posts_view_tag"""'], {'name': '"""posts_tag"""'}), "('^tag/(?P<slug>[\\\\w\\\\-]+)/', 'posts.views.posts_view_tag', name='posts_tag'\n )\n", (154, 236), False, 'from django.conf.urls import include, url\n'), ((236, 308), 'django.conf.urls.url', 'url', (['"""^popular/"""', '"""posts.views.posts_view_popular"""'], {'name': '"""posts_popular"""'}), "('^popular/', 'posts.views.posts_view_popular', name='posts_popular')\n", (239, 308), False, 'from django.conf.urls import include, url\n'), ((315, 386), 'django.conf.urls.url', 'url', (['"""^(?P<slug>[\\\\w\\\\-]+)/"""', '"""posts.views.post_view"""'], {'name': '"""post_view"""'}), "('^(?P<slug>[\\\\w\\\\-]+)/', 'posts.views.post_view', name='post_view')\n", (318, 386), False, 'from django.conf.urls import include, url\n')]
from hlt.positionals import Position, Direction from hlt import constants import random import logging # Import my stuff import helpers def navigate_old(ship, destination, game_map): curr_pos = ship.position move_cost = game_map[curr_pos].halite_amount/constants.MOVE_COST_RATIO if ship.halite_amount >= move_cost: move = game_map.naive_navigate(ship, destination) new_pos = curr_pos+Position(move[0], move[1]) game_map[curr_pos].ship = None game_map[new_pos].mark_unsafe(ship) return move return (0, 0) def navigate(game_map, ship, destination): destination = game_map.normalize(destination) logging.info("destination normalized") w = game_map.width h = game_map.height curr_pos = ship.position move_cost = game_map[curr_pos].halite_amount/constants.MOVE_COST_RATIO if ship.halite_amount < move_cost: # If the ship doesn't have enough halite on board to move # Then it MUST stay still. No other action is possible. logging.info("navigate: Ship {} decided there isn't enough halite to move.".format(ship.id)) return [(0, 0)] logging.info("navigate: Ship {} decided there is enough halite to move.".format(ship.id)) possible_moves = [] dy = destination.y - curr_pos.y if dy > w//2: dy -= w elif dy < -w//2: dy += w dx = destination.x - curr_pos.x if dx > w//2: dx -= w elif dx < -w//2: dx += w logging.info("navigate: Ship {} says dx={} and dy={}.".format(ship.id, dx, dy)) h_amount = {x: game_map[curr_pos+Position(*x)].halite_amount for x in Direction.get_all_cardinals()} logging.info("navigate: Ship {} got halite amount at adjacent positions.".format(ship.id)) # Possible moves sorted by preference only taking into account distance if abs(dy) > abs(dx): logging.info("navigate: Ship {} wants vertical move.".format(ship.id)) y_sign = dy//abs(dy) possible_moves.append((0, y_sign)) # dy>0 if dx == 0: logging.info("test1") possible_moves.append((0, 0)) if h_amount[(1, 0)] <= h_amount[(-1, 0)]: logging.info("test2") possible_moves.append((1, 0)) possible_moves.append((-1, 0)) else: logging.info("test3") possible_moves.append((-1, 0)) possible_moves.append((1, 0)) possible_moves.append((0, -1*y_sign)) else: logging.info("test4") x_sign = dx//abs(dx) possible_moves.append((x_sign, 0)) possible_moves.append((0, 0)) possible_moves.append((-1*x_sign, 0)) possible_moves.append((0, -1*y_sign)) # Take halite amount into consideration for preference # (weather or not to flip the first two and same but independent of the last two) # currently ignored elif abs(dy) < abs(dx) or (abs(dy) == abs(dx) and dy != 0): logging.info("navigate: Ship {} wants horizontal move.".format(ship.id)) x_sign = dx//abs(dx) possible_moves.append((x_sign, 0)) # dx>0 if dy == 0: logging.info("test1") possible_moves.append((0, 0)) if h_amount[(0, 1)] <= h_amount[(0, -1)]: logging.info("test2") possible_moves.append((0, 1)) possible_moves.append((0, -1)) else: logging.info("test3") possible_moves.append((0, -1)) possible_moves.append((0, 1)) possible_moves.append((-1*x_sign, 0)) else: logging.info("test4") y_sign = dy//abs(dy) possible_moves.append((0, y_sign)) possible_moves.append((0, 0)) possible_moves.append((0, -1*y_sign)) possible_moves.append((-1*x_sign, 0)) # Take halite amount into consideration for preference # (weather or not to flip the first two and same but independent of the last two) # currently ignored else: # This ship doesn't want to move logging.info("navigate: Ship {} doesn't want to move.".format(ship.id)) a = [(-1, 0), (1, 0), (0, -1), (0, 1)] random.shuffle(a) possible_moves = [(0, 0)] + a logging.info("navigate: Ship {} got possible_moves.".format(ship.id)) return possible_moves def group_navigate(game, ship_status, ship_destination, crash=False): me = game.me game_map = game.game_map # Can't navigate with no ships. if len(me.get_ships()) == 0: return {} logging.info("group_navigate: There is more than zero ships.") # List all moves for each ship move_list = {ship.id: navigate(game_map, ship, ship_destination[ship.id]) for ship in me.get_ships()} logging.info("group_navigate: Got moves.") priority_list = {} # Ship priorities will follow distances from current destination. # Ships making a dropoff have highest priority. sorted_ship_list = [] dist_list = [] for ship in me.get_ships(): sorted_ship_list.append(ship) if ship.id in ship_destination and ship_status[ship.id] != "returning": dist_list.append(game_map.calculate_distance(ship.position, ship_destination[ship.id])) elif ship_status[ship.id] == "dropoff": dist_list.append(-1) else: dist_list.append(0) z = zip(dist_list, sorted_ship_list) sz = sorted(z, key=lambda x: x[0]) dist_list, sorted_ship_list = list(zip(*sz)) for i in range(len(sorted_ship_list)): priority_list[sorted_ship_list[i].id] = i logging.info("group_navigate: Made priority_list.") solution = group_navigate_main(me.get_ships(), game, priority_list, move_list, crash) if solution is None: logging.info("group_navigate: No solution") return solution def group_navigate_main(ship_list, game, priority_list, move_list, crash): me = game.me game_map = game.game_map logging.info("group_navigate_main: "+str(move_list)) conflicting_positions = set() move_test = {x: move_list[x][0] for x in move_list.keys()} position_test = {} for ship in ship_list: s = str(game_map.normalize(ship.position + Position(*move_test[ship.id]))) if s in position_test: conflicting_positions.add(s) position_test[s].append(ship.id) else: position_test[s] = [ship.id] if crash: drop_s = str(me.shipyard.position) if drop_s in conflicting_positions: conflicting_positions.remove(drop_s) for drop in me.get_dropoffs(): drop_s = str(drop.position) if drop_s in conflicting_positions: conflicting_positions.remove(drop_s) # Solution is acceptable if len(conflicting_positions) == 0: return move_test # Conflict resolution # Attempt resolution to one conflict at a time when all are solved a # solution will be returned. logging.info("group_navigate_main: "+str(conflicting_positions)) for s in conflicting_positions: logging.info("group_navigate_main: "+s) crashing_ships = position_test[s] logging.info("group_navigate_main: "+str(crashing_ships)) priorities = [priority_list[x] for x in crashing_ships] logging.info("group_navigate_main: "+str(priorities)) # Allow one ship to move to this position but no more. # If there are any that don't have the ability to move at all # (not enough halite) then they must be the one to remain in # this position and all other ships that want to move here will # have to go somewhere else. If there is more than one that can't # move then there is no solution. only_one_move = [i for i, x in enumerate(crashing_ships) if len(move_list[x]) == 1] logging.info("group_navigate_main: "+str(only_one_move)) if len(only_one_move) == 1: sorted_inds = [only_one_move[0]] elif len(only_one_move) > 1: return None # There are no solutions else: _, sorted_inds = list(zip(*sorted(zip(priorities, range(len(priorities)))))) logging.info("group_navigate_main: "+str(sorted_inds)) for ind in sorted_inds: new_move_list = {x: [y for y in move_list[x]] for x in move_list} # Keep the other crashing ships from moving here. # Keep ship at ind the same. for i in range(len(crashing_ships)): if i != ind: shipid = crashing_ships[i] new_move_list[shipid] = new_move_list[shipid][1:] solution = group_navigate_main(ship_list, game, priority_list, new_move_list, crash) if solution is not None: return solution return None # failed to find any solutions def random_move(ship, game_map, params): curr_pos = ship.position # Don't move if there is enough halite here if game_map[curr_pos].halite_amount < params.minimum_useful_halite: move_cost = game_map[curr_pos].halite_amount/constants.MOVE_COST_RATIO # Don't move if I can't pay for it if ship.halite_amount >= move_cost: spaces = curr_pos.get_surrounding_cardinals() # Don't move if nowhere else is safe if len(spaces) > 0: new_pos = random.choice(spaces) return new_pos return curr_pos def returning_move(ship, me, game_map): closest, dist = helpers.closest_drop(ship.position, me, game_map) curr_pos = ship.position move_cost = game_map[curr_pos].halite_amount/constants.MOVE_COST_RATIO if ship.halite_amount >= move_cost: return closest return curr_pos def smart_explore(ship, game_map, params): curr_pos = ship.position # Don't move if there is enough halite here if game_map[curr_pos].halite_amount < params.minimum_useful_halite: logging.info("Ship {} decided there isn't enough halite here.".format(ship.id)) move_cost = game_map[curr_pos].halite_amount/constants.MOVE_COST_RATIO # Don't move if I can't pay for it if ship.halite_amount >= move_cost: logging.info("Ship {} is able to pay for movement.".format(ship.id)) spaces = helpers.get_spaces_in_region(ship, search_region=params.search_region) # spaces = curr_pos.get_surrounding_cardinals() # Don't set destination to be on top of another ship # unless it is necessary. new_spaces = [] for p in spaces: if not game_map[p].is_occupied: new_spaces.append(p) if len(new_spaces) > 0: spaces = new_spaces # Don't move if nowhere else is safe if len(spaces) > 0: h_amount = [game_map[x].halite_amount for x in spaces] # If none of the spaces have enough halite then move to a # better area if max(h_amount) < params.minimum_useful_halite: logging.info("Moving to better area") pos, dist = helpers.closest_dense_spot(ship, game_map, params) if dist == 0: logging.info("Moving to same location :/") if pos is None: # default to other method if none found over threshold # pos, dist = helpers.closest_most_dense_spot(ship, game_map, params, n=params.number_of_dense_spots_to_check) pos = vacuum_explore(ship, game_map, params) return pos h_amount, spaces = list(zip(*sorted(zip(h_amount, spaces), key=lambda x: x[0], reverse=True))) destination = spaces[0] return destination else: logging.info("Ship {} is NOT able to pay for movement.".format(ship.id)) else: logging.info("Ship {} decided there is plenty of halite here.".format(ship.id)) return curr_pos def vacuum_explore(ship, game_map, params): curr_pos = ship.position minimum_useful_halite = constants.EXTRACT_RATIO*2 explore_density = minimum_useful_halite*params.density_kernal_side_length**2 # Don't move if there is enough halite here if game_map[curr_pos].halite_amount < minimum_useful_halite: logging.info("Ship {} decided there isn't enough halite here.".format(ship.id)) # Movement cost should always be zero. logging.info("Ship {} is able to pay for movement.".format(ship.id)) spaces = helpers.get_spaces_in_region(ship, search_region=params.search_region) # spaces = curr_pos.get_surrounding_cardinals() # Don't set destination to be on top of another ship # unless it is necessary. new_spaces = [] for p in spaces: if not game_map[p].is_occupied: new_spaces.append(p) if len(new_spaces) > 0: spaces = new_spaces # Don't move if nowhere else is safe if len(spaces) > 0: h_amount = [game_map[x].halite_amount for x in spaces] # If none of the spaces have enough halite then move to a # better area if max(h_amount) < minimum_useful_halite: logging.info("Moving to better area") pos, dist = helpers.closest_dense_spot(ship, game_map, params, density_req=explore_density) if dist == 0: logging.info("Moving to same location :/") if pos is None: # default to other method if none found over threshold pos, dist = helpers.closest_most_dense_spot(ship, game_map, params, n=params.number_of_dense_spots_to_check) return pos h_amount, spaces = list(zip(*sorted(zip(h_amount, spaces), key=lambda x: x[0], reverse=True))) destination = spaces[0] return destination else: logging.info("Ship {} decided there is plenty of halite here.".format(ship.id)) return curr_pos
[ "random.choice", "helpers.closest_most_dense_spot", "random.shuffle", "hlt.positionals.Direction.get_all_cardinals", "hlt.positionals.Position", "helpers.closest_drop", "helpers.closest_dense_spot", "helpers.get_spaces_in_region", "logging.info" ]
[((666, 704), 'logging.info', 'logging.info', (['"""destination normalized"""'], {}), "('destination normalized')\n", (678, 704), False, 'import logging\n'), ((4722, 4784), 'logging.info', 'logging.info', (['"""group_navigate: There is more than zero ships."""'], {}), "('group_navigate: There is more than zero ships.')\n", (4734, 4784), False, 'import logging\n'), ((4932, 4974), 'logging.info', 'logging.info', (['"""group_navigate: Got moves."""'], {}), "('group_navigate: Got moves.')\n", (4944, 4974), False, 'import logging\n'), ((5772, 5823), 'logging.info', 'logging.info', (['"""group_navigate: Made priority_list."""'], {}), "('group_navigate: Made priority_list.')\n", (5784, 5823), False, 'import logging\n'), ((9714, 9763), 'helpers.closest_drop', 'helpers.closest_drop', (['ship.position', 'me', 'game_map'], {}), '(ship.position, me, game_map)\n', (9734, 9763), False, 'import helpers\n'), ((5948, 5991), 'logging.info', 'logging.info', (['"""group_navigate: No solution"""'], {}), "('group_navigate: No solution')\n", (5960, 5991), False, 'import logging\n'), ((7270, 7311), 'logging.info', 'logging.info', (["('group_navigate_main: ' + s)"], {}), "('group_navigate_main: ' + s)\n", (7282, 7311), False, 'import logging\n'), ((12817, 12887), 'helpers.get_spaces_in_region', 'helpers.get_spaces_in_region', (['ship'], {'search_region': 'params.search_region'}), '(ship, search_region=params.search_region)\n', (12845, 12887), False, 'import helpers\n'), ((417, 443), 'hlt.positionals.Position', 'Position', (['move[0]', 'move[1]'], {}), '(move[0], move[1])\n', (425, 443), False, 'from hlt.positionals import Position, Direction\n'), ((1662, 1691), 'hlt.positionals.Direction.get_all_cardinals', 'Direction.get_all_cardinals', ([], {}), '()\n', (1689, 1691), False, 'from hlt.positionals import Position, Direction\n'), ((2084, 2105), 'logging.info', 'logging.info', (['"""test1"""'], {}), "('test1')\n", (2096, 2105), False, 'import logging\n'), ((2558, 2579), 'logging.info', 'logging.info', (['"""test4"""'], {}), "('test4')\n", (2570, 2579), False, 'import logging\n'), ((4354, 4371), 'random.shuffle', 'random.shuffle', (['a'], {}), '(a)\n', (4368, 4371), False, 'import random\n'), ((10510, 10580), 'helpers.get_spaces_in_region', 'helpers.get_spaces_in_region', (['ship'], {'search_region': 'params.search_region'}), '(ship, search_region=params.search_region)\n', (10538, 10580), False, 'import helpers\n'), ((2218, 2239), 'logging.info', 'logging.info', (['"""test2"""'], {}), "('test2')\n", (2230, 2239), False, 'import logging\n'), ((2367, 2388), 'logging.info', 'logging.info', (['"""test3"""'], {}), "('test3')\n", (2379, 2388), False, 'import logging\n'), ((3255, 3276), 'logging.info', 'logging.info', (['"""test1"""'], {}), "('test1')\n", (3267, 3276), False, 'import logging\n'), ((3729, 3750), 'logging.info', 'logging.info', (['"""test4"""'], {}), "('test4')\n", (3741, 3750), False, 'import logging\n'), ((9578, 9599), 'random.choice', 'random.choice', (['spaces'], {}), '(spaces)\n', (9591, 9599), False, 'import random\n'), ((13542, 13579), 'logging.info', 'logging.info', (['"""Moving to better area"""'], {}), "('Moving to better area')\n", (13554, 13579), False, 'import logging\n'), ((13608, 13687), 'helpers.closest_dense_spot', 'helpers.closest_dense_spot', (['ship', 'game_map', 'params'], {'density_req': 'explore_density'}), '(ship, game_map, params, density_req=explore_density)\n', (13634, 13687), False, 'import helpers\n'), ((1609, 1621), 'hlt.positionals.Position', 'Position', (['*x'], {}), '(*x)\n', (1617, 1621), False, 'from hlt.positionals import Position, Direction\n'), ((3389, 3410), 'logging.info', 'logging.info', (['"""test2"""'], {}), "('test2')\n", (3401, 3410), False, 'import logging\n'), ((3538, 3559), 'logging.info', 'logging.info', (['"""test3"""'], {}), "('test3')\n", (3550, 3559), False, 'import logging\n'), ((6392, 6421), 'hlt.positionals.Position', 'Position', (['*move_test[ship.id]'], {}), '(*move_test[ship.id])\n', (6400, 6421), False, 'from hlt.positionals import Position, Direction\n'), ((11306, 11343), 'logging.info', 'logging.info', (['"""Moving to better area"""'], {}), "('Moving to better area')\n", (11318, 11343), False, 'import logging\n'), ((11376, 11426), 'helpers.closest_dense_spot', 'helpers.closest_dense_spot', (['ship', 'game_map', 'params'], {}), '(ship, game_map, params)\n', (11402, 11426), False, 'import helpers\n'), ((13738, 13780), 'logging.info', 'logging.info', (['"""Moving to same location :/"""'], {}), "('Moving to same location :/')\n", (13750, 13780), False, 'import logging\n'), ((13902, 14003), 'helpers.closest_most_dense_spot', 'helpers.closest_most_dense_spot', (['ship', 'game_map', 'params'], {'n': 'params.number_of_dense_spots_to_check'}), '(ship, game_map, params, n=params.\n number_of_dense_spots_to_check)\n', (13933, 14003), False, 'import helpers\n'), ((11485, 11527), 'logging.info', 'logging.info', (['"""Moving to same location :/"""'], {}), "('Moving to same location :/')\n", (11497, 11527), False, 'import logging\n')]
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor from sklearn.svm import SVR from sklearn.metrics import mean_squared_error from sklearn.linear_model import HuberRegressor import numpy as np import pickle from dataloader import HeadlineDataset from csv import writer import os, subprocess import math from collections import Counter def get_weights(ys, countings): total = sum(countings.values()) weights = [] for y in ys: bin_num = int(y * 5) weights.append(total / countings[bin_num]) print(ys[:10]) print(weights[:10]) return weights def load_data(ds): with open(f'data/{ds}_features.pkl', 'rb') as f: train_features = pickle.load(f) with open(f'data/{ds}-lstm.csv') as f: lines = f.readlines()[1:] for i, line in enumerate(lines): lstm_prediction = float(line.split(',')[1]) train_features[i][0]['lstm-output'] = lstm_prediction Xs = [] Ys = [] for features, y in train_features: Ys.append(y) x = [] for k in ["orig_score", "edit_score", "bert_sim", "glove_sim", "score_diff", "lstm-output"]: x.append(features[k]) x = np.array(x) Xs.append(x) return Xs, Ys # grouping bins countings = Counter() for i in range(30): countings[i] += 1 dev_dataset = HeadlineDataset('dev') train_dataset = HeadlineDataset('training') for sample in dev_dataset: bin_num = int(sample['label'] * 5) countings[bin_num] += 1 for sample in train_dataset: bin_num = int(sample['label'] * 5) countings[bin_num] += 1 print('load data') Xs, Ys = load_data('train') train_weights = get_weights(Ys, countings) dev_Xs, dev_Ys = load_data('dev') dev_weights = get_weights(dev_Ys, countings) model = GradientBoostingRegressor( learning_rate=0.05, n_estimators=50, subsample=0.5, min_samples_split=2, max_depth=3 ) print('train') model.fit(Xs, Ys, train_weights) print('trained') print(model.feature_importances_) pred_Ys = model.predict(dev_Xs) dev_rmse = math.sqrt(mean_squared_error(dev_Ys, pred_Ys)) print(dev_rmse) test_Xs, _ = load_data('test') pred_Ys = model.predict(test_Xs) test_dataset = HeadlineDataset('test') with open('data/task-1-output.csv', 'w') as f: output_writer = writer(f) output_writer.writerow(('id', 'pred')) for row, pred in zip(test_dataset, pred_Ys): output_writer.writerow((row['id'], pred.item())) os.chdir('data') subprocess.run(['zip', 'task-1-output.zip', 'task-1-output.csv']) os.chdir('..')
[ "subprocess.run", "dataloader.HeadlineDataset", "csv.writer", "pickle.load", "sklearn.metrics.mean_squared_error", "collections.Counter", "os.chdir", "numpy.array", "sklearn.ensemble.GradientBoostingRegressor" ]
[((1300, 1309), 'collections.Counter', 'Counter', ([], {}), '()\n', (1307, 1309), False, 'from collections import Counter\n'), ((1366, 1388), 'dataloader.HeadlineDataset', 'HeadlineDataset', (['"""dev"""'], {}), "('dev')\n", (1381, 1388), False, 'from dataloader import HeadlineDataset\n'), ((1405, 1432), 'dataloader.HeadlineDataset', 'HeadlineDataset', (['"""training"""'], {}), "('training')\n", (1420, 1432), False, 'from dataloader import HeadlineDataset\n'), ((1804, 1920), 'sklearn.ensemble.GradientBoostingRegressor', 'GradientBoostingRegressor', ([], {'learning_rate': '(0.05)', 'n_estimators': '(50)', 'subsample': '(0.5)', 'min_samples_split': '(2)', 'max_depth': '(3)'}), '(learning_rate=0.05, n_estimators=50, subsample=\n 0.5, min_samples_split=2, max_depth=3)\n', (1829, 1920), False, 'from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\n'), ((2222, 2245), 'dataloader.HeadlineDataset', 'HeadlineDataset', (['"""test"""'], {}), "('test')\n", (2237, 2245), False, 'from dataloader import HeadlineDataset\n'), ((2472, 2488), 'os.chdir', 'os.chdir', (['"""data"""'], {}), "('data')\n", (2480, 2488), False, 'import os, subprocess\n'), ((2489, 2554), 'subprocess.run', 'subprocess.run', (["['zip', 'task-1-output.zip', 'task-1-output.csv']"], {}), "(['zip', 'task-1-output.zip', 'task-1-output.csv'])\n", (2503, 2554), False, 'import os, subprocess\n'), ((2555, 2569), 'os.chdir', 'os.chdir', (['""".."""'], {}), "('..')\n", (2563, 2569), False, 'import os, subprocess\n'), ((2089, 2124), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['dev_Ys', 'pred_Ys'], {}), '(dev_Ys, pred_Ys)\n', (2107, 2124), False, 'from sklearn.metrics import mean_squared_error\n'), ((2313, 2322), 'csv.writer', 'writer', (['f'], {}), '(f)\n', (2319, 2322), False, 'from csv import writer\n'), ((707, 721), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (718, 721), False, 'import pickle\n'), ((1218, 1229), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (1226, 1229), True, 'import numpy as np\n')]
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from dataclasses import dataclass from typing import Iterable from pants.backend.swift.target_types import SWIFT_FILE_EXTENSIONS, SwiftSourcesGeneratorTarget from pants.core.goals.tailor import ( AllOwnedSources, PutativeTarget, PutativeTargets, PutativeTargetsRequest, group_by_dir, ) from pants.engine.fs import PathGlobs, Paths from pants.engine.internals.selectors import Get from pants.engine.rules import Rule, collect_rules, rule from pants.engine.target import Target from pants.engine.unions import UnionRule from pants.util.logging import LogLevel @dataclass(frozen=True) class PutativeSwiftTargetsRequest(PutativeTargetsRequest): pass def classify_source_files(paths: Iterable[str]) -> dict[type[Target], set[str]]: """Returns a dict of target type -> files that belong to targets of that type.""" sources_files = set(paths) return {SwiftSourcesGeneratorTarget: sources_files} @rule(level=LogLevel.DEBUG, desc="Determine candidate Swift targets to create") async def find_putative_targets( req: PutativeSwiftTargetsRequest, all_owned_sources: AllOwnedSources, ) -> PutativeTargets: all_swift_files = await Get( Paths, PathGlobs, req.path_globs(*(f"*{ext}" for ext in SWIFT_FILE_EXTENSIONS)) ) unowned_swift_files = set(all_swift_files.files) - set(all_owned_sources) classified_unowned_swift_files = classify_source_files(unowned_swift_files) putative_targets = [] for tgt_type, paths in classified_unowned_swift_files.items(): for dirname, filenames in group_by_dir(paths).items(): putative_targets.append( PutativeTarget.for_target_type( tgt_type, path=dirname, name=None, triggering_sources=sorted(filenames) ) ) return PutativeTargets(putative_targets) def rules() -> Iterable[Rule | UnionRule]: return ( *collect_rules(), UnionRule(PutativeTargetsRequest, PutativeSwiftTargetsRequest), )
[ "dataclasses.dataclass", "pants.engine.unions.UnionRule", "pants.engine.rules.rule", "pants.engine.rules.collect_rules", "pants.core.goals.tailor.PutativeTargets", "pants.core.goals.tailor.group_by_dir" ]
[((750, 772), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (759, 772), False, 'from dataclasses import dataclass\n'), ((1100, 1178), 'pants.engine.rules.rule', 'rule', ([], {'level': 'LogLevel.DEBUG', 'desc': '"""Determine candidate Swift targets to create"""'}), "(level=LogLevel.DEBUG, desc='Determine candidate Swift targets to create')\n", (1104, 1178), False, 'from pants.engine.rules import Rule, collect_rules, rule\n'), ((1975, 2008), 'pants.core.goals.tailor.PutativeTargets', 'PutativeTargets', (['putative_targets'], {}), '(putative_targets)\n', (1990, 2008), False, 'from pants.core.goals.tailor import AllOwnedSources, PutativeTarget, PutativeTargets, PutativeTargetsRequest, group_by_dir\n'), ((2101, 2163), 'pants.engine.unions.UnionRule', 'UnionRule', (['PutativeTargetsRequest', 'PutativeSwiftTargetsRequest'], {}), '(PutativeTargetsRequest, PutativeSwiftTargetsRequest)\n', (2110, 2163), False, 'from pants.engine.unions import UnionRule\n'), ((2076, 2091), 'pants.engine.rules.collect_rules', 'collect_rules', ([], {}), '()\n', (2089, 2091), False, 'from pants.engine.rules import Rule, collect_rules, rule\n'), ((1725, 1744), 'pants.core.goals.tailor.group_by_dir', 'group_by_dir', (['paths'], {}), '(paths)\n', (1737, 1744), False, 'from pants.core.goals.tailor import AllOwnedSources, PutativeTarget, PutativeTargets, PutativeTargetsRequest, group_by_dir\n')]
import json import requests import time from flask import Flask, render_template, request app = Flask(__name__) API_KEY='<insert_api_key_here>' @app.route('/') def index(): background, style, message = setParams() return render_template('index.html', background=background, style=style, message=message) #funstion to set parameters def setParams(): weather = getWeather() background, style = getBackground(weather) condition = weather['weather'][0]['description'] message = "Looks like it's " + condition + " outside" return background, style, message #get users city from IP address and return weather def getWeather(): try: ip_address = request.headers['x-appengine-user-ip'] url = f'http://ip-api.com/json/{ip_address}' location = requests.get(url, verify=False).json() city = location['city'] except Exception as e: print(e) city='london' url = f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}' weather = requests.get(url, verify=False).json() return weather #get current time in seconds def getCurrentTime(): now = round(time.time()) return now #return background image based on time of day def getBackground(weather): sunrise = weather['sys']['sunrise'] sunset = weather['sys']['sunset'] startSunset = sunset - 3600 endSunset = sunset + 3600 now = getCurrentTime() condition = weather['weather'][0]['main'] if (now < sunrise): background = 'https://storage.googleapis.com/apportunity.appspot.com/night_spain.jpeg' day = False elif (now > sunrise and now < startSunset): background = weatherPic(condition) day = True elif (now > startSunset and now < endSunset): background = sunsetPic(condition) day = True elif (now > endSunset): background = 'https://storage.googleapis.com/apportunity.appspot.com/night_spain.jpeg' day = False style = setStyle(day) return background, style #retrin sunset image based on weather def sunsetPic(condition): if (condition == 'Clear'): background = 'https://storage.googleapis.com/apportunity.appspot.com/sunset_burma.jpg' elif (condition == 'Clouds'): background = 'https://storage.googleapis.com/apportunity.appspot.com/sunset_england.jpg' else: background = 'https://storage.googleapis.com/apportunity.appspot.com/sunset_burma.jpg' return background #return daytime image based on weather def weatherPic(condition): if (condition == 'Clear'): background = 'https://storage.googleapis.com/apportunity.appspot.com/sun_spain.JPG' elif (condition == 'Clouds'): background = 'https://storage.googleapis.com/apportunity.appspot.com/clouds_london.jpg' elif (condition == 'Rain'): background = 'https://storage.googleapis.com/apportunity.appspot.com/sun_spain.JPG' elif (condition == 'Drizzle'): background = 'https://storage.googleapis.com/apportunity.appspot.com/sun_spain.JPG' elif (condition == 'Snow'): background = 'https://storage.googleapis.com/apportunity.appspot.com/sun_spain.JPG' elif (condition == 'Thunderstorm'): background = 'https://storage.googleapis.com/apportunity.appspot.com/sun_spain.JPG' else: background = 'https://storage.googleapis.com/apportunity.appspot.com/sun_spain.JPG' return background #fucntion to get style def setStyle(day): if (day == True): style = ['grey lighten-5','grey lighten-3'] else: style = ['grey darken-4','black'] return style if __name__ == '__main__': app.run(host='0.0.0.0', port=8080, debug=True)
[ "flask.render_template", "time.time", "requests.get", "flask.Flask" ]
[((97, 112), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (102, 112), False, 'from flask import Flask, render_template, request\n'), ((232, 319), 'flask.render_template', 'render_template', (['"""index.html"""'], {'background': 'background', 'style': 'style', 'message': 'message'}), "('index.html', background=background, style=style, message=\n message)\n", (247, 319), False, 'from flask import Flask, render_template, request\n'), ((1158, 1169), 'time.time', 'time.time', ([], {}), '()\n', (1167, 1169), False, 'import time\n'), ((1032, 1063), 'requests.get', 'requests.get', (['url'], {'verify': '(False)'}), '(url, verify=False)\n', (1044, 1063), False, 'import requests\n'), ((795, 826), 'requests.get', 'requests.get', (['url'], {'verify': '(False)'}), '(url, verify=False)\n', (807, 826), False, 'import requests\n')]
import torch def magic_box(x): """DiCE operation that saves computation graph inside tensor See ``Implementation of DiCE'' section in the DiCE Paper for details Args: x (tensor): Input tensor Returns: 1 (tensor): Tensor that has computation graph saved References: https://github.com/alshedivat/lola/blob/master/lola_dice/rpg.py https://github.com/alexis-jacq/LOLA_DiCE/blob/master/ipd_DiCE.py """ return torch.exp(x - x.detach()) def get_dice_loss(logprobs, reward, value, args, i_agent, is_train): """Compute DiCE loss In our code, we use DiCE in the inner loop to be able to keep the dependency in the adapted parameters. This is required in order to compute the opponent shaping term. Args: logprobs (list): Contains log probability of all agents reward (list): Contains rewards across trajectories for specific agent value (tensor): Contains value for advantage computed via linear baseline args (argparse): Python argparse that contains arguments i_agent (int): Agent to compute DiCE loss for is_train (bool): Flag to identify whether in meta-train or not Returns: dice loss (tensor): DiCE loss with baseline reduction References: https://github.com/alshedivat/lola/blob/master/lola_dice/rpg.py https://github.com/alexis-jacq/LOLA_DiCE/blob/master/ipd_DiCE.py """ # Get discounted_reward reward = torch.stack(reward, dim=1) cum_discount = torch.cumprod(args.discount * torch.ones(*reward.size()), dim=1) / args.discount discounted_reward = reward * cum_discount # Compute stochastic nodes involved in reward dependencies if args.opponent_shaping and is_train: logprob_sum, stochastic_nodes = 0., 0. for logprob in logprobs: logprob = torch.stack(logprob, dim=1) logprob_sum += logprob stochastic_nodes += logprob dependencies = torch.cumsum(logprob_sum, dim=1) else: logprob = torch.stack(logprobs[i_agent], dim=1) dependencies = torch.cumsum(logprob, dim=1) stochastic_nodes = logprob # Get DiCE loss dice_loss = torch.mean(torch.sum(magic_box(dependencies) * discounted_reward, dim=1)) # Apply variance_reduction if value is provided baseline_term = 0. if value is not None: discounted_value = value.detach() * cum_discount baseline_term = torch.mean(torch.sum((1 - magic_box(stochastic_nodes)) * discounted_value, dim=1)) return -(dice_loss + baseline_term)
[ "torch.stack", "torch.cumsum" ]
[((1475, 1501), 'torch.stack', 'torch.stack', (['reward'], {'dim': '(1)'}), '(reward, dim=1)\n', (1486, 1501), False, 'import torch\n'), ((1983, 2015), 'torch.cumsum', 'torch.cumsum', (['logprob_sum'], {'dim': '(1)'}), '(logprob_sum, dim=1)\n', (1995, 2015), False, 'import torch\n'), ((2044, 2081), 'torch.stack', 'torch.stack', (['logprobs[i_agent]'], {'dim': '(1)'}), '(logprobs[i_agent], dim=1)\n', (2055, 2081), False, 'import torch\n'), ((2105, 2133), 'torch.cumsum', 'torch.cumsum', (['logprob'], {'dim': '(1)'}), '(logprob, dim=1)\n', (2117, 2133), False, 'import torch\n'), ((1857, 1884), 'torch.stack', 'torch.stack', (['logprob'], {'dim': '(1)'}), '(logprob, dim=1)\n', (1868, 1884), False, 'import torch\n')]
import matplotlib.font_manager as fm import matplotlib.pyplot as plt import matplotlib.font_manager as fm import numpy as np freq = {} def read_file(filename='corpora.txt'): f = open(filename, "r", encoding="utf-8") for character in f.read(): if (character in freq): freq[character] += 1 else: freq[character] = 1 def main(): read_file() bangla_alphabets = 'অআ াই িঈ ীউ ুঊ ূঋ ৃএ েঐ ৈও োঔ ৌকখগঘঙচছজঝঞটঠডঢণতথদধনপফবভমযরলশষসহড়ঢ়য়ৎংঃ' bangla_alphabets = "".join(bangla_alphabets.split()) sorted_counts = [] for character in bangla_alphabets: if character in freq: sorted_counts.append(freq[character]) else: sorted_counts.append(0) total_count = 0 for value in sorted_counts: total_count += value sorted_counts = [100 * value / total_count for value in sorted_counts] fig, ax = plt.subplots(figsize=(40, 20)) prop = fm.FontProperties(fname='kalpurush.ttf') ax.legend(prop=prop) font_dirs = ['./', ] font_files = fm.findSystemFonts(fontpaths=font_dirs) font_list = fm.createFontList(font_files) fm.fontManager.ttflist.extend(font_list) plt.tick_params(labelsize=20) plt.bar(range(len(bangla_alphabets)), sorted_counts, align='center') plt.xticks(np.arange(len(bangla_alphabets)), list(bangla_alphabets), fontfamily='Kalpurush') plt.xlabel('বর্ণ-সমূহ', fontsize=24, fontfamily='Kalpurush') plt.ylabel('শতকরা-হার (%)', fontsize=24, fontfamily='Kalpurush') fig.suptitle( 'Relative Frequencies of letters in Bengali text\nCreated by <NAME>', fontsize=18) plt.show() if __name__ == "__main__": main()
[ "matplotlib.font_manager.createFontList", "matplotlib.pyplot.ylabel", "matplotlib.font_manager.FontProperties", "matplotlib.font_manager.findSystemFonts", "matplotlib.pyplot.tick_params", "matplotlib.pyplot.xlabel", "matplotlib.font_manager.fontManager.ttflist.extend", "matplotlib.pyplot.subplots", ...
[((915, 945), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(40, 20)'}), '(figsize=(40, 20))\n', (927, 945), True, 'import matplotlib.pyplot as plt\n'), ((957, 997), 'matplotlib.font_manager.FontProperties', 'fm.FontProperties', ([], {'fname': '"""kalpurush.ttf"""'}), "(fname='kalpurush.ttf')\n", (974, 997), True, 'import matplotlib.font_manager as fm\n'), ((1066, 1105), 'matplotlib.font_manager.findSystemFonts', 'fm.findSystemFonts', ([], {'fontpaths': 'font_dirs'}), '(fontpaths=font_dirs)\n', (1084, 1105), True, 'import matplotlib.font_manager as fm\n'), ((1122, 1151), 'matplotlib.font_manager.createFontList', 'fm.createFontList', (['font_files'], {}), '(font_files)\n', (1139, 1151), True, 'import matplotlib.font_manager as fm\n'), ((1156, 1196), 'matplotlib.font_manager.fontManager.ttflist.extend', 'fm.fontManager.ttflist.extend', (['font_list'], {}), '(font_list)\n', (1185, 1196), True, 'import matplotlib.font_manager as fm\n'), ((1201, 1230), 'matplotlib.pyplot.tick_params', 'plt.tick_params', ([], {'labelsize': '(20)'}), '(labelsize=20)\n', (1216, 1230), True, 'import matplotlib.pyplot as plt\n'), ((1422, 1482), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""বর্ণ-সমূহ"""'], {'fontsize': '(24)', 'fontfamily': '"""Kalpurush"""'}), "('বর্ণ-সমূহ', fontsize=24, fontfamily='Kalpurush')\n", (1432, 1482), True, 'import matplotlib.pyplot as plt\n'), ((1487, 1551), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""শতকরা-হার (%)"""'], {'fontsize': '(24)', 'fontfamily': '"""Kalpurush"""'}), "('শতকরা-হার (%)', fontsize=24, fontfamily='Kalpurush')\n", (1497, 1551), True, 'import matplotlib.pyplot as plt\n'), ((1667, 1677), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1675, 1677), True, 'import matplotlib.pyplot as plt\n')]
from caffe2.proto import caffe2_pb2 from caffe2.python import core, workspace import os import tempfile from zipfile import ZipFile ''' Generates a document in markdown format summrizing the coverage of serialized testing. The document lives in `caffe2/python/serialized_test/SerializedTestCoverage.md` ''' OpSchema = workspace.C.OpSchema def gen_serialized_test_coverage(source_dir, output_dir): (covered, not_covered, schemaless) = gen_coverage_sets(source_dir) num_covered = len(covered) num_not_covered = len(not_covered) num_schemaless = len(schemaless) total_ops = num_covered + num_not_covered with open(os.path.join(output_dir, 'SerializedTestCoverage.md'), 'w+') as f: f.write('# Serialized Test Coverage Report\n') f.write("This is an automatically generated file. Please see " "`caffe2/python/serialized_test/README.md` for details. " "In the case of merge conflicts, please rebase and regenerate.\n") f.write('## Summary\n') f.write( 'Serialized tests have covered {}/{} ({}%) operators\n\n'.format( num_covered, total_ops, (int)(num_covered / total_ops * 1000) / 10)) f.write('## Not covered operators\n') f.write('<details>\n') f.write( '<summary>There are {} not covered operators</summary>\n\n'.format( num_not_covered)) for n in sorted(not_covered): f.write('* ' + n + '\n') f.write('</details>\n\n') f.write('## Covered operators\n') f.write('<details>\n') f.write( '<summary>There are {} covered operators</summary>\n\n'.format( num_covered)) for n in sorted(covered): f.write('* ' + n + '\n') f.write('</details>\n\n') f.write('## Excluded from coverage statistics\n') f.write('### Schemaless operators\n') f.write('<details>\n') f.write( '<summary>There are {} schemaless operators</summary>\n\n'.format( num_schemaless)) for n in sorted(schemaless): f.write('* ' + n + '\n') f.write('</details>\n\n') def gen_coverage_sets(source_dir): covered_ops = gen_covered_ops(source_dir) not_covered_ops = set() schemaless_ops = [] for op_name in core._GetRegisteredOperators(): s = OpSchema.get(op_name) if s is not None and s.private: continue if s: if op_name not in covered_ops: not_covered_ops.add(op_name) else: if op_name.find("_ENGINE_") == -1: schemaless_ops.append(op_name) return (covered_ops, not_covered_ops, schemaless_ops) def gen_covered_ops(source_dir): def parse_proto(x): proto = caffe2_pb2.OperatorDef() proto.ParseFromString(x) return proto covered = set() for f in os.listdir(source_dir): zipfile = os.path.join(source_dir, f) if not os.path.isfile(zipfile): continue temp_dir = tempfile.mkdtemp() with ZipFile(zipfile) as z: z.extractall(temp_dir) op_path = os.path.join(temp_dir, 'op.pb') with open(op_path, 'rb') as f: loaded_op = f.read() op_proto = parse_proto(loaded_op) covered.add(op_proto.type) index = 0 grad_path = os.path.join(temp_dir, 'grad_{}.pb'.format(index)) while os.path.isfile(grad_path): with open(grad_path, 'rb') as f: loaded_grad = f.read() grad_proto = parse_proto(loaded_grad) covered.add(grad_proto.type) index += 1 grad_path = os.path.join(temp_dir, 'grad_{}.pb'.format(index)) return covered
[ "os.listdir", "zipfile.ZipFile", "os.path.join", "os.path.isfile", "tempfile.mkdtemp", "caffe2.python.core._GetRegisteredOperators", "caffe2.proto.caffe2_pb2.OperatorDef" ]
[((2435, 2465), 'caffe2.python.core._GetRegisteredOperators', 'core._GetRegisteredOperators', ([], {}), '()\n', (2463, 2465), False, 'from caffe2.python import core, workspace\n'), ((3040, 3062), 'os.listdir', 'os.listdir', (['source_dir'], {}), '(source_dir)\n', (3050, 3062), False, 'import os\n'), ((2922, 2946), 'caffe2.proto.caffe2_pb2.OperatorDef', 'caffe2_pb2.OperatorDef', ([], {}), '()\n', (2944, 2946), False, 'from caffe2.proto import caffe2_pb2\n'), ((3083, 3110), 'os.path.join', 'os.path.join', (['source_dir', 'f'], {}), '(source_dir, f)\n', (3095, 3110), False, 'import os\n'), ((3194, 3212), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (3210, 3212), False, 'import tempfile\n'), ((3305, 3336), 'os.path.join', 'os.path.join', (['temp_dir', '"""op.pb"""'], {}), "(temp_dir, 'op.pb')\n", (3317, 3336), False, 'import os\n'), ((3598, 3623), 'os.path.isfile', 'os.path.isfile', (['grad_path'], {}), '(grad_path)\n', (3612, 3623), False, 'import os\n'), ((672, 725), 'os.path.join', 'os.path.join', (['output_dir', '"""SerializedTestCoverage.md"""'], {}), "(output_dir, 'SerializedTestCoverage.md')\n", (684, 725), False, 'import os\n'), ((3127, 3150), 'os.path.isfile', 'os.path.isfile', (['zipfile'], {}), '(zipfile)\n', (3141, 3150), False, 'import os\n'), ((3227, 3243), 'zipfile.ZipFile', 'ZipFile', (['zipfile'], {}), '(zipfile)\n', (3234, 3243), False, 'from zipfile import ZipFile\n')]
# <<BEGIN-copyright>> # Copyright 2021, Lawrence Livermore National Security, LLC. # See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: BSD-3-Clause # <<END-copyright>> """ This module contains useful fudge math routines that do not fit into any other module. """ from pqu import PQU from fudge.core.utilities import brb try : import numpy numpyFloat64 = numpy.float64( 1. ) except : numpyFloat64 = 1. __metaclass__ = type def runningZSum( data, xLabel = None, yLabel = None, zLabel = None, normalize = False ) : """Returns the running sum of dy * z (normalized to 1 of normalize is True) for each x as an endl3dmath object. Data must be list of ( x, list of ( y, z ) ).""" d3 = [] for x_yz in data : d3.append( [ x_yz[0], runningYSum( x_yz[1], normalize = normalize ).data ] ) from brownies.legacy.endl import endl3dmathClasses return endl3dmathClasses.endl3dmath(d3, xLabel = xLabel, yLabel = yLabel, zLabel = zLabel, checkDataType = 0) def runningYSum( data, normalize = False ) : """Returns the running sum of dx * y (normalized to 1 of normalize is True) as an endl2dmath object. Data must be list of ( x, y ).""" x1 = None runningSum = [] for xy in data : x2 = xy[0] y2 = xy[1] if ( x1 is None ) : Sum = 0. else : Sum += 0.5 * ( y2 + y1 ) * ( x2 - x1 ) runningSum.append( [ x2, Sum ] ) x1 = x2 y1 = y2 if( normalize and ( Sum != 0. ) ) : for xy in runningSum : xy[1] /= Sum from brownies.legacy.endl import endl2dmathClasses return endl2dmathClasses.endl2dmath(runningSum, checkDataType = 0) def ZSum( data ) : """Returns the area under the curve z(y) for each x as an endl2dmath object. Data must be list of ( x, list of ( y, z ) ).""" d2 = [] for x_yz in data : d2.append( [ x_yz[0], YSum( x_yz[1] ) ] ) from brownies.legacy.endl import endl2dmathClasses return endl2dmathClasses.endl2dmath(d2, checkDataType = 0) def YSum( data ) : """Returns the area under the curve y(x). Data must be list of list( x, y ).""" x1 = None for x2, y2 in data : if ( x1 is None ) : Sum = 0. else : Sum += ( y2 + y1 ) * ( x2 - x1 ) x1 = x2 y1 = y2 return 0.5 * Sum class fastSumOfManyAddends : """This class in designed to sum a lot of endl2dmath or fudge2dmath object together efficiently. For example, consider the list f2d of 100,000 fudge2dmath objects that are to be summed. One way to do this is as s = fudge2dmath( ) for f in f2d : s = s + f In general, this is very inefficient and will take a long time. Using, this class as fs = fastSumOfManyAddends( ) for f in f2d : fs.appendAddend( f ) s = fs.returnSum( ) is, in general, much more efficient (i.e., runs a lot faster) and it should never be less efficient. While this class was designed for endl2dmath and fudge2dmath objects, it should work for any object for which the '+' operation is defined.""" def __init__( self ) : """Constructor for fastSumOfManyAddends.""" self.clear( ) def appendAddend( self, addend ) : """Adds addend to current sum efficiently.""" n = len( self.list ) for i in range( n ) : if( self.list[i] is None ) : self.list[i] = addend addend = None break else : addend = addend + self.list[i] self.list[i] = None if( addend is not None ) : self.list.append( addend ) def clear( self ) : """Clears currently summed data.""" self.list = [] def returnSum( self ) : """Returns the current sum of all addends appended.""" s = None for l in self.list : if( l is not None ) : if( s is None ) : s = l else : s = s + l return( s ) def getValue( n ) : if( isNumber( n ) ) : return( n ) if( isinstance( n, PQU.PQU ) ) : return( n.getValue( ) ) raise Exception( 'Invalue number object = %s' % brb.getType( n ) )
[ "brownies.legacy.endl.endl2dmathClasses.endl2dmath", "numpy.float64", "fudge.core.utilities.brb.getType", "brownies.legacy.endl.endl3dmathClasses.endl3dmath" ]
[((390, 408), 'numpy.float64', 'numpy.float64', (['(1.0)'], {}), '(1.0)\n', (403, 408), False, 'import numpy\n'), ((902, 1001), 'brownies.legacy.endl.endl3dmathClasses.endl3dmath', 'endl3dmathClasses.endl3dmath', (['d3'], {'xLabel': 'xLabel', 'yLabel': 'yLabel', 'zLabel': 'zLabel', 'checkDataType': '(0)'}), '(d3, xLabel=xLabel, yLabel=yLabel, zLabel=\n zLabel, checkDataType=0)\n', (930, 1001), False, 'from brownies.legacy.endl import endl3dmathClasses\n'), ((1627, 1684), 'brownies.legacy.endl.endl2dmathClasses.endl2dmath', 'endl2dmathClasses.endl2dmath', (['runningSum'], {'checkDataType': '(0)'}), '(runningSum, checkDataType=0)\n', (1655, 1684), False, 'from brownies.legacy.endl import endl2dmathClasses\n'), ((1985, 2034), 'brownies.legacy.endl.endl2dmathClasses.endl2dmath', 'endl2dmathClasses.endl2dmath', (['d2'], {'checkDataType': '(0)'}), '(d2, checkDataType=0)\n', (2013, 2034), False, 'from brownies.legacy.endl import endl2dmathClasses\n'), ((4214, 4228), 'fudge.core.utilities.brb.getType', 'brb.getType', (['n'], {}), '(n)\n', (4225, 4228), False, 'from fudge.core.utilities import brb\n')]
#!/usr/bin/env python3 import os import time import shutil import signal import yaml import sass import pyinotify from colorama import init, Fore, Style from jsmin import jsmin from csscompressor import compress VERSION = '1.4.7' class Kyk(object): """Kyk Build JS - if min: minify in place, append _minifed - concat to destfile Build SASS: - compile SASS file - concat to destfile Build partial js not yet implemented completely """ def __init__(self, folder, debug): self._folder = folder self._debug = debug init() self._load_config() signal.signal(signal.SIGINT, self.teardown) def teardown(self, signal, frame): if type(self.notifier) == pyinotify.ThreadedNotifier: print('stopping watching') self.notifier.stop() def _load_config(self, reloading=False): cfgfile = os.path.normpath(os.path.join(self._folder, 'kyk.yaml')) if not os.path.isfile(cfgfile) and reloading: time.sleep(1) # wait for it to appear (ftp program maybe?) if not os.path.isfile(cfgfile): raise Exception('no config file "{}" found!'.format(cfgfile)) with open(cfgfile, 'r', encoding='utf-8') as f: dat = f.read() self._cfg = yaml.load(dat) self._js = {} self._css = {} self._jswatchlist = [] self._listen_events = [] self._timestamp_file = None if 'watch_path' in self._cfg.keys(): self._folder = self._cfg['watch_path'] # no overwriting of command line debug, if config file does not hold debug: True we do not want to disable --debug if not self._debug: self._debug = 'debug' in self._cfg.keys() and self._cfg['debug'] self._version = self._cfg['version'] self._listen_events = self._cfg['events'] if 'timestamp_file' in self._cfg.keys(): self._timestamp_file = self._cfg['timestamp_file'] for minfile in self._cfg.keys(): if minfile.endswith('.js'): jsfile = self._cfg[minfile] minify = False for jsfile in self._cfg[minfile]: if jsfile.startswith('min:'): minify = True jsfile = jsfile.split('min:')[1].strip() if minfile not in self._js.keys(): self._js[minfile] = [] self._js[minfile].append({'file': os.path.abspath(jsfile), 'minify': minify}) self._jswatchlist.append(os.path.abspath(jsfile)) elif minfile.endswith('.css'): self._css[minfile] = self._cfg[minfile] print('Kyk version: {}'.format(VERSION)) print('config version: {}'.format(self._version)) def oneshot(self): print('oneshot') self.build_js() self.build_sass() def watch_forever(self): print('listening on:') print(self._listen_events) # first run, build everything self.build_js() self.build_sass() # now only changed files self.wm = pyinotify.WatchManager() self.notifier = pyinotify.ThreadedNotifier(self.wm, default_proc_fun=self.handler) self.wm.add_watch(self._folder, pyinotify.ALL_EVENTS, rec=True, auto_add=True) # self.notifier.loop() self.notifier.start() signal.pause() def reload(self): self.notifier.stop() self._load_config(True) self.watch_forever() def handler(self, event): # catch every scss file change, we can do this here because we are limited by the watchpath if getattr(event, 'pathname'): if event.pathname.endswith('.scss'): if event.maskname in self._listen_events: print('{} changed!'.format(event.pathname)) self.build_sass() # catch only changes to our configured jsfiles elif event.pathname in self._jswatchlist: if event.maskname in self._listen_events: print('{} changed!'.format(event.pathname)) self.build_js() elif event.pathname.endswith('kyk.yaml'): print('kyk config changed, reloading') self.reload() def build_js(self): """minify everything, then concat everything """ print('building js...') for minfile in self._js.keys(): with open(minfile, 'w', encoding='utf-8') as f: for jsfile in self._js[minfile]: if jsfile['minify'] and not self._debug: self.minify_js(jsfile['file']) out = self._load_js(jsfile['file'], load_minified=jsfile['minify']) f.write(out + "\n") print('finished') self._update_timestamp() def concat_js(self, destfile): print('building {}...'.format(destfile)) with open(destfile, 'w', encoding='utf-8') as f: for jsfile in self._js[destfile]: if self._debug: f.write('{}\n'.format(self._load_js(jsfile['file']))) f.write(self._load_js(jsfile['file']) + ';') print('finished') def minify_js(self, jsfile=None): """Minify JS in place, append _minified """ out = jsmin(self._load_js(jsfile, load_minified=False)) with open('{}_minified'.format(jsfile), 'w', encoding='utf-8') as f: f.write(out) def build_partial_js(self, changed): print('building partial js...') for minfile in self._js: for jsfile in self._js[minfile]: if changed == jsfile['file']: if jsfile['minify'] and not self._debug: self.minify_js(jsfile['file']) self.concat_js(minfile) print('finished') def _load_js(self, jsfile, load_minified=True): """Load js from file, load _minifed if exists and we want to have it (we do not want it if we minify anew) """ if load_minified and os.path.isfile('{}_minified'.format(jsfile)): jsfile = '{}_minified'.format(jsfile) if not os.path.isfile(jsfile): print(Fore.RED + 'File {} not found!'.format(jsfile)) print(Style.RESET_ALL) return '' else: with open(jsfile, 'r', encoding='utf-8') as f: out = f.read() return out def _update_timestamp(self): try: if self._timestamp_file: with open(self._timestamp_file, 'w') as f: f.write('{}'.format(int(time.time()))) print('timestamp file updated') except Exception as e: print(Fore.RED + 'Error updating timestamp file: {}'.format(e)) print(Style.RESET_ALL) def build_sass(self): print('building sass...') for minfile in self._css.keys(): try: # tmp minfile name for writing minfile_name = os.path.basename(minfile) tmp_minfile_name = 'kyk_{}'.format(minfile_name) tmp_minfile = minfile.replace(minfile_name, tmp_minfile_name) # only scss source map file mapfile = tmp_minfile.replace('.css', '.css.map') smapfile = tmp_minfile.replace('.css', '.smap.css') # this holds the css and the source comments with open(tmp_minfile, 'w', encoding='utf-8') as f, open(mapfile, 'w', encoding='utf-8') as smf, open(smapfile, 'w', encoding='utf-8') as sma: for sassfile in self._css[minfile]: if sassfile.endswith('.scss'): ost = 'compressed' if self._debug: ost = 'expanded' sc, sm = sass.compile(filename=sassfile, source_comments=True, source_map_filename=mapfile, output_style=ost) sc_clean = sass.compile(filename=sassfile, source_comments=False, output_style=ost) # without source comments f.write(sc_clean) smf.write(sm) sma.write(sc) else: sc = open(sassfile, 'r', encoding='utf-8').read() if not self._debug: sc = compress(sc) f.write(sc) shutil.copy(tmp_minfile, minfile) shutil.copy(mapfile, minfile.replace('.css', '.css.map')) shutil.copy(smapfile, minfile.replace('.css', '.smap.css')) except sass.CompileError as e: print(Fore.RED + 'SASS Error: {}'.format(e)) print(Style.RESET_ALL) # in debug mode we break things on purpose here if self._debug: shutil.copy(tmp_minfile, minfile) shutil.copy(mapfile, minfile.replace('.css', '.css.map')) shutil.copy(smapfile, minfile.replace('.css', '.smap.css')) print('finished') self._update_timestamp()
[ "signal.signal", "csscompressor.compress", "os.path.join", "yaml.load", "signal.pause", "time.sleep", "os.path.isfile", "os.path.basename", "shutil.copy", "sass.compile", "os.path.abspath", "pyinotify.ThreadedNotifier", "pyinotify.WatchManager", "time.time", "colorama.init" ]
[((585, 591), 'colorama.init', 'init', ([], {}), '()\n', (589, 591), False, 'from colorama import init, Fore, Style\n'), ((628, 671), 'signal.signal', 'signal.signal', (['signal.SIGINT', 'self.teardown'], {}), '(signal.SIGINT, self.teardown)\n', (641, 671), False, 'import signal\n'), ((1312, 1326), 'yaml.load', 'yaml.load', (['dat'], {}), '(dat)\n', (1321, 1326), False, 'import yaml\n'), ((3182, 3206), 'pyinotify.WatchManager', 'pyinotify.WatchManager', ([], {}), '()\n', (3204, 3206), False, 'import pyinotify\n'), ((3231, 3297), 'pyinotify.ThreadedNotifier', 'pyinotify.ThreadedNotifier', (['self.wm'], {'default_proc_fun': 'self.handler'}), '(self.wm, default_proc_fun=self.handler)\n', (3257, 3297), False, 'import pyinotify\n'), ((3454, 3468), 'signal.pause', 'signal.pause', ([], {}), '()\n', (3466, 3468), False, 'import signal\n'), ((927, 965), 'os.path.join', 'os.path.join', (['self._folder', '"""kyk.yaml"""'], {}), "(self._folder, 'kyk.yaml')\n", (939, 965), False, 'import os\n'), ((1033, 1046), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (1043, 1046), False, 'import time\n'), ((1108, 1131), 'os.path.isfile', 'os.path.isfile', (['cfgfile'], {}), '(cfgfile)\n', (1122, 1131), False, 'import os\n'), ((6311, 6333), 'os.path.isfile', 'os.path.isfile', (['jsfile'], {}), '(jsfile)\n', (6325, 6333), False, 'import os\n'), ((982, 1005), 'os.path.isfile', 'os.path.isfile', (['cfgfile'], {}), '(cfgfile)\n', (996, 1005), False, 'import os\n'), ((7196, 7221), 'os.path.basename', 'os.path.basename', (['minfile'], {}), '(minfile)\n', (7212, 7221), False, 'import os\n'), ((8759, 8792), 'shutil.copy', 'shutil.copy', (['tmp_minfile', 'minfile'], {}), '(tmp_minfile, minfile)\n', (8770, 8792), False, 'import shutil\n'), ((2614, 2637), 'os.path.abspath', 'os.path.abspath', (['jsfile'], {}), '(jsfile)\n', (2629, 2637), False, 'import os\n'), ((9235, 9268), 'shutil.copy', 'shutil.copy', (['tmp_minfile', 'minfile'], {}), '(tmp_minfile, minfile)\n', (9246, 9268), False, 'import shutil\n'), ((2525, 2548), 'os.path.abspath', 'os.path.abspath', (['jsfile'], {}), '(jsfile)\n', (2540, 2548), False, 'import os\n'), ((8085, 8190), 'sass.compile', 'sass.compile', ([], {'filename': 'sassfile', 'source_comments': '(True)', 'source_map_filename': 'mapfile', 'output_style': 'ost'}), '(filename=sassfile, source_comments=True, source_map_filename=\n mapfile, output_style=ost)\n', (8097, 8190), False, 'import sass\n'), ((8229, 8301), 'sass.compile', 'sass.compile', ([], {'filename': 'sassfile', 'source_comments': '(False)', 'output_style': 'ost'}), '(filename=sassfile, source_comments=False, output_style=ost)\n', (8241, 8301), False, 'import sass\n'), ((6774, 6785), 'time.time', 'time.time', ([], {}), '()\n', (6783, 6785), False, 'import time\n'), ((8681, 8693), 'csscompressor.compress', 'compress', (['sc'], {}), '(sc)\n', (8689, 8693), False, 'from csscompressor import compress\n')]
import os import sys import argparse _version_ = '0.0.1' class scaffold(): result = [] def new_project(self): if os.path.exists(self.result.project): print("project has been existed") exit(1) os.mkdir(self.result.project) os.chdir(self.result.project) os.system("touch hosts.yml") os.system("touch sites.yml") dir1 = ["group_vars", "host_vars", "roles"] for dir in dir1: os.mkdir(dir) if dir == "group_vars": os.system("touch group_vars/all") dir2 = ["tasks", "files", "templates", "handlers", "vars"] os.chdir("roles") for dir in dir2: os.mkdir(dir) if dir == "tasks": os.system("touch tasks/main.yml") print("create project %s successfully" % self.result.project) def new_role(self): if os.path.exists(self.result.role): print("dir has been existed") exit(1) os.mkdir(self.result.role) dirs = ["tasks", "files", "templates", "handlers", "vars"] os.chdir(self.result.role) for dir in dirs: os.mkdir(dir) if dir == "tasks": os.system("touch tasks/main.yml") print("create role %s successfully" % self.result.role) def find_dir(self,rootdir): for lists in os.listdir(rootdir): path = os.path.join(rootdir,lists) if os.path.isdir(path): if not os.listdir(path): os.rmdir(path) else: self.find_dir(path) def clean_dir(self): print("are you sure to clean?(y)") flag = input() if flag != "y": exit(1) self.find_dir(self.result.dir) def parse_opt(self): if len(sys.argv) > 3: print("error argv number,please check") exit(1) parser = argparse.ArgumentParser(usage="ansiscaf [opt] [argv]",description='ansible scaffold') parser.add_argument('-new', action="store", dest="project",help="create file tree") parser.add_argument('-add', action="store", dest="role",help="create role dir tree") parser.add_argument('-rm', action="store", dest="dir",help="delete all empty dir") self.result = parser.parse_args() if self.result.project: self.new_project() elif self.result.role: self.new_role() elif self.result.dir: self.clean_dir() if __name__ == '__main__': ansi = scaffold() ansi.parse_opt()
[ "os.path.exists", "os.listdir", "argparse.ArgumentParser", "os.path.join", "os.chdir", "os.rmdir", "os.path.isdir", "os.mkdir", "os.system" ]
[((133, 168), 'os.path.exists', 'os.path.exists', (['self.result.project'], {}), '(self.result.project)\n', (147, 168), False, 'import os\n'), ((244, 273), 'os.mkdir', 'os.mkdir', (['self.result.project'], {}), '(self.result.project)\n', (252, 273), False, 'import os\n'), ((282, 311), 'os.chdir', 'os.chdir', (['self.result.project'], {}), '(self.result.project)\n', (290, 311), False, 'import os\n'), ((320, 348), 'os.system', 'os.system', (['"""touch hosts.yml"""'], {}), "('touch hosts.yml')\n", (329, 348), False, 'import os\n'), ((357, 385), 'os.system', 'os.system', (['"""touch sites.yml"""'], {}), "('touch sites.yml')\n", (366, 385), False, 'import os\n'), ((650, 667), 'os.chdir', 'os.chdir', (['"""roles"""'], {}), "('roles')\n", (658, 667), False, 'import os\n'), ((908, 940), 'os.path.exists', 'os.path.exists', (['self.result.role'], {}), '(self.result.role)\n', (922, 940), False, 'import os\n'), ((1012, 1038), 'os.mkdir', 'os.mkdir', (['self.result.role'], {}), '(self.result.role)\n', (1020, 1038), False, 'import os\n'), ((1114, 1140), 'os.chdir', 'os.chdir', (['self.result.role'], {}), '(self.result.role)\n', (1122, 1140), False, 'import os\n'), ((1391, 1410), 'os.listdir', 'os.listdir', (['rootdir'], {}), '(rootdir)\n', (1401, 1410), False, 'import os\n'), ((1955, 2046), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'usage': '"""ansiscaf [opt] [argv]"""', 'description': '"""ansible scaffold"""'}), "(usage='ansiscaf [opt] [argv]', description=\n 'ansible scaffold')\n", (1978, 2046), False, 'import argparse\n'), ((475, 488), 'os.mkdir', 'os.mkdir', (['dir'], {}), '(dir)\n', (483, 488), False, 'import os\n'), ((705, 718), 'os.mkdir', 'os.mkdir', (['dir'], {}), '(dir)\n', (713, 718), False, 'import os\n'), ((1178, 1191), 'os.mkdir', 'os.mkdir', (['dir'], {}), '(dir)\n', (1186, 1191), False, 'import os\n'), ((1431, 1459), 'os.path.join', 'os.path.join', (['rootdir', 'lists'], {}), '(rootdir, lists)\n', (1443, 1459), False, 'import os\n'), ((1474, 1493), 'os.path.isdir', 'os.path.isdir', (['path'], {}), '(path)\n', (1487, 1493), False, 'import os\n'), ((541, 574), 'os.system', 'os.system', (['"""touch group_vars/all"""'], {}), "('touch group_vars/all')\n", (550, 574), False, 'import os\n'), ((766, 799), 'os.system', 'os.system', (['"""touch tasks/main.yml"""'], {}), "('touch tasks/main.yml')\n", (775, 799), False, 'import os\n'), ((1239, 1272), 'os.system', 'os.system', (['"""touch tasks/main.yml"""'], {}), "('touch tasks/main.yml')\n", (1248, 1272), False, 'import os\n'), ((1518, 1534), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (1528, 1534), False, 'import os\n'), ((1556, 1570), 'os.rmdir', 'os.rmdir', (['path'], {}), '(path)\n', (1564, 1570), False, 'import os\n')]
import keras import random import numpy as np from glob import glob from keras.models import Model from keras.utils import np_utils from keras.models import load_model import matplotlib.pyplot as plt import os import keras.backend as K import tensorflow as tf from keras.utils import to_categorical from tqdm import tqdm import sys sys.path.append('..') from helpers.losses import * from helpers.utils import load_vol_brats class intervention(): def __init__(self, model, test_path): self.model = model self.vol_path = glob(test_path) self.test_image, self.gt = load_vol_brats(self.vol_path[3], slicen = 78, pad = 0) def mean_swap(self, plot = True, save_path='/home/parth/Interpretable_ML/BioExp/results/RCT'): channel = 3 f_index = 0 test_image, gt = load_vol_brats(self.vol_path[f_index], slicen = 78, pad = 0) prediction = np.argmax(self.model.predict(test_image[None, ...]), axis = -1)[0] n_classes = (len(np.unique(prediction))) corr = np.zeros((n_classes, n_classes)) slices = [78] plt.figure(figsize = (20,20)) for vol in range(len(test_path)): for slicen in slices: test_image, gt = load_vol_brats(self.vol_path[vol], slicen = slicen, pad = 0) prediction = np.argmax(self.model.predict(test_image[None, ...]), axis = -1)[0] print("Original Dice Whole:", dice_whole_coef(prediction, gt)) class_dict = {0:'bg', 1:'core', 2:'edema', 3:'enhancing'} corr_temp = np.zeros((n_classes, n_classes)) for i in range(n_classes): for j in range(n_classes): new_mean = np.mean(test_image[gt == i], axis = 0) old_mean = np.mean(test_image[gt == j], axis = 0) test_image_intervention = np.copy(test_image) test_image_intervention[gt == j] += (new_mean - old_mean) prediction_intervention = np.argmax(self.model.predict(test_image_intervention[None, ...]), axis = -1)[0] corr[i,j] += dice_label_coef(prediction, gt, (j,)) - dice_label_coef(prediction_intervention, gt, (j,)) corr_temp[i,j] += dice_label_coef(prediction, gt, (j,)) - dice_label_coef(prediction_intervention, gt, (j,)) if plot == True: plt.subplot(n_classes, n_classes, 1+4*i+j) plt.xticks([]) plt.yticks([]) plt.title("{} --> {}, Dice Change={}".format(class_dict[j], class_dict[i], "{0:.2f}".format(-corr[i,j]))) plt.imshow(prediction_intervention, cmap = plt.cm.RdBu, vmin = 0, vmax = 3) plt.colorbar() print(corr_temp)#/(vol*len(slices)) np.set_printoptions(precision = 2) plt.rcParams.update({'font.size': 24}) intervention_importance = corr /(len(self.vol_path)*len(slices)) print(intervention_importance) os.makedirs(save_path, exist_ok = True) # np.save(save_path + '/mean_swap_all_images.npy', intervention_importance) if plot == True: plt.show() def blocks(self): test_image, gt = load_vol_brats(self.vol_path[1], slicen = 78, pad = 8) prediction = np.argmax(self.model.predict(test_image[None, ...]), axis = -1)[0] n_classes = (len(np.unique(prediction))) corr = np.zeros((n_classes, n_classes)) slices = [78] intervention_image = np.empty(test_image.shape) for _modality in range(4): for i in range(2): for j in range(2): try: intervention_image[:,:,_modality][test_image.shape[0]//2*i:test_image.shape[0]//2*(i+1), test_image.shape[1]//2*j:test_image.shape[1]//2*(j+1)].fill(np.mean(test_image[gt == 2*i+j], axis = 0)[_modality]) except Exception as e: print(e) prediction_intervention = model.predict(intervention_image[None, ...]) plt.imshow(intervention_image[:, :, 0]) plt.colorbar() plt.show() plt.imshow(np.argmax(prediction_intervention, axis = -1)[0], vmin=0, vmax=3) plt.colorbar() plt.show() def adverserial(self, epochs=100, epsilon = 0.01, mode = 'gradient', plot=False, test_image=None, gt=None): sess = K.get_session() keras.layers.core.K.set_learning_phase(0) image = test_image[None, ...] # if test_image is not None else self.test_image[None, ...] gt = gt[None, ...] # if gt is not None else self.gt[None, ...] noise = np.zeros_like(image) adverserial_image = image.copy() if mode == 'gradient': loss = keras.losses.categorical_crossentropy(self.model.output, tf.convert_to_tensor(to_categorical(gt, num_classes=4))) elif mode == 'random': loss = -keras.losses.categorical_crossentropy(self.model.output, tf.convert_to_tensor(self.generate_random_classification(mode='random'))) elif mode =='swap': loss = -keras.losses.categorical_crossentropy(self.model.output, tf.convert_to_tensor(self.generate_random_classification(mode='swap'))) grads = K.gradients(loss, self.model.input) delta = K.sign(grads[0]) noise = noise + delta adverserial_image = adverserial_image+epsilon*delta adverserial_image, noise_ar, delta_ = sess.run([adverserial_image, noise, delta], feed_dict={self.model.input: image}) delta_image_perc = (np.mean(np.abs(image - adverserial_image))*100)/np.ptp(image) delta_dice_perc = (dice_whole_coef(self.model.predict(image).argmax(axis=-1), gt) - dice_whole_coef(self.model.predict(adverserial_image).argmax(axis=-1), gt))*100/dice_whole_coef(self.model.predict(image).argmax(axis=-1), gt) # print("perc. change in image:{}, perc. change in dice:{}, Sensitivity:{}".format(delta_image_perc, # delta_dice_perc, delta_dice_perc/delta_image_perc)) imshape = image.shape[1] if plot==True: plt.figure(figsize = (40,10)) plt.rcParams.update({'font.size': 34}) plt.subplot(1,4,1) plt.title("Original image") plt.imshow(image[:, :, :, 0].reshape((imshape, imshape))) plt.xticks([]) plt.yticks([]) # plt.subplot(1,6,2) # plt.title("Added Noise") # plt.imshow(noise_ar[:, :, :, 0].reshape((imshape, imshape))) # plt.xticks([]) # plt.yticks([]) plt.subplot(1,4,2) plt.title("Image + Noise, % Change = {}".format("{0:.2f}".format(delta_image_perc))) plt.imshow(adverserial_image[:, :, :, 0].reshape((imshape, imshape))) plt.xticks([]) plt.yticks([]) # plt.subplot(1,6,4) # plt.title("Ground Truth") # plt.imshow(self.gt, vmin = 0, vmax=3) # plt.xticks([]) # plt.yticks([]) plt.subplot(1,4,3) plt.title("Old Seg, Dice = {}".format("{0:.2f}".format(dice_whole_coef(self.model.predict(image).argmax(axis=-1), gt)))) plt.imshow(np.argmax(self.model.predict(image), axis = -1).reshape((imshape, imshape)), vmin = 0, vmax=3) plt.xticks([]) plt.yticks([]) plt.subplot(1,4,4) plt.title("New Seg, Dice={}, Sensitivity={}".format("{0:.2f}".format(dice_whole_coef(self.model.predict(adverserial_image).argmax(axis=-1), gt)), "{0:.2f}".format(delta_dice_perc/delta_image_perc))) plt.imshow(np.argmax(self.model.predict(adverserial_image), axis = -1).reshape((imshape, imshape)), vmin = 0, vmax=3) plt.xticks([]) plt.yticks([]) plt.tight_layout(pad=0) plt.show() # plt.savefig('/home/parth/Interpretable_ML/Adverserial Examples/adv_{}.png'.format(epsilon)) return(delta_image_perc, delta_dice_perc, delta_dice_perc/delta_image_perc) def generate_random_classification(self, mode='random'): if mode == 'random': true_target = self.gt.flatten() true_target[true_target==4] = 3 index_list = [0, 1, 2, 3] adverserial_random = np.zeros_like(true_target) for i in range(adverserial_random.shape[0]): adverserial_random[i] = np.random.choice(np.setdiff1d(index_list, true_target[i])) print("Target image") plt.imshow(adverserial_random.reshape((256, 256)), vmin=0., vmax=3.) plt.show() return to_categorical(adverserial_random, num_classes=4).reshape(self.test_image.shape) elif mode == 'swap': true_target = self.gt.flatten() true_target[true_target==4] = 3 index_list = [0, 1, 2, 3] adverserial_random = np.zeros_like(true_target) for i in index_list: adverserial_random[true_target == i] = np.random.choice(np.setdiff1d(index_list, i)) print("Target image") plt.imshow(adverserial_random.reshape((256, 256)), vmin=0., vmax=3.) plt.show() return to_categorical(adverserial_random, num_classes=4).reshape(self.test_image.shape) if __name__ == "__main__": model = load_model('/home/parth/Interpretable_ML/saved_models/SimUnet/model_lrsch.hdf5', custom_objects={'gen_dice_loss':gen_dice_loss, 'dice_whole_metric':dice_whole_metric, 'dice_core_metric':dice_core_metric, 'dice_en_metric':dice_en_metric}) model.load_weights('/home/parth/Interpretable_ML/saved_models/SimUnet/SimUnet.40_0.060.hdf5') I = intervention(model, '/media/parth/DATA/datasets/brats_2018/val/**') test_path = glob('/media/parth/DATA/datasets/brats_2018/val/**') average_change = [] for epsilon in [0.7]: #, 0.07, 0.21, 0.7]: for i in tqdm(range(len(test_path))): test_image, gt = load_vol_brats(test_path[i], slicen = 78, pad = 0) if len(np.unique(gt)) == 4: print(len(np.unique(gt))) # I.blocks('/home/parth/Interpretable_ML/BioExp/sample_vol/brats/**') adv = I.adverserial(epsilon = epsilon, mode='gradient', test_image=test_image, gt=gt) if adv[1] > 0: average_change.append(adv) print(adv) print(np.mean(average_change, axis = 0)) # I.generate_random_classification(mode='swap') # I.mean_swap(plot = False)
[ "numpy.ptp", "keras.backend.gradients", "keras.utils.to_categorical", "sys.path.append", "keras.layers.core.K.set_learning_phase", "matplotlib.pyplot.imshow", "numpy.mean", "numpy.empty", "matplotlib.pyplot.yticks", "glob.glob", "numpy.abs", "matplotlib.pyplot.xticks", "numpy.argmax", "mat...
[((332, 353), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (347, 353), False, 'import sys\n'), ((8210, 8464), 'keras.models.load_model', 'load_model', (['"""/home/parth/Interpretable_ML/saved_models/SimUnet/model_lrsch.hdf5"""'], {'custom_objects': "{'gen_dice_loss': gen_dice_loss, 'dice_whole_metric': dice_whole_metric,\n 'dice_core_metric': dice_core_metric, 'dice_en_metric': dice_en_metric}"}), "('/home/parth/Interpretable_ML/saved_models/SimUnet/model_lrsch.hdf5'\n , custom_objects={'gen_dice_loss': gen_dice_loss, 'dice_whole_metric':\n dice_whole_metric, 'dice_core_metric': dice_core_metric,\n 'dice_en_metric': dice_en_metric})\n", (8220, 8464), False, 'from keras.models import load_model\n'), ((8745, 8797), 'glob.glob', 'glob', (['"""/media/parth/DATA/datasets/brats_2018/val/**"""'], {}), "('/media/parth/DATA/datasets/brats_2018/val/**')\n", (8749, 8797), False, 'from glob import glob\n'), ((526, 541), 'glob.glob', 'glob', (['test_path'], {}), '(test_path)\n', (530, 541), False, 'from glob import glob\n'), ((571, 621), 'helpers.utils.load_vol_brats', 'load_vol_brats', (['self.vol_path[3]'], {'slicen': '(78)', 'pad': '(0)'}), '(self.vol_path[3], slicen=78, pad=0)\n', (585, 621), False, 'from helpers.utils import load_vol_brats\n'), ((774, 830), 'helpers.utils.load_vol_brats', 'load_vol_brats', (['self.vol_path[f_index]'], {'slicen': '(78)', 'pad': '(0)'}), '(self.vol_path[f_index], slicen=78, pad=0)\n', (788, 830), False, 'from helpers.utils import load_vol_brats\n'), ((970, 1002), 'numpy.zeros', 'np.zeros', (['(n_classes, n_classes)'], {}), '((n_classes, n_classes))\n', (978, 1002), True, 'import numpy as np\n'), ((1022, 1050), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(20, 20)'}), '(figsize=(20, 20))\n', (1032, 1050), True, 'import matplotlib.pyplot as plt\n'), ((2476, 2508), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(2)'}), '(precision=2)\n', (2495, 2508), True, 'import numpy as np\n'), ((2513, 2551), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'font.size': 24}"], {}), "({'font.size': 24})\n", (2532, 2551), True, 'import matplotlib.pyplot as plt\n'), ((2655, 2692), 'os.makedirs', 'os.makedirs', (['save_path'], {'exist_ok': '(True)'}), '(save_path, exist_ok=True)\n', (2666, 2692), False, 'import os\n'), ((2846, 2896), 'helpers.utils.load_vol_brats', 'load_vol_brats', (['self.vol_path[1]'], {'slicen': '(78)', 'pad': '(8)'}), '(self.vol_path[1], slicen=78, pad=8)\n', (2860, 2896), False, 'from helpers.utils import load_vol_brats\n'), ((3036, 3068), 'numpy.zeros', 'np.zeros', (['(n_classes, n_classes)'], {}), '((n_classes, n_classes))\n', (3044, 3068), True, 'import numpy as np\n'), ((3109, 3135), 'numpy.empty', 'np.empty', (['test_image.shape'], {}), '(test_image.shape)\n', (3117, 3135), True, 'import numpy as np\n'), ((3557, 3596), 'matplotlib.pyplot.imshow', 'plt.imshow', (['intervention_image[:, :, 0]'], {}), '(intervention_image[:, :, 0])\n', (3567, 3596), True, 'import matplotlib.pyplot as plt\n'), ((3599, 3613), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (3611, 3613), True, 'import matplotlib.pyplot as plt\n'), ((3616, 3626), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3624, 3626), True, 'import matplotlib.pyplot as plt\n'), ((3708, 3722), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (3720, 3722), True, 'import matplotlib.pyplot as plt\n'), ((3725, 3735), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3733, 3735), True, 'import matplotlib.pyplot as plt\n'), ((3856, 3871), 'keras.backend.get_session', 'K.get_session', ([], {}), '()\n', (3869, 3871), True, 'import keras.backend as K\n'), ((3875, 3916), 'keras.layers.core.K.set_learning_phase', 'keras.layers.core.K.set_learning_phase', (['(0)'], {}), '(0)\n', (3913, 3916), False, 'import keras\n'), ((4086, 4106), 'numpy.zeros_like', 'np.zeros_like', (['image'], {}), '(image)\n', (4099, 4106), True, 'import numpy as np\n'), ((4643, 4678), 'keras.backend.gradients', 'K.gradients', (['loss', 'self.model.input'], {}), '(loss, self.model.input)\n', (4654, 4678), True, 'import keras.backend as K\n'), ((4690, 4706), 'keras.backend.sign', 'K.sign', (['grads[0]'], {}), '(grads[0])\n', (4696, 4706), True, 'import keras.backend as K\n'), ((937, 958), 'numpy.unique', 'np.unique', (['prediction'], {}), '(prediction)\n', (946, 958), True, 'import numpy as np\n'), ((2795, 2805), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2803, 2805), True, 'import matplotlib.pyplot as plt\n'), ((3003, 3024), 'numpy.unique', 'np.unique', (['prediction'], {}), '(prediction)\n', (3012, 3024), True, 'import numpy as np\n'), ((4980, 4993), 'numpy.ptp', 'np.ptp', (['image'], {}), '(image)\n', (4986, 4993), True, 'import numpy as np\n'), ((5446, 5474), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(40, 10)'}), '(figsize=(40, 10))\n', (5456, 5474), True, 'import matplotlib.pyplot as plt\n'), ((5480, 5518), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'font.size': 34}"], {}), "({'font.size': 34})\n", (5499, 5518), True, 'import matplotlib.pyplot as plt\n'), ((5522, 5542), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(4)', '(1)'], {}), '(1, 4, 1)\n', (5533, 5542), True, 'import matplotlib.pyplot as plt\n'), ((5544, 5571), 'matplotlib.pyplot.title', 'plt.title', (['"""Original image"""'], {}), "('Original image')\n", (5553, 5571), True, 'import matplotlib.pyplot as plt\n'), ((5637, 5651), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (5647, 5651), True, 'import matplotlib.pyplot as plt\n'), ((5655, 5669), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (5665, 5669), True, 'import matplotlib.pyplot as plt\n'), ((5840, 5860), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(4)', '(2)'], {}), '(1, 4, 2)\n', (5851, 5860), True, 'import matplotlib.pyplot as plt\n'), ((6024, 6038), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (6034, 6038), True, 'import matplotlib.pyplot as plt\n'), ((6042, 6056), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (6052, 6056), True, 'import matplotlib.pyplot as plt\n'), ((6198, 6218), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(4)', '(3)'], {}), '(1, 4, 3)\n', (6209, 6218), True, 'import matplotlib.pyplot as plt\n'), ((6453, 6467), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (6463, 6467), True, 'import matplotlib.pyplot as plt\n'), ((6471, 6485), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (6481, 6485), True, 'import matplotlib.pyplot as plt\n'), ((6489, 6509), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(4)', '(4)'], {}), '(1, 4, 4)\n', (6500, 6509), True, 'import matplotlib.pyplot as plt\n'), ((6839, 6853), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (6849, 6853), True, 'import matplotlib.pyplot as plt\n'), ((6857, 6871), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (6867, 6871), True, 'import matplotlib.pyplot as plt\n'), ((6875, 6898), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {'pad': '(0)'}), '(pad=0)\n', (6891, 6898), True, 'import matplotlib.pyplot as plt\n'), ((6902, 6912), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6910, 6912), True, 'import matplotlib.pyplot as plt\n'), ((7299, 7325), 'numpy.zeros_like', 'np.zeros_like', (['true_target'], {}), '(true_target)\n', (7312, 7325), True, 'import numpy as np\n'), ((7571, 7581), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7579, 7581), True, 'import matplotlib.pyplot as plt\n'), ((8926, 8972), 'helpers.utils.load_vol_brats', 'load_vol_brats', (['test_path[i]'], {'slicen': '(78)', 'pad': '(0)'}), '(test_path[i], slicen=78, pad=0)\n', (8940, 8972), False, 'from helpers.utils import load_vol_brats\n'), ((9278, 9309), 'numpy.mean', 'np.mean', (['average_change'], {'axis': '(0)'}), '(average_change, axis=0)\n', (9285, 9309), True, 'import numpy as np\n'), ((1136, 1192), 'helpers.utils.load_vol_brats', 'load_vol_brats', (['self.vol_path[vol]'], {'slicen': 'slicen', 'pad': '(0)'}), '(self.vol_path[vol], slicen=slicen, pad=0)\n', (1150, 1192), False, 'from helpers.utils import load_vol_brats\n'), ((1429, 1461), 'numpy.zeros', 'np.zeros', (['(n_classes, n_classes)'], {}), '((n_classes, n_classes))\n', (1437, 1461), True, 'import numpy as np\n'), ((3640, 3683), 'numpy.argmax', 'np.argmax', (['prediction_intervention'], {'axis': '(-1)'}), '(prediction_intervention, axis=-1)\n', (3649, 3683), True, 'import numpy as np\n'), ((7825, 7851), 'numpy.zeros_like', 'np.zeros_like', (['true_target'], {}), '(true_target)\n', (7838, 7851), True, 'import numpy as np\n'), ((8068, 8078), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (8076, 8078), True, 'import matplotlib.pyplot as plt\n'), ((4257, 4290), 'keras.utils.to_categorical', 'to_categorical', (['gt'], {'num_classes': '(4)'}), '(gt, num_classes=4)\n', (4271, 4290), False, 'from keras.utils import to_categorical\n'), ((4940, 4973), 'numpy.abs', 'np.abs', (['(image - adverserial_image)'], {}), '(image - adverserial_image)\n', (4946, 4973), True, 'import numpy as np\n'), ((7421, 7461), 'numpy.setdiff1d', 'np.setdiff1d', (['index_list', 'true_target[i]'], {}), '(index_list, true_target[i])\n', (7433, 7461), True, 'import numpy as np\n'), ((7593, 7642), 'keras.utils.to_categorical', 'to_categorical', (['adverserial_random'], {'num_classes': '(4)'}), '(adverserial_random, num_classes=4)\n', (7607, 7642), False, 'from keras.utils import to_categorical\n'), ((8987, 9000), 'numpy.unique', 'np.unique', (['gt'], {}), '(gt)\n', (8996, 9000), True, 'import numpy as np\n'), ((1542, 1578), 'numpy.mean', 'np.mean', (['test_image[gt == i]'], {'axis': '(0)'}), '(test_image[gt == i], axis=0)\n', (1549, 1578), True, 'import numpy as np\n'), ((1598, 1634), 'numpy.mean', 'np.mean', (['test_image[gt == j]'], {'axis': '(0)'}), '(test_image[gt == j], axis=0)\n', (1605, 1634), True, 'import numpy as np\n'), ((1669, 1688), 'numpy.copy', 'np.copy', (['test_image'], {}), '(test_image)\n', (1676, 1688), True, 'import numpy as np\n'), ((7938, 7965), 'numpy.setdiff1d', 'np.setdiff1d', (['index_list', 'i'], {}), '(index_list, i)\n', (7950, 7965), True, 'import numpy as np\n'), ((8090, 8139), 'keras.utils.to_categorical', 'to_categorical', (['adverserial_random'], {'num_classes': '(4)'}), '(adverserial_random, num_classes=4)\n', (8104, 8139), False, 'from keras.utils import to_categorical\n'), ((9022, 9035), 'numpy.unique', 'np.unique', (['gt'], {}), '(gt)\n', (9031, 9035), True, 'import numpy as np\n'), ((2128, 2176), 'matplotlib.pyplot.subplot', 'plt.subplot', (['n_classes', 'n_classes', '(1 + 4 * i + j)'], {}), '(n_classes, n_classes, 1 + 4 * i + j)\n', (2139, 2176), True, 'import matplotlib.pyplot as plt\n'), ((2178, 2192), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (2188, 2192), True, 'import matplotlib.pyplot as plt\n'), ((2200, 2214), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (2210, 2214), True, 'import matplotlib.pyplot as plt\n'), ((2335, 2404), 'matplotlib.pyplot.imshow', 'plt.imshow', (['prediction_intervention'], {'cmap': 'plt.cm.RdBu', 'vmin': '(0)', 'vmax': '(3)'}), '(prediction_intervention, cmap=plt.cm.RdBu, vmin=0, vmax=3)\n', (2345, 2404), True, 'import matplotlib.pyplot as plt\n'), ((2418, 2432), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (2430, 2432), True, 'import matplotlib.pyplot as plt\n'), ((3383, 3427), 'numpy.mean', 'np.mean', (['test_image[gt == 2 * i + j]'], {'axis': '(0)'}), '(test_image[gt == 2 * i + j], axis=0)\n', (3390, 3427), True, 'import numpy as np\n')]
import json from collections import OrderedDict def json_file(filename, converter): with open(filename, 'r') as file: raw = json.load( file, object_pairs_hook=OrderedDict # to insure that order of items in json won't be broken ) return converter(raw)
[ "json.load" ]
[((138, 184), 'json.load', 'json.load', (['file'], {'object_pairs_hook': 'OrderedDict'}), '(file, object_pairs_hook=OrderedDict)\n', (147, 184), False, 'import json\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # board.py # Author: <NAME> <<EMAIL>> # Version: 0.1 # License: MIT """Import modules""" from random import sample class Board: """board object which regroup the coordinates of the game's elements (walls, start, end, guard, components...)""" def __init__(self, x_tile, y_tile, tile_size): self.x_tile = x_tile self.y_tile = y_tile self.tile_size = tile_size self.walls = [] self.corridors = [] @property def width(self): """board's width in px""" return self.x_tile * self.tile_size @property def height(self): """board's height in px""" return self.y_tile * self.tile_size def read_map(self, map_path): """reads a .txt : 'w'=wall, 's'=start, 'e'=end, 'g'=guard, ' '=empty""" with open(map_path, 'r') as data: for y_index, line in enumerate(data): for x_index, char in enumerate(line.strip('\n')): coord = ((x_index * self.tile_size, y_index * self.tile_size)) if char == 'w': self.walls.append(coord) elif char == 's': setattr(self, 'start', coord) elif char == 'e': setattr(self, 'end', coord) elif char == 'g': setattr(self, 'guard', coord) else: self.corridors.append(coord) def set_components(self): """randomly pick-up 3 coordinates in a list of available tiles and create a dict {coordinate : index}""" components = {} component_list = sample(self.corridors, 3) for index, component in enumerate(component_list): components[component] = index setattr(self, 'components', components)
[ "random.sample" ]
[((1759, 1784), 'random.sample', 'sample', (['self.corridors', '(3)'], {}), '(self.corridors, 3)\n', (1765, 1784), False, 'from random import sample\n')]
""" tests.test_parser ~~~~~~~~~~~~~~~~~ Parser tests for Drowsy. """ # :copyright: (c) 2016-2020 by <NAME> and contributors. # See AUTHORS for more details. # :license: MIT - See LICENSE for more details. from marshmallow import fields from marshmallow.exceptions import ValidationError from drowsy.convert import ModelResourceConverter from drowsy.exc import PermissionValidationError from drowsy.schema import NestedOpts, ResourceSchema from tests.base import DrowsyDatabaseTests from tests.schemas import ( AlbumSchema, AlbumCamelSchema, ArtistSchema, CustomerSchema, TrackPermissionsSchema, TrackSchema ) import tests.resources from tests.models import Album, Track, ForeignPkExample from pytest import raises def test_schema_default_get_instance(): """Test a ResourceSchema handles get_instance properly.""" class TestSchema(ResourceSchema): class Meta: instance_cls = Album assert TestSchema().get_instance({}) is None def test_schema_fail_missing_key(): """Test schema failure missing key error message.""" schema = AlbumSchema() with raises(AssertionError): schema.make_error(key="test") def test_schema_default_id_keys(): """Test a ResourceSchema handles given id_keys properly.""" class TestSchema(ResourceSchema): class Meta: instance_cls = Album id_keys = ["album_id"] assert "album_id" in TestSchema().id_keys def test_schema_empty_id_keys(): """Test a ResourceSchema handles no id_keys properly.""" class TestSchema(ResourceSchema): class Meta: instance_cls = Album assert isinstance(TestSchema().id_keys, list) def test_schema_make_instance_default(): """Test making an instance from a non model schema.""" class TestSchema(ResourceSchema): """Simple schema for this test.""" class Meta: """Meta options for this schema.""" instance_cls = Album id_keys = ["album_id"] def get_instance(self, data): """Allows testing of the resource property.""" return None schema = TestSchema() result = schema.make_instance({"album_id": 1, "title": "test"}) assert result.album_id == 1 assert result.title == "test" assert isinstance(result, Album) def test_convert_property2field_instance(): """Test property2field can return a column type.""" converter = ModelResourceConverter() result = converter.property2field(Album.album_id.prop, instance=False) assert result == fields.Integer def test_convert_fk_as_pk(): """Test converter handles ForeignKey as part of Primary properly.""" converter = ModelResourceConverter() converted_fields = converter.fields_for_model( ForeignPkExample, include_fk=False, include_relationships=True, fields=None, exclude=None, base_fields=None, dict_cls=dict ) assert "parent_id" in converted_fields is not None class TestDrowsySchema(DrowsyDatabaseTests): """Test drowsy schema classes are working as expected.""" @staticmethod def test_schema_embed_top_level(db_session): """Test embedding a non nested field is treated like only.""" schema = AlbumCamelSchema(session=db_session) schema.embed("album_id") assert "album_id" in schema.only @staticmethod def test_schema_embed_fail(db_session): """Test trying to embed a non-existent field fails.""" schema = AlbumCamelSchema(session=db_session) with raises(AttributeError): schema.embed("test") @staticmethod def test_schema_disallow_all_op_permissions_many(db_session): """Make sure permission denial on a list resource works.""" schema = ArtistSchema(session=db_session) data = { "artist_id": 1, "name": "test", "albums": [ {"album_id": 1} ] } errors = {} try: schema.load(data=data) except ValidationError as exc: errors = exc.messages assert errors["albums"][0]["$op"][0] @staticmethod def test_schema_disallow_all_op_permissions(db_session): """Make sure permission denial works.""" schema = TrackPermissionsSchema(session=db_session, partial=True) data = { "track_id": 1, "album": {"album_id": 1} } errors = {} try: schema.load(data=data) except ValidationError as exc: errors = exc.messages assert errors["album"] @staticmethod def test_schema_disallow_all_op_permissions_strict(db_session): """Make sure permission denial works.""" schema = TrackPermissionsSchema(session=db_session, partial=True) data = { "track_id": 1, "album": {"album_id": 1} } with raises(ValidationError): schema.load(data=data) @staticmethod def test_schema_relationship_bad_data(db_session): """Test bad data supplied to a relationship fails properly.""" schema = AlbumSchema(session=db_session, partial=True) data = { "tracks": [{"bytes": "TEST"}] } errors = {} try: schema.load(data=data) except ValidationError as exc: errors = exc.messages assert errors["tracks"][0]["bytes"] @staticmethod def test_convert_doc_string(db_session): """Test converter properly handles a doc string.""" schema = CustomerSchema(session=db_session) assert (schema.fields["state"].metadata["description"] == "Two Character Abbreviation") @staticmethod def test_relationship_set_child(db_session): """Test setting a non list relationship works.""" data = { "track_id": 1, "album": { "album_id": 347, } } schema = TrackSchema(session=db_session) result = schema.load(data, partial=True) assert result.album.album_id == 347 @staticmethod def test_many_load(db_session): """Test loading many objects at once works.""" data = [ {"track_id": 1, "name": "test1"}, {"track_id": 2, "name": "test2"}, {"track_id": 3, "name": "test3"}, {"track_id": 4, "name": "test4"}, {"track_id": 5, "name": "test5"} ] schema = TrackSchema(session=db_session, many=True) result = schema.load(data, partial=True, many=True) assert len(result) == 5 @staticmethod def test_many_load_failure(db_session): """Test loading many objects with bad data fails accordingly.""" data = [ {"track_id": 1, "name": 1}, {"track_id": 2, "name": 2}, {"track_id": 3, "name": "test3"}, {"track_id": 4, "name": "test4"}, {"track_id": 5, "name": "test5"} ] schema = TrackSchema(session=db_session, many=True) errors = {} try: schema.load(data, partial=True, many=True) except ValidationError as exc: errors = exc.messages assert len(errors.keys()) == 2 assert 0 in errors and 1 in errors @staticmethod def test_base_instance_relationship_set_child(db_session): """Test setting a child when loading with a base instance.""" album = db_session.query(Album).filter( Album.album_id == 1).first() instance = Track(track_id=9999, album=album) data = { "track_id": 9999, "album": { "album_id": 1, }, "name": "<NAME>", "media_type": { "media_type_id": 1 }, "milliseconds": 1, "unit_price": 1.0 } schema = TrackSchema(session=db_session) result = schema.load(data, partial=True, instance=instance) assert result.album.album_id == 1 @staticmethod def test_base_instance_relationship_add_child(db_session): """Test adding a child when loading with a base instance.""" track = db_session.query(Track).filter( Track.track_id == 1).first() instance = Album(album_id=9999) instance.tracks.append(track) data = { "album_id": 1, "tracks": [ {"track_id": 1} ] } schema = AlbumSchema(session=db_session, partial=True) result = schema.load(data, instance=instance) assert result.tracks[0].track_id == 1 @staticmethod def test_relationship_invalid_remove(db_session): """Test trying to remove a child from the wrong parent fails.""" data = { "album_id": 1, "tracks": [{ "track_id": 597, "$op": "remove" }] } schema = AlbumSchema( session=db_session, partial=True) with raises(ValidationError): schema.load(data) @staticmethod def test_relationship_invalid_op(db_session): """Test an invalid operation on a relationship fails.""" data = { "album_id": 1, "tracks": [{ "track_id": 1, "$op": "test" }] } schema = AlbumSchema( session=db_session, partial=True) with raises(ValidationError): schema.load(data) @staticmethod def test_instance_relationship_nested_opts(db_session): """Test nested opts enable complete relation replacement.""" data = { "album_id": 2, "tracks": [ {"track_id": 1} ] } nested_opts = {"tracks": NestedOpts(partial=False)} schema = AlbumSchema(session=db_session, nested_opts=nested_opts, partial=True) result = schema.load(data) assert result.tracks[0].track_id == 1 assert len(result.tracks) == 1 @staticmethod def test_nested_relationship_nested_opts(db_session): """Test nested opts enable complete relation replacement.""" data = { "album_id": 2, "tracks": [ {"track_id": 1, "playlists": [ {"playlist_id": 1} ]} ] } nested_opts = { "tracks": NestedOpts(partial=False), "tracks.playlists": NestedOpts(partial=False)} schema = AlbumSchema(session=db_session, nested_opts=nested_opts, partial=True) result = schema.load(data) assert len(result.tracks[0].playlists) == 1 @staticmethod def test_permission_denied(db_session): """Test permission denied errors work as expected.""" data = { "album_id": 340, "title": "Denied" } schema = AlbumSchema(session=db_session, partial=True) with raises(PermissionValidationError): schema.load(data) @staticmethod def test_permission_denied_list(db_session): """Test permission denied errors for lists work as expected.""" data = [{"track_id": 1, "name": "Denied"}] schema = TrackSchema(session=db_session, partial=True) with raises(PermissionValidationError): schema.load(data, many=True)
[ "tests.schemas.CustomerSchema", "tests.schemas.AlbumCamelSchema", "tests.schemas.TrackPermissionsSchema", "tests.schemas.ArtistSchema", "tests.schemas.AlbumSchema", "drowsy.schema.NestedOpts", "tests.schemas.TrackSchema", "tests.models.Track", "pytest.raises", "tests.models.Album", "drowsy.conve...
[((1102, 1115), 'tests.schemas.AlbumSchema', 'AlbumSchema', ([], {}), '()\n', (1113, 1115), False, 'from tests.schemas import AlbumSchema, AlbumCamelSchema, ArtistSchema, CustomerSchema, TrackPermissionsSchema, TrackSchema\n'), ((2453, 2477), 'drowsy.convert.ModelResourceConverter', 'ModelResourceConverter', ([], {}), '()\n', (2475, 2477), False, 'from drowsy.convert import ModelResourceConverter\n'), ((2709, 2733), 'drowsy.convert.ModelResourceConverter', 'ModelResourceConverter', ([], {}), '()\n', (2731, 2733), False, 'from drowsy.convert import ModelResourceConverter\n'), ((1125, 1147), 'pytest.raises', 'raises', (['AssertionError'], {}), '(AssertionError)\n', (1131, 1147), False, 'from pytest import raises\n'), ((3290, 3326), 'tests.schemas.AlbumCamelSchema', 'AlbumCamelSchema', ([], {'session': 'db_session'}), '(session=db_session)\n', (3306, 3326), False, 'from tests.schemas import AlbumSchema, AlbumCamelSchema, ArtistSchema, CustomerSchema, TrackPermissionsSchema, TrackSchema\n'), ((3544, 3580), 'tests.schemas.AlbumCamelSchema', 'AlbumCamelSchema', ([], {'session': 'db_session'}), '(session=db_session)\n', (3560, 3580), False, 'from tests.schemas import AlbumSchema, AlbumCamelSchema, ArtistSchema, CustomerSchema, TrackPermissionsSchema, TrackSchema\n'), ((3821, 3853), 'tests.schemas.ArtistSchema', 'ArtistSchema', ([], {'session': 'db_session'}), '(session=db_session)\n', (3833, 3853), False, 'from tests.schemas import AlbumSchema, AlbumCamelSchema, ArtistSchema, CustomerSchema, TrackPermissionsSchema, TrackSchema\n'), ((4339, 4395), 'tests.schemas.TrackPermissionsSchema', 'TrackPermissionsSchema', ([], {'session': 'db_session', 'partial': '(True)'}), '(session=db_session, partial=True)\n', (4361, 4395), False, 'from tests.schemas import AlbumSchema, AlbumCamelSchema, ArtistSchema, CustomerSchema, TrackPermissionsSchema, TrackSchema\n'), ((4812, 4868), 'tests.schemas.TrackPermissionsSchema', 'TrackPermissionsSchema', ([], {'session': 'db_session', 'partial': '(True)'}), '(session=db_session, partial=True)\n', (4834, 4868), False, 'from tests.schemas import AlbumSchema, AlbumCamelSchema, ArtistSchema, CustomerSchema, TrackPermissionsSchema, TrackSchema\n'), ((5195, 5240), 'tests.schemas.AlbumSchema', 'AlbumSchema', ([], {'session': 'db_session', 'partial': '(True)'}), '(session=db_session, partial=True)\n', (5206, 5240), False, 'from tests.schemas import AlbumSchema, AlbumCamelSchema, ArtistSchema, CustomerSchema, TrackPermissionsSchema, TrackSchema\n'), ((5636, 5670), 'tests.schemas.CustomerSchema', 'CustomerSchema', ([], {'session': 'db_session'}), '(session=db_session)\n', (5650, 5670), False, 'from tests.schemas import AlbumSchema, AlbumCamelSchema, ArtistSchema, CustomerSchema, TrackPermissionsSchema, TrackSchema\n'), ((6050, 6081), 'tests.schemas.TrackSchema', 'TrackSchema', ([], {'session': 'db_session'}), '(session=db_session)\n', (6061, 6081), False, 'from tests.schemas import AlbumSchema, AlbumCamelSchema, ArtistSchema, CustomerSchema, TrackPermissionsSchema, TrackSchema\n'), ((6558, 6600), 'tests.schemas.TrackSchema', 'TrackSchema', ([], {'session': 'db_session', 'many': '(True)'}), '(session=db_session, many=True)\n', (6569, 6600), False, 'from tests.schemas import AlbumSchema, AlbumCamelSchema, ArtistSchema, CustomerSchema, TrackPermissionsSchema, TrackSchema\n'), ((7090, 7132), 'tests.schemas.TrackSchema', 'TrackSchema', ([], {'session': 'db_session', 'many': '(True)'}), '(session=db_session, many=True)\n', (7101, 7132), False, 'from tests.schemas import AlbumSchema, AlbumCamelSchema, ArtistSchema, CustomerSchema, TrackPermissionsSchema, TrackSchema\n'), ((7636, 7669), 'tests.models.Track', 'Track', ([], {'track_id': '(9999)', 'album': 'album'}), '(track_id=9999, album=album)\n', (7641, 7669), False, 'from tests.models import Album, Track, ForeignPkExample\n'), ((7982, 8013), 'tests.schemas.TrackSchema', 'TrackSchema', ([], {'session': 'db_session'}), '(session=db_session)\n', (7993, 8013), False, 'from tests.schemas import AlbumSchema, AlbumCamelSchema, ArtistSchema, CustomerSchema, TrackPermissionsSchema, TrackSchema\n'), ((8383, 8403), 'tests.models.Album', 'Album', ([], {'album_id': '(9999)'}), '(album_id=9999)\n', (8388, 8403), False, 'from tests.models import Album, Track, ForeignPkExample\n'), ((8583, 8628), 'tests.schemas.AlbumSchema', 'AlbumSchema', ([], {'session': 'db_session', 'partial': '(True)'}), '(session=db_session, partial=True)\n', (8594, 8628), False, 'from tests.schemas import AlbumSchema, AlbumCamelSchema, ArtistSchema, CustomerSchema, TrackPermissionsSchema, TrackSchema\n'), ((9051, 9096), 'tests.schemas.AlbumSchema', 'AlbumSchema', ([], {'session': 'db_session', 'partial': '(True)'}), '(session=db_session, partial=True)\n', (9062, 9096), False, 'from tests.schemas import AlbumSchema, AlbumCamelSchema, ArtistSchema, CustomerSchema, TrackPermissionsSchema, TrackSchema\n'), ((9484, 9529), 'tests.schemas.AlbumSchema', 'AlbumSchema', ([], {'session': 'db_session', 'partial': '(True)'}), '(session=db_session, partial=True)\n', (9495, 9529), False, 'from tests.schemas import AlbumSchema, AlbumCamelSchema, ArtistSchema, CustomerSchema, TrackPermissionsSchema, TrackSchema\n'), ((9960, 10030), 'tests.schemas.AlbumSchema', 'AlbumSchema', ([], {'session': 'db_session', 'nested_opts': 'nested_opts', 'partial': '(True)'}), '(session=db_session, nested_opts=nested_opts, partial=True)\n', (9971, 10030), False, 'from tests.schemas import AlbumSchema, AlbumCamelSchema, ArtistSchema, CustomerSchema, TrackPermissionsSchema, TrackSchema\n'), ((10691, 10761), 'tests.schemas.AlbumSchema', 'AlbumSchema', ([], {'session': 'db_session', 'nested_opts': 'nested_opts', 'partial': '(True)'}), '(session=db_session, nested_opts=nested_opts, partial=True)\n', (10702, 10761), False, 'from tests.schemas import AlbumSchema, AlbumCamelSchema, ArtistSchema, CustomerSchema, TrackPermissionsSchema, TrackSchema\n'), ((11106, 11151), 'tests.schemas.AlbumSchema', 'AlbumSchema', ([], {'session': 'db_session', 'partial': '(True)'}), '(session=db_session, partial=True)\n', (11117, 11151), False, 'from tests.schemas import AlbumSchema, AlbumCamelSchema, ArtistSchema, CustomerSchema, TrackPermissionsSchema, TrackSchema\n'), ((11438, 11483), 'tests.schemas.TrackSchema', 'TrackSchema', ([], {'session': 'db_session', 'partial': '(True)'}), '(session=db_session, partial=True)\n', (11449, 11483), False, 'from tests.schemas import AlbumSchema, AlbumCamelSchema, ArtistSchema, CustomerSchema, TrackPermissionsSchema, TrackSchema\n'), ((3594, 3616), 'pytest.raises', 'raises', (['AttributeError'], {}), '(AttributeError)\n', (3600, 3616), False, 'from pytest import raises\n'), ((4973, 4996), 'pytest.raises', 'raises', (['ValidationError'], {}), '(ValidationError)\n', (4979, 4996), False, 'from pytest import raises\n'), ((9123, 9146), 'pytest.raises', 'raises', (['ValidationError'], {}), '(ValidationError)\n', (9129, 9146), False, 'from pytest import raises\n'), ((9556, 9579), 'pytest.raises', 'raises', (['ValidationError'], {}), '(ValidationError)\n', (9562, 9579), False, 'from pytest import raises\n'), ((9916, 9941), 'drowsy.schema.NestedOpts', 'NestedOpts', ([], {'partial': '(False)'}), '(partial=False)\n', (9926, 9941), False, 'from drowsy.schema import NestedOpts, ResourceSchema\n'), ((10588, 10613), 'drowsy.schema.NestedOpts', 'NestedOpts', ([], {'partial': '(False)'}), '(partial=False)\n', (10598, 10613), False, 'from drowsy.schema import NestedOpts, ResourceSchema\n'), ((10647, 10672), 'drowsy.schema.NestedOpts', 'NestedOpts', ([], {'partial': '(False)'}), '(partial=False)\n', (10657, 10672), False, 'from drowsy.schema import NestedOpts, ResourceSchema\n'), ((11165, 11198), 'pytest.raises', 'raises', (['PermissionValidationError'], {}), '(PermissionValidationError)\n', (11171, 11198), False, 'from pytest import raises\n'), ((11497, 11530), 'pytest.raises', 'raises', (['PermissionValidationError'], {}), '(PermissionValidationError)\n', (11503, 11530), False, 'from pytest import raises\n')]
from distutils.core import setup setup( name='RL-EmsPy', version='0.0.1', packages=['emspy'], url='https://github.com/mechyai/RL-EmsPy', license='Apache License 2.0', author='<NAME>', )
[ "distutils.core.setup" ]
[((34, 192), 'distutils.core.setup', 'setup', ([], {'name': '"""RL-EmsPy"""', 'version': '"""0.0.1"""', 'packages': "['emspy']", 'url': '"""https://github.com/mechyai/RL-EmsPy"""', 'license': '"""Apache License 2.0"""', 'author': '"""<NAME>"""'}), "(name='RL-EmsPy', version='0.0.1', packages=['emspy'], url=\n 'https://github.com/mechyai/RL-EmsPy', license='Apache License 2.0',\n author='<NAME>')\n", (39, 192), False, 'from distutils.core import setup\n')]
import os from cv2 import cv2 for d in os.listdir(): if not d.endswith(".png"): continue img = cv2.imread(d) cv2.imwrite(d.replace(".png",".webp"), img) os.remove(d)
[ "cv2.cv2.imread", "os.listdir", "os.remove" ]
[((40, 52), 'os.listdir', 'os.listdir', ([], {}), '()\n', (50, 52), False, 'import os\n'), ((98, 111), 'cv2.cv2.imread', 'cv2.imread', (['d'], {}), '(d)\n', (108, 111), False, 'from cv2 import cv2\n'), ((158, 170), 'os.remove', 'os.remove', (['d'], {}), '(d)\n', (167, 170), False, 'import os\n')]
""" NLTK DRT module extended with presuppositions """ __author__ = "<NAME>, <NAME>, <NAME>" __version__ = "1.0" __date__ = "Tue, 24 Aug 2010" import re import operator from nltk.sem.logic import Variable from nltk.sem.logic import EqualityExpression, ApplicationExpression, ExistsExpression, AndExpression from nltk.sem.logic import IndividualVariableExpression from nltk.sem.logic import _counter, is_eventvar, is_funcvar from nltk.sem.logic import BasicType from nltk.sem.logic import Expression from nltk.sem.logic import ParseException from nltk.sem.drt import DrsDrawer, AnaphoraResolutionException import nltk.sem.drt as drt class TimeType(BasicType): """ Basic type of times added on top of nltk.sem.logic. """ def __str__(self): return 'i' def str(self): return 'TIME' TIME_TYPE = TimeType() class StateType(BasicType): """ Basic type of states added on top of nltk.sem.logic. """ def __str__(self): return 's' def str(self): return 'STATE' STATE_TYPE = StateType() def is_indvar(expr): """ An individual variable must be a single lowercase character other than 'e', 't', 'n', 's', followed by zero or more digits. @param expr: C{str} @return: C{boolean} True if expr is of the correct form """ assert isinstance(expr, str), "%s is not a string" % expr return re.match(r'^[a-df-mo-ru-z]\d*$', expr) def is_timevar(expr): """ An time variable must be a single lowercase 't' or 'n' character followed by zero or more digits. Do we need a separate type for utterance time n? @param expr: C{str} @return: C{boolean} True if expr is of the correct form """ assert isinstance(expr, str), "%s is not a string" % expr return re.match(r'^[tn]\d*$', expr) def is_statevar(expr): """ An state variable must be a single lowercase 's' character followed by zero or more digits. @param expr: C{str} @return: C{boolean} True if expr is of the correct form """ assert isinstance(expr, str), "%s is not a string" % expr return re.match(r'^s\d*$', expr) def is_uttervar(expr): """ An utterance time variable must be a single lowercase 'n' character followed by zero or more digits. @param expr: C{str} @return: C{boolean} True if expr is of the correct form """ assert isinstance(expr, str), "%s is not a string" % expr return re.match(r'^n\d*$', expr) def unique_variable(pattern=None, ignore=None): """ Return a new, unique variable. param pattern: C{Variable} that is being replaced. The new variable must be the same type. param term: a C{set} of C{Variable}s that should not be returned from this function. return: C{Variable} """ if pattern is not None: if is_indvar(pattern.name): prefix = 'z' elif is_funcvar(pattern.name): prefix = 'F' elif is_eventvar(pattern.name): prefix = 'e0' elif is_timevar(pattern.name): prefix = 't0' elif is_statevar(pattern.name): prefix = 's0' else: assert False, "Cannot generate a unique constant" else: prefix = 'z' v = Variable(prefix + str(_counter.get())) while ignore is not None and v in ignore: v = Variable(prefix + str(_counter.get())) return v class TimeVariableExpression(IndividualVariableExpression): """This class represents variables that take the form of a single lowercase 'i' character followed by zero or more digits.""" type = TIME_TYPE class StateVariableExpression(IndividualVariableExpression): """This class represents variables that take the form of a single lowercase 's' character followed by zero or more digits.""" type = STATE_TYPE def is_unary_predicate(expr): """check whether the given expression is an unary predicate""" return isinstance(expr, DrtApplicationExpression) and isinstance(expr.function, DrtAbstractVariableExpression) class ReverseIterator: """A generator which yields the given sequence in a reverse order""" def __init__(self, sequence, start= -1): self.sequence = sequence self.start = start def __iter__(self): if self.start > 0: i = self.start + 1 else: i = len(self.sequence) + self.start + 1 while i > 0: i -= 1 yield self.sequence[i] class Reading(list): """ A single reading, consists of a list of operations each operation is a tuple of a DRS and a function, where the function would be executed on the given DRS when the reading is generated """ pass class Binding(Reading): pass class LocalAccommodation(Reading): pass class IntermediateAccommodation(Reading): pass class GlobalAccommodation(Reading): pass class VariableReplacer(object): """A generic variable replacer functor to be used in readings""" def __init__(self, var, new_var, remove_ref=True): self.var = var self.new_var = new_var self.remove_ref = remove_ref def __call__(self, drs): if self.remove_ref: drs.refs.remove(self.var) return drs.__class__(drs.refs, [cond.replace(self.var, self.new_var, False) for cond in drs.conds]) class ConditionReplacer(object): """ A generic condition replacer functor to be used in readings replace the condition at the given index with any number of conditions, optionally adds a referent """ def __init__(self, index, conds, ref=None): self.index = index self.conds = conds self.ref = ref def __call__(self, drs): if self.ref: drs.refs.append(self.ref) drs.conds[self.index:self.index + 1] = self.conds return drs class ConditionRemover(object): """A generic condition remover functor to be used in readings""" def __init__(self, cond_index): self.cond_index = cond_index def __call__(self, drs): drs.conds.pop(self.cond_index) return drs class ResolutionException(Exception): pass class DrtTokens(drt.DrtTokens): OPEN_BRACE = '{' CLOSE_BRACE = '}' PUNCT = [OPEN_BRACE, CLOSE_BRACE] SYMBOLS = drt.DrtTokens.SYMBOLS + PUNCT TOKENS = drt.DrtTokens.TOKENS + PUNCT NEWINFO_DRS = 'NEWINFO' PROPER_NAME_DRS = 'PROP' DEFINITE_DESCRIPTION_DRS = 'DEF' PRONOUN_DRS = 'PRON' PRESUPPOSITION_DRS = [PROPER_NAME_DRS, DEFINITE_DESCRIPTION_DRS, PRONOUN_DRS] PRONOUN = 'PRO' REFLEXIVE_PRONOUN = 'RPRO' POSSESSIVE_PRONOUN = 'PPRO' class AbstractDrs(drt.AbstractDrs): """ A base abstract DRT Expression from which every DRT Expression inherits. """ def applyto(self, other): return DrtApplicationExpression(self, other) def __neg__(self): return DrtNegatedExpression(self) def __or__(self, other): assert isinstance(other, AbstractDrs) return DrtOrExpression(self, other) def __gt__(self, other): assert isinstance(other, AbstractDrs) return DrtImpExpression(self, other) def __lt__(self, other): assert isinstance(other, AbstractDrs) return DrtIffExpression(self, other) def __add__(self, other): return ConcatenationDRS(self, other) def __deepcopy__(self, memo): return self.deepcopy() def make_EqualityExpression(self, first, second): return DrtEqualityExpression(first, second) def make_VariableExpression(self, variable): return DrtVariableExpression(variable) def normalize(self): """Rename auto-generated unique variables""" def f(e): if isinstance(e, Variable): if re.match(r'^z\d+$', e.name) or re.match(r'^[est]0\d+$', e.name): return set([e]) else: return set([]) else: combinator = lambda * parts: reduce(operator.or_, parts) return e.visit(f, combinator, set()) result = self for i, v in enumerate(sorted(list(f(self)))): if is_eventvar(v.name): newVar = 'e0%s' % (i + 1) elif is_timevar(v.name): newVar = 't0%s' % (i + 1) elif is_statevar(v.name): newVar = 's0%s' % (i + 1) else: newVar = 'z%s' % (i + 1) result = result.replace(v, self.make_VariableExpression(Variable(newVar)), True) return result def substitute_bindings(self, bindings): expr = self for var in expr.variables(): val = bindings.get(var, None) if val: if isinstance(val, Variable): val = DrtVariableExpression(val) elif isinstance(val, Expression): val = val.substitute_bindings(bindings) elif isinstance(val, str): val = DrtFeatureExpression(Variable(val)) else: raise ValueError('Can not substitute a non-expression ' 'value into an expression: %r' % (val,)) expr = expr.replace(var, val) return expr.simplify() RESOLUTION_ORDER = {Binding:0, GlobalAccommodation:1, IntermediateAccommodation:2, LocalAccommodation:3} def resolve(self, inference_check=None, verbose=False): """ This method does the whole job of collecting multiple readings. We aim to get new readings from the old ones by resolving presuppositional DRSs one by one. Every time one presupposition is resolved, new readings are created and replace the old ones, until there are no presuppositions left to resolve. """ readings = [] errors = [] if inference_check: failed_readings = [] def traverse(base_reading, operations): for operation in sorted(operations, key=lambda o: AbstractDrs.RESOLUTION_ORDER[type(o)]): new_reading = base_reading.deepcopy(operation) if verbose: print("reading: %s" % new_reading) try: new_operations = new_reading.readings() except Exception as ex: errors.append(str(ex)) continue if not new_operations: if inference_check: success, error = inference_check(new_reading) if success: readings.append(new_reading) return True else: failed_readings.append((new_reading, error)) else: readings.append(new_reading) else: if traverse(new_reading, new_operations[0]): if len(operations) == 1 or AbstractDrs.RESOLUTION_ORDER[type(operation)] != 0: return True return False operations = self.readings() if operations: traverse(self, operations[0]) else: return [self] if not readings and errors: raise ResolutionException(". ".join(errors)) return readings, failed_readings if inference_check else readings def readings(self, trail=[]): raise NotImplementedError() class DRS(AbstractDrs, drt.DRS): """A Temporal Discourse Representation Structure.""" def fol(self): if not self.conds: raise Exception("Cannot convert DRS with no conditions to FOL.") accum = reduce(AndExpression, [c.fol() for c in self.conds]) for ref in ReverseIterator(self.refs): accum = ExistsExpression(ref, AndExpression(accum, self._ref_type(ref).fol())) return accum def _ref_type(self, referent): """Checks a referent type and returns corresponding predicate""" ref_cond = None if is_eventvar(referent.name): ref_cond = drt.DrtConstantExpression(Variable("event")) elif is_statevar(referent.name): ref_cond = drt.DrtConstantExpression(Variable("state")) elif is_timevar(referent.name): ref_cond = drt.DrtConstantExpression(Variable("time")) else: ref_cond = drt.DrtConstantExpression(Variable("individual")) return DrtApplicationExpression(ref_cond, DrtAbstractVariableExpression(referent)) def replace(self, variable, expression, replace_bound=False): """Replace all instances of variable v with expression E in self, where v is free in self.""" if variable in self.get_refs(): #if a bound variable is the thing being replaced if not replace_bound: return self else: if variable in self.refs: i = self.refs.index(variable) refs = self.refs[:i] + [expression.variable] + self.refs[i + 1:] else: refs = self.refs return self.__class__(refs, [cond.replace(variable, expression, True) for cond in self.conds]) else: #variable not bound by this DRS # any bound variable that appears in the expression must # be alpha converted to avoid a conflict for ref in (set(self.get_refs()) & expression.free()): newvar = unique_variable(ref) newvarex = DrtVariableExpression(newvar) if ref in self.refs: i = self.refs.index(ref) refs = self.refs[:i] + [newvar] + self.refs[i + 1:] else: refs = self.refs self = self.__class__(refs, [cond.replace(ref, newvarex, True) for cond in self.conds]) #replace in the conditions return self.__class__(self.refs, [cond.replace(variable, expression, replace_bound) for cond in self.conds]) def free(self, indvar_only=True): """@see: Expression.free()""" conds_free = reduce(operator.or_, [c.free(indvar_only) for c in self.conds], set()) return conds_free - (set(self.refs) | reduce(operator.or_, [set(c.refs) for c in self.conds if isinstance(c, PresuppositionDRS)], set())) def get_refs(self, recursive=False): """@see: AbstractExpression.get_refs()""" if recursive: cond_refs = reduce(operator.add, [c.get_refs(True) for c in self.conds], []) return self.refs + cond_refs else: return self.refs + reduce(operator.add, [c.refs for c in self.conds if isinstance(c, PresuppositionDRS)], []) def deepcopy(self, operations=[]): """This method returns a deep copy of the DRS. Optionally, it can take a list of lists of tuples (DRS, function) as an argument and generate a reading by performing a substitution in the DRS as specified by the function. @param operations: a list of lists of tuples """ functions = [function for drs, function in operations if drs is self] newdrs = self.__class__(list(self.refs), [cond.deepcopy(operations) for cond in self.conds]) for function in functions: newdrs = function(newdrs) return newdrs def simplify(self): return self.__class__(self.refs, [cond.simplify() for cond in self.conds]) def readings(self, trail=[]): """get the readings for this DRS""" for i, cond in enumerate(self.conds): _readings = cond.readings(trail + [self]) if _readings: if _readings[1]: for reading in _readings[0]: reading.append((self, ConditionRemover(i))) return _readings[0], False def str(self, syntax=DrtTokens.NLTK): if syntax == DrtTokens.PROVER9: return self.fol().str(syntax) else: return '([%s],[%s])' % (','.join([str(r) for r in self.refs]), ', '.join([c.str(syntax) for c in self.conds])) def DrtVariableExpression(variable): """ This is a factory method that instantiates and returns a subtype of C{DrtAbstractVariableExpression} appropriate for the given variable. """ if is_indvar(variable.name): return DrtIndividualVariableExpression(variable) elif is_funcvar(variable.name): return DrtFunctionVariableExpression(variable) elif is_eventvar(variable.name): return DrtEventVariableExpression(variable) elif is_statevar(variable.name): return DrtStateVariableExpression(variable) elif is_uttervar(variable.name): return DrtUtterVariableExpression(variable) elif is_timevar(variable.name): return DrtTimeVariableExpression(variable) else: return DrtConstantExpression(variable) class DrtAbstractVariableExpression(AbstractDrs, drt.DrtAbstractVariableExpression): def readings(self, trail=[]): return None def deepcopy(self, operations=[]): return self.__class__(self.variable) class DrtIndividualVariableExpression(DrtAbstractVariableExpression, drt.DrtIndividualVariableExpression): pass class DrtFunctionVariableExpression(DrtAbstractVariableExpression, drt.DrtFunctionVariableExpression): pass class DrtEventVariableExpression(DrtIndividualVariableExpression, drt.DrtEventVariableExpression): pass class DrtTimeVariableExpression(DrtIndividualVariableExpression, TimeVariableExpression): """expression of discourse referents of time""" pass class DrtStateVariableExpression(DrtIndividualVariableExpression, StateVariableExpression): """expression of discourse referents of state""" pass class DrtConstantExpression(DrtAbstractVariableExpression, drt.DrtConstantExpression): pass class DrtUtterVariableExpression(DrtTimeVariableExpression): """expression of utterance time referent""" pass class DrtFeatureExpression(DrtConstantExpression): """expression for a single syntactic feature""" pass class DrtFeatureConstantExpression(DrtConstantExpression): """A constant expression with syntactic features attached""" def __init__(self, variable, features): DrtConstantExpression.__init__(self, variable) self.features = features def replace(self, variable, expression, replace_bound=False): """@see: Expression.replace()""" assert isinstance(variable, Variable), "%s is not a Variable" % variable assert isinstance(expression, Expression), "%s is not an Expression" % expression return self.__class__(DrtConstantExpression.replace(self, variable, expression, replace_bound).variable, [feature.replace(variable, expression, replace_bound) for feature in self.features]) def visit(self, function, combinator, default): """@see: Expression.visit()""" re = combinator(function(self.variable), reduce(combinator, [function(e) for e in self.features], default)) return re def str(self, syntax=DrtTokens.NLTK): return str(self.variable) + "{" + ",".join([str(feature) for feature in self.features]) + "}" def deepcopy(self, operations=[]): return self.__class__(self.variable, self.features) def fol(self): return DrtConstantExpression(self.variable) class DrtProperNameExpression(DrtConstantExpression): """proper names""" pass class DrtNegatedExpression(AbstractDrs, drt.DrtNegatedExpression): def readings(self, trail=[]): return self.term.readings(trail + [self]) def deepcopy(self, operations=None): return self.__class__(self.term.deepcopy(operations)) class DrtLambdaExpression(AbstractDrs, drt.DrtLambdaExpression): def alpha_convert(self, newvar): """Rename all occurrences of the variable introduced by this variable binder in the expression to @C{newvar}. @param newvar: C{Variable}, for the new variable """ return self.__class__(newvar, self.term.replace(self.variable, DrtVariableExpression(newvar), True)) def replace(self, variable, expression, replace_bound=False): """@see: Expression.replace()""" assert isinstance(variable, Variable), "%s is not a Variable" % variable assert isinstance(expression, Expression), "%s is not an Expression" % expression #if the bound variable is the thing being replaced if self.variable == variable: if replace_bound: assert isinstance(expression, DrtAbstractVariableExpression), \ "%s is not a AbstractVariableExpression" % expression return self.__class__(expression.variable, self.term.replace(variable, expression, True)) else: return self else: # if the bound variable appears in the expression, then it must # be alpha converted to avoid a conflict if self.variable in expression.free(): self = self.alpha_convert(unique_variable(pattern=self.variable)) #replace in the term return self.__class__(self.variable, self.term.replace(variable, expression, replace_bound)) def readings(self, trail=[]): return self.term.readings(trail + [self]) def deepcopy(self, operations=[]): return self.__class__(self.variable, self.term.deepcopy(operations)) def get_refs(self, recursive=False): """@see: AbstractExpression.get_refs()""" return [] class DrtBooleanExpression(AbstractDrs, drt.DrtBooleanExpression): def readings(self, trail=[]): first_readings = self.first.readings(trail + [self]) if first_readings: return first_readings else: return self.second.readings(trail + [self]) def deepcopy(self, operations=[]): return self.__class__(self.first.deepcopy(operations), self.second.deepcopy(operations)) def simplify(self): """When dealing with DRSs, it is good to have unique names for the referents bound by each DRS.""" if isinstance(self.first, DRS) and isinstance(self.second, DRS): new_second = self.second for ref in set(self.first.get_refs(True)) & set(self.second.get_refs(True)): newref = DrtVariableExpression(unique_variable(ref)) new_second = self.second.replace(ref, newref, True) return drt.DrtBooleanExpression.simplify(self.__class__(self.first, new_second)) else: return drt.DrtBooleanExpression.simplify(self) class DrtOrExpression(DrtBooleanExpression, drt.DrtOrExpression): pass class DrtImpExpression(DrtBooleanExpression, drt.DrtImpExpression): def readings(self, trail=[]): first_readings = self.first.readings(trail + [self]) if first_readings: return first_readings else: return self.second.readings(trail + [self, self.first]) def __eq__(self, other): if (isinstance(self, other.__class__) or isinstance(other, self.__class__)): if isinstance(self.first, DRS) and isinstance(self.second, DRS) and isinstance(other.first, DRS) and isinstance(other.second, DRS): if len(self.first.conds) == len(other.first.conds) and len(self.second.conds) == len(other.second.conds): for (r1, r2) in zip(self.first.refs + self.second.refs, other.first.refs + other.second.refs): varex = self.make_VariableExpression(r1) other = other.replace(r2, varex, True) return self.first.conds == other.first.conds and self.second.conds == other.second.conds else: return self.first == other.first and self.second == other.second return False class DrtIffExpression(DrtBooleanExpression, drt.DrtIffExpression): pass class DrtEqualityExpression(AbstractDrs, drt.DrtEqualityExpression): def readings(self, trail=[]): return None def deepcopy(self, operations=[]): return self.__class__(self.first.deepcopy(operations), self.second.deepcopy(operations)) class ConcatenationDRS(DrtBooleanExpression, drt.ConcatenationDRS): """DRS of the form '(DRS + DRS)'""" def replace(self, variable, expression, replace_bound=False): """Replace all instances of variable v with expression E in self, where v is free in self.""" first = self.first second = self.second # If variable is bound by both first and second if isinstance(first, DRS) and isinstance(second, DRS) and \ variable in (set(first.get_refs(True)) & set(second.get_refs(True))): first = first.replace(variable, expression, True) second = second.replace(variable, expression, True) # If variable is bound by first elif isinstance(first, DRS) and variable in first.refs: if replace_bound: first = first.replace(variable, expression, replace_bound) second = second.replace(variable, expression, replace_bound) # If variable is bound by second elif isinstance(second, DRS) and variable in second.refs: if replace_bound: first = first.replace(variable, expression, replace_bound) second = second.replace(variable, expression, replace_bound) else: # alpha convert every ref that is free in 'expression' for ref in (set(self.get_refs(True)) & expression.free()): v = DrtVariableExpression(unique_variable(ref)) first = first.replace(ref, v, True) second = second.replace(ref, v, True) first = first.replace(variable, expression, replace_bound) second = second.replace(variable, expression, replace_bound) return self.__class__(first, second) def simplify(self): first = self.first.simplify() second = self.second.simplify() if isinstance(first, DRS) and isinstance(second, DRS): # For any ref that is in both 'first' and 'second' for ref in (set(first.get_refs(True)) & set(second.get_refs(True))): # alpha convert the ref in 'second' to prevent collision newvar = DrtVariableExpression(unique_variable(ref)) second = second.replace(ref, newvar, True) #DRS type is derived from the first member or from the second one drs_type = first.__class__ if isinstance(first, PresuppositionDRS) else second.__class__ return drs_type(first.refs + second.refs, first.conds + second.conds) else: return self.__class__(first, second) class DrtApplicationExpression(AbstractDrs, drt.DrtApplicationExpression): def fol(self): if self.is_propername(): return EqualityExpression(self.function.fol(), self.argument.fol()) else: return ApplicationExpression(self.function.fol(), self.argument.fol()) def is_propername(self): """ A proper name is capitalised. We assume that John(x) uniquely identifies the bearer of the name John and so, when going from Kamp & Reyle's DRT format into classical FOL logic, we change a condition like that into John = x. @return: C{boolean} True if expr is of the correct form """ return isinstance(self.function, DrtConstantExpression) and\ self.function.variable.name.istitle() def readings(self, trail=[]): function_readings = self.function.readings(trail + [self]) if function_readings: return function_readings else: return self.argument.readings(trail + [self]) def deepcopy(self, operations=[]): return self.__class__(self.function.deepcopy(operations), self.argument.deepcopy(operations)) class DrtEventualityApplicationExpression(DrtApplicationExpression): """application expression with state or event argument""" pass class PresuppositionDRS(DRS): def readings(self, trail=[]): inner_readings = DRS.readings(self, trail) if inner_readings: return inner_readings else: self._init_presupp_data() return self._presupposition_readings(trail) def _find_outer_drs(self, trail): for expr in trail: if expr.__class__ is DRS: return expr def _find_local_drs(self, trail): drs = None for expr in ReverseIterator(trail): if drs: if not isinstance(expr, DrtNegatedExpression): return drs else: drs = None if expr.__class__ is DRS: drs = expr return drs def is_possible_binding(self, cond): return is_unary_predicate(cond) and self.has_same_features(cond) and cond.argument.__class__ is DrtIndividualVariableExpression def find_bindings(self, trail, collect_event_data=False, filter=lambda x: type(x) is DRS, individuals=None): bindings = [] if collect_event_data: event_data_map = {} event_strings_map = {} is_bindable = True # do not allow forward binding for drs in (expr for expr in trail if filter(expr)): for cond in drs.conds: # Ignore conditions following the presupposition DRS if cond is self: if not collect_event_data: break # assuming that the filtered_trail has drss ordered from the outermost to the innermost if not isinstance(cond, DrtApplicationExpression): continue is_bindable = False if is_bindable and self.is_possible_binding(cond): bindings.append(cond) if collect_event_data: self.collect_event_data(cond, event_data_map, event_strings_map, individuals) if collect_event_data: self._enrich_event_data_map(event_data_map, event_strings_map) return (bindings, event_data_map) if collect_event_data else bindings def collect_event_data(self, cond, event_data_map, event_strings_map, individuals=None): if isinstance(cond.function, DrtApplicationExpression) and \ isinstance(cond.argument, DrtIndividualVariableExpression) and not isinstance(cond.argument, DrtTimeVariableExpression): event_data_map.setdefault(cond.argument.variable, []).append((cond.function.argument, cond.function.function.variable.name)) elif cond.__class__ == DrtEventualityApplicationExpression and \ (isinstance(cond.argument, DrtEventVariableExpression) or isinstance(cond.argument, DrtStateVariableExpression)) and\ not isinstance(cond.function, DrtApplicationExpression): assert cond.argument not in event_strings_map event_strings_map[cond.argument] = cond.function.variable.name # The rest are nouns and attributive adjectives elif individuals is not None and cond.__class__ == DrtApplicationExpression and \ not isinstance(cond.function, DrtApplicationExpression): individuals.setdefault(cond.argument.variable, []).append(cond) def _enrich_event_data_map(self, event_data_map, event_strings_map): for individual in event_data_map: new_event_list = [] for event_tuple in event_data_map[individual]: new_event_list.append((event_tuple[0], event_tuple[1], event_strings_map.get(event_tuple[0], None))) event_data_map[individual] = new_event_list def is_presupposition_cond(self, cond): return True def _init_presupp_data(self): presupp_cond_list = [cond for cond in self.conds if is_unary_predicate(cond) and cond.argument.variable == self.refs[0] and self.is_presupposition_cond(cond)] for cond in presupp_cond_list: if isinstance(cond.function, DrtFeatureConstantExpression): # this is the one # There can be more than one DrtFeatureConstantExpression on the conditions on list, e.g. # "Tom, a kind boy, took her hand", or "Tom, who is a kind boy,...", or "Linguist Grimm suggested ...", # or "The distinguished physicist Einstein ...". But 'is_presupposition_cond' helps us find the right one. self.variable = cond.argument.variable self.features = cond.function.features self.function_name = cond.function.variable.name self.cond = cond return self.variable = self.refs[0] self.features = None self.function_name = presupp_cond_list[0].variable.name self.cond = presupp_cond_list[0] def has_same_features(self, cond): return (not isinstance(cond.function, DrtFeatureConstantExpression) and not self.features) \ or (isinstance(cond.function, DrtFeatureConstantExpression) and cond.function.features == self.features) def _get_condition_index(self, superordinate_drs, trail, condition_index_cache={}): # Keep a condition index cache if not condition_index_cache: condition_index_cache = {} superordinate_drs_index = id(superordinate_drs) if superordinate_drs_index in condition_index_cache: return condition_index_cache[superordinate_drs_index] # Use a for loop and 'is' to find the condition. # Do not use index(), because it calls a time-consuming equals method. for ind, trailee in enumerate(trail): if trailee is superordinate_drs: # The condition might be not in superordinate_drs, but inside one of its conditions (however deep we might need to go) look_for = trail[ind + 1] if ind < len(trail) - 1 else self for i, cond in enumerate(superordinate_drs.conds): if cond is look_for: condition_index_cache[superordinate_drs_index] = i return i # condition_index return None class Operation(object): """An interface for all operations""" def __call__(self, drs): raise NotImplementedError class Accommodate(Operation): def __init__(self, presupp_drs, condition_index): # We need the condition index so that the conditions are not just appended to the list of conditions of the DRS, # but inserted where the presuppositional DRS had been. The order of conditions is important, because it reflects # the proximity of a possible antecedent, which affects antecedent ranking (and our architecture does not allow us to use the # index on the list of referents to reflect the proximity/thematic role). self.presupp_drs = presupp_drs self.condition_index = condition_index def __call__(self, drs): """Accommodation: put all referents and conditions from the presupposition DRS into the given DRS""" drs.refs.extend(self.presupp_drs.refs) if self.condition_index is None: drs.conds.extend(self.presupp_drs.conds) else: drs.conds = drs.conds[:self.condition_index + 1] + self.presupp_drs.conds + drs.conds[self.condition_index + 1:] return drs class Bind(Operation): def __init__(self, presupp_drs, presupp_variable, presupp_funcname, antecedent_cond, condition_index): self.presupp_drs = presupp_drs self.presupp_variable = presupp_variable self.presupp_funcname = presupp_funcname self.antecedent_cond = antecedent_cond self.condition_index = condition_index def __call__(self, drs): """Put all conditions from the presuppositional DRS into the DRS (but do not create duplicates), and replace the presupposition condition referent in them with antecedent referent""" newdrs = self.presupp_drs.replace(self.presupp_variable, self.antecedent_cond.argument, True) # There will be referents and conditions to move # if there is a relative clause modifying the noun that has triggered the presuppositon drs.refs.extend([ref for ref in newdrs.refs \ if ref != self.antecedent_cond.argument.variable]) conds_to_move = [cond for cond in newdrs.conds \ if not cond in drs.conds] # Put the conditions at the position of the original presupposition DRS if self.condition_index is None: # it is an index, it can be zero drs.conds.extend(conds_to_move) else: drs.conds = drs.conds[:self.condition_index + 1] + conds_to_move + drs.conds[self.condition_index + 1:] return drs class InnerReplace(Operation): def __init__(self, presupp_variable, antecedent_ref): self.presupp_variable = presupp_variable self.antecedent_ref = antecedent_ref def __call__(self, drs): """In the conditions of the local DRS, replace the referent of the presupposition condition with antecedent_ref""" return drs.replace(self.presupp_variable, self.antecedent_ref, True) class MoveTemporalConditions(Operation): def __init__(self, temporal_conditions): self.temporal_conditions = temporal_conditions def __call__(self, drs): drs.conds.extend(self.temporal_conditions) return drs class DoMultipleOperations(Operation): def __init__(self, operations_list): self.operations_list = operations_list def __call__(self, drs): """Do the operations one by one""" for operation in self.operations_list: drs = operation(drs) return drs def binding_reading(self, inner_drs, target_drs, antecedent_cond, trail, temporal_conditions=None, local_drs=None): condition_index = self._get_condition_index(target_drs, trail) binder = self.Bind(self, self.variable, self.function_name, antecedent_cond, condition_index) inner_replacer = self.InnerReplace(self.variable, antecedent_cond.argument) temp_cond_mover = self.MoveTemporalConditions(temporal_conditions) if temporal_conditions else None if inner_drs is target_drs: if temp_cond_mover: if local_drs is target_drs: return Binding([(inner_drs, binder), (inner_drs, temp_cond_mover), (inner_drs, inner_replacer)]) else: return Binding([(local_drs, temp_cond_mover), (inner_drs, binder), (inner_drs, inner_replacer)]) else: return Binding([(inner_drs, binder), (inner_drs, inner_replacer)]) else: if temp_cond_mover: if local_drs is target_drs: return Binding([(target_drs, binder), (target_drs, temp_cond_mover), (inner_drs, inner_replacer)]) elif local_drs is inner_drs: return Binding([(target_drs, binder), (inner_drs, temp_cond_mover), (inner_drs, inner_replacer)]) else: return Binding([(target_drs, binder), (local_drs, temp_cond_mover), (inner_drs, inner_replacer)]) else: return Binding([(target_drs, binder), (inner_drs, inner_replacer)]) def accommodation_reading(self, target_drs, trail, temporal_conditions=None, local_drs=None, reading_type=Binding): condition_index = self._get_condition_index(target_drs, trail) accommodator = self.Accommodate(self, condition_index) if temporal_conditions: temp_cond_mover = self.MoveTemporalConditions(temporal_conditions) if local_drs is target_drs: return reading_type([(target_drs, temp_cond_mover), (target_drs, accommodator)]) else: return reading_type([(target_drs, accommodator), (local_drs, temp_cond_mover)]) else: return reading_type([(target_drs, accommodator)]) class PronounDRS(PresuppositionDRS): """ A class for DRSs for personal, reflexive, and possessive pronouns """ PRONOUNS = [DrtTokens.PRONOUN, DrtTokens.REFLEXIVE_PRONOUN, DrtTokens.POSSESSIVE_PRONOUN] def is_presupposition_cond(self, cond): return cond.function.variable.name in PronounDRS.PRONOUNS def _presupposition_readings(self, trail=[]): #trail[0].draw() possible_bindings, event_data = self.find_bindings(trail, True, filter=lambda x: x.__class__ is DRS or isinstance(x, PresuppositionDRS)) bindings = [cond for cond in possible_bindings if self._is_binding(cond, self._get_pro_events(event_data), event_data)] ranked_bindings = self._rank_bindings(bindings, event_data) return [Binding([(trail[-1], VariableReplacer(self.variable, cond.argument, False))]) for cond, rank in sorted(ranked_bindings, key=lambda e: e[1], reverse=True)], True def _get_pro_events(self, event_data): #in case pronoun participates in only one eventuality, which has no other participants, #try to extend it with interlinked eventualities #f.e. THEME(z5,z3), THEME(e,z5) where z3 only participates in eventuality z5 #will be extended to participate in e, but only in case z5 has one participant pro_events = [event for event, role, event_string in event_data.get(self.variable, ())] if len(pro_events) == 1: pro_event = pro_events[0] #number of participants in the pro_event participant_count = sum((1 for event_list in event_data.itervalues() for event, role, event_string in event_list if event == pro_event)) # if there is only one participant in the pro_event and pro_event itself participates in other eventualities if participant_count == 1 and pro_event.variable in event_data: pro_events.extend((event for event, role, event_string in event_data[pro_event.variable])) return set(pro_events) def _rank_bindings(self, bindings, event_data): #ranking system #increment ranking for matching roles and map the positions of antecedents if len(bindings) == 0: raise AnaphoraResolutionException("Variable '%s' does not " "resolve to anything." % self.variable) elif len(bindings) == 1: bindings[0] = (bindings[0], 0) else: pro_roles = set((role for event, role, event_string in event_data.get(self.variable, ()))) for index, variable in enumerate(bindings): var_roles = set((role for event_list in event_data.get(variable, ()) for event, role, event_string in event_list)) bindings[index] = (variable, index + len(var_roles.intersection(pro_roles))) return bindings def _is_binding(self, cond, pro_events, event_data): #non reflexive pronouns can not resolve to variables having a role in the same eventuality if self.function_name == DrtTokens.POSSESSIVE_PRONOUN: return True else: variable = cond.argument.variable variable_events = set((event for event, role, event_string in event_data.get(variable, ()))) if self.function_name == DrtTokens.PRONOUN: return variable_events.isdisjoint(pro_events) elif self.function_name == DrtTokens.REFLEXIVE_PRONOUN: return not variable_events.isdisjoint(pro_events) else: return True class ProperNameDRS(PresuppositionDRS): def _presupposition_readings(self, trail=[]): """A proper name always has one reading: it is either global binding or global accommodation (if binding is not possible)""" outer_drs = self._find_outer_drs(trail) inner_drs = trail[-1] possible_bindings = self.find_bindings([outer_drs]) assert len(possible_bindings) <= 1 if possible_bindings: # Return the reading return [self.binding_reading(inner_drs, outer_drs, possible_bindings[0], trail)], True # If no suitable antecedent has been found in the outer DRS, # binding is not possible, so we go for accommodation instead. return [self.accommodation_reading(outer_drs, trail)], True def is_possible_binding(self, cond): return super(ProperNameDRS, self).is_possible_binding(cond) and cond.is_propername() and cond.function.variable.name == self.function_name def is_presupposition_cond(self, cond): return cond.is_propername() class DefiniteDescriptionDRS(PresuppositionDRS): def _presupposition_readings(self, trail=[], overgenerate=False, generate_intermediate=True): # If there is a restrictive clause or an adjunct PP, find the perfect binding or accommodate the presupposition presupp_event_data = {} presupp_event_strings = {} presupp_individuals = {} # Are there any states/events in this presuppositional DRS that the presupposition referent takes part in? for cond in (c for c in self.conds if isinstance(c, DrtApplicationExpression)): self.collect_event_data(cond, presupp_event_data, presupp_event_strings, presupp_individuals) self._enrich_event_data_map(presupp_event_data, presupp_event_strings) possible_bindings = {} event_data = {} individuals = {} accommod_indices = set() intermediate_next = False # find the closest antecedent DRS outer_drs = self._find_outer_drs(trail) local_drs = self._find_local_drs(trail) all_refs = [] free, temporal_conditions = self._get_free() # Go through the filtered trail, find bindings and find the intermediate DRS for possible accommodation for index, drs in enumerate(trail): if isinstance(drs, DrtImpExpression): intermediate_next = True if not drs.__class__ is DRS: continue # Free variable check if not self._free_variable_check(drs, free, all_refs): intermediate_next = False continue # Find the (maximum) three DRSs if drs is outer_drs or drs is local_drs or intermediate_next: accommod_indices.add(index) intermediate_next = False # Find the bindings drs_possible_bindings, drs_event_data = self.find_bindings([drs], True, individuals=individuals) for var in drs_event_data: event_data.setdefault(var, []).extend(drs_event_data[var]) if drs_possible_bindings: possible_bindings[index] = drs_possible_bindings # Make accommodation indices a sorted list accommod_indices = sorted(list(accommod_indices)) def accommodation_cite(drsindex):#LocalAccommodation, IntermediateAccommodation, GlobalAccommodation if not drsindex in accommod_indices: return None ind = accommod_indices.index(drsindex) if ind == 0: return [LocalAccommodation, GlobalAccommodation, GlobalAccommodation][len(accommod_indices) - 1] elif ind == 1: return [LocalAccommodation, IntermediateAccommodation][len(accommod_indices) - 2] else: assert ind == 2 return LocalAccommodation # Filter the bindings, create the readings antecedent_tracker = [] # do not bind to the same referent twice readings = [] inner_drs = trail[-1] for drsindex, drs in enumerate(trail): drs_readings = [] if drsindex in possible_bindings: for cond in ReverseIterator(possible_bindings[drsindex]): variable = cond.argument.variable if self._is_binding(variable, individuals[variable], self._get_defdescr_events(event_data), event_data, presupp_event_data, presupp_individuals) and \ not cond.argument in antecedent_tracker: antecedent_tracker.append(cond.argument) drs_readings.append(self.binding_reading(inner_drs, drs, \ cond, trail, temporal_conditions, local_drs)) # If binding is possible, no accommodation at this level or below will take place # (unless we set the 'overgenerate' parameter to True) if not overgenerate and drs_readings: accommod_indices = [None] else: acc_cite = accommodation_cite(drsindex) if acc_cite and not (generate_intermediate is False and acc_cite is IntermediateAccommodation): drs_readings.append(self.accommodation_reading(drs, trail, temporal_conditions, local_drs, acc_cite)) accommod_indices.remove(drsindex) readings.extend(drs_readings) return readings, True def _get_free(self): free = self.free(True) return free, [] def _get_defdescr_events(self, event_data): return [item[0] for item in event_data.get(self.variable, ())] def _is_binding(self, variable, var_individuals, defdescr_events, event_data, presupp_event_data, presupp_individuals): # No binding is possible to variables having a role in the same eventuality (look for eventualities in DRSs other than self) variable_events = set((event for event, role, event_string in event_data.get(variable, ()))) if not variable_events.isdisjoint(defdescr_events): return False # Don't allow binding if the potential antecedent participates in the same eventuality (in the relative clause) as self.variable, e.g.: # If John has a child, the child that likes him (him = the child in the antecedent of the impl. cond) is away. variable_presupp_events = set((event for event, role, event_string in presupp_event_data.get(variable, ()))) defdescr_presupp_events = set((event for event, role, event_string in presupp_event_data.get(self.variable, ()))) if not variable_presupp_events.isdisjoint(defdescr_presupp_events): return False # Don't allow binding x to y if there are conditions like POSS(x,y), POSS(y,x), REL(x,y), REL(y,x) and suchlike for event_tuple in presupp_event_data.get(variable, []): event = event_tuple[0] if event.__class__ == DrtIndividualVariableExpression and event.variable == self.variable: return False for event_tuple in presupp_event_data.get(self.variable, []): event = event_tuple[0] if event.__class__ == DrtIndividualVariableExpression and event.variable == variable: return False # Perform the semantic check return self.semantic_check(var_individuals, presupp_individuals) def semantic_check(self, individuals, presupp_individuals, strict=False): """ Users can plug in their more sophisticated semantic checks here. As for this project, we confine ourselves to ontologies provided by WordNet. See the other file for how this is supposed to work.""" if strict: # ------------------------ Plug in ontologies here if isinstance(self.cond, DrtFeatureConstantExpression): for individual in individuals: if isinstance(individual, DrtFeatureConstantExpression) and self.function_name == individual.function.variable.name: return True return False else: # If no features are used, we cannot guarantee that the condition we got self.function_name from wasn't an adjective for individual in individuals: for presupp_individual in presupp_individuals[self.variable]: if presupp_individual.function.variable.name == individual.function.variable.name: return True return False else: return True def _free_variable_check(self, drs, free, all_refs): if free: all_refs.extend(drs.refs) for variable in free: if not variable in all_refs: return False return True class DrtParser(drt.DrtParser): def get_all_symbols(self): return DrtTokens.SYMBOLS def isvariable(self, tok): return tok not in DrtTokens.TOKENS def handle(self, tok, context): """We add new types of DRS to represent presuppositions""" if tok.upper() in DrtTokens.PRESUPPOSITION_DRS: return self.handle_PresuppositionDRS(tok.upper(), context) else: return drt.DrtParser.handle(self, tok, context) def handle_PresuppositionDRS(self, tok, context): """Parse all the Presuppositon DRSs.""" self.assertNextToken(DrtTokens.OPEN) drs = self.handle_DRS(tok, context) if tok == DrtTokens.PROPER_NAME_DRS: return ProperNameDRS(drs.refs, drs.conds) elif tok == DrtTokens.DEFINITE_DESCRIPTION_DRS: return DefiniteDescriptionDRS(drs.refs, drs.conds) elif tok == DrtTokens.PRONOUN_DRS: return PronounDRS(drs.refs, drs.conds) def handle_variable(self, tok, context): #It's either: 1) a predicate expression: sees(x,y) # 2) an application expression: P(x) # 3) a solo variable: john OR x accum = self.make_VariableExpression(tok) # handle the feature structure of the variable features = [] try: if self.token(0) == DrtTokens.OPEN_BRACE: self.token() # swallow the OPEN_BRACE while self.token(0) != DrtTokens.CLOSE_BRACE: features.append(DrtFeatureExpression(Variable(self.token()))) if self.token(0) == drt.DrtTokens.COMMA: self.token() # swallow the comma self.token() # swallow the CLOSE_BRACE except ParseException: #we've reached the end of input, this constant has no features pass if self.inRange(0) and self.token(0) == DrtTokens.OPEN: if features: accum = DrtFeatureConstantExpression(accum.variable, features) #The predicate has arguments if isinstance(accum, drt.DrtIndividualVariableExpression): raise ParseException(self._currentIndex, '\'%s\' is an illegal predicate name. ' 'Individual variables may not be used as ' 'predicates.' % tok) self.token() #swallow the Open Paren #curry the arguments accum = self.make_ApplicationExpression(accum, self.parse_Expression('APP')) while self.inRange(0) and self.token(0) == DrtTokens.COMMA: self.token() #swallow the comma accum = self.make_ApplicationExpression(accum, self.parse_Expression('APP')) self.assertNextToken(DrtTokens.CLOSE) elif features: accum = DrtFeatureConstantExpression(accum.variable, map(Variable, features)) return accum def handle_DRS(self, tok, context): drs = drt.DrtParser.handle_DRS(self, tok, context) return DRS(drs.refs, drs.conds) def get_BooleanExpression_factory(self, tok): """This method serves as a hook for other logic parsers that have different boolean operators""" if tok == DrtTokens.DRS_CONC: return ConcatenationDRS elif tok in DrtTokens.OR: return DrtOrExpression elif tok in DrtTokens.IMP: return DrtImpExpression elif tok in DrtTokens.IFF: return DrtIffExpression else: return None def make_VariableExpression(self, name): return DrtVariableExpression(Variable(name)) def make_ApplicationExpression(self, function, argument): return DrtApplicationExpression(function, argument) def make_ConstantExpression(self, name): return DrtConstantExpression(Variable(name)) def make_NegatedExpression(self, expression): return DrtNegatedExpression(expression) def make_EqualityExpression(self, first, second): """This method serves as a hook for other logic parsers that have different equality expression classes""" return DrtEqualityExpression(first, second) def make_LambdaExpression(self, variables, term): return DrtLambdaExpression(variables, term)
[ "nltk.sem.logic.ParseException", "nltk.sem.drt.DrtBooleanExpression.simplify", "re.match", "nltk.sem.logic.Variable", "nltk.sem.logic.is_eventvar", "nltk.sem.logic._counter.get", "nltk.sem.logic.is_funcvar", "nltk.sem.drt.DrtParser.handle_DRS", "nltk.sem.drt.DrtParser.handle", "nltk.sem.drt.Anapho...
[((1392, 1430), 're.match', 're.match', (['"""^[a-df-mo-ru-z]\\\\d*$"""', 'expr'], {}), "('^[a-df-mo-ru-z]\\\\d*$', expr)\n", (1400, 1430), False, 'import re\n'), ((1788, 1816), 're.match', 're.match', (['"""^[tn]\\\\d*$"""', 'expr'], {}), "('^[tn]\\\\d*$', expr)\n", (1796, 1816), False, 'import re\n'), ((2121, 2146), 're.match', 're.match', (['"""^s\\\\d*$"""', 'expr'], {}), "('^s\\\\d*$', expr)\n", (2129, 2146), False, 'import re\n'), ((2460, 2485), 're.match', 're.match', (['"""^n\\\\d*$"""', 'expr'], {}), "('^n\\\\d*$', expr)\n", (2468, 2485), False, 'import re\n'), ((12314, 12340), 'nltk.sem.logic.is_eventvar', 'is_eventvar', (['referent.name'], {}), '(referent.name)\n', (12325, 12340), False, 'from nltk.sem.logic import _counter, is_eventvar, is_funcvar\n'), ((17017, 17042), 'nltk.sem.logic.is_funcvar', 'is_funcvar', (['variable.name'], {}), '(variable.name)\n', (17027, 17042), False, 'from nltk.sem.logic import _counter, is_eventvar, is_funcvar\n'), ((57452, 57496), 'nltk.sem.drt.DrtParser.handle_DRS', 'drt.DrtParser.handle_DRS', (['self', 'tok', 'context'], {}), '(self, tok, context)\n', (57476, 57496), True, 'import nltk.sem.drt as drt\n'), ((2909, 2933), 'nltk.sem.logic.is_funcvar', 'is_funcvar', (['pattern.name'], {}), '(pattern.name)\n', (2919, 2933), False, 'from nltk.sem.logic import _counter, is_eventvar, is_funcvar\n'), ((8251, 8270), 'nltk.sem.logic.is_eventvar', 'is_eventvar', (['v.name'], {}), '(v.name)\n', (8262, 8270), False, 'from nltk.sem.logic import _counter, is_eventvar, is_funcvar\n'), ((17108, 17134), 'nltk.sem.logic.is_eventvar', 'is_eventvar', (['variable.name'], {}), '(variable.name)\n', (17119, 17134), False, 'from nltk.sem.logic import _counter, is_eventvar, is_funcvar\n'), ((23392, 23431), 'nltk.sem.drt.DrtBooleanExpression.simplify', 'drt.DrtBooleanExpression.simplify', (['self'], {}), '(self)\n', (23425, 23431), True, 'import nltk.sem.drt as drt\n'), ((43982, 44076), 'nltk.sem.drt.AnaphoraResolutionException', 'AnaphoraResolutionException', (['("Variable \'%s\' does not resolve to anything." % self.variable)'], {}), '("Variable \'%s\' does not resolve to anything." %\n self.variable)\n', (44009, 44076), False, 'from nltk.sem.drt import DrsDrawer, AnaphoraResolutionException\n'), ((54699, 54739), 'nltk.sem.drt.DrtParser.handle', 'drt.DrtParser.handle', (['self', 'tok', 'context'], {}), '(self, tok, context)\n', (54719, 54739), True, 'import nltk.sem.drt as drt\n'), ((58122, 58136), 'nltk.sem.logic.Variable', 'Variable', (['name'], {}), '(name)\n', (58130, 58136), False, 'from nltk.sem.logic import Variable\n'), ((58348, 58362), 'nltk.sem.logic.Variable', 'Variable', (['name'], {}), '(name)\n', (58356, 58362), False, 'from nltk.sem.logic import Variable\n'), ((2973, 2998), 'nltk.sem.logic.is_eventvar', 'is_eventvar', (['pattern.name'], {}), '(pattern.name)\n', (2984, 2998), False, 'from nltk.sem.logic import _counter, is_eventvar, is_funcvar\n'), ((3303, 3317), 'nltk.sem.logic._counter.get', '_counter.get', ([], {}), '()\n', (3315, 3317), False, 'from nltk.sem.logic import _counter, is_eventvar, is_funcvar\n'), ((12391, 12408), 'nltk.sem.logic.Variable', 'Variable', (['"""event"""'], {}), "('event')\n", (12399, 12408), False, 'from nltk.sem.logic import Variable\n'), ((56457, 56598), 'nltk.sem.logic.ParseException', 'ParseException', (['self._currentIndex', '("\'%s\' is an illegal predicate name. Individual variables may not be used as predicates."\n % tok)'], {}), '(self._currentIndex, \n "\'%s\' is an illegal predicate name. Individual variables may not be used as predicates."\n % tok)\n', (56471, 56598), False, 'from nltk.sem.logic import ParseException\n'), ((3400, 3414), 'nltk.sem.logic._counter.get', '_counter.get', ([], {}), '()\n', (3412, 3414), False, 'from nltk.sem.logic import _counter, is_eventvar, is_funcvar\n'), ((7848, 7875), 're.match', 're.match', (['"""^z\\\\d+$"""', 'e.name'], {}), "('^z\\\\d+$', e.name)\n", (7856, 7875), False, 'import re\n'), ((7879, 7911), 're.match', 're.match', (['"""^[est]0\\\\d+$"""', 'e.name'], {}), "('^[est]0\\\\d+$', e.name)\n", (7887, 7911), False, 'import re\n'), ((8624, 8640), 'nltk.sem.logic.Variable', 'Variable', (['newVar'], {}), '(newVar)\n', (8632, 8640), False, 'from nltk.sem.logic import Variable\n'), ((12500, 12517), 'nltk.sem.logic.Variable', 'Variable', (['"""state"""'], {}), "('state')\n", (12508, 12517), False, 'from nltk.sem.logic import Variable\n'), ((12608, 12624), 'nltk.sem.logic.Variable', 'Variable', (['"""time"""'], {}), "('time')\n", (12616, 12624), False, 'from nltk.sem.logic import Variable\n'), ((12689, 12711), 'nltk.sem.logic.Variable', 'Variable', (['"""individual"""'], {}), "('individual')\n", (12697, 12711), False, 'from nltk.sem.logic import Variable\n'), ((9139, 9152), 'nltk.sem.logic.Variable', 'Variable', (['val'], {}), '(val)\n', (9147, 9152), False, 'from nltk.sem.logic import Variable\n')]
from openem.models import ImageModel from openem.models import Preprocessor import cv2 import numpy as np import tensorflow as tf from collections import namedtuple import csv Detection=namedtuple('Detection', ['location', 'confidence', 'species', 'frame', 'video_id']) # Bring in SSD detector to top-level from openem.Detect.SSD import SSDDetector class IO: def from_csv(filepath_like): detections=[] with open(filepath_like, 'r') as csv_file: reader = csv.DictReader(csv_file) last_idx = -1 for row in reader: location=np.array([float(row['x']), float(row['y']), float(row['w']), float(row['h'])]) item = Detection(location=location, confidence=float(row['detection_conf']), species=int(float(row['detection_species'])), frame=int(row['frame']), video_id=row['video_id']) frame_num = int(float(row['frame'])) if last_idx == frame_num: detections[last_idx].append(item) else: # Add empties for _ in range(frame_num-1-last_idx): detections.append([]) detections.append([item]) last_idx = frame_num return detections
[ "collections.namedtuple", "csv.DictReader" ]
[((189, 276), 'collections.namedtuple', 'namedtuple', (['"""Detection"""', "['location', 'confidence', 'species', 'frame', 'video_id']"], {}), "('Detection', ['location', 'confidence', 'species', 'frame',\n 'video_id'])\n", (199, 276), False, 'from collections import namedtuple\n'), ((631, 655), 'csv.DictReader', 'csv.DictReader', (['csv_file'], {}), '(csv_file)\n', (645, 655), False, 'import csv\n')]
# -*- coding: utf-8 -*- import asyncio import datetime import importlib import io import json import logging import os import platform import re import subprocess import sys import textwrap import traceback from contextlib import redirect_stderr, redirect_stdout from functools import partial from glob import glob from logging import WARNING, getLogger from typing import Any, Callable, List, Optional, Tuple, Union import aiohttp from aioconsole import ainput from aiofiles import open as aopen from aiofiles.os import remove as aremove from tzlocal import get_localzone from .auth import MyAdvancedAuth from .auto_updater import Updater from .client import Client, MyClientParty, MyClientPartyMember from .colors import cyan, green, yellow from .commands import Command, DefaultCommands, MyMessage, PartyPrivacy from .cosmetics import CaseInsensitiveDict, Searcher from .discord_client import DiscordClient from .encoder import MyJSONEncoder from .formatter import EvalFormatter from .http import HTTPClient from .localize import LocalizedText from .web import Web, WebMessage, WebUser from .webhook import WebhookClient if (os.getenv('REPLIT_DB_URL') is not None and os.getcwd().startswith('/home/runner') and sys.platform == 'linux'): from replit import db else: db = None discord = importlib.import_module('discord') fortnitepy = importlib.import_module('fortnitepy') _ = importlib.import_module('pykakasi') kakasi = _.kakasi Message = Union[ fortnitepy.FriendMessage, fortnitepy.PartyMessage, discord.Message, WebMessage ] Author = Union[ fortnitepy.Friend, fortnitepy.PartyMember, discord.User, discord.Member, WebUser ] class Bot: BACKEND_TO_API_CONVERTER = { 'AthenaBackpack': 'backpack', 'AthenaPickaxe': 'pickaxe', 'AthenaItemWrap': 'wrap', 'AthenaGlider': 'glider', 'AthenaCharacter': 'outfit', 'AthenaPet': 'pet', 'AthenaMusicPack': 'music', 'AthenaLoadingScreen': 'loadingscreen', 'AthenaDance': 'emote', 'AthenaSpray': 'spray', 'AthenaEmoji': 'emoji', 'AthenaSkyDiveContrail': 'contrail', 'AthenaPetCarrier': 'petcarrier', 'AthenaToy': 'toy', 'AthenaConsumableEmote': 'consumableemote', 'AthenaBattleBus': 'battlebus', 'AthenaVictoryPose': 'ridethepony', 'BannerToken': 'banner' } API_TO_BACKEND_CONVERTER = { v: k for k, v in BACKEND_TO_API_CONVERTER.items() } BACKEND_TO_KEY_CONVERTER = { 'AthenaBackpack': 'backpack', 'AthenaPickaxe': 'pickaxe', 'AthenaItemWrap': 'wrap', 'AthenaGlider': 'glider', 'AthenaCharacter': 'outfit', 'AthenaPet': 'backpack', 'AthenaMusicPack': 'music', 'AthenaLoadingScreen': 'loadingscreen', 'AthenaDance': 'emote', 'AthenaSpray': 'emote', 'AthenaEmoji': 'emote', 'AthenaSkyDiveContrail': 'contrail', 'AthenaPetCarrier': 'backpack', 'AthenaToy': 'emote', 'AthenaConsumableEmote': 'emote', 'AthenaBattleBus': 'battlebus', 'AthenaVictoryPose': 'emote', 'BannerToken': 'banner' } BACKEND_TO_ID_CONVERTER = { 'AthenaCharacter': 'CID', 'AthenaBackpack': 'BID', 'AthenaPetCarrier': 'PetCarrier', 'AthenaPet': 'PetID', 'AthenaPickaxe': 'Pickaxe_ID', 'AthenaDance': 'EID', 'AthenaEmoji': 'Emoji', 'AthenaToy': 'Toy', 'AthenaConsumableEmote': 'EID', } VARIANT_FORMATS = [ 'Mat', 'Stage', 'Emissive', 'Stage', 'Particle' 'Numeric.', 'Color.' ] def __init__(self, mode: str, loop: asyncio.AbstractEventLoop, dev: Optional[bool] = False, use_device_code: Optional[bool] = False, use_device_auth: Optional[bool] = False) -> None: self.mode = mode self.loop = loop self.dev = dev self.use_device_code = use_device_code self.use_device_auth = use_device_auth self.clients = [] self.updater = Updater(self) self.web = Web(self, __name__) self.web_text = '' self.server = None self.lang_dir = 'lang' self.item_dir = 'item' os.makedirs(self.item_dir, exist_ok=True) self.booted_at = None self.email_pattern = re.compile( r'[a-zA-Z0-9.+-_]+@[a-zA-Z0-9-_]+\.[a-zA-Z0-9]+' ) self.return_pattern = re.compile( r'(?P<space>\s*)(return|return\s+(?P<text>.*))\s*' ) self.formatter = EvalFormatter() self.kakasi = kakasi() self.kakasi.setMode('J', 'H') self.converter = self.kakasi.getConverter() self.localize = None self.all_commands = { attr.name: attr for attr in DefaultCommands.__dict__.values() if isinstance(attr, Command) } self.none_data = { 'real_value': None, 'value': 'null', 'display_value': self.l('none_none', default='null') } self.select_bool = [ { 'real_value': True, 'value': 'true', 'display_value': self.l('bool_true', default='true') }, { 'real_value': False, 'value': 'false', 'display_value': self.l('bool_false', default='false') } ] self.select_event = [ { 'real_value': i, 'value': i, 'display_value': self.l(f'event_{i}', default=i) } for i in ['me', 'user'] ] self.select_platform = [ { 'real_value': i, 'value': i, 'display_value': self.l(f'platform_{i}', default=i) } for i in ['WIN', 'MAC', 'PSN', 'PS5', 'XBL', 'XBX', 'XBS', 'SWT', 'IOS', 'AND'] ] self.select_privacy = [ { 'real_value': i, 'value': i, 'display_value': self.l(f'privacy_{i.lower()}', default=i.upper()) } for i in ['PUBLIC', 'FRIENDS_ALLOW_FRIENDS_OF_FRIENDS', 'FRIENDS', 'PRIVATE_ALLOW_FRIENDS_OF_FRIENDS', 'PRIVATE'] ] self.select_status = [ { 'real_value': i, 'value': i, 'display_value': self.l(f'status_type_{i}', default=i) } for i in ['playing', 'streaming', 'listening', 'watching', 'competing'] ] self.select_matchmethod = [ { 'real_value': i, 'value': i, 'display_value': self.l(f'matchmethod_{i}', default=i) } for i in ['full', 'contains', 'starts', 'ends'] ] self.select_lang = [ { 'real_value': re.sub(r'lang(\\|/)', '', i).replace('.json', ''), 'value': re.sub(r'lang(\\|/)', '', i).replace('.json', ''), 'display_value': re.sub(r'lang(\\|/)', '', i).replace('.json', '') } for i in glob('lang/*.json') if not i.endswith('_old.json') ] self.select_api_lang = [ { 'real_value': i, 'value': i, 'display_value': i } for i in ['ar', 'de', 'en', 'es', 'es-419', 'fr', 'it', 'ja', 'ko', 'pl', 'pt-BR', 'ru', 'tr', 'zh-CN', 'zh-Hant'] ] self.select_api = [ { 'real_value': i, 'value': i, 'display_value': i } for i in ['BenBot', 'Fortnite-API', 'FortniteApi.io'] ] self.select_loglevel = [ { 'real_value': i, 'value': i, 'display_value': self.l(f'loglevel_{i}', default=i) } for i in ['normal', 'info', 'debug'] ] self.select_run_when = [ { 'real_value': i, 'value': i, 'display_value': self.l(f'run_when_{i}', default=i) } for i in ['before_command', 'after_command'] ] self.multiple_select_user_type = [ { 'real_value': i, 'value': i, 'display_value': self.l(f'multiple_select_user_{i}', default=i) } for i in ['user', 'whitelist', 'blacklist', 'owner', 'bot'] ] self.multiple_select_user_operation = [ { 'real_value': i, 'value': i, 'display_value': self.l(f'multiple_select_operation_{i}', default=i) } for i in ['kick', 'chatban', 'remove', 'block', 'blacklist'] ] self.multiple_select_platform = self.select_platform self.config = None self.config_tags = { "['clients']": [list, dict, 'client_config'], "['discord']": [dict], "['discord']['enabled']": [bool, 'select_bool'], "['discord']['token']": [str], "['discord']['owner']": [list, str, 'can_be_none'], "['discord']['channels']": [list, str], "['discord']['status']": [str], "['discord']['status_type']": [str, 'select_status'], "['discord']['chat_max']": [int, 'can_be_none'], "['discord']['chat_max_for']": [list, str, 'multiple_select_user_type', 'can_be_none'], "['discord']['command_enable_for']": [list, str, 'multiple_select_user_type', 'can_be_none'], "['discord']['blacklist']": [list, str], "['discord']['whitelist']": [list, str], "['discord']['prefix']": [list, str, 'can_be_none'], "['discord']['exec']": [dict], "['discord']['exec']['ready']": [list, str, 'can_be_none', 'accept_empty'], "['web']": [dict], "['web']['enabled']": [bool, 'select_bool'], "['web']['ip']": [str], "['web']['port']": [int], "['web']['password']": [str], "['web']['login_required']": [bool, 'select_bool'], "['web']['command_web']": [bool, 'select_bool'], "['web']['access_log']": [bool, 'select_bool'], "['web']['prefix']": [list, str, 'can_be_none'], "['check_update_on_startup']": [bool, 'select_bool'], "['restart_in']": [int, 'can_be_none'], "['lang']": [str, 'select_lang'], "['search_lang']": [str, 'select_api_lang'], "['sub_search_lang']": [str, 'select_api_lang'], "['api']": [str, 'select_api'], "['api_key']": [str, 'can_be_none'], "['discord_log']": [str, 'can_be_none'], "['omit_over2000']": [bool, 'select_bool'], "['skip_if_overflow']": [bool, 'select_bool'], "['hide_email']": [bool, 'select_bool'], "['hide_password']": [bool, 'select_bool'], "['hide_token']": [bool, 'select_bool'], "['hide_webhook']": [bool, 'select_bool'], "['no_logs']": [bool, 'select_bool'], "['loglevel']": [str, 'select_loglevel'], "['debug']": [bool, 'select_bool'] } self.client_config_tags = { "['fortnite']": [dict], "['fortnite']['email']": [str, 'lambda x: x and self.email_pattern.match(x) is not None'], "['fortnite']['nickname']": [str, 'can_be_none'], "['fortnite']['owner']": [list, str, 'can_be_none'], "['fortnite']['outfit']": [str, 'can_be_none'], "['fortnite']['outfit_style']": [list, str, 'can_be_none'], "['fortnite']['ng_outfits']": [list, str, 'can_be_none'], "['fortnite']['ng_outfit_for']": [list, str, 'multiple_select_user_type', 'can_be_none'], "['fortnite']['ng_outfit_operation']": [list, str, 'multiple_select_user_operation', 'can_be_none'], "['fortnite']['ng_outfit_reply']": [str, 'can_be_none'], "['fortnite']['join_outfit']": [str, 'can_be_none'], "['fortnite']['join_outfit_style']": [list, str, 'can_be_none'], "['fortnite']['join_outfit_on']": [str, 'select_event'], "['fortnite']['leave_outfit']": [str, 'can_be_none'], "['fortnite']['leave_outfit_style']": [list, str, 'can_be_none'], "['fortnite']['leave_outfit_on']": [str, 'select_event'], "['fortnite']['outfit_mimic_for']": [list, str, 'multiple_select_user_type', 'can_be_none'], "['fortnite']['outfit_lock_for']": [list, str, 'multiple_select_user_type', 'can_be_none'], "['fortnite']['backpack']": [str, 'can_be_none'], "['fortnite']['backpack_style']": [list, str, 'can_be_none'], "['fortnite']['ng_backpacks']": [list, str, 'can_be_none'], "['fortnite']['ng_backpack_for']": [list, str, 'multiple_select_user_type', 'can_be_none'], "['fortnite']['ng_backpack_operation']": [list, str, 'multiple_select_user_operation', 'can_be_none'], "['fortnite']['ng_backpack_reply']": [str, 'can_be_none'], "['fortnite']['join_backpack']": [str, 'can_be_none'], "['fortnite']['join_backpack_style']": [list, str, 'can_be_none'], "['fortnite']['join_backpack_on']": [str, 'select_event'], "['fortnite']['leave_backpack']": [str, 'can_be_none'], "['fortnite']['leave_backpack_style']": [list, str, 'can_be_none'], "['fortnite']['leave_backpack_on']": [str, 'select_event'], "['fortnite']['backpack_mimic_for']": [list, str, 'multiple_select_user_type', 'can_be_none'], "['fortnite']['backpack_lock_for']": [list, str, 'multiple_select_user_type', 'can_be_none'], "['fortnite']['pickaxe']": [str, 'can_be_none'], "['fortnite']['pickaxe_style']": [list, str, 'can_be_none'], "['fortnite']['do_point']": [bool, 'select_bool'], "['fortnite']['ng_pickaxes']": [list, str, 'can_be_none'], "['fortnite']['ng_pickaxe_for']": [list, str, 'multiple_select_user_type', 'can_be_none'], "['fortnite']['ng_pickaxe_operation']": [list, str, 'multiple_select_user_operation', 'can_be_none'], "['fortnite']['ng_pickaxe_reply']": [str, 'can_be_none'], "['fortnite']['join_pickaxe']": [str, 'can_be_none'], "['fortnite']['join_pickaxe_style']": [list, str, 'can_be_none'], "['fortnite']['join_pickaxe_on']": [str, 'select_event'], "['fortnite']['leave_pickaxe']": [str, 'can_be_none'], "['fortnite']['leave_pickaxe_style']": [list, str, 'can_be_none'], "['fortnite']['leave_pickaxe_on']": [str, 'select_event'], "['fortnite']['pickaxe_mimic_for']": [list, str, 'multiple_select_user_type', 'can_be_none'], "['fortnite']['pickaxe_lock_for']": [list, str, 'multiple_select_user_type', 'can_be_none'], "['fortnite']['emote']": [str], "['fortnite']['emote_section']": [int, 'can_be_none'], "['fortnite']['repeat_emote_when_join']": [bool, 'select_bool'], "['fortnite']['ng_emotes']": [list, str, 'can_be_none'], "['fortnite']['ng_emote_for']": [list, str, 'multiple_select_user_type', 'can_be_none'], "['fortnite']['ng_emote_operation']": [list, str, 'multiple_select_user_operation', 'can_be_none'], "['fortnite']['ng_emote_reply']": [str, 'can_be_none'], "['fortnite']['join_emote']": [str, 'can_be_none'], "['fortnite']['join_emote_section']": [int, 'can_be_none'], "['fortnite']['join_emote_on']": [str, 'select_event'], "['fortnite']['leave_emote']": [str, 'can_be_none'], "['fortnite']['leave_emote_section']": [int, 'can_be_none'], "['fortnite']['leave_emote_on']": [str, 'select_event'], "['fortnite']['emote_mimic_for']": [list, str, 'multiple_select_user_type', 'can_be_none'], "['fortnite']['emote_lock_for']": [list, str, 'multiple_select_user_type', 'can_be_none'], "['fortnite']['leave_delay_for']": [float], "['fortnite']['refresh_on_reload']": [bool, 'select_bool'], "['fortnite']['party']": [dict], "['fortnite']['party']['privacy']": [str, 'select_privacy'], "['fortnite']['party']['max_size']": [int, 'lambda x: 1 <= x <= 16'], "['fortnite']['party']['allow_swap']": [bool, 'select_bool'], "['fortnite']['party']['playlist']": [str], "['fortnite']['party']['disable_voice_chat']": [bool, 'select_bool'], "['fortnite']['avatar_id']": [str, 'can_be_none'], "['fortnite']['avatar_color']": [str, 'can_be_multiple', 'lambda x: x and (len(x.split(",")) >= 3) if "," in x else (getattr(fortnitepy.KairosBackgroundColorPreset, x.upper(), None) is not None)'], # noqa "['fortnite']['banner_id']": [str], "['fortnite']['banner_color']": [str], "['fortnite']['level']": [int], "['fortnite']['tier']": [int], "['fortnite']['platform']": [str, 'select_platform'], "['fortnite']['ng_platforms']": [list, str, 'multiple_select_platform', 'can_be_none'], "['fortnite']['ng_platform_for']": [list, str, 'multiple_select_user_type', 'can_be_none'], "['fortnite']['ng_platform_operation']": [list, str, 'multiple_select_user_operation', 'can_be_none'], "['fortnite']['ng_platform_reply']": [str, 'can_be_none'], "['fortnite']['ng_names']": [list, dict, 'ng_names_config'], "['fortnite']['ng_name_for']": [list, str, 'multiple_select_user_type', 'can_be_none'], "['fortnite']['ng_name_operation']": [list, str, 'multiple_select_user_operation', 'can_be_none'], "['fortnite']['ng_name_reply']": [str, 'can_be_none'], "['fortnite']['status']": [str], "['fortnite']['accept_invite_for']": [list, str, 'multiple_select_user_type', 'can_be_none'], "['fortnite']['decline_invite_when']": [list, str, 'multiple_select_user_type', 'can_be_none'], "['fortnite']['invite_interval']": [float, 'can_be_none'], "['fortnite']['invite_interval_for']": [list, str, 'multiple_select_user_type', 'can_be_none'], "['fortnite']['accept_friend_for']": [list, str, 'multiple_select_user_type', 'can_be_none'], "['fortnite']['send_friend_request']": [bool, 'select_bool'], "['fortnite']['whisper_enable_for']": [list, str, 'multiple_select_user_type', 'can_be_none'], "['fortnite']['party_chat_enable_for']": [list, str, 'multiple_select_user_type', 'can_be_none'], "['fortnite']['permission_command_operation']": [list, str, 'multiple_select_user_operation', 'can_be_none'], "['fortnite']['accept_join_for']": [list, str, 'multiple_select_user_type', 'can_be_none'], "['fortnite']['join_message']": [list, str, 'can_be_none', 'accept_empty'], "['fortnite']['join_message_whisper']": [list, str, 'can_be_none', 'accept_empty'], "['fortnite']['random_message']": [list, list, str, 'can_be_none', 'accept_empty'], "['fortnite']['random_message_whisper']": [list, list, str, 'can_be_none', 'accept_empty'], "['fortnite']['chat_max']": [int, 'can_be_none'], "['fortnite']['chat_max_for']": [list, str, 'multiple_select_user_type', 'can_be_none'], "['fortnite']['chat_max_operation']": [list, str, 'multiple_select_user_operation', 'can_be_none'], "['fortnite']['kick_disconnect']": [bool, 'select_bool'], "['fortnite']['kick_in_match']": [bool, 'select_bool'], "['fortnite']['hide_for']": [list, str, 'multiple_select_user_type', 'can_be_none'], "['fortnite']['blacklist']": [list, str], "['fortnite']['blacklist_operation']": [list, str, 'multiple_select_user_operation', 'can_be_none'], "['fortnite']['whitelist']": [list, str], "['fortnite']['invitelist']": [list, str], "['fortnite']['botlist']": [list, str], "['fortnite']['botlist_operation']": [list, str, 'multiple_select_user_operation', 'can_be_none'], "['fortnite']['prefix']": [list, str, 'can_be_none'], "['fortnite']['exec']": [dict], "['fortnite']['exec']['ready']": [list, str, 'can_be_none'], "['fortnite']['exec']['party_join_request']": [list, str, 'can_be_none'], "['fortnite']['exec']['party_invite']": [list, str, 'can_be_none'], "['fortnite']['exec']['friend_request']": [list, str, 'can_be_none'], "['fortnite']['exec']['friend_add']": [list, str, 'can_be_none'], "['fortnite']['exec']['friend_remove']": [list, str, 'can_be_none'], "['fortnite']['exec']['party_member_join']": [list, str, 'can_be_none'], "['fortnite']['exec']['party_member_leave']": [list, str, 'can_be_none'], "['fortnite']['exec']['party_member_confirm']": [list, str, 'can_be_none'], "['fortnite']['exec']['party_member_kick']": [list, str, 'can_be_none'], "['fortnite']['exec']['party_member_promote']": [list, str, 'can_be_none'], "['fortnite']['exec']['party_update']": [list, str, 'can_be_none'], "['fortnite']['exec']['party_member_update']": [list, str, 'can_be_none'], "['fortnite']['exec']['party_member_disconnect']": [list, str, 'can_be_none'], "['discord']": [dict], "['discord']['enabled']": [bool, 'select_bool'], "['discord']['token']": [str], "['discord']['owner']": [list, str, 'can_be_none'], "['discord']['channels']": [list, str], "['discord']['status']": [str], "['discord']['status_type']": [str, 'select_status'], "['discord']['chat_max']": [int, 'can_be_none'], "['discord']['chat_max_for']": [list, str, 'multiple_select_user_type', 'can_be_none'], "['discord']['command_enable_for']": [list, str, 'multiple_select_user_type', 'can_be_none'], "['discord']['blacklist']": [list, str], "['discord']['whitelist']": [list, str], "['discord']['prefix']": [list, str, 'can_be_none'], "['discord']['exec']": [dict], "['discord']['exec']['ready']": [list, str, 'can_be_none'], "['ng_words']": [list, dict, 'ng_words_config'], "['ng_word_for']": [list, str, 'multiple_select_user_type', 'can_be_none'], "['ng_word_operation']": [list, str, 'multiple_select_user_operation', 'can_be_none'], "['ng_word_reply']": [str, 'can_be_none'], "['relogin_in']": [int, 'can_be_none'], "['search_max']": [int, 'can_be_none'], "['no_logs']": [bool, 'select_bool'], "['loglevel']": [str, 'select_loglevel'], "['discord_log']": [str, 'can_be_none'], "['omit_over2000']": [bool, 'select_bool'], "['skip_if_overflow']": [bool, 'select_bool'], "['case_insensitive']": [bool, 'select_bool'], "['convert_kanji']": [bool, 'select_bool'] } self.ng_names_config_tags = { "['matchmethod']": [str, 'select_matchmethod'], "['word']": [str] } self.ng_words_config_tags = { "['count']": [int], "['matchmethod']": [str, 'select_matchmethod'], "['words']": [list, str] } self.commands = None tags = [list, str, 'can_be_multiple'] tags2 = [list, str, 'can_be_multiple', 'lambda x: len(x) > 0'] self.commands_tags = { **{ "['whitelist_commands']": tags, "['user_commands']": tags, "['prefix_to_item_search']": [bool, 'select_bool'], "['command']": tags2, "['ng_word']": tags2, "['most']": tags2, "['user']": tags2, "['whitelist']": tags2, "['blacklist']": tags2, "['owner']": tags2, "['bot']": tags2, "['null']": tags2, "['operation_kick']": tags2, "['operation_chatban']": tags2, "['operation_remove']": tags2, "['operation_block']": tags2, "['operation_blacklist']": tags2, "['add']": tags2, "['remove']": tags2, "['true']": tags2, "['false']": tags2, "['accept']": tags2, "['decline']": tags2, "['me']": tags2, "['public']": tags2, "['friends_allow_friends_of_friends']": tags2, "['friends']": tags2, "['private_allow_friends_of_friends']": tags2, "['private']": tags2, "['outfit']": tags2, "['backpack']": tags2, "['pickaxe']": tags2, "['save']": tags2, "['load']": tags2, "['commands']": [dict] }, **{ f"['commands']['{command}']": tags for command in self.all_commands.keys() } } self.custom_commands = None self.custom_commands_tags = { "['run_when']": [str, 'select_run_when'], "['commands']": [list, dict, 'custom_commands_config'] } self.custom_commands_config_tags = { "['word']": [str], "['allow_for']": [list, str, 'multiple_select_user_type', 'can_be_none'], "['run']": [list, str, 'can_be_multiple'] } self.replies = None self.replies_tags = { "['run_when']": [str, 'select_run_when'], "['prefix_to_replies']": [bool, 'select_bool'], "['replies']": [list, dict, 'replies_config'] } self.replies_config_tags = { "['matchmethod']": [str, 'select_matchmethod'], "['word']": [str], "['reply']": [list, str, 'can_be_multiple', 'accept_empty'], "['ct']": [int, 'can_be_none'] } self.cosmetic_presets = None self.config_item_pattern = re.compile( r"<Item name='(?P<name>.+)' " r"id='(?P<id>.+)' " r"path='(?P<path>.+)'>" ) self.config_playlist_pattern = re.compile( r"<Playlist name='(?P<name>.+)' " r"id='(?P<id>.+)'>" ) self.config_variant_pattern = re.compile( r"<Variant name='(?P<name>.+)' " r"channel='(?P<channel>.+)' " r"tag='(?P<tag>.+)'>" ) self.http = HTTPClient(aiohttp.ClientSession()) self.webhook = None self.discord_client = None @property def loaded_clients(self) -> List[Client]: return [client for client in self.clients if client.is_ready()] @property def loaded_client_ids(self) -> List[Client]: return [client.user.id for client in self.loaded_clients] def add_command(self, command: Command) -> None: if not isinstance(command, Command): raise TypeError(f'command argument must be instance of {Command.__name__}') if command.name in self.all_commands: raise ValueError(f"Command '{command.name}' is already registered") self.all_commands[command.name] = command for client in self.clients: client.add_command(command) def is_error(self) -> bool: return ( self.error_config or self.error_commands or self.error_custom_commands or self.error_replies ) def get_device_auth_details(self) -> dict: if self.isfile('device_auths'): return self.load_json('device_auths') else: return {} def store_device_auth_details(self, email: str, details: dict) -> None: existing = self.get_device_auth_details() existing[email.lower()] = details self.save_json('device_auths', existing) def get_refresh_tokens(self) -> dict: if self.isfile('refresh_tokens'): return self.load_json('refresh_tokens') else: return {} def store_refresh_token(self, email: str, refresh_token: str) -> None: existing = self.get_refresh_tokens() existing[email.lower()] = refresh_token self.save_json('refresh_tokens', existing) def get_cosmetic_presets(self) -> dict: if self.isfile('cosmetic_presets'): return self.load_json('cosmetic_presets') else: return {} async def store_cosmetic_presets(self, account_id: str, details: dict) -> None: existing = self.get_cosmetic_presets() existing[account_id] = details self.save_json('cosmetic_presets', existing) def get_command_stats(self) -> dict: if self.isfile('command_stats'): return self.load_json('command_stats') else: return {} def store_command_stats(self) -> None: self.save_json('command_stats', self.command_stats) def convert_td(self, td: datetime.timedelta) -> Tuple[int, int, int, int]: m, s = divmod(td.seconds, 60) h, m = divmod(m, 60) return td.days, h, m, s def isfile(self, key: str, force_file: Optional[bool] = False) -> bool: if self.mode == 'repl' and not force_file: if db.get(key) is None: return False else: if not os.path.isfile(f'{key}.json'): return False return True def remove(self, key: str, force_file: Optional[bool] = False) -> None: if self.mode == 'repl' and not force_file: try: del db[key] except KeyError as e: raise FileNotFoundError from e else: os.remove(f'{key}.json') async def aremove(self, key: str, force_file: Optional[bool] = False) -> None: if self.mode == 'repl' and not force_file: try: del db[key] except KeyError as e: raise FileNotFoundError from e else: await aremove(f'{key}.json') def rename(self, key_src: str, key_dst: str, force_file: Optional[bool] = False) -> None: if self.mode == 'repl' and not force_file: try: db[key_dst] = db[key_src] del db[key_src] except KeyError as e: raise FileNotFoundError from e else: os.rename(f'{key_src}.json', f'{key_dst}.json') def load_json(self, key: str, force_file: Optional[bool] = False) -> Union[dict, list]: if self.mode == 'repl' and not force_file: data = db[key]['value'] if isinstance(data, str): return json.loads(db[key]['value']) return data else: try: with open(f'{key}.json', encoding='utf-8') as f: data = f.read() except UnicodeDecodeError: try: with open(f'{key}.json', encoding='utf-8-sig') as f: data = f.read() except UnicodeDecodeError: with open(f'{key}.json', encoding='shift_jis') as f: data = f.read() return json.loads(data) async def aload_json(self, key: str, force_file: Optional[bool] = False) -> Union[dict, list]: if self.mode == 'repl' and not force_file: data = db[key]['value'] if isinstance(data, str): return json.loads(db[key]['value']) return data else: try: async with aopen(f'{key}.json', encoding='utf-8') as f: data = await f.read() except UnicodeDecodeError: try: async with aopen(f'{key}.json', encoding='utf-8-sig') as f: data = await f.read() except UnicodeDecodeError: async with aopen(f'{key}.json', encoding='shift_jis') as f: data = await f.read() return json.loads(data) def save_json(self, key: str, value: Union[dict, list], force_file: Optional[bool] = False, compact: Optional[bool] = False) -> None: if self.mode == 'repl' and not force_file: db[key] = { 'last_edited': self.utcnow(), 'value': json.dumps( value, ensure_ascii=False, cls=MyJSONEncoder ) } else: with open(f'{key}.json', 'w', encoding='utf-8') as f: if compact: json.dump( value, f, ensure_ascii=False, cls=MyJSONEncoder ) else: json.dump( value, f, indent=4, ensure_ascii=False, cls=MyJSONEncoder ) def dumps(self, data: Union[dict, list]) -> str: return json.dumps( data, ensure_ascii=False, cls=MyJSONEncoder ) def get_last_edited(self, key: str, force_file: Optional[bool] = False) -> datetime.datetime: if self.mode == 'repl' and not force_file: return datetime.datetime.fromisoformat(db[key]['last_edited']) else: stat = os.stat(f'{key}.json') return datetime.datetime.fromtimestamp(stat.st_mtime) def is_not_edited_for(self, key: str, td: datetime.timedelta, force_file: Optional[bool] = False) -> bool: last_edited = self.get_last_edited(key, force_file=force_file) if last_edited < (datetime.datetime.utcnow() - td): return True return False def l(self, key: str, *args: tuple, default: Optional[str] = '', **kwargs: dict) -> LocalizedText: return LocalizedText(self, ['main', key], default, *args, **kwargs) def send(self, content: Any, user_name: Optional[str] = None, color: Optional[Callable] = None, add_p: Optional[Union[Callable, List[Callable]]] = None, add_d: Optional[Union[Callable, List[Callable]]] = None, file: Optional[io.IOBase] = None) -> Optional[str]: file = file or sys.stdout content = str(content) color = color or (lambda x: x) add_p = (add_p if isinstance(add_p, list) else [add_p or (lambda x: x)]) add_d = (add_d if isinstance(add_d, list) else [add_d or (lambda x: x)]) if file == sys.stderr: add_d.append(self.discord_error) if not self.config['no_logs'] if self.config else True: text = content for func in add_p: text = func(text) print(color(text), file=file) if self.webhook: content = discord.utils.escape_markdown(content) name = user_name or 'Fortnite-LobbyBot' text = content for func in add_d: text = func(text) self.webhook.send(text, name) def time(self, text: str) -> str: return f'[{self.now()}] {text}' def discord_error(self, text: str) -> str: texts = [] for line in text.split('\n'): texts.append(f'> {line}') return '\n'.join(texts) def debug_message(self, text: str) -> str: return f'```\n{text}\n```' def format_exception(self, exc: Optional[Exception] = None) -> str: if exc is not None: return ''.join(list(traceback.TracebackException.from_exception(exc).format())) return traceback.format_exc() def print_exception(self, exc: Optional[Exception] = None) -> None: if exc is not None: self.send( ''.join(['Ignoring exception\n'] + list(traceback.TracebackException.from_exception(exc).format())), file=sys.stderr ) else: self.send( traceback.format_exc(), file=sys.stderr ) def debug_print_exception(self, exc: Optional[Exception] = None) -> None: if self.config is not None and self.config['loglevel'] == 'debug': self.print_exception(exc) def now(self) -> str: return datetime.datetime.now().strftime('%H:%M:%S') def utcnow(self) -> str: return datetime.datetime.utcnow().strftime('%H:%M:%S') def strftime(self, dt: datetime.datetime) -> str: dt = dt.astimezone(get_localzone()) if dt.hour >= 12 and self.config['lang'] == 'en': dt -= datetime.timedelta(hours=12) return f"{dt.strftime('%H:%M PM')}" return f"{dt.strftime('%H:%M')}" def str_to_bool(self, text: str) -> bool: if text.lower() == 'true': return True elif text.lower() == 'false': return False raise ValueError(f"{text!r} does not match to any of True, False") def get_list_index(self, data: list, index: int, default: Optional[Any] = None) -> Any: return data[index] if data[index:index + 1] else default def eval_format(self, text: str, variables: dict) -> str: return self.formatter.format(text, **variables) def eval_dict(self, data: dict, keys: list) -> str: text = '' for key in keys: text += f"[{repr(key)}]" return text def get_dict_key(self, data: dict, keys: list, func: Optional[Callable] = None) -> Any: func = func or (lambda x: x) text = self.eval_dict(data, keys) return func(eval(f'data{text}')) def set_dict_key(self, data: dict, keys: list, value: Any, func: Optional[Callable] = None) -> None: func = func or (lambda x: x) text = self.eval_dict(data, keys) exec(f'data{text} = func(value)') def eval_dict_default(self, data: dict, keys: list) -> Tuple[str, str]: text = '' text2 = '' for nest, key in enumerate(keys, 1): text += f"[{repr(key)}]" if nest == len(keys): if isinstance(key, str): text2 += f".get('{key}', default)" else: text2 = f"self.get_list_index(data{text2}, key, default)" else: text2 += f"[{repr(key)}]" return text, text2 def get_dict_key_default(self, data: dict, keys: list, default: Any, func: Optional[Callable] = None) -> Any: func = func or (lambda x: x) _, text2 = self.eval_dict_default(data, keys) try: value = eval(f'data{text2}') except (TypeError, KeyError): value = default return func(value) def set_dict_key_default(self, data: dict, keys: list, default: Any, func: Optional[Callable] = None) -> None: func = func or (lambda x: x) text, text2 = self.eval_dict_default(data, keys) try: value = eval(f'data{text2}') # noqa except ValueError: value = default # noqa exec(f'data{text} = func(value)') def load_config(self) -> Optional[Tuple[dict, list]]: try: config = self.load_json('config') except (json.decoder.JSONDecodeError, UnicodeDecodeError) as e: self.send( (f'{self.format_exception(e)}\n{e}\n' + self.l( 'load_failed_json', 'config', default=( "'{0}' ファイルの読み込みに失敗しました。正しく書き込めているか確認してください\n" "Failed to load '{0}' file. Make sure you wrote correctly" ) )), file=sys.stderr ) return None, None except FileNotFoundError as e: self.send( (f'{self.format_exception(e)}\n{e}\n' + self.l( 'load_failed_not_found', 'config', default=( "'{0}' ファイルが存在しません\n" "'{0}' file does not exist" ) )), file=sys.stderr ) return None, None self.set_dict_key_default(config, ['clients'], []) self.set_dict_key_default(config, ['web'], {}) self.set_dict_key_default(config, ['web', 'enabled'], True) self.set_dict_key_default(config, ['web', 'ip'], '{ip}') self.set_dict_key_default(config, ['web', 'port'], 8000) self.set_dict_key_default(config, ['check_update_on_startup'], True) self.set_dict_key_default(config, ['lang'], 'en') self.set_dict_key_default(config, ['api'], 'BenBot') self.set_dict_key_default(config, ['api_key'], None) self.set_dict_key_default(config, ['discord_log'], None) self.set_dict_key_default(config, ['loglevel'], 'normal') self.set_dict_key_default(config, ['no_logs'], 'normal') self.set_dict_key_default(config, ['debug'], False) self.set_dict_key_default(config, ['status'], 0) if self.mode != 'pc': replace = '0.0.0.0' else: replace = 'localhost' config['web']['ip'] = config['web']['ip'].format(ip=replace) error_config = [] self.tag_check(config, error_config, '', self.config_tags) if config['loglevel'] == 'debug': self.send(json.dumps(config, indent=4, ensure_ascii=False), color=yellow, add_d=lambda x: f'{self.debug_message(x)}\n') self.save_json('config', config) if config['api'] == 'FortniteApi.io' and not config['api_key']: self.send( self.l('api_key_required'), add_p=self.time, file=sys.stderr ) error_config.append("['api_key']") return config, error_config def load_localize(self, lang: str) -> Optional[dict]: try: localize = self.load_json(f'{self.lang_dir}/{lang}', force_file=True) except (json.decoder.JSONDecodeError, UnicodeDecodeError) as e: self.send( (f'{self.format_exception(e)}\n{e}\n' + self.l( 'load_failed_json', f'{self.lang_dir}/{lang}', default=( "'{0}' ファイルの読み込みに失敗しました。正しく書き込めているか確認してください\n" "Failed to load '{0}' file. Make sure you wrote correctly" ) )), file=sys.stderr ) return None except FileNotFoundError as e: self.send( (f'{self.format_exception(e)}\n{e}\n' + self.l( 'load_failed_not_found', f'{self.lang_dir}/{lang}', default=( "'{0}' ファイルが存在しません\n" "'{0}' file does not exist" ) )), file=sys.stderr ) return None return localize def load_commands(self) -> Optional[Tuple[dict, list]]: try: commands = self.load_json('commands') except (json.decoder.JSONDecodeError, UnicodeDecodeError) as e: self.send( (f'{self.format_exception(e)}\n{e}\n' + self.l( 'load_failed_json', 'commands', default=( "'{0}' ファイルの読み込みに失敗しました。正しく書き込めているか確認してください\n" "Failed to load '{0}' file. Make sure you wrote correctly" ) )), file=sys.stderr ) return None, None except FileNotFoundError as e: self.send( (f'{self.format_exception(e)}\n{e}\n' + self.l( 'load_failed_not_found', 'commands', default=( "'{0}' ファイルが存在しません\n" "'{0}' file does not exist" ) )), file=sys.stderr ) return None, None error_commands = [] self.tag_check(commands, error_commands, '', self.commands_tags) if self.config['loglevel'] == 'debug': self.send(json.dumps(commands, indent=4, ensure_ascii=False), color=yellow, add_d=lambda x: f'{self.debug_message(x)}\n') self.save_json('commands', commands) return commands, error_commands def load_custom_commands(self) -> Optional[Tuple[dict, list]]: try: custom_commands = self.load_json('custom_commands') except (json.decoder.JSONDecodeError, UnicodeDecodeError) as e: self.send( (f'{self.format_exception(e)}\n{e}\n' + self.l( 'load_failed_json', 'custom_commands', default=( "'{0}' ファイルの読み込みに失敗しました。正しく書き込めているか確認してください\n" "Failed to load '{0}' file. Make sure you wrote correctly" ) )), file=sys.stderr ) return None, None except FileNotFoundError as e: self.send( (f'{self.format_exception(e)}\n{e}\n' + self.l( 'load_failed_not_found', 'custom_commands', default=( "'{0}' ファイルが存在しません\n" "'{0}' file does not exist" ) )), file=sys.stderr ) return None, None error_custom_commands = [] self.tag_check(custom_commands, error_custom_commands, '', self.custom_commands_tags) if self.config['loglevel'] == 'debug': self.send(json.dumps(custom_commands, indent=4, ensure_ascii=False), color=yellow, add_d=lambda x: f'{self.debug_message(x)}\n') self.save_json('custom_commands', custom_commands) return custom_commands, error_custom_commands def load_replies(self) -> Optional[Tuple[dict, list]]: try: replies = self.load_json('replies') except (json.decoder.JSONDecodeError, UnicodeDecodeError) as e: self.send( (f'{self.format_exception(e)}\n{e}\n' + self.l( 'load_failed_json', 'replies', default=( "'{0}' ファイルの読み込みに失敗しました。正しく書き込めているか確認してください\n" "Failed to load '{0}' file. Make sure you wrote correctly" ) )), file=sys.stderr ) return None, None except FileNotFoundError as e: self.send( (f'{self.format_exception(e)}\n{e}\n' + self.l( 'load_failed_not_found', 'replies', default=( "'{0}' ファイルが存在しません\n" "'{0}' file does not exist" ) )), file=sys.stderr ) return None, None error_replies = [] self.tag_check(replies, error_replies, '', self.replies_tags) if self.config['loglevel'] == 'debug': self.send(json.dumps(replies, indent=4, ensure_ascii=False), color=yellow, add_d=lambda x: f'{self.debug_message(x)}\n') self.save_json('replies', replies) return replies, error_replies def get_select_tag(self, data: list) -> Optional[str]: for tag in data: if isinstance(tag, str) and tag.startswith('select'): return tag def get_multiple_select_tag(self, data: list) -> Optional[str]: for tag in data: if isinstance(tag, str) and tag.startswith('multiple_select'): return tag def get_config_tag(self, data: list) -> Optional[str]: for tag in data: if isinstance(tag, str) and tag.endswith('_config'): return tag def flat_dict(self, data: dict) -> dict: final = {} for key, value in data.items(): if isinstance(value, dict): for k, v in self.flat_dict(value).items(): final[f"[{repr(key)}]{k}"] = v elif isinstance(value, list): for num, val in enumerate(value): if isinstance(val, dict): for k, v in self.flat_dict(val).items(): final[f"[{repr(key)}][{num}]{k}"] = v elif isinstance(val, list): for n, v in enumerate(val): final[f"[{repr(key)}][{num}][{n}]"] = v else: final[f"[{repr(key)}][{num}]"] = val else: final[f"[{repr(key)}]"] = value return final def tag_check(self, data: dict, error_list: list, prefix: str, tag_data: dict) -> None: for key, tags in tag_data.items(): self.value_check(data, error_list, prefix, key, tags) def value_check(self, data: dict, error_list: list, prefix: str, key: str, tags: list) -> None: try: value = eval(f'data{key}') except Exception: self.send( self.l( 'is_missing', f'{prefix}{key}', default=( "{0} がありません\n" "{0} is missing" ) ), file=sys.stderr ) error_list.append(f'{prefix}{key}') else: select_tag = self.get_select_tag(tags) multiple_select_tag = self.get_multiple_select_tag(tags) config_tag = self.get_config_tag(tags) valid_tags = (tags[0],) if tags[0] is float: valid_tags = (*valid_tags, int) if 'can_be_none' in tags: valid_tags = (*valid_tags, None.__class__) if select_tag is not None: tag_data = getattr(self, select_tag) if self.none_data not in tag_data: tag_data.append(self.none_data) if multiple_select_tag is not None: tag_data = getattr(self, multiple_select_tag) if self.none_data not in tag_data: tag_data.append(self.none_data) if not isinstance(value, valid_tags): expected = f'{tags[0].__name__}' if 'can_be_none' in tags: expected += f', {None.__class__.__name__}' provided = type(value).__name__ converter = None if tags[0] is bool: if isinstance(value, str): converter = 'self.str_to_bool(value)' else: converter = 'tags[0](value)' elif tags[0] in [str, int]: converter = 'tags[0](value)' elif tags[0] is list: if tags[1] is list: converter = 'json.loads(value)' elif tags[1] is str: if isinstance(value, str): converter = 'value.split(",")' elif tags[1] is int: if isinstance(value, int): converter = '[value]' else: converter = '[int(value)]' success = False if converter is not None: try: exec(f'data{key} = {converter}') value = eval(f'data{key}') except Exception as e: self.debug_print_exception(e) else: success = True if not success: self.send( self.l( 'type_mismatch', f'{prefix}{key}', expected, provided, default=( "'{0}' 型が一致しません(予想: '{1}' 実際: '{2}')\n" "'{0}' type mismatch(Expected: '{1}' Provided: '{2}')\n" ) ), file=sys.stderr ) error_list.append(f'{prefix}{key}') else: self.send( self.l( 'type_mismatch_fixed', f'{prefix}{key}', expected, provided, eval(f'data{key}'), default=( "'{0}' 型が一致しません(予想: '{1}' 実際: '{2}') -> 修正されました: '{3}'\n" "'{0}' type mismatch(Expected: '{1}' Provided: '{2}') -> Fixed to: '{3}'\n" ) ), color=yellow, add_d=self.discord_error ) if f'{prefix}{key}' not in error_list: if tags[0] is list and value is not None: try: exec(f'data{key} = self.cleanup_list(value, "accept_empty" not in tags)') except Exception as e: self.debug_print_exception(e) else: if config_tag is None: for num, val in enumerate(value): tags_ = tags[1:].copy() if select_tag is not None: tags_.remove(select_tag) if multiple_select_tag is not None: tags_.remove(multiple_select_tag) self.value_check(data, error_list, prefix, f'{key}[{num}]', tags_) if select_tag is not None: values = [ (i['real_value'].lower() if isinstance(i['real_value'], str) else i['real_value']) for i in getattr(self, select_tag) ] if (value.lower() if isinstance(value, str) else value) not in values: self.send( self.l( 'not_in_select', f'{prefix}{key}', value, values, default=( "'{0}' '{1}' は {2} のどれにも一致しません\n" "'{0}' '{1}' don't match to any of {2}\n" ) ), file=sys.stderr ) error_list.append(f'{prefix}{key}') else: v = CaseInsensitiveDict({i['real_value']: i for i in getattr(self, select_tag)}) exec(f"data{key} = v[value]['real_value']") if multiple_select_tag is not None and value is not None: values = [ (i['real_value'].lower() if isinstance(i['real_value'], str) else i['real_value']) for i in getattr(self, multiple_select_tag) ] for num, val in enumerate(value): if (val.lower() if isinstance(val, str) else val) not in values: self.send( self.l( 'not_in_select', f'{prefix}{key}', value, values, default=( "'{0}' '{1}' は {2} のどれにも一致しません\n" "'{0}' '{1}' don't match to any of {2}\n" ) ), file=sys.stderr ) error_list.append(f'{prefix}{key}') break else: v = CaseInsensitiveDict({i['real_value']: i for i in getattr(self, multiple_select_tag)}) value[num] = v[val]['real_value'] func_str = tags[-1] if isinstance(func_str, str) and func_str.startswith('lambda '): try: func = eval(func_str, {**globals(), **locals()}) except Exception: pass else: if not func(value): self.send( self.l( 'check_failed', f'{prefix}{key}', value, func_str, default=( "{0} '{1}' はチェック '{2}' に一致しません\n" "{0} '{1}' don't match to check '{2}'\n" ) ), file=sys.stderr ) error_list.append(f'{prefix}{key}') if config_tag is not None: for num, val in enumerate(value): self.tag_check(eval(f'data{key}[{num}]'), error_list, f'{prefix}{key}[{num}]', getattr(self, f'{config_tag}_tags')) def cleanup_email(self, email: str) -> str: return re.sub(r'\.|\+', '', email).lower() def cleanup_code(self, content: str) -> str: if content.startswith('```') and content.endswith('```'): return '\n'.join(content.split('\n')[1:-1]) return content.strip(' \n') def cleanup_list(self, data: list, remove_empty: Optional[bool] = True) -> list: return [d for d in data if d is not None and (d != '' if remove_empty else True)] def cleanup_channel_name(self, text: str) -> str: converter = { ' ': '-', '.': '-', ',': '-', '--': '-' } for word, replace in converter.items(): text = text.replace(word, replace) return text.lower() def convert_backend_type(self, backendType: str) -> str: return self.BACKEND_TO_API_CONVERTER.get(backendType) def convert_to_backend_type(self, type: str) -> str: return self.API_TO_BACKEND_CONVERTER.get(type) def convert_backend_to_key(self, backendType: str) -> str: return self.BACKEND_TO_KEY_CONVERTER.get(backendType) def convert_backend_to_id(self, backendType: str) -> str: return self.BACKEND_TO_ID_CONVERTER.get(backendType) def convert_variant(self, variants: list) -> list: if variants is None: return None return [ { 'name': option['name'], 'variants': [ { 'c': variant['channel'], 'v': ( option['tag'] if any([option['tag'].startswith(fmt) for fmt in self.VARIANT_FORMATS]) else f'Color.{option["tag"]}' ), 'dE': 0 } ] } for variant in variants for option in variant.get('options', []) ] def get_item_str(self, item: dict) -> str: return "<Item name='{0[name]}' id='{0[id]}' path='{0[path]}'>".format( item ) def get_playlist_str(self, playlist: dict) -> str: return '<Playlist name={0[name]!r} id={0[id]!r}>'.format( playlist ) def get_variant_str(self, variant: dict) -> str: return ('<Variant name={0[name]!r} ' 'channel={1[c]!r} ' 'tag={1[v]!r}>'.format( variant, variant['variants'][0] )) def get_config_item_id(self, text: str) -> str: if text is None: return None match = self.config_item_pattern.match(text) if match is None: return None return match.group('id') def get_config_item_path(self, text: str) -> str: if text is None: return None match = self.config_item_pattern.match(text) if match is None: return None return match.group('path') def get_config_playlist_id(self, text: str) -> str: if text is None: return None match = self.config_playlist_pattern.match(text) if match is None: return None return match.group('id') def get_config_variant(self, text: str) -> dict: if text is None: return None match = self.config_variant_pattern.match(text) if match is None: return None return { 'name': match.group('name'), 'variants': [ { 'c': match.group('channel'), 'v': match.group('tag'), 'dE': 0 } ] } def port_file(self, filename: str, backup: Optional[bool] = True) -> None: if self.mode == 'repl' and os.path.isfile(f'{filename}.json'): data = self.load_json(filename, force_file=True) if backup: if self.isfile(f'{filename}_old', force_file=True): self.remove(f'{filename}_old', force_file=True) self.rename(filename, f'{filename}_old', force_file=True) try: self.remove(filename, force_file=True) except Exception as e: self.debug_print_exception(e) self.save_json(filename, data) def remove_unneeded_files(self) -> None: pc_only = [ 'INSTALL.bat', 'requirements.txt', 'RUN.bat' ] repl_only = [ '.replit', 'pyproject.toml' ] if self.mode == 'pc': for filename in repl_only: if os.path.isfile(filename): os.remove(filename) windows_only = [ 'INSTALL.bat', 'RUN.bat' ] else_only = [ 'INSTALL.sh', 'RUN.sh' ] if sys.platform == 'win32': for filename in else_only: if os.path.isfile(filename): os.remove(filename) else: for filename in windows_only: if os.path.isfile(filename): os.remove(filename) elif self.mode == 'repl': for filename in pc_only: if os.path.isfile(filename): os.remove(filename) def setup(self) -> None: self.remove_unneeded_files() files = [ ('config',), ('commands',), ('custom_commands',), ('replies',), ('cosmetic_preset',), ('command_stats', False), ('device_auths', False) ] for detail in files: self.port_file(*detail) self.config, self.error_config = self.load_config() if self.config is None and self.error_config is None: sys.exit(1) if self.error_config: self.send( self.l( 'error_keys', '\n'.join(self.error_config), default=( "以下のキーに問題がありました\n{0}\n" "There was an error on these keys\n{0}\n" ) ), file=sys.stderr ) self.webhook = WebhookClient(self, self, self.loop, self.http) self.webhook.start() if self.config['discord']['enabled']: self.discord_client = DiscordClient(self, self.config, loop=self.loop) if self.isfile(f"{self.lang_dir}/{self.config['lang']}", force_file=True): self.localize = self.load_localize(self.config['lang']) else: self.localize = self.load_localize('en') self.commands, self.error_commands = self.load_commands() if self.commands is None and self.error_commands is None: sys.exit(1) if self.error_commands: self.send( self.l( 'error_keys', '\n'.join(self.error_commands), default=( "以下のキーに問題がありました\n{0}\n" "There was an error on keys\n{0}\n" ) ), file=sys.stderr ) self.custom_commands, self.error_custom_commands = self.load_custom_commands() if self.custom_commands is None and self.error_custom_commands is None: sys.exit(1) if self.error_custom_commands: self.send( self.l( 'error_keys', '\n'.join(self.error_custom_commands), default=( "以下のキーに問題がありました\n{0}\n" "There was an error on keys\n{0}\n" ) ), file=sys.stderr ) self.replies, self.error_replies = self.load_replies() if self.replies is None and self.error_replies is None: sys.exit(1) if self.error_replies: self.send( self.l( 'error_keys', '\n'.join(self.error_replies), default=( "以下のキーに問題がありました\n{0}\n" "There was an error on keys\n{0}\n" ) ), file=sys.stderr ) ids = [f'{prefix}_'.lower() for prefix in self.BACKEND_TO_ID_CONVERTER.values()] self.whitelist_commands = [] for identifier in self.commands['whitelist_commands']: identifier = identifier.lower() command = self.all_commands.get(identifier) if command is None and identifier not in [*ids, 'playlist_', 'item_search']: self.send( self.l( 'command_not_found', self.l('whitelist_command'), identifier ) ) else: self.whitelist_commands.append(identifier) self.user_commands = [] for identifier in self.commands['user_commands']: identifier = identifier.lower() command = self.all_commands.get(identifier) if command is None and identifier not in [*ids, 'playlist_', 'item_search']: self.send( self.l( 'command_not_found', self.l('user_command'), identifier ) ) else: self.user_commands.append(identifier) if not self.is_error(): self.send( self.l( 'load_success', default=( "正常に読み込みが完了しました\n" "Loading successfully finished\n" ) ), color=green ) elif self.config['web']['enabled']: self.send( self.l( 'load_failed_web', default=( "正常に読み込みが完了しませんでした。ファイルを直接修正するか、Webから修正してください\n" "Loading didn't finish successfully. Please fix files directly or fix from web\n" ) ), file=sys.stderr ) else: self.send( self.l( 'load_failed', default=( "正常に読み込みが完了しませんでした。ファイルを修正してください\n" "Loading didn't finish successfully. Please fix files\n" ) ), file=sys.stderr ) sys.exit(1) try: self.cosmetic_presets = self.get_cosmetic_presets() except (json.decoder.JSONDecodeError, UnicodeDecodeError) as e: self.debug_print_exception(e) if self.isfile('cosmetic_presets_old'): self.remove('cosmetic_presets_old') self.rename('cosmetic_presets', 'cosmetic_presets_old') try: self.remove('cosmetic_presets') except Exception as e: self.debug_print_exception(e) self.cosmetic_presets = {} try: self.command_stats = self.get_command_stats() except (json.decoder.JSONDecodeError, UnicodeDecodeError) as e: self.debug_print_exception(e) if self.isfile('command_stats_old'): self.remove('command_stats_old') self.rename('command_stats', 'command_stats_old') try: self.remove('command_stats') except Exception as e: self.debug_print_exception(e) self.command_stats = {} async def aexec(self, body: str, variables: dict) -> Tuple[Any, str, str]: body = self.cleanup_code(body) stdout = io.StringIO() stderr = io.StringIO() exc = f"async def __exc__():\n{textwrap.indent(body,' ')}" exec(exc, variables) func = variables['__exc__'] with redirect_stdout(stdout), redirect_stderr(stderr): return await func(), stdout.getvalue(), stderr.getvalue() def format_item(self, data: dict, mode: str) -> dict: if mode == 'BenBot': return { 'id': data['id'], 'path': f"{self.convert_backend_type(data['backendType'])}ItemDefinition'{data['path'].replace('FortniteGame/Content', '/Game')}.{data['path'].split('/')[-1]}'", 'name': data['name'], 'url': data['icons']['icon'], 'type': { 'value': self.convert_backend_type(data['backendType']), 'displayValue': data['shortDescription'], 'backendValue': data['backendType'] }, 'set': data['set'], 'variants': self.convert_variant(data['variants']) } elif mode == 'Fortnite-API': return { 'id': data['id'], 'path': f"{data['type']['backendValue']}ItemDefinition'{data['path'].replace('FortniteGame/Content', '/Game')}.{data['path'].split('/')[-1]}'", 'name': data['name'], 'url': data['images']['icon'], 'type': data['type'], 'set': data['set']['value'] if data['set'] is not None else None, 'variants': self.convert_variant(data['variants']) } elif mode == 'FortniteApi.io': return { 'id': data['id'], 'path': MyClientPartyMember.get_asset_path(self.convert_to_backend_type(data['type']), data['id']), 'name': data['name'], 'url': data['images']['icon'], 'type': { 'value': data['type'], 'displayValue': ( self.l(data['type']).get_text() ), 'backendValue': self.convert_to_backend_type(data['type']) }, 'set': data['set'] if data['set'] else None, 'variants': None } def format_items(self, data: list, mode: str) -> list: types = [ 'AthenaCharacter', 'AthenaBackpack', 'AthenaPet', 'AthenaPetCarrier', 'AthenaPickaxe', 'AthenaDance', 'AthenaEmoji', 'AthenaToy' ] return [item for item in [ self.format_item(item, mode) for item in sorted(data, key=lambda x: x['id']) ] if item['type']['backendValue'] in types] async def get_item_data(self, lang: str) -> list: if self.config['api'] == 'BenBot': return self.format_items(await self.http.get( 'http://benbot.app/api/v1/cosmetics/br', params={'lang': lang} ), self.config['api']) elif self.config['api'] == 'Fortnite-API': return self.format_items((await self.http.get( 'https://fortnite-api.com/v2/cosmetics/br', params={'language': lang} ))['data'], self.config['api']) elif self.config['api'] == 'FortniteApi.io': items = (await self.http.get( 'https://fortniteapi.io/v1/items/list', params={'lang': lang}, headers={'Authorization': self.config['api_key']} ))['items'] return self.format_items( sum( [v for k, v in items.items() if k not in [ 'bannertoken', 'bundle', 'cosmeticvariant' ]], [] ), self.config['api'] ) async def store_item_data(self, lang: str) -> None: if self.isfile(f'{self.item_dir}/items_{lang}', force_file=True): items = await self.aload_json(f'{self.item_dir}/items_{lang}', force_file=True) items['items'] = CaseInsensitiveDict(items['items']) else: items = {'api': None, 'items': CaseInsensitiveDict()} data = await self.get_item_data(lang) if self.config['api'] == 'FortniteApi.io': for item in data: i = items['items'].get(item['id']) if i is None: items['items'][item['id']] = item elif i['variants'] is not None: item['variants'] = i['variants'] items['items'][item['id']] = item else: for item in data: items['items'][item['id']] = item items['api'] = self.config['api'] self.save_json( f'{self.item_dir}/items_{lang}', items, force_file=True, compact=True ) async def get_new_item_data(self, lang: str) -> list: if self.config['api'] == 'BenBot': return self.format_items((await self.http.get( 'http://benbot.app/api/v1/newCosmetics', params={'lang': lang} ))['items'], self.config['api']) elif self.config['api'] == 'Fortnite-API': return self.format_items((await self.http.get( 'https://fortnite-api.com/v2/cosmetics/br/new', params={'language': lang} ))['data']['items'], self.config['api']) elif self.config['api'] == 'FortniteApi.io': return self.format_items((await self.http.get( 'https://fortniteapi.io/v1/items/upcoming', params={'lang': lang}, headers={'Authorization': self.config['api_key']} ))['items'], self.config['api']) async def store_new_item_data(self, lang: str) -> None: if self.isfile(f'{self.item_dir}/new_items_{lang}', force_file=True): items = await self.aload_json(f'{self.item_dir}/new_items_{lang}', force_file=True) items['items'] = CaseInsensitiveDict(items['items']) else: items = {'api': None, 'items': CaseInsensitiveDict()} data = {i['id']: i for i in await self.get_new_item_data(lang)} if self.config['api'] == 'FortniteApi.io': for item in items['items'].values(): i = data.get(item['id']) if i is None: continue if item['variants'] is not None: data[item['id']]['variants'] = item['variants'] items['api'] = self.config['api'] self.save_json( f'{self.item_dir}/new_items_{lang}', {'api': self.config['api'], 'items': data}, force_file=True, compact=True ) def format_playlist(self, data: dict, mode: str) -> dict: if mode == 'Fortnite-API': return { 'id': data['id'], 'name': data['name'] } elif mode == 'FortniteApi.io': return { 'id': f'Playlist_{data["id"]}', 'name': data['name'] } def format_playlists(self, data: list, mode: str) -> list: return [ self.format_playlist(playlist, mode) for playlist in sorted(data, key=lambda x: x['id']) ] async def get_playlists_data(self, lang: str) -> list: if self.config['api'] == 'BenBot': return [] elif self.config['api'] == 'Fortnite-API': return self.format_playlists( (await self.http.get( 'https://fortnite-api.com/v1/playlists', params={'language': lang} ))['data'], self.config['api'] ) elif self.config['api'] == 'FortniteApi.io': return self.format_playlists( (await self.http.get( 'https://fortniteapi.io/v1/game/modes', params={'lang': lang}, headers={'Authorization': self.config['api_key']} ))['modes'], self.config['api'] ) async def store_playlists_data(self, lang: str) -> None: if self.isfile(f'{self.item_dir}/playlists_{lang}', force_file=True): playlists = await self.aload_json(f'{self.item_dir}/playlists_{lang}', force_file=True) playlists['playlists'] = CaseInsensitiveDict(playlists['playlists']) else: playlists = {'api': None, 'playlists': CaseInsensitiveDict()} data = await self.get_playlists_data(lang) for playlist in data: playlists['playlists'][playlist['id']] = playlist playlists['api'] = self.config['api'] self.save_json( f'{self.item_dir}/playlists_{lang}', playlists, force_file=True, compact=True ) async def get_banner_data(self) -> dict: if self.config['api'] == 'BenBot': data = await self.http.get( 'https://benbot.app/api/v1/files/search', params={ 'matchMethod': 'starts', 'path': 'FortniteGame/Content/Items/BannerIcons/' } ) url = 'https://benbot.app/api/v1/exportAsset?path={}&rawIcon=true' return { banner[39:-7]: url.format(banner) for banner in data } elif self.config['api'] == 'Fortnite-API': data = (await self.http.get( 'https://fortnite-api.com/v1/banners' ))['data'] return { banner['id']: banner['images']['icon'] for banner in data } elif self.config['api'] == 'FortniteApi.io': return {} async def store_banner_data(self) -> None: if self.isfile(f'{self.item_dir}/banners', force_file=True): banners = await self.aload_json(f'{self.item_dir}/banners', force_file=True) banners['banners'] = CaseInsensitiveDict(banners['banners']) else: banners = {'api': None, 'banners': CaseInsensitiveDict()} data = await self.get_banner_data() for id, image in data.items(): banners['banners'][id] = image banners['api'] = self.config['api'] self.save_json( f'{self.item_dir}/banners', banners, force_file=True, compact=True ) def get_banner_url(self, banner_id: str) -> Optional[str]: return self.banners.get(banner_id, self.web.url_for('static', filename='images/banner.jpg')) async def error_callback(self, client: Client, e: Exception): if isinstance(e, fortnitepy.AuthException): if 'Invalid device auth details passed.' in e.args[0]: self.debug_print_exception(e) self.send( self.l( 'device_auth_error', client.config['fortnite']['email'] ), add_p=self.time, file=sys.stderr ) details = self.get_device_auth_details() details.pop(client.config['fortnite']['email']) self.save_json('device_auths', details) else: self.print_exception(e) self.send( self.l( 'login_failed', client.config['fortnite']['email'] ), add_p=self.time, file=sys.stderr ) else: self.print_exception(e) self.send( self.l( 'login_failed', client.config['fortnite']['email'] ), add_p=self.time, file=sys.stderr ) async def all_ready_callback(self): if len(self.clients) > 1: await asyncio.gather(*[client.wait_until_ready() for client in self.clients]) self.send( self.l( 'all_login' ), color=green, add_p=self.time ) async def update_data(self) -> None: # Cosmetics tasks = [] if self.isfile(f"{self.item_dir}/items_{self.config['search_lang']}", force_file=True): try: items = await self.aload_json(f"{self.item_dir}/items_{self.config['search_lang']}", force_file=True) except json.decoder.JSONDecodeError as e: self.debug_print_exception(e) await self.aremove(f"{self.item_dir}/items_{self.config['search_lang']}", force_file=True) flag = True else: if items['api'] != self.config['api']: flag = True else: flag = self.is_not_edited_for( f"{self.item_dir}/items_{self.config['search_lang']}", datetime.timedelta(hours=2), force_file=True ) else: flag = True if flag: tasks.append(self.loop.create_task(self.store_item_data(self.config['search_lang']))) if self.isfile(f"{self.item_dir}/items_{self.config['sub_search_lang']}", force_file=True): try: items = await self.aload_json(f"{self.item_dir}/items_{self.config['sub_search_lang']}", force_file=True) except json.decoder.JSONDecodeError as e: self.debug_print_exception(e) await self.aremove(f"{self.item_dir}/items_{self.config['sub_search_lang']}", force_file=True) flag = True else: if items['api'] != self.config['api']: flag = True else: flag = self.is_not_edited_for( f"{self.item_dir}/items_{self.config['sub_search_lang']}", datetime.timedelta(hours=2), force_file=True ) else: flag = True if flag: tasks.append(self.loop.create_task(self.store_item_data(self.config['sub_search_lang']))) exception = False if tasks: done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION) for p in pending: if not p.done(): p.cancel() for d in done: if d.exception() is not None: exception = True self.print_exception(d.exception()) if exception: self.send( self.l( 'get_item_failed' ), file=sys.stderr ) for lang in (self.config['search_lang'], self.config['sub_search_lang']): if not self.isfile(f'{self.item_dir}/items_{lang}', force_file=True): sys.exit(1) # New cosmetics tasks = [] if self.isfile(f"{self.item_dir}/new_items_{self.config['search_lang']}", force_file=True): try: items = await self.aload_json(f"{self.item_dir}/new_items_{self.config['search_lang']}", force_file=True) except json.decoder.JSONDecodeError as e: self.debug_print_exception(e) await self.aremove(f"{self.item_dir}/new_items_{self.config['search_lang']}", force_file=True) flag = True else: if items['api'] != self.config['api']: flag = True else: flag = self.is_not_edited_for( f"{self.item_dir}/new_items_{self.config['search_lang']}", datetime.timedelta(hours=2), force_file=True ) else: flag = True if flag: try: await self.store_new_item_data(self.config['search_lang']) except Exception as e: self.print_exception(e) self.send( self.l( 'get_item_failed' ), file=sys.stderr ) # Playlists tasks = [] if self.isfile(f"{self.item_dir}/playlists_{self.config['search_lang']}", force_file=True): try: playlists = await self.aload_json(f"{self.item_dir}/playlists_{self.config['search_lang']}", force_file=True) except json.decoder.JSONDecodeError as e: self.debug_print_exception(e) await self.aremove(f"{self.item_dir}/playlists_{self.config['search_lang']}", force_file=True) flag = True else: if playlists['api'] != self.config['api']: flag = True else: flag = self.is_not_edited_for( f"{self.item_dir}/playlists_{self.config['search_lang']}", datetime.timedelta(hours=2), force_file=True ) else: flag = True if flag: tasks.append(self.loop.create_task(self.store_playlists_data(self.config['search_lang']))) if self.isfile(f"{self.item_dir}/playlists_{self.config['sub_search_lang']}", force_file=True): try: playlists = await self.aload_json(f"{self.item_dir}/playlists_{self.config['sub_search_lang']}", force_file=True) except json.decoder.JSONDecodeError as e: self.debug_print_exception(e) await self.aremove(f"{self.item_dir}/playlists_{self.config['sub_search_lang']}", force_file=True) flag = True else: if playlists['api'] != self.config['api']: flag = True else: flag = self.is_not_edited_for( f"{self.item_dir}/playlists_{self.config['sub_search_lang']}", datetime.timedelta(hours=2), force_file=True ) else: flag = True if flag: tasks.append(self.loop.create_task(self.store_playlists_data(self.config['sub_search_lang']))) exception = False if tasks: done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION) for p in pending: if not p.done(): p.cancel() for d in done: if d.exception() is not None: exception = True self.print_exception(d.exception()) if exception: self.send( self.l( 'get_playlist_failed' ), file=sys.stderr ) for lang in (self.config['search_lang'], self.config['sub_search_lang']): if not self.isfile(f'{self.item_dir}/playlists_{lang}', force_file=True): sys.exit(1) # Banner if not exception: if self.isfile(f'{self.item_dir}/banners', force_file=True): try: banners = await self.aload_json(f"{self.item_dir}/banners", force_file=True) except json.decoder.JSONDecodeError as e: self.debug_print_exception(e) await self.aremove(f"{self.item_dir}/banners", force_file=True) flag = True else: if banners['api'] != self.config['api']: flag = True else: flag = self.is_not_edited_for( f'{self.item_dir}/banners', datetime.timedelta(hours=2), force_file=True ) else: flag = True if flag: await self.store_banner_data() def load_data(self) -> None: self.main_items = CaseInsensitiveDict(self.load_json( f'{self.item_dir}/items_{self.config["search_lang"]}', force_file=True )['items']) self.sub_items = CaseInsensitiveDict(self.load_json( f'{self.item_dir}/items_{self.config["sub_search_lang"]}', force_file=True )['items']) self.new_items = CaseInsensitiveDict(self.load_json( f'{self.item_dir}/new_items_{self.config["search_lang"]}', force_file=True )['items']) self.main_playlists = CaseInsensitiveDict(self.load_json( f'{self.item_dir}/playlists_{self.config["search_lang"]}', force_file=True )['playlists']) self.sub_playlists = CaseInsensitiveDict(self.load_json( f'{self.item_dir}/playlists_{self.config["sub_search_lang"]}', force_file=True )['playlists']) self.banners = CaseInsensitiveDict(self.load_json( f'{self.item_dir}/banners', force_file=True )['banners']) def fix_config(self, config: dict) -> None: if isinstance(config['fortnite']['party']['privacy'], str): config['fortnite']['party']['privacy'] = getattr( PartyPrivacy, config['fortnite']['party']['privacy'].upper() ) if isinstance(config['fortnite']['platform'], str): config['fortnite']['platform'] = fortnitepy.Platform( config['fortnite']['platform'].upper() ) for num, channel in enumerate(config['discord']['channels']): config['discord']['channels'][num] = self.cleanup_channel_name(channel) if isinstance(config['discord']['status_type'], str): config['discord']['status_type'] = getattr( discord.ActivityType, config['discord']['status_type'].lower() ) if config['fortnite']['ng_platforms'] is not None: for num, ng_platform in enumerate(config['fortnite']['ng_platforms']): config['fortnite']['ng_platforms'][num] = fortnitepy.Platform( ng_platform.upper() ) self.fix_cosmetic_config(config) def fix_config_all(self) -> None: if isinstance(self.config['discord']['status_type'], str): self.config['discord']['status_type'] = getattr( discord.ActivityType, self.config['discord']['status_type'].lower() ) for num, channel in enumerate(self.config['discord']['channels']): self.config['discord']['channels'][num] = self.cleanup_channel_name(channel) for config in self.config['clients']: self.fix_config(config) def fix_cosmetic_config(self, config: dict) -> None: if config['fortnite']['party']['playlist']: if self.get_config_playlist_id(config['fortnite']['party']['playlist']) is None: playlist = self.searcher.get_playlist( config['fortnite']['party']['playlist'] ) if playlist is None: playlists = self.searcher.search_playlist_name_id( config['fortnite']['party']['playlist'] ) if len(playlists) != 0: playlist = playlists[0] if playlist is not None: config['fortnite']['party']['playlist'] = ( self.get_playlist_str(playlist) ) else: self.send( self.l( 'not_found', self.l('playlist'), config['fortnite']['party']['playlist'] ), add_p=self.time, file=sys.stderr ) for item in ['AthenaCharacter', 'AthenaBackpack,AthenaPet,AthenaPetCarrier', 'AthenaPickaxe', 'AthenaDance,AthenaEmoji,AthenaToy']: lang_key = self.convert_backend_type(item.split(",")[0]) for prefix in ['', 'join_', 'leave_']: key = f'{prefix}{lang_key}' style_key = f'{key}_style' if not config['fortnite'][key]: continue def fix_cosmetic_style_config(): if 'AthenaDance' in item or not config['fortnite'][style_key]: return for num, style_info in enumerate(config['fortnite'][style_key]): if self.get_config_variant(style_info) is not None: continue styles = self.searcher.search_style( self.get_config_item_id(config['fortnite'][key]), style_info ) if len(styles) != 0: style = styles[0] config['fortnite'][style_key][num] = ( self.get_variant_str(style) ) else: self.send( self.l( 'not_found', self.l('style'), config['fortnite'][key] ), add_p=self.time, file=sys.stderr ) if self.get_config_item_id(config['fortnite'][key]) is not None: fix_cosmetic_style_config() continue if config['fortnite'][key]: old = re.compile( r"<Item name='(?P<name>.+)' " r"id='(?P<id>.+)'>" ) match = old.match(config['fortnite'][key]) cosmetic = self.searcher.get_item( match.group('id') if match is not None else config['fortnite'][key] ) if cosmetic is None: cosmetics = self.searcher.search_item_name_id( config['fortnite'][key], item ) if len(cosmetics) != 0: cosmetic = cosmetics[0] if cosmetic is not None: config['fortnite'][key] = ( self.get_item_str(cosmetic) ) fix_cosmetic_style_config() else: self.send( self.l( 'not_found', self.l(lang_key), config['fortnite'][key] ), add_p=self.time, file=sys.stderr ) key = f'ng_{lang_key}s' if not config['fortnite'][key]: continue for num, value in enumerate(config['fortnite'][key]): if self.get_config_item_id(value) is not None: continue if value: cosmetic = self.searcher.get_item( value ) if cosmetic is None: cosmetics = self.searcher.search_item_name_id( value, item ) if len(cosmetics) != 0: cosmetic = cosmetics[0] if cosmetic is not None: config['fortnite'][key][num] = ( self.get_item_str(cosmetic) ) else: self.send( self.l( 'not_found', self.l(lang_key), value ), add_p=self.time, file=sys.stderr ) def fix_cosmetic_config_all(self) -> None: for config in self.config['clients']: self.fix_cosmetic_config(config) async def reboot(self) -> None: await self.close() os.execv(sys.executable, [sys.executable, sys.argv[0], *sys.argv[1:]]) async def close(self) -> None: if self.server is not None: await self.server.close() coros = {client.wait_until_ready() for client in self.clients} if coros: await asyncio.wait(coros) await fortnitepy.close_multiple( [client for client in self.clients if client.is_ready() or client.is_booting()] ) await self.http.close() async def rebooter(self) -> None: await asyncio.sleep(self.config['restart_in']) await self.reboot() async def save_command_stats(self) -> None: while True: await asyncio.sleep(60) self.store_command_stats() async def keep_alive(self) -> None: url = None if self.mode == 'glitch': url = f'https://{os.getenv("PROJECT_DOMAIN")}.glitch.me' elif self.mode == 'repl': url = f'https://{os.getenv("REPL_SLUG")}.{os.getenv("REPL_OWNER")}.repl.co' await self.http.post('https://PublicPinger.gomashio1596.repl.co/api/add', json={'url': url}) while True: await asyncio.sleep(300) await self.http.get(url) async def start(self) -> None: self.send( self.l('credit'), color=cyan ) self.send( f'{self.l("loglevel", self.l("loglevel_" + self.config["loglevel"]))}\n', color=green ) if self.config['debug']: logger = logging.getLogger('fortnitepy.auth') logger.setLevel(level=logging.DEBUG) handler = logging.StreamHandler(sys.stdout) handler.setFormatter(logging.Formatter('\u001b[35m %(asctime)s:%(levelname)s:%(name)s: %(message)s \u001b[0m')) logger.addHandler(handler) logger = logging.getLogger('fortnitepy.http') logger.setLevel(level=logging.DEBUG) handler = logging.StreamHandler(sys.stdout) handler.setFormatter(logging.Formatter('\u001b[35m %(asctime)s:%(levelname)s:%(name)s: %(message)s \u001b[0m')) logger.addHandler(handler) logger = logging.getLogger('fortnitepy.xmpp') logger.setLevel(level=logging.DEBUG) handler = logging.StreamHandler(sys.stdout) handler.setFormatter(logging.Formatter('\u001b[35m %(asctime)s:%(levelname)s:%(name)s: %(message)s \u001b[0m')) logger.addHandler(handler) version = sys.version_info if version.minor != 7: self.send( self.l( 'not_recommended_version', platform.python_version() ), color=yellow ) python_64bit = sys.maxsize > 2 ** 32 if sys.platform == 'win32': os_64bit = os.getenv('PROCESSOR_ARCHITECTURE') != 'x86' elif sys.platform == 'linux': output = subprocess.check_output(['uname', '-a']).decode() os_64bit = 'x86_64' in output or 'amd64' in output elif sys.platform == 'darwin': os_64bit = ( subprocess.check_output(['uname', '-a']).decode() ).endswith('x86_64') else: os_64bit = python_64bit if os_64bit and not python_64bit: self.send( self.l( 'bit_mismatch', '64' if python_64bit else '32', '64' if os_64bit else '32' ), color=yellow ) if self.config['check_update_on_startup']: if await self.updater.check_updates(self.dev): await self.reboot() sys.exit(0) if not self.is_error() and self.config['status'] == 1: self.send( self.l( 'updating', ), add_p=self.time ) await self.update_data() self.load_data() self.searcher = Searcher( self, self.main_items, self.sub_items, self.main_playlists, self.sub_playlists, True, False ) self.send( self.l( 'booting', ), add_p=self.time ) if self.config['restart_in']: self.loop.create_task(self.rebooter()) self.loop.create_task(self.save_command_stats()) if self.mode != 'pc' and self.config['web']['enabled']: self.loop.create_task(self.keep_alive()) if self.config['web']['enabled'] or self.config['status'] == 0: if not self.config['web']['access_log']: logger = getLogger('sanic.root') logger.setLevel(WARNING) try: self.server = await self.web.create_server( host=self.config['web']['ip'], port=self.config['web']['port'], access_log=self.config['web']['access_log'], return_asyncio_server=True ) except OSError as e: self.debug_print_exception(e) self.send( self.l( 'web_already_running' ), add_p=self.time, file=sys.stderr ) else: if self.mode == 'glitch': url = f'https://{os.getenv("PROJECT_DOMAIN")}.glitch.me' elif self.mode == 'repl': url = f'https://{os.getenv("REPL_SLUG")}--{os.getenv("REPL_OWNER")}.repl.co' else: url = f"http://{self.config['web']['ip']}:{self.config['web']['port']}" self.send( self.l( 'web_running', url ), color=green, add_p=self.time ) if (self.mode == 'repl' and (not self.config['web']['login_required'] or (self.config['web']['login_required'] and not self.config['web']['password']))): self.send( self.l('password_not_set'), color=yellow ) if not self.is_error() and self.config['status'] == 1: self.fix_config_all() self.save_json('config', self.config) refresh_tokens = {} device_auths = {} if self.use_device_auth: try: device_auths = self.get_device_auth_details() except (json.decoder.JSONDecodeError, UnicodeDecodeError) as e: self.debug_print_exception(e) if self.isfile('device_auths_old'): self.remove('device_auths_old') self.rename('device_auths', 'device_auths_old') try: self.remove('device_auths') except Exception as e: self.debug_print_exception(e) else: try: refresh_tokens = self.get_refresh_tokens() except (json.decoder.JSONDecodeError, UnicodeDecodeError) as e: self.debug_print_exception(e) if self.isfile('refresh_tokens_old'): self.remove('refresh_tokens_old') self.rename('refresh_tokens', 'refresh_tokens_old') try: self.remove('refresh_tokens') except Exception as e: self.debug_print_exception(e) def session_id(email): async def _session_id(): while True: text = self.l('session_id', email).get_text() self.web_text = text data = await ainput(f'{text}\n') match = re.search(r'[a-z0-9]{32}', data) if match is not None: return match.group() return _session_id for num, config in enumerate(self.config['clients']): refresh_token = refresh_tokens.get(config['fortnite']['email'].lower(), None) device_auth_details = device_auths.get(config['fortnite']['email'].lower(), {}) party_meta = [] if config['fortnite']['party']['playlist']: party_meta.append(partial( MyClientParty.set_playlist, playlist=(self.get_config_playlist_id(config['fortnite']['party']['playlist']) or config['fortnite']['party']['playlist']) )) if config['fortnite']['party']['disable_voice_chat']: party_meta.append(partial( MyClientParty.disable_voice_chat )) member_meta = [ partial( MyClientPartyMember.set_banner, icon=config['fortnite']['banner_id'], color=config['fortnite']['banner_color'], season_level=config['fortnite']['level'] ), partial( MyClientPartyMember.set_battlepass_info, has_purchased=True, level=config['fortnite']['tier'] ) ] items = [ 'AthenaCharacter', 'AthenaBackpack', 'AthenaPickaxe', 'AthenaDance' ] for item in items: conf = self.convert_backend_type(item) variants = [] if item != 'AthenaDance' and config['fortnite'][f'{conf}_style'] is not None: for style in config['fortnite'][f'{conf}_style']: variant = self.get_config_variant(style) if variant is not None: variants.extend(variant['variants']) section = 0 if item == 'AthenaDance': section = config['fortnite'][f'{conf}_section'] coro = fortnitepy.EditEntry( MyClientPartyMember.change_asset, item, (self.get_config_item_path(config['fortnite'][conf]) or config['fortnite'][conf]), variants=variants, section=section, keep=False, name=f'ClientPartyMember.set_{conf}' ) member_meta.append(coro) avatar = fortnitepy.kairos.get_random_default_avatar() background_colors = ( config['fortnite']['avatar_color'].split(',') if ',' in config['fortnite']['avatar_color'] else getattr(fortnitepy.KairosBackgroundColorPreset, config['fortnite']['avatar_color'].upper()) ) auth = None if self.use_device_auth and device_auth_details: auth = fortnitepy.DeviceAuth(**device_auth_details) if auth is None: if self.use_device_code: auth = MyAdvancedAuth(refresh_token) else: auth = MyAdvancedAuth(refresh_token, session_id(config['fortnite']['email'])) client = Client( self, config, num, auth=auth, avatar=fortnitepy.Avatar( asset=( config['fortnite']['avatar_id'] or avatar.asset ), background_colors=( background_colors if config['fortnite']['avatar_color'] else avatar.background_colors ) ), status=config['fortnite']['status'], platform=config['fortnite']['platform'], wait_for_member_meta_in_events=False, loop=self.loop ) client.default_party_config = fortnitepy.DefaultPartyConfig( cls=MyClientParty, privacy=config['fortnite']['party']['privacy'], team_change_allowed=config['fortnite']['party']['allow_swap'], max_size=config['fortnite']['party']['max_size'], meta=party_meta ) client.default_party_member_config = fortnitepy.DefaultPartyMemberConfig( cls=MyClientPartyMember, meta=member_meta ) self.clients.append(client) if len(self.clients) == 0: self.send( self.l('no_clients') ) while True: await asyncio.sleep(0.1) else: tasks = [ fortnitepy.start_multiple( self.clients, shutdown_on_error=False, error_callback=self.error_callback, all_ready_callback=self.all_ready_callback ) ] if self.discord_client is not None and self.config['discord']['token']: tasks.append(self.discord_client.start(self.config['discord']['token'])) try: await asyncio.gather(*tasks) except Exception as e: self.print_exception(e) while True: await asyncio.sleep(0.1) async def process_command(self, message: MyMessage, *args: Any, **kwargs: Any) -> None: if not message.args: return for client in self.clients: message.client = client self.loop.create_task(client.process_command(message, None))
[ "logging.getLogger", "aioconsole.ainput", "logging.StreamHandler", "re.compile", "aiofiles.open", "contextlib.redirect_stderr", "sys.exit", "datetime.timedelta", "os.remove", "re.search", "textwrap.indent", "aiofiles.os.remove", "json.dumps", "os.execv", "asyncio.sleep", "asyncio.gathe...
[((1363, 1397), 'importlib.import_module', 'importlib.import_module', (['"""discord"""'], {}), "('discord')\n", (1386, 1397), False, 'import importlib\n'), ((1412, 1449), 'importlib.import_module', 'importlib.import_module', (['"""fortnitepy"""'], {}), "('fortnitepy')\n", (1435, 1449), False, 'import importlib\n'), ((1455, 1490), 'importlib.import_module', 'importlib.import_module', (['"""pykakasi"""'], {}), "('pykakasi')\n", (1478, 1490), False, 'import importlib\n'), ((1171, 1197), 'os.getenv', 'os.getenv', (['"""REPLIT_DB_URL"""'], {}), "('REPLIT_DB_URL')\n", (1180, 1197), False, 'import os\n'), ((4496, 4537), 'os.makedirs', 'os.makedirs', (['self.item_dir'], {'exist_ok': '(True)'}), '(self.item_dir, exist_ok=True)\n', (4507, 4537), False, 'import os\n'), ((4601, 4661), 're.compile', 're.compile', (['"""[a-zA-Z0-9.+-_]+@[a-zA-Z0-9-_]+\\\\.[a-zA-Z0-9]+"""'], {}), "('[a-zA-Z0-9.+-_]+@[a-zA-Z0-9-_]+\\\\.[a-zA-Z0-9]+')\n", (4611, 4661), False, 'import re\n'), ((4717, 4781), 're.compile', 're.compile', (['"""(?P<space>\\\\s*)(return|return\\\\s+(?P<text>.*))\\\\s*"""'], {}), "('(?P<space>\\\\s*)(return|return\\\\s+(?P<text>.*))\\\\s*')\n", (4727, 4781), False, 'import re\n'), ((27205, 27281), 're.compile', 're.compile', (['"""<Item name=\'(?P<name>.+)\' id=\'(?P<id>.+)\' path=\'(?P<path>.+)\'>"""'], {}), '("<Item name=\'(?P<name>.+)\' id=\'(?P<id>.+)\' path=\'(?P<path>.+)\'>")\n', (27215, 27281), False, 'import re\n'), ((27381, 27441), 're.compile', 're.compile', (['"""<Playlist name=\'(?P<name>.+)\' id=\'(?P<id>.+)\'>"""'], {}), '("<Playlist name=\'(?P<name>.+)\' id=\'(?P<id>.+)\'>")\n', (27391, 27441), False, 'import re\n'), ((27523, 27620), 're.compile', 're.compile', (['"""<Variant name=\'(?P<name>.+)\' channel=\'(?P<channel>.+)\' tag=\'(?P<tag>.+)\'>"""'], {}), '(\n "<Variant name=\'(?P<name>.+)\' channel=\'(?P<channel>.+)\' tag=\'(?P<tag>.+)\'>"\n )\n', (27533, 27620), False, 'import re\n'), ((34564, 34619), 'json.dumps', 'json.dumps', (['data'], {'ensure_ascii': '(False)', 'cls': 'MyJSONEncoder'}), '(data, ensure_ascii=False, cls=MyJSONEncoder)\n', (34574, 34619), False, 'import json\n'), ((37235, 37257), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (37255, 37257), False, 'import traceback\n'), ((73729, 73742), 'io.StringIO', 'io.StringIO', ([], {}), '()\n', (73740, 73742), False, 'import io\n'), ((73761, 73774), 'io.StringIO', 'io.StringIO', ([], {}), '()\n', (73772, 73774), False, 'import io\n'), ((103669, 103739), 'os.execv', 'os.execv', (['sys.executable', '[sys.executable, sys.argv[0], *sys.argv[1:]]'], {}), '(sys.executable, [sys.executable, sys.argv[0], *sys.argv[1:]])\n', (103677, 103739), False, 'import os\n'), ((1223, 1234), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1232, 1234), False, 'import os\n'), ((27704, 27727), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ([], {}), '()\n', (27725, 27727), False, 'import aiohttp\n'), ((31016, 31040), 'os.remove', 'os.remove', (['f"""{key}.json"""'], {}), "(f'{key}.json')\n", (31025, 31040), False, 'import os\n'), ((31720, 31767), 'os.rename', 'os.rename', (['f"""{key_src}.json"""', 'f"""{key_dst}.json"""'], {}), "(f'{key_src}.json', f'{key_dst}.json')\n", (31729, 31767), False, 'import os\n'), ((32561, 32577), 'json.loads', 'json.loads', (['data'], {}), '(data)\n', (32571, 32577), False, 'import json\n'), ((33417, 33433), 'json.loads', 'json.loads', (['data'], {}), '(data)\n', (33427, 33433), False, 'import json\n'), ((34843, 34898), 'datetime.datetime.fromisoformat', 'datetime.datetime.fromisoformat', (["db[key]['last_edited']"], {}), "(db[key]['last_edited'])\n", (34874, 34898), False, 'import datetime\n'), ((34934, 34956), 'os.stat', 'os.stat', (['f"""{key}.json"""'], {}), "(f'{key}.json')\n", (34941, 34956), False, 'import os\n'), ((34977, 35023), 'datetime.datetime.fromtimestamp', 'datetime.datetime.fromtimestamp', (['stat.st_mtime'], {}), '(stat.st_mtime)\n', (35008, 35023), False, 'import datetime\n'), ((38172, 38187), 'tzlocal.get_localzone', 'get_localzone', ([], {}), '()\n', (38185, 38187), False, 'from tzlocal import get_localzone\n'), ((38267, 38295), 'datetime.timedelta', 'datetime.timedelta', ([], {'hours': '(12)'}), '(hours=12)\n', (38285, 38295), False, 'import datetime\n'), ((65239, 65273), 'os.path.isfile', 'os.path.isfile', (['f"""{filename}.json"""'], {}), "(f'{filename}.json')\n", (65253, 65273), False, 'import os\n'), ((67424, 67435), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (67432, 67435), False, 'import sys\n'), ((68446, 68457), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (68454, 68457), False, 'import sys\n'), ((69044, 69055), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (69052, 69055), False, 'import sys\n'), ((69616, 69627), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (69624, 69627), False, 'import sys\n'), ((73929, 73952), 'contextlib.redirect_stdout', 'redirect_stdout', (['stdout'], {}), '(stdout)\n', (73944, 73952), False, 'from contextlib import redirect_stderr, redirect_stdout\n'), ((73954, 73977), 'contextlib.redirect_stderr', 'redirect_stderr', (['stderr'], {}), '(stderr)\n', (73969, 73977), False, 'from contextlib import redirect_stderr, redirect_stdout\n'), ((104221, 104261), 'asyncio.sleep', 'asyncio.sleep', (["self.config['restart_in']"], {}), "(self.config['restart_in'])\n", (104234, 104261), False, 'import asyncio\n'), ((105257, 105293), 'logging.getLogger', 'logging.getLogger', (['"""fortnitepy.auth"""'], {}), "('fortnitepy.auth')\n", (105274, 105293), False, 'import logging\n'), ((105367, 105400), 'logging.StreamHandler', 'logging.StreamHandler', (['sys.stdout'], {}), '(sys.stdout)\n', (105388, 105400), False, 'import logging\n'), ((105590, 105626), 'logging.getLogger', 'logging.getLogger', (['"""fortnitepy.http"""'], {}), "('fortnitepy.http')\n", (105607, 105626), False, 'import logging\n'), ((105700, 105733), 'logging.StreamHandler', 'logging.StreamHandler', (['sys.stdout'], {}), '(sys.stdout)\n', (105721, 105733), False, 'import logging\n'), ((105923, 105959), 'logging.getLogger', 'logging.getLogger', (['"""fortnitepy.xmpp"""'], {}), "('fortnitepy.xmpp')\n", (105940, 105959), False, 'import logging\n'), ((106033, 106066), 'logging.StreamHandler', 'logging.StreamHandler', (['sys.stdout'], {}), '(sys.stdout)\n', (106054, 106066), False, 'import logging\n'), ((7507, 7526), 'glob.glob', 'glob', (['"""lang/*.json"""'], {}), "('lang/*.json')\n", (7511, 7526), False, 'from glob import glob\n'), ((30559, 30570), 'replit.db.get', 'db.get', (['key'], {}), '(key)\n', (30565, 30570), False, 'from replit import db\n'), ((30645, 30674), 'os.path.isfile', 'os.path.isfile', (['f"""{key}.json"""'], {}), "(f'{key}.json')\n", (30659, 30674), False, 'import os\n'), ((31343, 31365), 'aiofiles.os.remove', 'aremove', (['f"""{key}.json"""'], {}), "(f'{key}.json')\n", (31350, 31365), True, 'from aiofiles.os import remove as aremove\n'), ((32015, 32043), 'json.loads', 'json.loads', (["db[key]['value']"], {}), "(db[key]['value'])\n", (32025, 32043), False, 'import json\n'), ((32832, 32860), 'json.loads', 'json.loads', (["db[key]['value']"], {}), "(db[key]['value'])\n", (32842, 32860), False, 'import json\n'), ((33763, 33819), 'json.dumps', 'json.dumps', (['value'], {'ensure_ascii': '(False)', 'cls': 'MyJSONEncoder'}), '(value, ensure_ascii=False, cls=MyJSONEncoder)\n', (33773, 33819), False, 'import json\n'), ((35237, 35263), 'datetime.datetime.utcnow', 'datetime.datetime.utcnow', ([], {}), '()\n', (35261, 35263), False, 'import datetime\n'), ((37633, 37655), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (37653, 37655), False, 'import traceback\n'), ((37946, 37969), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (37967, 37969), False, 'import datetime\n'), ((38039, 38065), 'datetime.datetime.utcnow', 'datetime.datetime.utcnow', ([], {}), '()\n', (38063, 38065), False, 'import datetime\n'), ((43334, 43382), 'json.dumps', 'json.dumps', (['config'], {'indent': '(4)', 'ensure_ascii': '(False)'}), '(config, indent=4, ensure_ascii=False)\n', (43344, 43382), False, 'import json\n'), ((46441, 46491), 'json.dumps', 'json.dumps', (['commands'], {'indent': '(4)', 'ensure_ascii': '(False)'}), '(commands, indent=4, ensure_ascii=False)\n', (46451, 46491), False, 'import json\n'), ((48090, 48147), 'json.dumps', 'json.dumps', (['custom_commands'], {'indent': '(4)', 'ensure_ascii': '(False)'}), '(custom_commands, indent=4, ensure_ascii=False)\n', (48100, 48147), False, 'import json\n'), ((49702, 49751), 'json.dumps', 'json.dumps', (['replies'], {'indent': '(4)', 'ensure_ascii': '(False)'}), '(replies, indent=4, ensure_ascii=False)\n', (49712, 49751), False, 'import json\n'), ((61332, 61360), 're.sub', 're.sub', (['"""\\\\.|\\\\+"""', '""""""', 'email'], {}), "('\\\\.|\\\\+', '', email)\n", (61338, 61360), False, 'import re\n'), ((66120, 66144), 'os.path.isfile', 'os.path.isfile', (['filename'], {}), '(filename)\n', (66134, 66144), False, 'import os\n'), ((72475, 72486), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (72483, 72486), False, 'import sys\n'), ((73817, 73844), 'textwrap.indent', 'textwrap.indent', (['body', '""" """'], {}), "(body, ' ')\n", (73832, 73844), False, 'import textwrap\n'), ((88690, 88746), 'asyncio.wait', 'asyncio.wait', (['tasks'], {'return_when': 'asyncio.FIRST_EXCEPTION'}), '(tasks, return_when=asyncio.FIRST_EXCEPTION)\n', (88702, 88746), False, 'import asyncio\n'), ((92994, 93050), 'asyncio.wait', 'asyncio.wait', (['tasks'], {'return_when': 'asyncio.FIRST_EXCEPTION'}), '(tasks, return_when=asyncio.FIRST_EXCEPTION)\n', (93006, 93050), False, 'import asyncio\n'), ((103966, 103985), 'asyncio.wait', 'asyncio.wait', (['coros'], {}), '(coros)\n', (103978, 103985), False, 'import asyncio\n'), ((104382, 104399), 'asyncio.sleep', 'asyncio.sleep', (['(60)'], {}), '(60)\n', (104395, 104399), False, 'import asyncio\n'), ((104874, 104892), 'asyncio.sleep', 'asyncio.sleep', (['(300)'], {}), '(300)\n', (104887, 104892), False, 'import asyncio\n'), ((105435, 105525), 'logging.Formatter', 'logging.Formatter', (['"""\x1b[35m %(asctime)s:%(levelname)s:%(name)s: %(message)s \x1b[0m"""'], {}), "(\n '\\x1b[35m %(asctime)s:%(levelname)s:%(name)s: %(message)s \\x1b[0m')\n", (105452, 105525), False, 'import logging\n'), ((105768, 105858), 'logging.Formatter', 'logging.Formatter', (['"""\x1b[35m %(asctime)s:%(levelname)s:%(name)s: %(message)s \x1b[0m"""'], {}), "(\n '\\x1b[35m %(asctime)s:%(levelname)s:%(name)s: %(message)s \\x1b[0m')\n", (105785, 105858), False, 'import logging\n'), ((106101, 106191), 'logging.Formatter', 'logging.Formatter', (['"""\x1b[35m %(asctime)s:%(levelname)s:%(name)s: %(message)s \x1b[0m"""'], {}), "(\n '\\x1b[35m %(asctime)s:%(levelname)s:%(name)s: %(message)s \\x1b[0m')\n", (106118, 106191), False, 'import logging\n'), ((106618, 106653), 'os.getenv', 'os.getenv', (['"""PROCESSOR_ARCHITECTURE"""'], {}), "('PROCESSOR_ARCHITECTURE')\n", (106627, 106653), False, 'import os\n'), ((107520, 107531), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (107528, 107531), False, 'import sys\n'), ((108671, 108694), 'logging.getLogger', 'getLogger', (['"""sanic.root"""'], {}), "('sanic.root')\n", (108680, 108694), False, 'from logging import WARNING, getLogger\n'), ((118369, 118387), 'asyncio.sleep', 'asyncio.sleep', (['(0.1)'], {}), '(0.1)\n', (118382, 118387), False, 'import asyncio\n'), ((32947, 32985), 'aiofiles.open', 'aopen', (['f"""{key}.json"""'], {'encoding': '"""utf-8"""'}), "(f'{key}.json', encoding='utf-8')\n", (32952, 32985), True, 'from aiofiles import open as aopen\n'), ((34049, 34107), 'json.dump', 'json.dump', (['value', 'f'], {'ensure_ascii': '(False)', 'cls': 'MyJSONEncoder'}), '(value, f, ensure_ascii=False, cls=MyJSONEncoder)\n', (34058, 34107), False, 'import json\n'), ((34275, 34343), 'json.dump', 'json.dump', (['value', 'f'], {'indent': '(4)', 'ensure_ascii': '(False)', 'cls': 'MyJSONEncoder'}), '(value, f, indent=4, ensure_ascii=False, cls=MyJSONEncoder)\n', (34284, 34343), False, 'import json\n'), ((66167, 66186), 'os.remove', 'os.remove', (['filename'], {}), '(filename)\n', (66176, 66186), False, 'import os\n'), ((66499, 66523), 'os.path.isfile', 'os.path.isfile', (['filename'], {}), '(filename)\n', (66513, 66523), False, 'import os\n'), ((66660, 66684), 'os.path.isfile', 'os.path.isfile', (['filename'], {}), '(filename)\n', (66674, 66684), False, 'import os\n'), ((66824, 66848), 'os.path.isfile', 'os.path.isfile', (['filename'], {}), '(filename)\n', (66838, 66848), False, 'import os\n'), ((100813, 100869), 're.compile', 're.compile', (['"""<Item name=\'(?P<name>.+)\' id=\'(?P<id>.+)\'>"""'], {}), '("<Item name=\'(?P<name>.+)\' id=\'(?P<id>.+)\'>")\n', (100823, 100869), False, 'import re\n'), ((104568, 104595), 'os.getenv', 'os.getenv', (['"""PROJECT_DOMAIN"""'], {}), "('PROJECT_DOMAIN')\n", (104577, 104595), False, 'import os\n'), ((106420, 106445), 'platform.python_version', 'platform.python_version', ([], {}), '()\n', (106443, 106445), False, 'import platform\n'), ((113192, 113363), 'functools.partial', 'partial', (['MyClientPartyMember.set_banner'], {'icon': "config['fortnite']['banner_id']", 'color': "config['fortnite']['banner_color']", 'season_level': "config['fortnite']['level']"}), "(MyClientPartyMember.set_banner, icon=config['fortnite']['banner_id'\n ], color=config['fortnite']['banner_color'], season_level=config[\n 'fortnite']['level'])\n", (113199, 113363), False, 'from functools import partial\n'), ((113499, 113606), 'functools.partial', 'partial', (['MyClientPartyMember.set_battlepass_info'], {'has_purchased': '(True)', 'level': "config['fortnite']['tier']"}), "(MyClientPartyMember.set_battlepass_info, has_purchased=True, level=\n config['fortnite']['tier'])\n", (113506, 113606), False, 'from functools import partial\n'), ((7271, 7300), 're.sub', 're.sub', (['"""lang(\\\\\\\\|/)"""', '""""""', 'i'], {}), "('lang(\\\\\\\\|/)', '', i)\n", (7277, 7300), False, 'import re\n'), ((7348, 7377), 're.sub', 're.sub', (['"""lang(\\\\\\\\|/)"""', '""""""', 'i'], {}), "('lang(\\\\\\\\|/)', '', i)\n", (7354, 7377), False, 'import re\n'), ((7433, 7462), 're.sub', 're.sub', (['"""lang(\\\\\\\\|/)"""', '""""""', 'i'], {}), "('lang(\\\\\\\\|/)', '', i)\n", (7439, 7462), False, 'import re\n'), ((66550, 66569), 'os.remove', 'os.remove', (['filename'], {}), '(filename)\n', (66559, 66569), False, 'import os\n'), ((66711, 66730), 'os.remove', 'os.remove', (['filename'], {}), '(filename)\n', (66720, 66730), False, 'import os\n'), ((66871, 66890), 'os.remove', 'os.remove', (['filename'], {}), '(filename)\n', (66880, 66890), False, 'import os\n'), ((87324, 87351), 'datetime.timedelta', 'datetime.timedelta', ([], {'hours': '(2)'}), '(hours=2)\n', (87342, 87351), False, 'import datetime\n'), ((88353, 88380), 'datetime.timedelta', 'datetime.timedelta', ([], {'hours': '(2)'}), '(hours=2)\n', (88371, 88380), False, 'import datetime\n'), ((89428, 89439), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (89436, 89439), False, 'import sys\n'), ((90264, 90291), 'datetime.timedelta', 'datetime.timedelta', ([], {'hours': '(2)'}), '(hours=2)\n', (90282, 90291), False, 'import datetime\n'), ((91594, 91621), 'datetime.timedelta', 'datetime.timedelta', ([], {'hours': '(2)'}), '(hours=2)\n', (91612, 91621), False, 'import datetime\n'), ((92652, 92679), 'datetime.timedelta', 'datetime.timedelta', ([], {'hours': '(2)'}), '(hours=2)\n', (92670, 92679), False, 'import datetime\n'), ((93740, 93751), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (93748, 93751), False, 'import sys\n'), ((104673, 104695), 'os.getenv', 'os.getenv', (['"""REPL_SLUG"""'], {}), "('REPL_SLUG')\n", (104682, 104695), False, 'import os\n'), ((104698, 104721), 'os.getenv', 'os.getenv', (['"""REPL_OWNER"""'], {}), "('REPL_OWNER')\n", (104707, 104721), False, 'import os\n'), ((106724, 106764), 'subprocess.check_output', 'subprocess.check_output', (["['uname', '-a']"], {}), "(['uname', '-a'])\n", (106747, 106764), False, 'import subprocess\n'), ((112102, 112133), 're.search', 're.search', (['"""[a-z0-9]{32}"""', 'data'], {}), "('[a-z0-9]{32}', data)\n", (112111, 112133), False, 'import re\n'), ((113045, 113086), 'functools.partial', 'partial', (['MyClientParty.disable_voice_chat'], {}), '(MyClientParty.disable_voice_chat)\n', (113052, 113086), False, 'from functools import partial\n'), ((117614, 117632), 'asyncio.sleep', 'asyncio.sleep', (['(0.1)'], {}), '(0.1)\n', (117627, 117632), False, 'import asyncio\n'), ((118221, 118243), 'asyncio.gather', 'asyncio.gather', (['*tasks'], {}), '(*tasks)\n', (118235, 118243), False, 'import asyncio\n'), ((33129, 33171), 'aiofiles.open', 'aopen', (['f"""{key}.json"""'], {'encoding': '"""utf-8-sig"""'}), "(f'{key}.json', encoding='utf-8-sig')\n", (33134, 33171), True, 'from aiofiles import open as aopen\n'), ((37159, 37207), 'traceback.TracebackException.from_exception', 'traceback.TracebackException.from_exception', (['exc'], {}), '(exc)\n', (37202, 37207), False, 'import traceback\n'), ((94512, 94539), 'datetime.timedelta', 'datetime.timedelta', ([], {'hours': '(2)'}), '(hours=2)\n', (94530, 94539), False, 'import datetime\n'), ((109458, 109485), 'os.getenv', 'os.getenv', (['"""PROJECT_DOMAIN"""'], {}), "('PROJECT_DOMAIN')\n", (109467, 109485), False, 'import os\n'), ((112049, 112068), 'aioconsole.ainput', 'ainput', (['f"""{text}\n"""'], {}), "(f'{text}\\n')\n", (112055, 112068), False, 'from aioconsole import ainput\n'), ((33301, 33343), 'aiofiles.open', 'aopen', (['f"""{key}.json"""'], {'encoding': '"""shift_jis"""'}), "(f'{key}.json', encoding='shift_jis')\n", (33306, 33343), True, 'from aiofiles import open as aopen\n'), ((109579, 109601), 'os.getenv', 'os.getenv', (['"""REPL_SLUG"""'], {}), "('REPL_SLUG')\n", (109588, 109601), False, 'import os\n'), ((109605, 109628), 'os.getenv', 'os.getenv', (['"""REPL_OWNER"""'], {}), "('REPL_OWNER')\n", (109614, 109628), False, 'import os\n'), ((37468, 37516), 'traceback.TracebackException.from_exception', 'traceback.TracebackException.from_exception', (['exc'], {}), '(exc)\n', (37511, 37516), False, 'import traceback\n'), ((106921, 106961), 'subprocess.check_output', 'subprocess.check_output', (["['uname', '-a']"], {}), "(['uname', '-a'])\n", (106944, 106961), False, 'import subprocess\n')]
import pytest grblas = pytest.importorskip("grblas") from metagraph.tests.util import default_plugin_resolver from . import RoundTripper from metagraph.plugins.numpy.types import NumpyMatrixType from metagraph.plugins.graphblas.types import GrblasMatrixType import numpy as np def test_matrix_roundtrip_dense_square(default_plugin_resolver): rt = RoundTripper(default_plugin_resolver) mat = np.array([[1.1, 2.2, 3.3], [3.3, 3.3, 9.9], [3.3, 0.0, -3.3]]) rt.verify_round_trip(mat) rt.verify_round_trip(mat.astype(int)) rt.verify_round_trip(mat.astype(bool)) def test_matrix_roundtrip_dense_rect(default_plugin_resolver): rt = RoundTripper(default_plugin_resolver) mat = np.array( [[1.1, 2.2, 3.3], [3.3, 3.3, 9.9], [3.3, 0.0, -3.3], [-1.1, 2.7, 3.3]] ) rt.verify_round_trip(mat) rt.verify_round_trip(mat.astype(int)) rt.verify_round_trip(mat.astype(bool)) def test_numpy_2_grblas(default_plugin_resolver): dpr = default_plugin_resolver x = np.array([[1, 2, 3], [3, 3, 9], [3, 0, 3], [4, 2, 2]]) assert x.shape == (4, 3) # Convert numpy -> grblas.Matrix intermediate = grblas.Matrix.from_values( [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2], [1, 2, 3, 3, 3, 9, 3, 0, 3, 4, 2, 2], nrows=4, ncols=3, dtype=grblas.dtypes.INT64, ) y = dpr.translate(x, grblas.Matrix) dpr.assert_equal(y, intermediate) # Convert numpy <- grblas.Matrix x2 = dpr.translate(y, NumpyMatrixType) dpr.assert_equal(x, x2)
[ "numpy.array", "pytest.importorskip" ]
[((24, 53), 'pytest.importorskip', 'pytest.importorskip', (['"""grblas"""'], {}), "('grblas')\n", (43, 53), False, 'import pytest\n'), ((403, 465), 'numpy.array', 'np.array', (['[[1.1, 2.2, 3.3], [3.3, 3.3, 9.9], [3.3, 0.0, -3.3]]'], {}), '([[1.1, 2.2, 3.3], [3.3, 3.3, 9.9], [3.3, 0.0, -3.3]])\n', (411, 465), True, 'import numpy as np\n'), ((703, 788), 'numpy.array', 'np.array', (['[[1.1, 2.2, 3.3], [3.3, 3.3, 9.9], [3.3, 0.0, -3.3], [-1.1, 2.7, 3.3]]'], {}), '([[1.1, 2.2, 3.3], [3.3, 3.3, 9.9], [3.3, 0.0, -3.3], [-1.1, 2.7, 3.3]]\n )\n', (711, 788), True, 'import numpy as np\n'), ((1007, 1061), 'numpy.array', 'np.array', (['[[1, 2, 3], [3, 3, 9], [3, 0, 3], [4, 2, 2]]'], {}), '([[1, 2, 3], [3, 3, 9], [3, 0, 3], [4, 2, 2]])\n', (1015, 1061), True, 'import numpy as np\n')]
#!/usr/bin/env python """ This file is a Python translation of the MATLAB file acm.m Python version by RDL 29 Mar 2012 Copyright notice from acm.m: copyright 1996, by <NAME>. For use with the book "Statistical Digital Signal Processing and Modeling" (John Wiley & Sons, 1996). """ from __future__ import print_function,division import numpy as np from convm import convm def acm(x,p): """ Find an all-pole model using the autocorrelation method Usage: a,err = acm(x,p) The input sequence x is modeled as the unit sample response of a filter having a system function of the form H(z) = b(0)/A(z) where the coefficients of A(z) are contained in the vector a=[1, a(1), ... a(p)] The input p defines the number of poles in the model. The modeling error is returned in err. The numerator b(0) is typically set equal to the square root of err. """ x = x.flatten() N = len(x) if p > N: print('ERROR: model order too large') else: X = convm(x, p+1) Xq = X[0:N+p-1,0:p] xq1 = -X[1:N+p, 0] a = np.linalg.lstsq(Xq, xq1)[0] a = np.insert(a, 0, 1) err = np.dot(X[0:N+p,0].conj().T, X) err = np.dot(err, a) err = np.abs(err) return a, err
[ "numpy.insert", "numpy.abs", "numpy.dot", "numpy.linalg.lstsq", "convm.convm" ]
[((995, 1010), 'convm.convm', 'convm', (['x', '(p + 1)'], {}), '(x, p + 1)\n', (1000, 1010), False, 'from convm import convm\n'), ((1117, 1135), 'numpy.insert', 'np.insert', (['a', '(0)', '(1)'], {}), '(a, 0, 1)\n', (1126, 1135), True, 'import numpy as np\n'), ((1195, 1209), 'numpy.dot', 'np.dot', (['err', 'a'], {}), '(err, a)\n', (1201, 1209), True, 'import numpy as np\n'), ((1224, 1235), 'numpy.abs', 'np.abs', (['err'], {}), '(err)\n', (1230, 1235), True, 'import numpy as np\n'), ((1077, 1101), 'numpy.linalg.lstsq', 'np.linalg.lstsq', (['Xq', 'xq1'], {}), '(Xq, xq1)\n', (1092, 1101), True, 'import numpy as np\n')]
import os import shutil import doctest from crds.core import log, utils from crds import tests, data_file from crds.tests import test_config from crds.refactoring import checksum from crds.refactoring.checksum import ChecksumScript def dt_checksum_script_fits_add(): """ >>> old_state = test_config.setup() >>> _ = shutil.copy("data/s7g1700gl_dead.fits", "added.fits") >>> header = data_file.get_header("./added.fits") >>> assert "CHECKSUM" not in header >>> assert "DATASUM" not in header >>> ChecksumScript("crds.refactor.checksum ./added.fits")() # doctest: +ELLIPSIS CRDS - INFO - Adding checksum for './added.fits' 0 >>> utils.clear_function_caches() >>> header = data_file.get_header("./added.fits") >>> assert "CHECKSUM" in header >>> assert "DATASUM" in header >>> ChecksumScript("crds.refactor.checksum --verify ./added.fits")() # doctest: +ELLIPSIS CRDS - INFO - Verifying checksum for './added.fits' 0 >>> os.remove("added.fits") >>> test_config.cleanup(old_state) """ def dt_checksum_script_fits_remove(): """ >>> old_state = test_config.setup() >>> _ = shutil.copy("data/s7g1700gl_dead_good_xsum.fits", "removed.fits") >>> header = data_file.get_header("./removed.fits") >>> assert "CHECKSUM" in header >>> assert "DATASUM" in header >>> ChecksumScript("crds.refactor.checksum --remove ./removed.fits")() # doctest: +ELLIPSIS CRDS - INFO - Removing checksum for './removed.fits' 0 >>> utils.clear_function_caches() >>> header = data_file.get_header("./removed.fits") >>> assert "CHECKSUM" not in header >>> assert "DATASUM" not in header >>> ChecksumScript("crds.refactor.checksum --verify ./removed.fits")() # doctest: +ELLIPSIS CRDS - INFO - Verifying checksum for './removed.fits' 0 >>> os.remove("removed.fits") >>> test_config.cleanup(old_state) """ def dt_checksum_script_fits_verify_good(): """ >>> old_state = test_config.setup() >>> _ = shutil.copy("data/s7g1700gl_dead_good_xsum.fits", "verify_good.fits") >>> header = data_file.get_header("verify_good.fits") >>> header["CHECKSUM"] 'i2PMi1MJi1MJi1MJ' >>> header["DATASUM"] '0' >>> ChecksumScript("crds.refactor.checksum --verify ./verify_good.fits")() # doctest: +ELLIPSIS CRDS - INFO - Verifying checksum for './verify_good.fits' 0 >>> os.remove("verify_good.fits") >>> test_config.cleanup(old_state) """ def dt_checksum_script_fits_verify_bad(): """ >>> old_state = test_config.setup() >>> _ = shutil.copy("data/s7g1700gl_dead_bad_xsum.fits", "./verify_bad.fits") >>> ChecksumScript("crds.refactor.checksum --verify ./verify_bad.fits")() # doctest: +ELLIPSIS CRDS - INFO - Verifying checksum for './verify_bad.fits' CRDS - WARNING - AstropyUserWarning : astropy.io.fits.hdu.base : Checksum verification failed for HDU ('', 1). CRDS - WARNING - AstropyUserWarning : astropy.io.fits.hdu.base : Datasum verification failed for HDU ('', 1). 0 >>> os.remove("verify_bad.fits") >>> test_config.cleanup(old_state) """ # ---------------------------------------------------------------------- def dt_checksum_script_rmap_verify_good(): """ >>> old_state = test_config.setup() >>> ChecksumScript("crds.refactor.checksum --verify data/hst.pmap")() # doctest: +ELLIPSIS CRDS - INFO - Verifying checksum for 'data/hst.pmap' 0 >>> test_config.cleanup(old_state) """ def dt_checksum_script_rmap_add_bad(): """ >>> old_state = test_config.setup() >>> _ = shutil.copy("data/hst-bad-xsum.rmap", "./add_bad.rmap") >>> ChecksumScript("crds.refactor.checksum ./add_bad.rmap")() # doctest: +ELLIPSIS CRDS - INFO - Adding checksum for './add_bad.rmap' 0 >>> ChecksumScript("crds.refactor.checksum --verify ./add_bad.rmap")() # doctest: +ELLIPSIS CRDS - INFO - Verifying checksum for './add_bad.rmap' 0 >>> os.remove("add_bad.rmap") >>> test_config.cleanup(old_state) """ def dt_checksum_script_rmap_verify_bad(): """ >>> old_state = test_config.setup() >>> _ = shutil.copy("data/hst-bad-xsum.rmap", "./verify_bad.rmap") >>> ChecksumScript("crds.refactor.checksum --verify ./verify_bad.rmap")() # doctest: +ELLIPSIS CRDS - INFO - Verifying checksum for './verify_bad.rmap' CRDS - ERROR - Checksum operation FAILED : sha1sum mismatch in 'verify_bad.rmap' 1 >>> os.remove("verify_bad.rmap") >>> test_config.cleanup(old_state) """ def dt_checksum_script_rmap_remove_bad(): """ >>> old_state = test_config.setup() >>> _ = shutil.copy("data/hst-bad-xsum.rmap", "./remove_bad.rmap") >>> ChecksumScript("crds.refactor.checksum --remove ./remove_bad.rmap")() # doctest: +ELLIPSIS CRDS - INFO - Removing checksum for './remove_bad.rmap' CRDS - ERROR - Checksum operation FAILED : Mapping checksums cannot be removed for: './remove_bad.rmap' 1 >>> os.remove("remove_bad.rmap") >>> test_config.cleanup(old_state) """ def dt_checksum_script_rmap_verify_missing(): """ >>> old_state = test_config.setup() >>> _ = shutil.copy("data/hst-missing-xsum.rmap", "./verify_missing.rmap") >>> ChecksumScript("crds.refactor.checksum --verify ./verify_missing.rmap")() # doctest: +ELLIPSIS CRDS - INFO - Verifying checksum for './verify_missing.rmap' CRDS - ERROR - Checksum operation FAILED : sha1sum is missing in 'verify_missing.rmap' 1 >>> os.remove("verify_missing.rmap") >>> test_config.cleanup(old_state) """ def dt_checksum_script_unsupported_asdf(): """ >>> old_state = test_config.setup() >>> ChecksumScript("crds.refactor.checksum data/valid.asdf")() # doctest: +ELLIPSIS CRDS - INFO - Adding checksum for 'data/valid.asdf' CRDS - ERROR - Failed updating checksum for 'data/valid.asdf' : Method 'add_checksum' is not supported for file format 'ASDF' 1 >>> ChecksumScript("crds.refactor.checksum --remove data/valid.asdf")() # doctest: +ELLIPSIS CRDS - INFO - Removing checksum for 'data/valid.asdf' CRDS - ERROR - Checksum operation FAILED : Method 'remove_checksum' is not supported for file format 'ASDF' 1 >>> ChecksumScript("crds.refactor.checksum --verify data/valid.asdf")() # doctest: +ELLIPSIS CRDS - INFO - Verifying checksum for 'data/valid.asdf' CRDS - ERROR - Checksum operation FAILED : Method 'verify_checksum' is not supported for file format 'ASDF' 1 >>> test_config.cleanup(old_state) """ def dt_checksum_script_unsupported_json(): """ >>> old_state = test_config.setup() >>> ChecksumScript("crds.refactor.checksum data/valid.json")() # doctest: +ELLIPSIS CRDS - INFO - Adding checksum for 'data/valid.json' CRDS - ERROR - Failed updating checksum for 'data/valid.json' : Method 'add_checksum' is not supported for file format 'JSON' 1 >>> ChecksumScript("crds.refactor.checksum --remove data/valid.json")() # doctest: +ELLIPSIS CRDS - INFO - Removing checksum for 'data/valid.json' CRDS - ERROR - Checksum operation FAILED : Method 'remove_checksum' is not supported for file format 'JSON' 1 >>> ChecksumScript("crds.refactor.checksum --verify data/valid.json")() # doctest: +ELLIPSIS CRDS - INFO - Verifying checksum for 'data/valid.json' CRDS - ERROR - Checksum operation FAILED : Method 'verify_checksum' is not supported for file format 'JSON' 1 >>> test_config.cleanup(old_state) """ def dt_checksum_script_unsupported_text(): """ >>> old_state = test_config.setup() >>> ChecksumScript("crds.refactor.checksum data/opaque_fts.tmp")() # doctest: +ELLIPSIS CRDS - INFO - Adding checksum for 'data/opaque_fts.tmp' CRDS - ERROR - Checksum operation FAILED : File 'data/opaque_fts.tmp' does not appear to be a CRDS reference or mapping file. 1 >>> ChecksumScript("crds.refactor.checksum --remove ddata/opaque_fts.tmp")() # doctest: +ELLIPSIS CRDS - INFO - Removing checksum for 'ddata/opaque_fts.tmp' CRDS - ERROR - Checksum operation FAILED : File 'ddata/opaque_fts.tmp' does not appear to be a CRDS reference or mapping file. 1 >>> ChecksumScript("crds.refactor.checksum --verify data/opaque_fts.tmp")() # doctest: +ELLIPSIS CRDS - INFO - Verifying checksum for 'data/opaque_fts.tmp' CRDS - ERROR - Checksum operation FAILED : File 'data/opaque_fts.tmp' does not appear to be a CRDS reference or mapping file. 1 >>> test_config.cleanup(old_state) """ def test(): """Run module tests, for now just doctests only. test_config.setup() and cleanup() are done inline above because bracketing the tests here does not get picked up by nose test discovery. Combining tests into one giant docstring works but is hard to analyze and debug when things go wrong. """ from crds.tests import test_checksum, tstmod return tstmod(test_checksum) if __name__ == "__main__": print(test())
[ "crds.tests.tstmod" ]
[((9085, 9106), 'crds.tests.tstmod', 'tstmod', (['test_checksum'], {}), '(test_checksum)\n', (9091, 9106), False, 'from crds.tests import test_checksum, tstmod\n')]
from fsspec import AbstractFileSystem # type: ignore from fsspec.implementations.local import LocalFileSystem # type: ignore from typing import Callable, Optional class Pipe(object): """A container for piping data through transformations. Args: src_fs (AbstractFileSystem): The source file system. dest_fs (AbstractFileSystem): The destination file system. """ src_fs: AbstractFileSystem dest_fs: AbstractFileSystem min_s3_blocksize: int = 5242880 @staticmethod def _get_block_size(bufsize: int, fs: AbstractFileSystem, filepath: str): """Instead of checking for an S3 file system, just be mindful of the S3 minimum block size. """ if bufsize < 0: # block size is the file size unless min block size is bigger filesize = fs.size(filepath) blocksize = max(filesize, Pipe.min_s3_blocksize) else: # block size is buffer size unless min block size is bigger blocksize = max(bufsize, Pipe.min_s3_blocksize) return blocksize def __init__(self, src_fs: Optional[AbstractFileSystem] = None, dest_fs: Optional[AbstractFileSystem] = None): if src_fs is None and dest_fs is None: src_fs = dest_fs = LocalFileSystem() elif bool(src_fs is None) != bool(dest_fs is None): if src_fs is None: raise ValueError("src_fs is empty") if dest_fs is None: raise ValueError("dest_fs is empty") self.src_fs = src_fs self.dest_fs = dest_fs def copy(self, src: str, dest: str, readmode: str = 'rb', writemode: str = 'wb', bufsize: int = -1) -> None: """Copies src to dest. Both src and dest paths must be valid in the respective file systems. """ block_size = Pipe._get_block_size(bufsize, self.src_fs, src) with self.src_fs.open(src, readmode, block_size) as rdr: with self.dest_fs.open(dest, writemode, block_size) as wr: wr.write(rdr.read()) def fcopy(self, src: str, dest: str, fltr: Callable, readmode: str = 'rb', writemode: str = 'wb', bufsize: int = -1, **kwargs) -> None: """Copies src to dest, passing read bytes through a filter. The filter takes a sequence of bytes and whatever keyword arguments are passed in, and returns a sequence of bytes. Both src and dest paths must be valid in the respective file systems. """ block_size = Pipe._get_block_size(bufsize, self.src_fs, src) with self.src_fs.open(src, readmode, block_size) as rdr: with self.dest_fs.open(dest, writemode, block_size) as wr: while True: b = rdr.read(bufsize) if not b: wr.flush() break wr.write(fltr(b, **kwargs))
[ "fsspec.implementations.local.LocalFileSystem" ]
[((1293, 1310), 'fsspec.implementations.local.LocalFileSystem', 'LocalFileSystem', ([], {}), '()\n', (1308, 1310), False, 'from fsspec.implementations.local import LocalFileSystem\n')]
""" Regression tests for custom manager classes. """ from django.db import models class RestrictedManager(models.Manager): """ A manager that filters out non-public instances. """ def get_query_set(self): return super(RestrictedManager, self).get_query_set().filter(is_public=True) class RelatedModel(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return self.name class RestrictedModel(models.Model): name = models.CharField(max_length=50) is_public = models.BooleanField(default=False) related = models.ForeignKey(RelatedModel) objects = RestrictedManager() plain_manager = models.Manager() def __unicode__(self): return self.name class OneToOneRestrictedModel(models.Model): name = models.CharField(max_length=50) is_public = models.BooleanField(default=False) related = models.OneToOneField(RelatedModel) objects = RestrictedManager() plain_manager = models.Manager() def __unicode__(self): return self.name __test__ = {"tests": """ Even though the default manager filters out some records, we must still be able to save (particularly, save by updating existing records) those filtered instances. This is a regression test for #8990, #9527 >>> related = RelatedModel.objects.create(name="xyzzy") >>> obj = RestrictedModel.objects.create(name="hidden", related=related) >>> obj.name = "still hidden" >>> obj.save() # If the hidden object wasn't seen during the save process, there would now be # two objects in the database. >>> RestrictedModel.plain_manager.count() 1 Deleting related objects should also not be distracted by a restricted manager on the related object. This is a regression test for #2698. >>> RestrictedModel.plain_manager.all().delete() >>> for name, public in (('one', True), ('two', False), ('three', False)): ... _ = RestrictedModel.objects.create(name=name, is_public=public, related=related) # Reload the RelatedModel instance, just to avoid any instance artifacts. >>> obj = RelatedModel.objects.get(name="xyzzy") >>> obj.delete() # All of the RestrictedModel instances should have been deleted, since they # *all* pointed to the RelatedModel. If the default manager is used, only the # public one will be deleted. >>> RestrictedModel.plain_manager.all() [] # The same test case as the last one, but for one-to-one models, which are # implemented slightly different internally, so it's a different code path. >>> obj = RelatedModel.objects.create(name="xyzzy") >>> _ = OneToOneRestrictedModel.objects.create(name="foo", is_public=False, related=obj) >>> obj = RelatedModel.objects.get(name="xyzzy") >>> obj.delete() >>> OneToOneRestrictedModel.plain_manager.all() [] """ }
[ "django.db.models.OneToOneField", "django.db.models.Manager", "django.db.models.ForeignKey", "django.db.models.BooleanField", "django.db.models.CharField" ]
[((354, 385), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)'}), '(max_length=50)\n', (370, 385), False, 'from django.db import models\n'), ((488, 519), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)'}), '(max_length=50)\n', (504, 519), False, 'from django.db import models\n'), ((536, 570), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (555, 570), False, 'from django.db import models\n'), ((585, 616), 'django.db.models.ForeignKey', 'models.ForeignKey', (['RelatedModel'], {}), '(RelatedModel)\n', (602, 616), False, 'from django.db import models\n'), ((672, 688), 'django.db.models.Manager', 'models.Manager', ([], {}), '()\n', (686, 688), False, 'from django.db import models\n'), ((799, 830), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)'}), '(max_length=50)\n', (815, 830), False, 'from django.db import models\n'), ((847, 881), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (866, 881), False, 'from django.db import models\n'), ((896, 930), 'django.db.models.OneToOneField', 'models.OneToOneField', (['RelatedModel'], {}), '(RelatedModel)\n', (916, 930), False, 'from django.db import models\n'), ((986, 1002), 'django.db.models.Manager', 'models.Manager', ([], {}), '()\n', (1000, 1002), False, 'from django.db import models\n')]
import torch import torch.nn.functional as f from torch import nn from einops import rearrange def scaled_dot_product_attention(query, key, value): attention = torch.einsum('bdtc,beuc->bdteu',[query,key]) mask = torch.zeros_like(attention) for frame in torch.arange(mask.size(-2)): mask[:, frame, :, frame:, :] = float('-inf') attention +=mask scale = query.size(-1) ** 0.5 attention = rearrange(attention, 'b f t g u->b f t (g u)') softmax = f.softmax(attention / scale, dim=-1) return softmax.bmm(value) class AttentionHead(nn.Module): def __init__(self, dim_in, dim_k, dim_v): super(AttentionHead, self).__init__() self.q = nn.Linear(dim_in, dim_k) self.k = nn.Linear(dim_in, dim_k) self.v = nn.Linear(dim_in, dim_v) def forward(self, query, key, value): return scaled_dot_product_attention(self.q(query), self.k(key), self.v(value)) class MultiHeadAttention(nn.Module): def __init__(self, num_heads, dim_in, dim_k, dim_v): super(MultiHeadAttention, self).__init__() self.heads = nn.ModuleList( [AttentionHead(dim_in, dim_k, dim_v) for _ in range(num_heads)] ) self.linear = nn.Linear(num_heads * dim_v, dim_in) def forward(self, query, key, value): return self.linear( torch.cat([h(query, key, value) for h in self.heads], dim=-1) ) def feed_forward(dim_input, dim_feedforward): return nn.Sequential( nn.Linear(dim_input, dim_feedforward), nn.ReLU(), nn.Linear(dim_feedforward, dim_input), ) class Residual(nn.Module): def __init__(self, sublayer, dimension, dropout): super(Residual, self).__init__() self.sublayer = sublayer self.norm = nn.LayerNorm(dimension) self.dropout = nn.Dropout(dropout) def forward(self, *tensors): return self.norm(tensors[-1] + self.dropout(self.sublayer(*tensors))) class TransformerEncoderLayer(nn.Module): def __init__(self, dim_model=64, num_heads=8, dim_feedforward=128, dropout=0.1, ): super(TransformerEncoderLayer, self).__init__() dim_k = dim_v = dim_model // num_heads self.attention = Residual( MultiHeadAttention(num_heads, dim_model, dim_k, dim_v), dimension=dim_model, dropout=dropout, ) self.feed_forward = Residual( feed_forward(dim_model, dim_feedforward), dimension=dim_model, dropout=dropout, ) def forward(self, src): src = self.attention(src, src, src) return self.feed_forward(src) class TransformerEncoder(nn.Module): def __init__(self, num_layers=6, dim_model=64, num_heads=8, dim_feedforward=128, dropout=0.1, ): super(TransformerEncoder, self).__init__() self.layers = nn.ModuleList([ TransformerEncoderLayer(dim_model, num_heads, dim_feedforward, dropout) for _ in range(num_layers) ]) def forward(self, src): for layer in self.layers: src = layer(src) return src # # head_params # num_heads = 8 # dim_in = 64 # dim_k = dim_v = dim_in // num_heads # # # data params # batch_size = 16 # sequence_length = 10 # num_features = 64 # # query = torch.rand(batch_size, sequence_length, num_features) # key = torch.rand(batch_size, sequence_length, num_features) # value = torch.rand(batch_size, sequence_length, num_features) # # transformer_encoder = TransformerEncoder() # transformer_encoder(value)
[ "torch.nn.ReLU", "torch.nn.Dropout", "torch.nn.LayerNorm", "einops.rearrange", "torch.einsum", "torch.nn.Linear", "torch.zeros_like", "torch.nn.functional.softmax" ]
[((166, 212), 'torch.einsum', 'torch.einsum', (['"""bdtc,beuc->bdteu"""', '[query, key]'], {}), "('bdtc,beuc->bdteu', [query, key])\n", (178, 212), False, 'import torch\n'), ((222, 249), 'torch.zeros_like', 'torch.zeros_like', (['attention'], {}), '(attention)\n', (238, 249), False, 'import torch\n'), ((420, 466), 'einops.rearrange', 'rearrange', (['attention', '"""b f t g u->b f t (g u)"""'], {}), "(attention, 'b f t g u->b f t (g u)')\n", (429, 466), False, 'from einops import rearrange\n'), ((481, 517), 'torch.nn.functional.softmax', 'f.softmax', (['(attention / scale)'], {'dim': '(-1)'}), '(attention / scale, dim=-1)\n', (490, 517), True, 'import torch.nn.functional as f\n'), ((692, 716), 'torch.nn.Linear', 'nn.Linear', (['dim_in', 'dim_k'], {}), '(dim_in, dim_k)\n', (701, 716), False, 'from torch import nn\n'), ((734, 758), 'torch.nn.Linear', 'nn.Linear', (['dim_in', 'dim_k'], {}), '(dim_in, dim_k)\n', (743, 758), False, 'from torch import nn\n'), ((776, 800), 'torch.nn.Linear', 'nn.Linear', (['dim_in', 'dim_v'], {}), '(dim_in, dim_v)\n', (785, 800), False, 'from torch import nn\n'), ((1222, 1258), 'torch.nn.Linear', 'nn.Linear', (['(num_heads * dim_v)', 'dim_in'], {}), '(num_heads * dim_v, dim_in)\n', (1231, 1258), False, 'from torch import nn\n'), ((1496, 1533), 'torch.nn.Linear', 'nn.Linear', (['dim_input', 'dim_feedforward'], {}), '(dim_input, dim_feedforward)\n', (1505, 1533), False, 'from torch import nn\n'), ((1543, 1552), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (1550, 1552), False, 'from torch import nn\n'), ((1562, 1599), 'torch.nn.Linear', 'nn.Linear', (['dim_feedforward', 'dim_input'], {}), '(dim_feedforward, dim_input)\n', (1571, 1599), False, 'from torch import nn\n'), ((1784, 1807), 'torch.nn.LayerNorm', 'nn.LayerNorm', (['dimension'], {}), '(dimension)\n', (1796, 1807), False, 'from torch import nn\n'), ((1831, 1850), 'torch.nn.Dropout', 'nn.Dropout', (['dropout'], {}), '(dropout)\n', (1841, 1850), False, 'from torch import nn\n')]
""" License: Apache-2.0 Author: <NAME> E-mail: <EMAIL> """ import tensorflow as tf import rnn_cell_GRU as rnn_cell import rnn import numpy as np from config import cfg from utils import get_batch_data from capsLayer import CapsLayer from sklearn import metrics import pickle from sklearn.cross_validation import train_test_split from sklearn import preprocessing from plot_confusion_matrix import plot_confusion_matrix from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt import os import tensorflow as tf from tensorflow.contrib.tensor_forest.python import tensor_forest from tensorflow.python.ops import resources class CapsNet(object): def __init__(self, is_training=True): self.graph = tf.Graph() with self.graph.as_default(): self.n_classes=52 self.X, self.labels = get_batch_data(cfg.dataset, cfg.batch_size, cfg.num_threads) self.Y = tf.one_hot(self.labels, depth=self.n_classes, axis=1, dtype=tf.float32) # LSTM Parameters self.n_input=45 self.n_steps=45 # tf Graph input self.lstm_x = tf.reshape(self.X, shape=(cfg.batch_size, self.n_steps, self.n_input)) self.lstm_y = tf.reshape(self.Y, shape=(cfg.batch_size, self.n_classes)) self.kernel_size1=13 self.kernel_size2=9 self.conv1_outa=self.n_input-self.kernel_size1+1 self.conv1_outb=self.n_steps-self.kernel_size1+1 # self.cap1_out=(self.conv1_outa-self.kernel_size+1)/2*((self.conv1_outb-self.kernel_size+1)/2) # self.cap1_out=int((self.conv1_outa-self.kernel_size2+1)*(self.conv1_outb-self.kernel_size2+1)*32/4) self.cap1_out=5408 self.n_hidden= self.conv1_outb # Define weights self.lstm_weights = { 'out': tf.Variable(tf.random_normal([self.n_hidden, self.n_classes])) } self.lstm_biases = { 'out': tf.Variable(tf.random_normal([self.n_classes])) } if is_training: self.build_arch() self.loss() self._summary() # t_vars = tf.trainable_variables() self.global_step = tf.Variable(0, name='global_step', trainable=False) self.optimizer = tf.train.AdamOptimizer() self.train_op = self.optimizer.minimize(self.total_loss, global_step=self.global_step) # var_list=t_vars) self.train_c1 = self.optimizer.minimize(self.lstm_cost, global_step=self.global_step) self.train_c2 = self.optimizer.minimize(self.dense_cov1_cost, global_step=self.global_step) self.train_c3 = self.optimizer.minimize(self.dense_caps1_cost, global_step=self.global_step) print('end net') else: self.X = tf.placeholder(tf.float32, shape=(cfg.batch_size,self.n_input, self.n_steps, 1)) self.labels = tf.placeholder(tf.int32, shape=(cfg.batch_size, )) self.Y = tf.reshape(self.labels, shape=(cfg.batch_size, self.n_classes, 1)) self.build_arch() tf.logging.info('Seting up the main structure') def RNN(self): # Prepare data shape to match `rnn` function requirements # Current data input shape: (batch_size, n_steps, n_input) # Required shape: 'n_steps' tensors list of shape (batch_size, n_input) # Permuting batch_size and n_steps x = tf.transpose(self.lstm_x, [1, 0, 2]) # Reshaping to (n_steps*batch_size, n_input) x = tf.reshape(tensor=x, shape=[-1, self.n_input]) # Split to get a list of 'n_steps' tensors of shape (batch_size, n_input) x = tf.split(value=x, num_or_size_splits=self.n_steps, axis=0) # Define a lstm cell with tensorflow #lstm_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1) lstm_cell = rnn_cell.GRUCell(self.n_hidden) #lstm_cell = rnn_cell.LSTMCell(n_hidden,use_peepholes=True) # avoid overfitting lstm_cell = rnn_cell.DropoutWrapper(lstm_cell, output_keep_prob=0.5) # 2 layers lstm lstm_cell = rnn_cell.MultiRNNCell([lstm_cell]*2) # Get lstm cell output outputs, states = rnn.rnn(cell=lstm_cell, inputs=x, dtype=tf.float32) # Linear activation, using rnn inner loop last output return tf.matmul(outputs[-1], self.lstm_weights['out']) + self.lstm_biases['out'],outputs[-1] def build_arch(self): with tf.variable_scope('LSTM_layer'): #pred batch*4d out batch*128d pred,out = self.RNN() out=tf.reshape(out,(-1,1,self.n_hidden,1)) # cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=pred, labels=y)) # #Adam optimizer # optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # Evaluate model # correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1)) # accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) with tf.variable_scope('Conv1_layer'): # Conv1, [batch_size, 20, 20, 256] conv1 = tf.contrib.layers.conv2d(self.X, num_outputs=256, kernel_size=self.kernel_size1, stride=1, padding='VALID') # print(conv1.get_shape(),[cfg.batch_size, self.conv1_outa,self.conv1_outb, 256]) assert conv1.get_shape() == [cfg.batch_size, self.conv1_outa,self.conv1_outb, 256] out=tf.tile(out,[1,self.conv1_outa,1,256]) self.conv1=tf.add(conv1,out) # out_temp= tf.placeholder(tf.float32, shape=(cfg.batch_size,self.conv1_outa+1,self.conv1_outb, 256)) # self.dense1 = tf.layers.dense(inputs=tf.reshape(self.conv1,(cfg.batch_size,-1)), units=self.n_classes, activation=tf.nn.relu) #全连接层 pool = tf.layers.max_pooling2d(inputs=self.conv1, pool_size=[2, 2], strides=2) fc1 = tf.layers.dense(inputs=pool, units=1024, activation=tf.nn.relu) fc2 = tf.layers.dense(inputs=fc1, units=512, activation=tf.nn.relu) self.dense1 = tf.layers.dense(inputs=tf.reshape(fc2,(cfg.batch_size,-1)), units=self.n_classes, activation=None) self.dense1_index = tf.to_int32(tf.argmax(tf.nn.softmax(self.dense1, axis=1), axis=1)) # Primary Capsules layer, return [batch_size, 1152, 8, 1] with tf.variable_scope('PrimaryCaps_layer'): primaryCaps = CapsLayer(num_outputs=32, vec_len=8, with_routing=False, layer_type='CONV', conv1_outa=self.conv1_outa, conv1_outb=self.conv1_outb, cap1_out=self.cap1_out,n_classes=self.n_classes) (self.caps1,pred) = primaryCaps(self.conv1, kernel_size=self.kernel_size2, stride=2) self.lstmpred=pred assert self.caps1.get_shape() == [cfg.batch_size, self.cap1_out, 8, 1] # self.dense2= tf.layers.dense(inputs=tf.reshape(self.caps1,(cfg.batch_size,-1)), units=self.n_classes, activation=tf.nn.relu) pool = tf.layers.max_pooling2d(inputs=self.caps1, pool_size=[2, 2], strides=2) fc1 = tf.layers.dense(inputs=pool, units=1024, activation=tf.nn.relu) fc2 = tf.layers.dense(inputs=fc1, units=512, activation=tf.nn.relu) self.dense2 = tf.layers.dense(inputs=tf.reshape(fc2,(cfg.batch_size,-1)), units=self.n_classes, activation=None) self.dense2_index = tf.to_int32(tf.argmax(tf.nn.softmax(self.dense2, axis=1), axis=1)) # DigitCaps layer, return [batch_size, 10, 16, 1] with tf.variable_scope('DigitCaps_layer'): digitCaps = CapsLayer(num_outputs=self.n_classes, vec_len=8, with_routing=True, layer_type='FC',conv1_outa=self.conv1_outa, conv1_outb=self.conv1_outb, cap1_out=self.cap1_out,n_classes=self.n_classes) self.caps2 = digitCaps(self.caps1) # self.caps2 = tf.add(tf.tile(tf.reshape(self.lstmpred,(cfg.batch_size,self.n_classes,1,1)),[1,1,16,1]),self.caps2) # Decoder structure in Fig. 2 # 1. Do masking, how: with tf.variable_scope('Masking'): # a). calc ||v_c||, then do softmax(||v_c||) # [batch_size, 10, 16, 1] => [batch_size, 10, 1, 1] self.v_length = tf.sqrt(tf.reduce_sum(tf.square(self.caps2), axis=2, keepdims=True)) self.softmax_v = tf.nn.softmax(self.v_length, axis=1) assert self.softmax_v.get_shape() == [cfg.batch_size, self.n_classes, 1, 1] # b). pick out the index of max softmax val of the 10 caps # [batch_size, 10, 1, 1] => [batch_size] (index) self.argmax_idx = tf.to_int32(tf.argmax(self.softmax_v, axis=1)) assert self.argmax_idx.get_shape() == [cfg.batch_size, 1, 1] self.argmax_idx = tf.reshape(self.argmax_idx, shape=(cfg.batch_size, )) # self.max_index_list= tf.Variable(tf.ones([cfg.batch_size, ],dtype=tf.int32)) # index_list=tf.stack([self.dense1_index,self.dense2_index,self.argmax_idx],1) # # for i in range(cfg.batch_size): # max_index=tf.to_int32(tf.argmax(tf.bincount(index_list[i]))) # self.update_op=tf.assign(self.max_index_list[i],max_index) # # Method 1. # if not cfg.mask_with_y: # # c). indexing # # It's not easy to understand the indexing process with argmax_idx # # as we are 3-dim animal # masked_v = [] # for batch_size in range(cfg.batch_size): # v = self.caps2[batch_size][self.argmax_idx[batch_size], :] # masked_v.append(tf.reshape(v, shape=(1, 1, 8, 1))) # # self.masked_v = tf.concat(masked_v, axis=0) # assert self.masked_v.get_shape() == [cfg.batch_size, 1, 8, 1] # # Method 2. masking with true label, default mode # else: # # self.masked_v = tf.matmul(tf.squeeze(self.caps2), tf.reshape(self.Y, (-1, 10, 1)), transpose_a=True) # self.masked_v = tf.multiply(tf.squeeze(self.caps2), tf.reshape(self.Y, (-1, self.n_classes, 1))) # self.v_length = tf.sqrt(tf.reduce_sum(tf.square(self.caps2), axis=2, keepdims=True) + epsilon) # # # 2. Reconstructe the MNIST images with 3 FC layers # # [batch_size, 1, 16, 1] => [batch_size, 16] => [batch_size, 512] # with tf.variable_scope('Decoder'): # vector_j = tf.reshape(self.masked_v, shape=(cfg.batch_size, -1)) # fc1 = tf.contrib.layers.fully_connected(vector_j, num_outputs=512) # assert fc1.get_shape() == [cfg.batch_size, 512] # fc2 = tf.contrib.layers.fully_connected(fc1, num_outputs=1024) # assert fc2.get_shape() == [cfg.batch_size, 1024] # self.decoded = tf.contrib.layers.fully_connected(fc2, num_outputs=self.n_steps*self.n_input, activation_fn=tf.sigmoid) def loss(self): # 1. The margin loss # [batch_size, 10, 1, 1] # max_l = max(0, m_plus-||v_c||)^2 max_l = tf.square(tf.maximum(0., cfg.m_plus - self.v_length)) # max_r = max(0, ||v_c||-m_minus)^2 max_r = tf.square(tf.maximum(0., self.v_length - cfg.m_minus)) assert max_l.get_shape() == [cfg.batch_size,self.n_classes, 1, 1] # reshape: [batch_size, 10, 1, 1] => [batch_size, 10] max_l = tf.reshape(max_l, shape=(cfg.batch_size, -1)) max_r = tf.reshape(max_r, shape=(cfg.batch_size, -1)) # calc T_c: [batch_size, 10] # T_c = Y, is my understanding correct? Try it. T_c = self.Y # [batch_size, 10], element-wise multiply L_c = T_c * max_l + cfg.lambda_val * (1 - T_c) * max_r self.margin_loss = tf.reduce_mean(tf.reduce_sum(L_c, axis=1)) # # 2. The reconstruction loss # orgin = tf.reshape(self.X, shape=(cfg.batch_size, -1)) # squared = tf.square(self.decoded - orgin) # self.reconstruction_err = tf.reduce_mean(squared) # lstm loss self.lstm_cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=self.lstmpred, labels=self.lstm_y)) self.lstm_index = tf.to_int32(tf.argmax(self.lstmpred, axis=1)) self.dense_cov1_cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=self.dense1, labels=self.lstm_y)) self.dense_caps1_cost= tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=self.dense2, labels=self.lstm_y)) # 3. Total loss # The paper uses sum of squared error as reconstruction error, but we # have used reduce_mean in `# 2 The reconstruction loss` to calculate # mean squared error. In order to keep in line with the paper,the # regularization scale should be 0.0005*784=0.392 # self.total_loss = self.margin_loss + cfg.regularization_scale * self.reconstruction_err+lstm_cost # self.total_loss = self.margin_loss+self.lstm_cost self.total_loss = self.margin_loss+self.lstm_cost+self.dense_cov1_cost+self.dense_caps1_cost # Summary def _summary(self): train_summary = [] train_summary.append(tf.summary.scalar('train/margin_loss', self.margin_loss)) # train_summary.append(tf.summary.scalar('train/reconstruction_loss', self.reconstruction_err)) train_summary.append(tf.summary.scalar('train/total_loss', self.total_loss)) # train_summary.append(tf.summary.scalar('train/rf_loss', self.rf_loss_op)) # recon_img = tf.reshape(self.decoded, shape=(cfg.batch_size, self.n_input,self.n_steps, 1)) # train_summary.append(tf.summary.image('reconstruction_img', recon_img)) self.train_summary = tf.summary.merge(train_summary) # correct_prediction = tf.equal(tf.to_int32(self.labels), self.max_index_list) # self.accuracy = tf.reduce_sum(tf.cast(correct_prediction, tf.float32))
[ "tensorflow.tile", "tensorflow.contrib.layers.conv2d", "tensorflow.transpose", "tensorflow.reduce_sum", "tensorflow.split", "tensorflow.nn.softmax", "tensorflow.Graph", "tensorflow.random_normal", "tensorflow.placeholder", "capsLayer.CapsLayer", "tensorflow.matmul", "tensorflow.maximum", "te...
[((734, 744), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (742, 744), True, 'import tensorflow as tf\n'), ((3264, 3311), 'tensorflow.logging.info', 'tf.logging.info', (['"""Seting up the main structure"""'], {}), "('Seting up the main structure')\n", (3279, 3311), True, 'import tensorflow as tf\n'), ((3620, 3656), 'tensorflow.transpose', 'tf.transpose', (['self.lstm_x', '[1, 0, 2]'], {}), '(self.lstm_x, [1, 0, 2])\n', (3632, 3656), True, 'import tensorflow as tf\n'), ((3731, 3777), 'tensorflow.reshape', 'tf.reshape', ([], {'tensor': 'x', 'shape': '[-1, self.n_input]'}), '(tensor=x, shape=[-1, self.n_input])\n', (3741, 3777), True, 'import tensorflow as tf\n'), ((3872, 3930), 'tensorflow.split', 'tf.split', ([], {'value': 'x', 'num_or_size_splits': 'self.n_steps', 'axis': '(0)'}), '(value=x, num_or_size_splits=self.n_steps, axis=0)\n', (3880, 3930), True, 'import tensorflow as tf\n'), ((4065, 4096), 'rnn_cell_GRU.GRUCell', 'rnn_cell.GRUCell', (['self.n_hidden'], {}), '(self.n_hidden)\n', (4081, 4096), True, 'import rnn_cell_GRU as rnn_cell\n'), ((4213, 4269), 'rnn_cell_GRU.DropoutWrapper', 'rnn_cell.DropoutWrapper', (['lstm_cell'], {'output_keep_prob': '(0.5)'}), '(lstm_cell, output_keep_prob=0.5)\n', (4236, 4269), True, 'import rnn_cell_GRU as rnn_cell\n'), ((4314, 4352), 'rnn_cell_GRU.MultiRNNCell', 'rnn_cell.MultiRNNCell', (['([lstm_cell] * 2)'], {}), '([lstm_cell] * 2)\n', (4335, 4352), True, 'import rnn_cell_GRU as rnn_cell\n'), ((4411, 4462), 'rnn.rnn', 'rnn.rnn', ([], {'cell': 'lstm_cell', 'inputs': 'x', 'dtype': 'tf.float32'}), '(cell=lstm_cell, inputs=x, dtype=tf.float32)\n', (4418, 4462), False, 'import rnn\n'), ((11716, 11761), 'tensorflow.reshape', 'tf.reshape', (['max_l'], {'shape': '(cfg.batch_size, -1)'}), '(max_l, shape=(cfg.batch_size, -1))\n', (11726, 11761), True, 'import tensorflow as tf\n'), ((11778, 11823), 'tensorflow.reshape', 'tf.reshape', (['max_r'], {'shape': '(cfg.batch_size, -1)'}), '(max_r, shape=(cfg.batch_size, -1))\n', (11788, 11823), True, 'import tensorflow as tf\n'), ((14055, 14086), 'tensorflow.summary.merge', 'tf.summary.merge', (['train_summary'], {}), '(train_summary)\n', (14071, 14086), True, 'import tensorflow as tf\n'), ((847, 907), 'utils.get_batch_data', 'get_batch_data', (['cfg.dataset', 'cfg.batch_size', 'cfg.num_threads'], {}), '(cfg.dataset, cfg.batch_size, cfg.num_threads)\n', (861, 907), False, 'from utils import get_batch_data\n'), ((929, 1000), 'tensorflow.one_hot', 'tf.one_hot', (['self.labels'], {'depth': 'self.n_classes', 'axis': '(1)', 'dtype': 'tf.float32'}), '(self.labels, depth=self.n_classes, axis=1, dtype=tf.float32)\n', (939, 1000), True, 'import tensorflow as tf\n'), ((1155, 1225), 'tensorflow.reshape', 'tf.reshape', (['self.X'], {'shape': '(cfg.batch_size, self.n_steps, self.n_input)'}), '(self.X, shape=(cfg.batch_size, self.n_steps, self.n_input))\n', (1165, 1225), True, 'import tensorflow as tf\n'), ((1252, 1310), 'tensorflow.reshape', 'tf.reshape', (['self.Y'], {'shape': '(cfg.batch_size, self.n_classes)'}), '(self.Y, shape=(cfg.batch_size, self.n_classes))\n', (1262, 1310), True, 'import tensorflow as tf\n'), ((4668, 4699), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""LSTM_layer"""'], {}), "('LSTM_layer')\n", (4685, 4699), True, 'import tensorflow as tf\n'), ((4785, 4827), 'tensorflow.reshape', 'tf.reshape', (['out', '(-1, 1, self.n_hidden, 1)'], {}), '(out, (-1, 1, self.n_hidden, 1))\n', (4795, 4827), True, 'import tensorflow as tf\n'), ((5186, 5218), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""Conv1_layer"""'], {}), "('Conv1_layer')\n", (5203, 5218), True, 'import tensorflow as tf\n'), ((5287, 5399), 'tensorflow.contrib.layers.conv2d', 'tf.contrib.layers.conv2d', (['self.X'], {'num_outputs': '(256)', 'kernel_size': 'self.kernel_size1', 'stride': '(1)', 'padding': '"""VALID"""'}), "(self.X, num_outputs=256, kernel_size=self.\n kernel_size1, stride=1, padding='VALID')\n", (5311, 5399), True, 'import tensorflow as tf\n'), ((5702, 5744), 'tensorflow.tile', 'tf.tile', (['out', '[1, self.conv1_outa, 1, 256]'], {}), '(out, [1, self.conv1_outa, 1, 256])\n', (5709, 5744), True, 'import tensorflow as tf\n'), ((5764, 5782), 'tensorflow.add', 'tf.add', (['conv1', 'out'], {}), '(conv1, out)\n', (5770, 5782), True, 'import tensorflow as tf\n'), ((6071, 6142), 'tensorflow.layers.max_pooling2d', 'tf.layers.max_pooling2d', ([], {'inputs': 'self.conv1', 'pool_size': '[2, 2]', 'strides': '(2)'}), '(inputs=self.conv1, pool_size=[2, 2], strides=2)\n', (6094, 6142), True, 'import tensorflow as tf\n'), ((6161, 6224), 'tensorflow.layers.dense', 'tf.layers.dense', ([], {'inputs': 'pool', 'units': '(1024)', 'activation': 'tf.nn.relu'}), '(inputs=pool, units=1024, activation=tf.nn.relu)\n', (6176, 6224), True, 'import tensorflow as tf\n'), ((6243, 6304), 'tensorflow.layers.dense', 'tf.layers.dense', ([], {'inputs': 'fc1', 'units': '(512)', 'activation': 'tf.nn.relu'}), '(inputs=fc1, units=512, activation=tf.nn.relu)\n', (6258, 6304), True, 'import tensorflow as tf\n'), ((6635, 6673), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""PrimaryCaps_layer"""'], {}), "('PrimaryCaps_layer')\n", (6652, 6673), True, 'import tensorflow as tf\n'), ((6701, 6891), 'capsLayer.CapsLayer', 'CapsLayer', ([], {'num_outputs': '(32)', 'vec_len': '(8)', 'with_routing': '(False)', 'layer_type': '"""CONV"""', 'conv1_outa': 'self.conv1_outa', 'conv1_outb': 'self.conv1_outb', 'cap1_out': 'self.cap1_out', 'n_classes': 'self.n_classes'}), "(num_outputs=32, vec_len=8, with_routing=False, layer_type='CONV',\n conv1_outa=self.conv1_outa, conv1_outb=self.conv1_outb, cap1_out=self.\n cap1_out, n_classes=self.n_classes)\n", (6710, 6891), False, 'from capsLayer import CapsLayer\n'), ((7264, 7335), 'tensorflow.layers.max_pooling2d', 'tf.layers.max_pooling2d', ([], {'inputs': 'self.caps1', 'pool_size': '[2, 2]', 'strides': '(2)'}), '(inputs=self.caps1, pool_size=[2, 2], strides=2)\n', (7287, 7335), True, 'import tensorflow as tf\n'), ((7354, 7417), 'tensorflow.layers.dense', 'tf.layers.dense', ([], {'inputs': 'pool', 'units': '(1024)', 'activation': 'tf.nn.relu'}), '(inputs=pool, units=1024, activation=tf.nn.relu)\n', (7369, 7417), True, 'import tensorflow as tf\n'), ((7436, 7497), 'tensorflow.layers.dense', 'tf.layers.dense', ([], {'inputs': 'fc1', 'units': '(512)', 'activation': 'tf.nn.relu'}), '(inputs=fc1, units=512, activation=tf.nn.relu)\n', (7451, 7497), True, 'import tensorflow as tf\n'), ((7796, 7832), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""DigitCaps_layer"""'], {}), "('DigitCaps_layer')\n", (7813, 7832), True, 'import tensorflow as tf\n'), ((7858, 8056), 'capsLayer.CapsLayer', 'CapsLayer', ([], {'num_outputs': 'self.n_classes', 'vec_len': '(8)', 'with_routing': '(True)', 'layer_type': '"""FC"""', 'conv1_outa': 'self.conv1_outa', 'conv1_outb': 'self.conv1_outb', 'cap1_out': 'self.cap1_out', 'n_classes': 'self.n_classes'}), "(num_outputs=self.n_classes, vec_len=8, with_routing=True,\n layer_type='FC', conv1_outa=self.conv1_outa, conv1_outb=self.conv1_outb,\n cap1_out=self.cap1_out, n_classes=self.n_classes)\n", (7867, 8056), False, 'from capsLayer import CapsLayer\n'), ((8321, 8349), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""Masking"""'], {}), "('Masking')\n", (8338, 8349), True, 'import tensorflow as tf\n'), ((8648, 8684), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['self.v_length'], {'axis': '(1)'}), '(self.v_length, axis=1)\n', (8661, 8684), True, 'import tensorflow as tf\n'), ((9086, 9138), 'tensorflow.reshape', 'tf.reshape', (['self.argmax_idx'], {'shape': '(cfg.batch_size,)'}), '(self.argmax_idx, shape=(cfg.batch_size,))\n', (9096, 9138), True, 'import tensorflow as tf\n'), ((11404, 11447), 'tensorflow.maximum', 'tf.maximum', (['(0.0)', '(cfg.m_plus - self.v_length)'], {}), '(0.0, cfg.m_plus - self.v_length)\n', (11414, 11447), True, 'import tensorflow as tf\n'), ((11518, 11562), 'tensorflow.maximum', 'tf.maximum', (['(0.0)', '(self.v_length - cfg.m_minus)'], {}), '(0.0, self.v_length - cfg.m_minus)\n', (11528, 11562), True, 'import tensorflow as tf\n'), ((12095, 12121), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['L_c'], {'axis': '(1)'}), '(L_c, axis=1)\n', (12108, 12121), True, 'import tensorflow as tf\n'), ((12395, 12484), 'tensorflow.nn.softmax_cross_entropy_with_logits_v2', 'tf.nn.softmax_cross_entropy_with_logits_v2', ([], {'logits': 'self.lstmpred', 'labels': 'self.lstm_y'}), '(logits=self.lstmpred, labels=\n self.lstm_y)\n', (12437, 12484), True, 'import tensorflow as tf\n'), ((12519, 12551), 'tensorflow.argmax', 'tf.argmax', (['self.lstmpred'], {'axis': '(1)'}), '(self.lstmpred, axis=1)\n', (12528, 12551), True, 'import tensorflow as tf\n'), ((12600, 12687), 'tensorflow.nn.softmax_cross_entropy_with_logits_v2', 'tf.nn.softmax_cross_entropy_with_logits_v2', ([], {'logits': 'self.dense1', 'labels': 'self.lstm_y'}), '(logits=self.dense1, labels=self.\n lstm_y)\n', (12642, 12687), True, 'import tensorflow as tf\n'), ((12730, 12817), 'tensorflow.nn.softmax_cross_entropy_with_logits_v2', 'tf.nn.softmax_cross_entropy_with_logits_v2', ([], {'logits': 'self.dense2', 'labels': 'self.lstm_y'}), '(logits=self.dense2, labels=self.\n lstm_y)\n', (12772, 12817), True, 'import tensorflow as tf\n'), ((13516, 13572), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""train/margin_loss"""', 'self.margin_loss'], {}), "('train/margin_loss', self.margin_loss)\n", (13533, 13572), True, 'import tensorflow as tf\n'), ((13706, 13760), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""train/total_loss"""', 'self.total_loss'], {}), "('train/total_loss', self.total_loss)\n", (13723, 13760), True, 'import tensorflow as tf\n'), ((2322, 2373), 'tensorflow.Variable', 'tf.Variable', (['(0)'], {'name': '"""global_step"""', 'trainable': '(False)'}), "(0, name='global_step', trainable=False)\n", (2333, 2373), True, 'import tensorflow as tf\n'), ((2407, 2431), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {}), '()\n', (2429, 2431), True, 'import tensorflow as tf\n'), ((2967, 3053), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(cfg.batch_size, self.n_input, self.n_steps, 1)'}), '(tf.float32, shape=(cfg.batch_size, self.n_input, self.\n n_steps, 1))\n', (2981, 3053), True, 'import tensorflow as tf\n'), ((3078, 3127), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': '(cfg.batch_size,)'}), '(tf.int32, shape=(cfg.batch_size,))\n', (3092, 3127), True, 'import tensorflow as tf\n'), ((3154, 3220), 'tensorflow.reshape', 'tf.reshape', (['self.labels'], {'shape': '(cfg.batch_size, self.n_classes, 1)'}), '(self.labels, shape=(cfg.batch_size, self.n_classes, 1))\n', (3164, 3220), True, 'import tensorflow as tf\n'), ((4540, 4588), 'tensorflow.matmul', 'tf.matmul', (['outputs[-1]', "self.lstm_weights['out']"], {}), "(outputs[-1], self.lstm_weights['out'])\n", (4549, 4588), True, 'import tensorflow as tf\n'), ((8948, 8981), 'tensorflow.argmax', 'tf.argmax', (['self.softmax_v'], {'axis': '(1)'}), '(self.softmax_v, axis=1)\n', (8957, 8981), True, 'import tensorflow as tf\n'), ((1929, 1978), 'tensorflow.random_normal', 'tf.random_normal', (['[self.n_hidden, self.n_classes]'], {}), '([self.n_hidden, self.n_classes])\n', (1945, 1978), True, 'import tensorflow as tf\n'), ((2062, 2096), 'tensorflow.random_normal', 'tf.random_normal', (['[self.n_classes]'], {}), '([self.n_classes])\n', (2078, 2096), True, 'import tensorflow as tf\n'), ((6354, 6391), 'tensorflow.reshape', 'tf.reshape', (['fc2', '(cfg.batch_size, -1)'], {}), '(fc2, (cfg.batch_size, -1))\n', (6364, 6391), True, 'import tensorflow as tf\n'), ((6484, 6518), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['self.dense1'], {'axis': '(1)'}), '(self.dense1, axis=1)\n', (6497, 6518), True, 'import tensorflow as tf\n'), ((7547, 7584), 'tensorflow.reshape', 'tf.reshape', (['fc2', '(cfg.batch_size, -1)'], {}), '(fc2, (cfg.batch_size, -1))\n', (7557, 7584), True, 'import tensorflow as tf\n'), ((7677, 7711), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['self.dense2'], {'axis': '(1)'}), '(self.dense2, axis=1)\n', (7690, 7711), True, 'import tensorflow as tf\n'), ((8522, 8543), 'tensorflow.square', 'tf.square', (['self.caps2'], {}), '(self.caps2)\n', (8531, 8543), True, 'import tensorflow as tf\n')]
import numpy as np import cv2 img = cv2.imread("test_image.jpg") gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml') faces = face_cascade.detectMultiScale(gray, 1.3, 5) camera = cv2.VideoCapture(0) while True: ret,img = camera.read() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x,y,w,h) in faces: img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) roi_gray = gray[y:y+h, x:x+w] roi_color = img[y:y+h, x:x+w] eyes = eye_cascade.detectMultiScale(roi_gray) for (ex,ey,ew,eh) in eyes: cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2) cv2.imshow('img',img) if cv2.waitKey(1) & 0xFF == ord('q'): break # cv2.waitKey(0) cv2.destroyAllWindows()
[ "cv2.rectangle", "cv2.imshow", "cv2.waitKey", "cv2.destroyAllWindows", "cv2.VideoCapture", "cv2.cvtColor", "cv2.CascadeClassifier", "cv2.imread" ]
[((36, 64), 'cv2.imread', 'cv2.imread', (['"""test_image.jpg"""'], {}), "('test_image.jpg')\n", (46, 64), False, 'import cv2\n'), ((72, 109), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (84, 109), False, 'import cv2\n'), ((125, 185), 'cv2.CascadeClassifier', 'cv2.CascadeClassifier', (['"""haarcascade_frontalface_default.xml"""'], {}), "('haarcascade_frontalface_default.xml')\n", (146, 185), False, 'import cv2\n'), ((200, 244), 'cv2.CascadeClassifier', 'cv2.CascadeClassifier', (['"""haarcascade_eye.xml"""'], {}), "('haarcascade_eye.xml')\n", (221, 244), False, 'import cv2\n'), ((306, 325), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (322, 325), False, 'import cv2\n'), ((844, 867), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (865, 867), False, 'import cv2\n'), ((371, 408), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (383, 408), False, 'import cv2\n'), ((495, 553), 'cv2.rectangle', 'cv2.rectangle', (['img', '(x, y)', '(x + w, y + h)', '(255, 0, 0)', '(2)'], {}), '(img, (x, y), (x + w, y + h), (255, 0, 0), 2)\n', (508, 553), False, 'import cv2\n'), ((747, 769), 'cv2.imshow', 'cv2.imshow', (['"""img"""', 'img'], {}), "('img', img)\n", (757, 769), False, 'import cv2\n'), ((686, 756), 'cv2.rectangle', 'cv2.rectangle', (['roi_color', '(ex, ey)', '(ex + ew, ey + eh)', '(0, 255, 0)', '(2)'], {}), '(roi_color, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2)\n', (699, 756), False, 'import cv2\n'), ((773, 787), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (784, 787), False, 'import cv2\n')]
import os import sys import torch from torch import nn from torch.nn import functional as F, init from src.utils import bernoulli_log_pdf from src.objectives.elbo import \ log_bernoulli_marginal_estimate_sets class Statistician(nn.Module): def __init__(self, c_dim, z_dim, hidden_dim_statistic=3, hidden_dim=400): super(Statistician, self).__init__() self.c_dim = c_dim self.z_dim = z_dim self.hidden_dim_statistic = hidden_dim_statistic self.hidden_dim = hidden_dim self.input_dim = 784 self.statistic_net = LinearStatisticNetwork( self.input_dim, self.c_dim, hidden_dim=self.hidden_dim_statistic) self.inference_net = LinearInferenceNetwork( self.input_dim, self.c_dim, self.z_dim, hidden_dim=self.hidden_dim) self.latent_decoder = LinearLatentDecoder( self.input_dim, self.c_dim, self.z_dim, hidden_dim=self.hidden_dim) self.observation_decoder = LinearObservationDecoder( self.input_dim, self.c_dim, self.z_dim, hidden_dim=self.hidden_dim) # initialize weights self.apply(self.weights_init) def forward(self, x): batch_size, n_samples = x.size(0), x.size(1) x = x.view(batch_size, n_samples, self.input_dim) c_mean, c_logvar = self.statistic_net(x) c = self.reparameterize_gaussian(c_mean, c_logvar) qz_mu, qz_logvar = self.inference_net(x, c) qz_mu = qz_mu.view(batch_size, -1, self.z_dim) qz_logvar = qz_logvar.view(batch_size, -1, self.z_dim) z = self.reparameterize_gaussian(qz_mu, qz_logvar) qz_params = [qz_mu, qz_logvar] cz_mu, cz_logvar = self.latent_decoder(c) pz_params = [cz_mu, cz_logvar] x_mu = self.observation_decoder(z, c) outputs = ( (c_mean, c_logvar), (qz_params, pz_params), (x, x_mu), ) return outputs def bernoulli_elbo_loss_sets(self, outputs, reduce=True): c_outputs, z_outputs, x_outputs = outputs # 1. reconstruction loss x, x_mu = x_outputs recon_loss = bernoulli_log_pdf(x, x_mu) # (n_datasets, batch_size) # a) Context divergence: this is the positive D_KL c_mu, c_logvar = c_outputs kl_c = -0.5 * (1 + c_logvar - c_mu.pow(2) - c_logvar.exp()) kl_c = torch.sum(kl_c, dim=-1) # (n_datasets) # b) Latent divergence: this is also the positive D_KL qz_params, pz_params = z_outputs # this is kl(q_z||p_z) p_mu, p_logvar = pz_params q_mu, q_logvar = qz_params # the dimensions won't line up, so you'll need to broadcast! p_mu = p_mu.unsqueeze(1).expand_as(q_mu) p_logvar = p_logvar.unsqueeze(1).expand_as(q_logvar) kl_z = 0.5 * (p_logvar - q_logvar + ((q_mu - p_mu)**2 + q_logvar.exp())/p_logvar.exp() - 1) kl_z = torch.sum(kl_z, dim=-1) # (n_datasets, batch_size) # THESE ARE ALSO UNNORMALIZED!!! ELBO = -recon_loss + kl_z # these will both be (n_datasets, batch_size) ELBO = ELBO.sum(-1) / x.size()[1] # averaging over (batch_size == self.sample_size) ELBO = ELBO + kl_c # now this is (n_datasets,) if reduce: return torch.mean(ELBO) # averaging over (n_datasets) else: return ELBO # (n_datasets) def estimate_marginal(self, x, n_samples=100): # need to compute a bunch of outputs with torch.no_grad(): elbo_list = [] for i in range(n_samples): outputs = self.forward(x) elbo = self.bernoulli_elbo_loss_sets(outputs, reduce=False) elbo_list.append(elbo) # bernoulli decoder log_p_x = log_bernoulli_marginal_estimate_sets(elbo_list) return log_p_x @staticmethod def reparameterize_gaussian(mean, logvar): std = torch.exp(0.5 * logvar) eps = torch.randn_like(std) return eps.mul(std).add_(mean) @staticmethod def weights_init(m): if isinstance(m, (nn.Linear, nn.Conv2d)): init.xavier_normal(m.weight.data, gain=init.calculate_gain('relu')) init.constant(m.bias.data, 0) elif isinstance(m, nn.BatchNorm1d): pass def extract_codes(self, x): batch_size, n_samples = x.size(0), x.size(1) x = x.view(batch_size, n_samples, self.input_dim) c_mean, c_logvar = self.statistic_net(x) c = self.reparameterize_gaussian(c_mean, c_logvar) z_mu, _ = self.inference_net(x, c) return z_mu class LinearStatisticNetwork(nn.Module): def __init__(self, n_features, c_dim, hidden_dim=128): super(LinearStatisticNetwork, self).__init__() self.n_features = n_features self.hidden_dim = hidden_dim self.c_dim = c_dim self.prepool = PrePool(self.n_features, self.hidden_dim) self.postpool = PostPool(self.hidden_dim, self.c_dim) def forward(self, h): batch_size = h.size(0) e = self.prepool(h) e = e.view(batch_size, -1, self.hidden_dim) e = self.pool(e) e = self.postpool(e) return e def pool(self, e): """ average pooling WITHIN each dataset! """ e = e.mean(1).view(-1, self.hidden_dim) return e class LinearInferenceNetwork(nn.Module): def __init__(self, n_features, c_dim, z_dim, hidden_dim=128): super(LinearInferenceNetwork, self).__init__() self.n_features = n_features self.hidden_dim = hidden_dim self.c_dim = c_dim self.z_dim = z_dim self.fc_h = nn.Linear(self.n_features, self.hidden_dim) self.fc_c = nn.Linear(self.c_dim, self.hidden_dim) self.fc1 = nn.Linear(2 * self.hidden_dim, self.hidden_dim) self.fc_params = nn.Linear(self.hidden_dim, 2 * self.z_dim) def forward(self, h, c): batch_size = h.size(0) eh = h.view(-1, self.n_features) # embed h eh = self.fc_h(eh) eh = eh.view(batch_size, -1, self.hidden_dim) ec = self.fc_c(c) ec = ec.view(batch_size, -1, self.hidden_dim).expand_as(eh) e = torch.cat([eh, ec], dim=2) e = F.elu(e.view(-1, 2 * self.hidden_dim)) e = F.elu(self.fc1(e)) e = self.fc_params(e) mean, logvar = torch.chunk(e, 2, dim=1) return mean, logvar class LinearLatentDecoder(nn.Module): def __init__(self, n_features, c_dim, z_dim, hidden_dim=128): super(LinearLatentDecoder, self).__init__() self.n_features = n_features self.hidden_dim = hidden_dim self.c_dim = c_dim self.z_dim = z_dim self.fc_c = nn.Linear(self.c_dim, self.hidden_dim) self.fc1 = nn.Linear(self.hidden_dim, self.hidden_dim) self.fc_params = nn.Linear(self.hidden_dim, 2 * self.z_dim) def forward(self, c): batch_size = c.size(0) ec = self.fc_c(c) ec = ec.view(batch_size, -1, self.hidden_dim) e = F.elu(ec.view(-1, self.hidden_dim)) e = F.elu(self.fc1(e)) e = self.fc_params(e) mean, logvar = torch.chunk(e, 2, dim=1) return mean, logvar class LinearObservationDecoder(nn.Module): def __init__(self, n_features, c_dim, z_dim, hidden_dim=128): super(LinearObservationDecoder, self).__init__() self.n_features = n_features self.hidden_dim = hidden_dim self.c_dim = c_dim self.z_dim = z_dim self.fc_z = nn.Linear(self.z_dim, self.hidden_dim) self.fc_c = nn.Linear(self.c_dim, self.hidden_dim) self.fc_initial = nn.Linear(2 * self.hidden_dim, 256 * 4 * 4) self.fc3 = nn.Linear(256 * 4 * 4, 784) def forward(self, z, c): batch_size = z.size(0) ez = self.fc_z(z) ez = ez.view(batch_size, -1, self.hidden_dim) ec = self.fc_c(c) ec = ec.view(batch_size, -1, self.hidden_dim).expand_as(ez) e = torch.cat([ez, ec], dim=2) e = F.elu(e) e = e.view(-1, 2 * self.hidden_dim) e = F.elu(self.fc_initial(e)) e = self.fc3(e) e = e.view(batch_size, -1, 784) e = torch.sigmoid(e) return e class PrePool(nn.Module): def __init__(self, n_features, hidden_dim): super(PrePool, self).__init__() self.n_features = n_features self.hidden_dim = hidden_dim # modules: 1 fc layer self.fc = nn.Linear(self.n_features, self.hidden_dim) def forward(self, h): # reshape and affine e = h.view(-1, self.n_features) # batch_size * sample_size e = F.elu(self.fc(e)) return e class PostPool(nn.Module): def __init__(self, hidden_dim, c_dim): super(PostPool, self).__init__() self.hidden_dim = hidden_dim self.c_dim = c_dim self.fc_params = nn.Linear(self.hidden_dim, 2 * self.c_dim) def forward(self, e): e = self.fc_params(e) mean, logvar = torch.chunk(e, 2, dim=1) return mean, logvar
[ "torch.mean", "torch.nn.functional.elu", "torch.sigmoid", "torch.exp", "torch.no_grad", "torch.randn_like", "torch.chunk", "torch.sum", "src.objectives.elbo.log_bernoulli_marginal_estimate_sets", "torch.nn.Linear", "torch.nn.init.constant", "torch.nn.init.calculate_gain", "src.utils.bernoull...
[((2186, 2212), 'src.utils.bernoulli_log_pdf', 'bernoulli_log_pdf', (['x', 'x_mu'], {}), '(x, x_mu)\n', (2203, 2212), False, 'from src.utils import bernoulli_log_pdf\n'), ((2420, 2443), 'torch.sum', 'torch.sum', (['kl_c'], {'dim': '(-1)'}), '(kl_c, dim=-1)\n', (2429, 2443), False, 'import torch\n'), ((2963, 2986), 'torch.sum', 'torch.sum', (['kl_z'], {'dim': '(-1)'}), '(kl_z, dim=-1)\n', (2972, 2986), False, 'import torch\n'), ((3983, 4006), 'torch.exp', 'torch.exp', (['(0.5 * logvar)'], {}), '(0.5 * logvar)\n', (3992, 4006), False, 'import torch\n'), ((4021, 4042), 'torch.randn_like', 'torch.randn_like', (['std'], {}), '(std)\n', (4037, 4042), False, 'import torch\n'), ((5740, 5783), 'torch.nn.Linear', 'nn.Linear', (['self.n_features', 'self.hidden_dim'], {}), '(self.n_features, self.hidden_dim)\n', (5749, 5783), False, 'from torch import nn\n'), ((5804, 5842), 'torch.nn.Linear', 'nn.Linear', (['self.c_dim', 'self.hidden_dim'], {}), '(self.c_dim, self.hidden_dim)\n', (5813, 5842), False, 'from torch import nn\n'), ((5867, 5914), 'torch.nn.Linear', 'nn.Linear', (['(2 * self.hidden_dim)', 'self.hidden_dim'], {}), '(2 * self.hidden_dim, self.hidden_dim)\n', (5876, 5914), False, 'from torch import nn\n'), ((5940, 5982), 'torch.nn.Linear', 'nn.Linear', (['self.hidden_dim', '(2 * self.z_dim)'], {}), '(self.hidden_dim, 2 * self.z_dim)\n', (5949, 5982), False, 'from torch import nn\n'), ((6284, 6310), 'torch.cat', 'torch.cat', (['[eh, ec]'], {'dim': '(2)'}), '([eh, ec], dim=2)\n', (6293, 6310), False, 'import torch\n'), ((6446, 6470), 'torch.chunk', 'torch.chunk', (['e', '(2)'], {'dim': '(1)'}), '(e, 2, dim=1)\n', (6457, 6470), False, 'import torch\n'), ((6807, 6845), 'torch.nn.Linear', 'nn.Linear', (['self.c_dim', 'self.hidden_dim'], {}), '(self.c_dim, self.hidden_dim)\n', (6816, 6845), False, 'from torch import nn\n'), ((6865, 6908), 'torch.nn.Linear', 'nn.Linear', (['self.hidden_dim', 'self.hidden_dim'], {}), '(self.hidden_dim, self.hidden_dim)\n', (6874, 6908), False, 'from torch import nn\n'), ((6934, 6976), 'torch.nn.Linear', 'nn.Linear', (['self.hidden_dim', '(2 * self.z_dim)'], {}), '(self.hidden_dim, 2 * self.z_dim)\n', (6943, 6976), False, 'from torch import nn\n'), ((7247, 7271), 'torch.chunk', 'torch.chunk', (['e', '(2)'], {'dim': '(1)'}), '(e, 2, dim=1)\n', (7258, 7271), False, 'import torch\n'), ((7618, 7656), 'torch.nn.Linear', 'nn.Linear', (['self.z_dim', 'self.hidden_dim'], {}), '(self.z_dim, self.hidden_dim)\n', (7627, 7656), False, 'from torch import nn\n'), ((7677, 7715), 'torch.nn.Linear', 'nn.Linear', (['self.c_dim', 'self.hidden_dim'], {}), '(self.c_dim, self.hidden_dim)\n', (7686, 7715), False, 'from torch import nn\n'), ((7742, 7785), 'torch.nn.Linear', 'nn.Linear', (['(2 * self.hidden_dim)', '(256 * 4 * 4)'], {}), '(2 * self.hidden_dim, 256 * 4 * 4)\n', (7751, 7785), False, 'from torch import nn\n'), ((7805, 7832), 'torch.nn.Linear', 'nn.Linear', (['(256 * 4 * 4)', '(784)'], {}), '(256 * 4 * 4, 784)\n', (7814, 7832), False, 'from torch import nn\n'), ((8082, 8108), 'torch.cat', 'torch.cat', (['[ez, ec]'], {'dim': '(2)'}), '([ez, ec], dim=2)\n', (8091, 8108), False, 'import torch\n'), ((8121, 8129), 'torch.nn.functional.elu', 'F.elu', (['e'], {}), '(e)\n', (8126, 8129), True, 'from torch.nn import functional as F, init\n'), ((8289, 8305), 'torch.sigmoid', 'torch.sigmoid', (['e'], {}), '(e)\n', (8302, 8305), False, 'import torch\n'), ((8563, 8606), 'torch.nn.Linear', 'nn.Linear', (['self.n_features', 'self.hidden_dim'], {}), '(self.n_features, self.hidden_dim)\n', (8572, 8606), False, 'from torch import nn\n'), ((8982, 9024), 'torch.nn.Linear', 'nn.Linear', (['self.hidden_dim', '(2 * self.c_dim)'], {}), '(self.hidden_dim, 2 * self.c_dim)\n', (8991, 9024), False, 'from torch import nn\n'), ((9105, 9129), 'torch.chunk', 'torch.chunk', (['e', '(2)'], {'dim': '(1)'}), '(e, 2, dim=1)\n', (9116, 9129), False, 'import torch\n'), ((3325, 3341), 'torch.mean', 'torch.mean', (['ELBO'], {}), '(ELBO)\n', (3335, 3341), False, 'import torch\n'), ((3536, 3551), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3549, 3551), False, 'import torch\n'), ((3831, 3878), 'src.objectives.elbo.log_bernoulli_marginal_estimate_sets', 'log_bernoulli_marginal_estimate_sets', (['elbo_list'], {}), '(elbo_list)\n', (3867, 3878), False, 'from src.objectives.elbo import log_bernoulli_marginal_estimate_sets\n'), ((4268, 4297), 'torch.nn.init.constant', 'init.constant', (['m.bias.data', '(0)'], {}), '(m.bias.data, 0)\n', (4281, 4297), False, 'from torch.nn import functional as F, init\n'), ((4227, 4254), 'torch.nn.init.calculate_gain', 'init.calculate_gain', (['"""relu"""'], {}), "('relu')\n", (4246, 4254), False, 'from torch.nn import functional as F, init\n')]
from corehq.project_limits.rate_limiter import RateDefinition, RateLimiter, \ PerUserRateDefinition from corehq.util.datadog.gauges import datadog_counter from corehq.util.datadog.utils import bucket_value from corehq.util.decorators import silence_and_report_error, enterprise_skip from corehq.util.timer import TimingContext # Danny promised in an Aug 2019 email not to enforce limits that were lower than this. # If we as a team end up regretting this decision, we'll have to reset expectations # with the Dimagi NDoH team. rates_promised_not_to_go_lower_than = RateDefinition( per_week=115, per_day=23, per_hour=3, per_minute=0.07, per_second=0.005, ) floor_for_small_domain = RateDefinition( per_week=100, per_day=50, per_hour=30, per_minute=10, per_second=1, ) test_rates = PerUserRateDefinition( per_user_rate_definition=rates_promised_not_to_go_lower_than.times(2.0), constant_rate_definition=floor_for_small_domain, ) submission_rate_limiter = RateLimiter( feature_key='submissions', get_rate_limits=test_rates.get_rate_limits ) @enterprise_skip @silence_and_report_error("Exception raised in the submission rate limiter", 'commcare.xform_submissions.rate_limiter_errors') def rate_limit_submission_by_delaying(domain, max_wait): if not submission_rate_limiter.allow_usage(domain): with TimingContext() as timer: acquired = submission_rate_limiter.wait(domain, timeout=max_wait) if acquired: duration_tag = bucket_value(timer.duration, [1, 5, 10, 15, 20], unit='s') else: duration_tag = 'timeout' datadog_counter('commcare.xform_submissions.rate_limited.test', tags=[ 'domain:{}'.format(domain), 'duration:{}'.format(duration_tag) ]) submission_rate_limiter.report_usage(domain)
[ "corehq.project_limits.rate_limiter.RateLimiter", "corehq.util.datadog.utils.bucket_value", "corehq.util.timer.TimingContext", "corehq.project_limits.rate_limiter.RateDefinition", "corehq.util.decorators.silence_and_report_error" ]
[((572, 663), 'corehq.project_limits.rate_limiter.RateDefinition', 'RateDefinition', ([], {'per_week': '(115)', 'per_day': '(23)', 'per_hour': '(3)', 'per_minute': '(0.07)', 'per_second': '(0.005)'}), '(per_week=115, per_day=23, per_hour=3, per_minute=0.07,\n per_second=0.005)\n', (586, 663), False, 'from corehq.project_limits.rate_limiter import RateDefinition, RateLimiter, PerUserRateDefinition\n'), ((709, 795), 'corehq.project_limits.rate_limiter.RateDefinition', 'RateDefinition', ([], {'per_week': '(100)', 'per_day': '(50)', 'per_hour': '(30)', 'per_minute': '(10)', 'per_second': '(1)'}), '(per_week=100, per_day=50, per_hour=30, per_minute=10,\n per_second=1)\n', (723, 795), False, 'from corehq.project_limits.rate_limiter import RateDefinition, RateLimiter, PerUserRateDefinition\n'), ((1011, 1098), 'corehq.project_limits.rate_limiter.RateLimiter', 'RateLimiter', ([], {'feature_key': '"""submissions"""', 'get_rate_limits': 'test_rates.get_rate_limits'}), "(feature_key='submissions', get_rate_limits=test_rates.\n get_rate_limits)\n", (1022, 1098), False, 'from corehq.project_limits.rate_limiter import RateDefinition, RateLimiter, PerUserRateDefinition\n'), ((1124, 1253), 'corehq.util.decorators.silence_and_report_error', 'silence_and_report_error', (['"""Exception raised in the submission rate limiter"""', '"""commcare.xform_submissions.rate_limiter_errors"""'], {}), "('Exception raised in the submission rate limiter',\n 'commcare.xform_submissions.rate_limiter_errors')\n", (1148, 1253), False, 'from corehq.util.decorators import silence_and_report_error, enterprise_skip\n'), ((1402, 1417), 'corehq.util.timer.TimingContext', 'TimingContext', ([], {}), '()\n', (1415, 1417), False, 'from corehq.util.timer import TimingContext\n'), ((1554, 1612), 'corehq.util.datadog.utils.bucket_value', 'bucket_value', (['timer.duration', '[1, 5, 10, 15, 20]'], {'unit': '"""s"""'}), "(timer.duration, [1, 5, 10, 15, 20], unit='s')\n", (1566, 1612), False, 'from corehq.util.datadog.utils import bucket_value\n')]
from django.shortcuts import render, redirect from django.views.generic import UpdateView, DeleteView from .models import Storage from django_tables2 import RequestConfig from .tables import StorageTable from django.contrib.auth.decorators import login_required from .forms import StorageForm, QuestionForm def index(request): table = Storage.objects.reverse()[0:3] return render(request, '../templates/index.html', {'storages': table}) def about(request): if request.method == "POST": form = QuestionForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.save() return '/about' else: form = QuestionForm() return render(request, '../templates/about.html', {'form': form}) def current_storages(request): table = StorageTable(Storage.objects.all()) RequestConfig(request).configure(table) return render(request, '../templates/current_storages.html', {'table': table}) @login_required(login_url='/accounts/login') def create_storage(request): if request.method == "POST": form = StorageForm(request.POST, request.FILES) if form.is_valid(): model_instance = form.save(commit=False) model_instance.user_id = request.user model_instance.save() return redirect('/current_storages') else: form = StorageForm() return render(request, '../templates/create_storage.html', {'form': form}) def storage(request, storage_id): storage_request = Storage.objects.get(pk=storage_id) return render(request, '../templates/storage.html', {'storage': storage_request}) class EditStorage(UpdateView): model = Storage form_class = StorageForm template_name = 'storage_update_form.html' success_url = '/current_storages' class DeleteStorage(DeleteView): model = Storage template_name = 'storage_confirm_delete.html' success_url = '/current_storages' def show_image(request, storage_id): photo_request = Storage.objects.get(pk=storage_id) return render(request, '../templates/show_image.html', {'storage': photo_request}) def logout(request): return render(request, '../templates/registration/logout.html', {})
[ "django.shortcuts.render", "django.shortcuts.redirect", "django_tables2.RequestConfig", "django.contrib.auth.decorators.login_required" ]
[((996, 1039), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'login_url': '"""/accounts/login"""'}), "(login_url='/accounts/login')\n", (1010, 1039), False, 'from django.contrib.auth.decorators import login_required\n'), ((383, 446), 'django.shortcuts.render', 'render', (['request', '"""../templates/index.html"""', "{'storages': table}"], {}), "(request, '../templates/index.html', {'storages': table})\n", (389, 446), False, 'from django.shortcuts import render, redirect\n'), ((727, 785), 'django.shortcuts.render', 'render', (['request', '"""../templates/about.html"""', "{'form': form}"], {}), "(request, '../templates/about.html', {'form': form})\n", (733, 785), False, 'from django.shortcuts import render, redirect\n'), ((922, 993), 'django.shortcuts.render', 'render', (['request', '"""../templates/current_storages.html"""', "{'table': table}"], {}), "(request, '../templates/current_storages.html', {'table': table})\n", (928, 993), False, 'from django.shortcuts import render, redirect\n'), ((1423, 1490), 'django.shortcuts.render', 'render', (['request', '"""../templates/create_storage.html"""', "{'form': form}"], {}), "(request, '../templates/create_storage.html', {'form': form})\n", (1429, 1490), False, 'from django.shortcuts import render, redirect\n'), ((1595, 1669), 'django.shortcuts.render', 'render', (['request', '"""../templates/storage.html"""', "{'storage': storage_request}"], {}), "(request, '../templates/storage.html', {'storage': storage_request})\n", (1601, 1669), False, 'from django.shortcuts import render, redirect\n'), ((2085, 2160), 'django.shortcuts.render', 'render', (['request', '"""../templates/show_image.html"""', "{'storage': photo_request}"], {}), "(request, '../templates/show_image.html', {'storage': photo_request})\n", (2091, 2160), False, 'from django.shortcuts import render, redirect\n'), ((2195, 2255), 'django.shortcuts.render', 'render', (['request', '"""../templates/registration/logout.html"""', '{}'], {}), "(request, '../templates/registration/logout.html', {})\n", (2201, 2255), False, 'from django.shortcuts import render, redirect\n'), ((871, 893), 'django_tables2.RequestConfig', 'RequestConfig', (['request'], {}), '(request)\n', (884, 893), False, 'from django_tables2 import RequestConfig\n'), ((1342, 1371), 'django.shortcuts.redirect', 'redirect', (['"""/current_storages"""'], {}), "('/current_storages')\n", (1350, 1371), False, 'from django.shortcuts import render, redirect\n')]
import unittest from app.models import User,Post,Comments from app import db class PostTest(unittest.TestCase): def setUp(self): """ Set up method that will run before every Test """ self.post= Post(category='Product', content='Yes we can!') self.user_Derrick = User(username = 'Derrick',password = 'password', email = '<EMAIL>') self.new_comment = Comments(text='This is good', user=self.user_Derrick ) def tearDown(self): Comments.query.delete() Post.query.delete() User.query.delete() def test_instance(self): self.assertTrue(isinstance(self.post, Post)) def test_check_instance_variables(self): self.assertEquals(self.post.category,'Product') self.assertEquals(self.post.content,'Yes we can!') self.assertEquals(self.new_comment.text,'This is good') self.assertEquals(self.new_comment.user,self.user_Derrick) def test_save_comment(self): self.new_comment.save_comment() self.assertTrue(len(Comments.query.all())>0)
[ "app.models.Comments.query.delete", "app.models.Post", "app.models.Post.query.delete", "app.models.User", "app.models.User.query.delete", "app.models.Comments.query.all", "app.models.Comments" ]
[((233, 280), 'app.models.Post', 'Post', ([], {'category': '"""Product"""', 'content': '"""Yes we can!"""'}), "(category='Product', content='Yes we can!')\n", (237, 280), False, 'from app.models import User, Post, Comments\n'), ((309, 371), 'app.models.User', 'User', ([], {'username': '"""Derrick"""', 'password': '"""password"""', 'email': '"""<EMAIL>"""'}), "(username='Derrick', password='password', email='<EMAIL>')\n", (313, 371), False, 'from app.models import User, Post, Comments\n'), ((404, 457), 'app.models.Comments', 'Comments', ([], {'text': '"""This is good"""', 'user': 'self.user_Derrick'}), "(text='This is good', user=self.user_Derrick)\n", (412, 457), False, 'from app.models import User, Post, Comments\n'), ((492, 515), 'app.models.Comments.query.delete', 'Comments.query.delete', ([], {}), '()\n', (513, 515), False, 'from app.models import User, Post, Comments\n'), ((524, 543), 'app.models.Post.query.delete', 'Post.query.delete', ([], {}), '()\n', (541, 543), False, 'from app.models import User, Post, Comments\n'), ((552, 571), 'app.models.User.query.delete', 'User.query.delete', ([], {}), '()\n', (569, 571), False, 'from app.models import User, Post, Comments\n'), ((1051, 1071), 'app.models.Comments.query.all', 'Comments.query.all', ([], {}), '()\n', (1069, 1071), False, 'from app.models import User, Post, Comments\n')]
# -*- encoding:utf-8 -*- from kscore.session import get_session import json if __name__ == "__main__": s = get_session() client = s.create_client("monitor", "cn-beijing-6", use_ssl=True) clientv2 = s.create_client("monitorv2", "cn-beijing-6", use_ssl=True) ''' 通用产品线,不包含容器(docker) ''' #ListMetrics m = client.list_metrics(InstanceID="293bbbc1-6c27-4567-89fc-xxxxx", Namespace="kec", PageIndex="1", PageSize="10") print(json.dumps(m, sort_keys=True, indent=4)) #GetMetricStatistics #m = client.get_metric_statistics( # InstanceID="ef6eaa98-8e2b-4629-98e0-xxxxx", # Namespace="eip", # MetricName="eip.bps.in", # StartTime="2021-09-15T10:09:00Z", # EndTime="2021-09-15T10:19:00Z", # Period="60", # Aggregate="Average,Max,Min") #print(json.dumps(m, sort_keys=True, indent=4)) #GetMetricStatisticsBatch version=2018-11-14 param = { "Namespace": "kec", "StartTime": "2021-09-15T10:00:00Z", "EndTime": "2021-09-15T10:09:00Z", "Period": "180", "Aggregate": ["Max", "Min", "Avg"], "Metrics": [{ "InstanceID": "293bbbc1-6c27-4567-89fc-xxxxx", "MetricName": "net.if.in" }, { "InstanceID": "293bbbc1-6c27-4567-89fc-xxxxx", "MetricName": "cpu.utilizition.total" }, { "InstanceID": "6a725f27-1c7e-4704-95c8-xxxxx", "MetricName": "net.if.out" }] } #m = client.get_metric_statistics_batch_v2(**param) #print(json.dumps(m, sort_keys=True, indent=4)) ''' 只支持容器docker(kce),其余产品线不支持。 ''' #ListMetrics paraml = { "Action": "ListMetrics", "Version": "2019-08-12", "Namespace": "kce", "PageIndex": "1", "PageSize": "10", "Dimensions.0.Name": "ClusterId", "Dimensions.0.Value": "807a4149-b7e2-4e05-8a35-xxxxx", "Dimensions.1.Name": "NamespaceName", "Dimensions.1.Value": "xxxxx", "Dimensions.2.Name": "WorkloadType", "Dimensions.2.Value": "deployment", "Dimensions.3.Name": "WorkloadName", "Dimensions.3.Value": "xxxxx", "Dimensions.4.Name": "PodName", "Dimensions.4.Value": "xxxxx-xxxxx-xxxxx", # "Dimensions.5.Name":"ContainerName", # "Dimensions.5.Value":"xxxxx" } #m = client.list_metrics_v3(**paraml) #print(json.dumps(m, sort_keys=True, indent=4)) #GetMetricStatistics paramg = { "Action": "GetMetricStatistics", "Version": "2019-08-12", "Namespace": "kce", "MetricName": "pod.network.rx", "StartTime": "2021-09-15T10:09:00Z", "EndTime": "2021-09-15T10:19:00Z", "Period": "60", "Aggregate": "Average,Max,Min", "Dimensions.0.Name": "ClusterId", "Dimensions.0.Value": "807a4149-b7e2-4e05-8a35-xxxxx", "Dimensions.1.Name": "NamespaceName", "Dimensions.1.Value": "xxxxx", "Dimensions.2.Name": "WorkloadType", "Dimensions.2.Value": "deployment", "Dimensions.3.Name": "WorkloadName", "Dimensions.3.Value": "xxxxx", "Dimensions.4.Name": "PodName", "Dimensions.4.Value": "xxxxx", # "Dimensions.5.Name":"ContainerName", # "Dimensions.5.Value":"xxxxx" } #m = client.get_metric_statistics_v3(**paramg) #print(json.dumps(m, sort_keys=True, indent=4)) #ListAlarmPolicy #m = clientv2.list_alarm_policy(PageIndex=1, PageSize=10) #print(json.dumps(m, sort_keys=True, indent=4)) #DescribeAlarmPolicy #m = clientv2.describe_alarm_policy(PolicyId=25232) #print(json.dumps(m, sort_keys=True, indent=4)) #DescribePolicyObject #m = clientv2.describe_policy_object(PolicyId=25232, PageIndex=1, PageSize=10) #print(json.dumps(m, sort_keys=True, indent=4)) #DescribeAlarmReceives #m = clientv2.describe_alarm_receives(PolicyId=25232) #print(json.dumps(m, sort_keys=True, indent=4)) #AddAlarmReceives paraml = { "PolicyId": 25232, "ContactFlag": 2, "ContactWay": 3, "ContactId": [1985, 3607], } #m = clientv2.add_alarm_receives(**paraml) #print(json.dumps(m, sort_keys=True, indent=4)) #DeleteAlarmReceives paraml = { "PolicyId": 25232, "ContactFlag": 2, "ContactId": [1985, 3607], } #m = clientv2.delete_alarm_receives(**paraml) #print(json.dumps(m, sort_keys=True, indent=4)) #GetUserGroup #m = clientv2.get_user_group() #print(json.dumps(m, sort_keys=True, indent=4)) #GetAlertUser #m = clientv2.get_alert_user(UserGrpId=[879, 1484]) #print(json.dumps(m, sort_keys=True, indent=4)) #UpdateAlertUserStatus paraml = { "UserId": [1985, 3607], "UserStatus": 1, } #m = clientv2.update_alert_user_status(**paraml) #print(json.dumps(m, sort_keys=True, indent=4))
[ "kscore.session.get_session", "json.dumps" ]
[((113, 126), 'kscore.session.get_session', 'get_session', ([], {}), '()\n', (124, 126), False, 'from kscore.session import get_session\n'), ((542, 581), 'json.dumps', 'json.dumps', (['m'], {'sort_keys': '(True)', 'indent': '(4)'}), '(m, sort_keys=True, indent=4)\n', (552, 581), False, 'import json\n')]
import numpy as np class RegularizeOrthogonal(object): """ Orthogonal """ def __init__(self, coeff_lambda=0.0): self.coeff_lambda = coeff_lambda def cost(self, layers): c = 0.0 for layer in layers: wt = layer.w.transpose() for j in range(layer.output_size): wtj = wt[j] / np.sqrt(wt[j].dot(wt[j])) for k in range(layer.output_size): if j == k: continue wtk = wt[k] / np.sqrt(wt[k].dot(wt[k])) c += np.abs(wtj.dot(wtk)) return self.coeff_lambda * c def cost_gradient(self, layers, dc_db, dc_dw): for l, layer in enumerate(layers): wt = layer.w.transpose() tmp = np.zeros_like(wt) for j in range(layer.output_size): dj = np.sqrt(wt[j].dot(wt[j])) wtj = wt[j] / dj # TODO: simplify this s = 2 * (np.eye(len(wtj)) - np.outer(wtj, wtj)) / dj for k in range(layer.output_size): if j == k: continue dk = np.sqrt(wt[k].dot(wt[k])) wtk = wt[k] / dk tmp[j] += wtk.dot(s) * np.sign(wtj.dot(wtk)) dc_dw[l] += self.coeff_lambda * tmp.transpose() return dc_db, dc_dw
[ "numpy.outer", "numpy.zeros_like" ]
[((795, 812), 'numpy.zeros_like', 'np.zeros_like', (['wt'], {}), '(wt)\n', (808, 812), True, 'import numpy as np\n'), ((1022, 1040), 'numpy.outer', 'np.outer', (['wtj', 'wtj'], {}), '(wtj, wtj)\n', (1030, 1040), True, 'import numpy as np\n')]
import pandas as pd file = r'8_calculate_spacer_len.csv' with open(file, 'r') as f: data = pd.read_csv(f) for i in data.index: box_motif = data.at[i, 'box motif'] if '[' in box_motif: data.at[i, 'Upstream mismatch'] = data.at[i, 'Upstream mismatch'] + 0.5 data.at[i, 'Downstream mismatch'] = data.at[i, 'Downstream mismatch'] + 0.5 data.to_csv('9_adjust_box_mismatch.csv', index=False)
[ "pandas.read_csv" ]
[((100, 114), 'pandas.read_csv', 'pd.read_csv', (['f'], {}), '(f)\n', (111, 114), True, 'import pandas as pd\n')]
import numpy as np import pandas as pd from pandas.util import testing as pdt import pytest from spandex import TableFrame from spandex.io import db_to_df, df_to_db def test_tableframe(loader): table = loader.tables.sample.hf_bg for cache in [False, True]: tf = TableFrame(table, index_col='gid', cache=cache) assert isinstance(tf.index, pd.Index) num_rows = len(tf) assert num_rows > 1 assert set(tf.columns) == set(table.__table__.columns.keys()) for column_name in tf.columns: if column_name != 'gid': if cache: assert column_name not in tf._cached.keys() assert isinstance(tf[column_name], pd.Series) if cache: assert column_name in tf._cached.keys() assert isinstance(getattr(tf, column_name), pd.Series) df = tf[['objectid']] assert isinstance(df, pd.DataFrame) assert len(df) == num_rows assert set(df.columns) == set(['objectid']) assert np.issubdtype(df.objectid.dtype, int) def test_sim_export(loader): # Try importing the UrbanSim simulation framework, otherwise skip test. sim = pytest.importorskip('urbansim.sim.simulation') # Register input parcels table. parcels = loader.tables.sample.heather_farms parcels_in = TableFrame(parcels, index_col='gid') sim.add_table('parcels_in', parcels_in, copy_col=False) # Register output parcels table. @sim.table() def parcels_out(parcels_in): return pd.DataFrame(index=parcels_in.parcel_id) # Specify default table for output columns as decorator. out = sim.column('parcels_out') # Specify some output columns. @out def apn(apn='parcels_in.puid'): return apn.groupby(parcels_in.parcel_id).first().astype(str) @out def county_id(): return 13 @out def area(acr='parcels_in.parcel_acr'): return 4047. * acr.groupby(parcels_in.parcel_id).median() # Register model to export output table to database. @sim.model() def export(parcels_out): schema = loader.tables.sample df_to_db(parcels_out.to_frame(), 'parcels_out', schema=schema) # Inspect output table. column_names = ['apn', 'county_id', 'area'] parcels_out_df1 = sim.get_table('parcels_out').to_frame() assert set(parcels_out_df1.columns) == set(column_names) assert parcels_out_df1.county_id.unique() == [13] # Export table to database and import back to compare. sim.run(['export']) parcels_out_table = loader.tables.sample.parcels_out parcels_out_df2 = db_to_df(parcels_out_table, index_col='parcel_id') pdt.assert_frame_equal(parcels_out_df1[column_names], parcels_out_df2[column_names])
[ "spandex.io.db_to_df", "numpy.issubdtype", "spandex.TableFrame", "pytest.importorskip", "pandas.DataFrame", "pandas.util.testing.assert_frame_equal" ]
[((1216, 1262), 'pytest.importorskip', 'pytest.importorskip', (['"""urbansim.sim.simulation"""'], {}), "('urbansim.sim.simulation')\n", (1235, 1262), False, 'import pytest\n'), ((1366, 1402), 'spandex.TableFrame', 'TableFrame', (['parcels'], {'index_col': '"""gid"""'}), "(parcels, index_col='gid')\n", (1376, 1402), False, 'from spandex import TableFrame\n'), ((2653, 2703), 'spandex.io.db_to_df', 'db_to_df', (['parcels_out_table'], {'index_col': '"""parcel_id"""'}), "(parcels_out_table, index_col='parcel_id')\n", (2661, 2703), False, 'from spandex.io import db_to_df, df_to_db\n'), ((2708, 2797), 'pandas.util.testing.assert_frame_equal', 'pdt.assert_frame_equal', (['parcels_out_df1[column_names]', 'parcels_out_df2[column_names]'], {}), '(parcels_out_df1[column_names], parcels_out_df2[\n column_names])\n', (2730, 2797), True, 'from pandas.util import testing as pdt\n'), ((281, 328), 'spandex.TableFrame', 'TableFrame', (['table'], {'index_col': '"""gid"""', 'cache': 'cache'}), "(table, index_col='gid', cache=cache)\n", (291, 328), False, 'from spandex import TableFrame\n'), ((1061, 1098), 'numpy.issubdtype', 'np.issubdtype', (['df.objectid.dtype', 'int'], {}), '(df.objectid.dtype, int)\n', (1074, 1098), True, 'import numpy as np\n'), ((1566, 1606), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': 'parcels_in.parcel_id'}), '(index=parcels_in.parcel_id)\n', (1578, 1606), True, 'import pandas as pd\n')]
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.getcwd()))) from training_structures.MFM import train_MFM,test_MFM from fusions.common_fusions import Concat from unimodals.MVAE import LeNetEncoder,DeLeNet from unimodals.common_models import MLP from torch import nn import torch from objective_functions.recon import recon_weighted_sum,sigmloss1dcentercrop from datasets.avmnist.get_data_robust import get_dataloader filename='avmnist_MFM_robust_best.pt' traindata, validdata, testdata, robustdata = get_dataloader('../../../../yiwei/avmnist/_MFAS/avmnist') channels=6 classes=10 n_latent=200 fuse=Concat() encoders=[LeNetEncoder(1,channels,3,n_latent,twooutput=False).cuda(),LeNetEncoder(1,channels,5,n_latent,twooutput=False).cuda()] decoders=[DeLeNet(1,channels,3,n_latent).cuda(),DeLeNet(1,channels,5,n_latent).cuda()] intermediates=[MLP(n_latent,n_latent//2,n_latent//2).cuda(),MLP(n_latent,n_latent//2,n_latent//2).cuda(),MLP(2*n_latent,n_latent,n_latent//2).cuda()] head=MLP(n_latent//2,40,classes).cuda() recon_loss=recon_weighted_sum([sigmloss1dcentercrop(28,34),sigmloss1dcentercrop(112,130)],[1.0,1.0]) train_MFM(encoders,decoders,head,intermediates,fuse,recon_loss,traindata,validdata,25,savedir=filename) model=torch.load(filename) print("Testing:") test_MFM(model,testdata) print("Robustness testing:") test(model,testdata)
[ "unimodals.MVAE.LeNetEncoder", "unimodals.MVAE.DeLeNet", "datasets.avmnist.get_data_robust.get_dataloader", "fusions.common_fusions.Concat", "torch.load", "objective_functions.recon.sigmloss1dcentercrop", "os.getcwd", "unimodals.common_models.MLP", "training_structures.MFM.train_MFM", "training_st...
[((526, 583), 'datasets.avmnist.get_data_robust.get_dataloader', 'get_dataloader', (['"""../../../../yiwei/avmnist/_MFAS/avmnist"""'], {}), "('../../../../yiwei/avmnist/_MFAS/avmnist')\n", (540, 583), False, 'from datasets.avmnist.get_data_robust import get_dataloader\n'), ((625, 633), 'fusions.common_fusions.Concat', 'Concat', ([], {}), '()\n', (631, 633), False, 'from fusions.common_fusions import Concat\n'), ((1144, 1260), 'training_structures.MFM.train_MFM', 'train_MFM', (['encoders', 'decoders', 'head', 'intermediates', 'fuse', 'recon_loss', 'traindata', 'validdata', '(25)'], {'savedir': 'filename'}), '(encoders, decoders, head, intermediates, fuse, recon_loss,\n traindata, validdata, 25, savedir=filename)\n', (1153, 1260), False, 'from training_structures.MFM import train_MFM, test_MFM\n'), ((1255, 1275), 'torch.load', 'torch.load', (['filename'], {}), '(filename)\n', (1265, 1275), False, 'import torch\n'), ((1294, 1319), 'training_structures.MFM.test_MFM', 'test_MFM', (['model', 'testdata'], {}), '(model, testdata)\n', (1302, 1319), False, 'from training_structures.MFM import train_MFM, test_MFM\n'), ((1007, 1038), 'unimodals.common_models.MLP', 'MLP', (['(n_latent // 2)', '(40)', 'classes'], {}), '(n_latent // 2, 40, classes)\n', (1010, 1038), False, 'from unimodals.common_models import MLP\n'), ((1073, 1101), 'objective_functions.recon.sigmloss1dcentercrop', 'sigmloss1dcentercrop', (['(28)', '(34)'], {}), '(28, 34)\n', (1093, 1101), False, 'from objective_functions.recon import recon_weighted_sum, sigmloss1dcentercrop\n'), ((1101, 1131), 'objective_functions.recon.sigmloss1dcentercrop', 'sigmloss1dcentercrop', (['(112)', '(130)'], {}), '(112, 130)\n', (1121, 1131), False, 'from objective_functions.recon import recon_weighted_sum, sigmloss1dcentercrop\n'), ((69, 80), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (78, 80), False, 'import os\n'), ((645, 700), 'unimodals.MVAE.LeNetEncoder', 'LeNetEncoder', (['(1)', 'channels', '(3)', 'n_latent'], {'twooutput': '(False)'}), '(1, channels, 3, n_latent, twooutput=False)\n', (657, 700), False, 'from unimodals.MVAE import LeNetEncoder, DeLeNet\n'), ((704, 759), 'unimodals.MVAE.LeNetEncoder', 'LeNetEncoder', (['(1)', 'channels', '(5)', 'n_latent'], {'twooutput': '(False)'}), '(1, channels, 5, n_latent, twooutput=False)\n', (716, 759), False, 'from unimodals.MVAE import LeNetEncoder, DeLeNet\n'), ((774, 807), 'unimodals.MVAE.DeLeNet', 'DeLeNet', (['(1)', 'channels', '(3)', 'n_latent'], {}), '(1, channels, 3, n_latent)\n', (781, 807), False, 'from unimodals.MVAE import LeNetEncoder, DeLeNet\n'), ((812, 845), 'unimodals.MVAE.DeLeNet', 'DeLeNet', (['(1)', 'channels', '(5)', 'n_latent'], {}), '(1, channels, 5, n_latent)\n', (819, 845), False, 'from unimodals.MVAE import LeNetEncoder, DeLeNet\n'), ((867, 910), 'unimodals.common_models.MLP', 'MLP', (['n_latent', '(n_latent // 2)', '(n_latent // 2)'], {}), '(n_latent, n_latent // 2, n_latent // 2)\n', (870, 910), False, 'from unimodals.common_models import MLP\n'), ((912, 955), 'unimodals.common_models.MLP', 'MLP', (['n_latent', '(n_latent // 2)', '(n_latent // 2)'], {}), '(n_latent, n_latent // 2, n_latent // 2)\n', (915, 955), False, 'from unimodals.common_models import MLP\n'), ((957, 999), 'unimodals.common_models.MLP', 'MLP', (['(2 * n_latent)', 'n_latent', '(n_latent // 2)'], {}), '(2 * n_latent, n_latent, n_latent // 2)\n', (960, 999), False, 'from unimodals.common_models import MLP\n')]
#!/usr/bin/python3 # By <NAME> import sys import random import pygame from pygame.locals import * class Colours: BLACK = (0, 0, 0) WHITE = (255, 255, 255) AQUA = (0, 255, 255) GREY = (128, 128, 128) NAVY = (0, 0, 128) SILVER = (192, 192 ,192) GREEN = (0, 128, 0) OLIVE = (128, 128, 0) TEAL = (0, 128, 128) BLUE = (0, 0, 255) LIME = (0, 255, 0) PURPLE = (128, 0, 128) FUCHSIA = (255, 0, 255) MAROON = (128, 0, 0) RED = (255, 0, 0) YELLOW = (255, 255, 0) @staticmethod def RANDOM(): return (random.randrange(0, 255), random.randrange(0, 255), random.randrange(0, 255)) class PyGame(object): def __init__(self, width = 640, height = 480): pygame.init() self.fps = 60 self.fpsClock = pygame.time.Clock() self.width, self.height = width, height self.screen = pygame.display.set_mode((self.width, self.height)) def game_loop(self): self.screen.fill(Colours.BLACK) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() pygame.display.flip() fpsClock.tick(fps) def run(self): while True: self.game_loop()
[ "sys.exit", "pygame.init", "pygame.quit", "pygame.event.get", "random.randrange", "pygame.display.set_mode", "pygame.display.flip", "pygame.time.Clock" ]
[((780, 793), 'pygame.init', 'pygame.init', ([], {}), '()\n', (791, 793), False, 'import pygame\n'), ((852, 871), 'pygame.time.Clock', 'pygame.time.Clock', ([], {}), '()\n', (869, 871), False, 'import pygame\n'), ((954, 1004), 'pygame.display.set_mode', 'pygame.display.set_mode', (['(self.width, self.height)'], {}), '((self.width, self.height))\n', (977, 1004), False, 'import pygame\n'), ((1096, 1114), 'pygame.event.get', 'pygame.event.get', ([], {}), '()\n', (1112, 1114), False, 'import pygame\n'), ((1222, 1243), 'pygame.display.flip', 'pygame.display.flip', ([], {}), '()\n', (1241, 1243), False, 'import pygame\n'), ((603, 627), 'random.randrange', 'random.randrange', (['(0)', '(255)'], {}), '(0, 255)\n', (619, 627), False, 'import random\n'), ((629, 653), 'random.randrange', 'random.randrange', (['(0)', '(255)'], {}), '(0, 255)\n', (645, 653), False, 'import random\n'), ((655, 679), 'random.randrange', 'random.randrange', (['(0)', '(255)'], {}), '(0, 255)\n', (671, 679), False, 'import random\n'), ((1169, 1182), 'pygame.quit', 'pygame.quit', ([], {}), '()\n', (1180, 1182), False, 'import pygame\n'), ((1200, 1210), 'sys.exit', 'sys.exit', ([], {}), '()\n', (1208, 1210), False, 'import sys\n')]
try: import unzip_requirements except ImportError: pass import json import os import tarfile import boto3 import tensorflow as tf import numpy as np import census_data import logging logger = logging.getLogger() logger.setLevel(logging.WARNING) FILE_DIR = '/tmp/' BUCKET = os.environ['BUCKET'] import queue import concurrent.futures from concurrent.futures import ThreadPoolExecutor q = queue.Queue() lambda_client = boto3.client('lambda') def feed_the_workers(datapoints, spacing): """ Outside actors sending in work to do """ count = 0 for datapoint in datapoints: print(spacing) count = count + 1 print(count) q.put(datapoint) return "DONE FEEDING" def process_one_datapoint(executor, payload_one_item): """ Process a single item """ payload_one_item_json = {} payload_one_item_json['input'] = [payload_one_item] payload_one_item_json['epoch'] = '' payload_one_item_json = json.dumps(payload_one_item_json) logging.warning('payload_one_item_json from process_one_datapoint is %s', payload_one_item_json) predictions = executor.submit(lambda_client.invoke( FunctionName='tflambdademo-dev-infer', InvocationType='RequestResponse', LogType='Tail', Payload=payload_one_item_json) ) logging.warning('predictions raw from process_one_datapoint is %s', predictions) #logging.warning('predictions result from process_one_datapoint is %s', predictions.result()) responseFromChild = json.load(predictions['Payload']) logging.warning('responseFromChild is %s', responseFromChild) return responseFromChild def inferqueueHandler(event, context): body = json.loads(event.get('body')) # Read in prediction data as dictionary # Keys should match _CSV_COLUMNS, values should be lists predict_input = body['input'] logging.warning('predict_input type is %s', type(predict_input)) logging.warning('predict_input is %s', predict_input) # Read in epoch epoch_files = body['epoch'] logging.warning('epoch_files is %s', epoch_files) if isinstance(predict_input, list): predict_datapoints = predict_input else: predict_datapoints = [predict_input] logging.warning('predict_datapoints is %s', predict_datapoints) results = [] results_datapoint_order = [] # We can use a with statement to ensure threads are cleaned up promptly with concurrent.futures.ThreadPoolExecutor(max_workers=30) as executor: # start a future for a thread which sends work in through the queue future_to_datapoint = { executor.submit(feed_the_workers, predict_datapoints, 0): 'FEEDER DONE'} while future_to_datapoint: # check for status of the futures which are currently working done, not_done = concurrent.futures.wait( future_to_datapoint, timeout=0.0, return_when=concurrent.futures.FIRST_COMPLETED) #done, not_done = concurrent.futures.wait( # future_to_datapoint, timeout=0.0, # return_when=concurrent.futures.ALL_COMPLETED) # if there is incoming work, start a new future while not q.empty(): # fetch a url from the queue datapoint = q.get() payload_one_item = datapoint logging.warning('payload_one_item value is %s', payload_one_item) # Start the load operation and mark the future with its datapoint future_to_datapoint[executor.submit(process_one_datapoint, executor, payload_one_item)] = payload_one_item # process any completed futures for future in done: datapoint = future_to_datapoint[future] try: logging.warning('In try loop') logging.warning('In try loop future is %s', future) if datapoint != 'FEEDER DONE': print('In NOT FEEDER DONE') data = future.result() logging.warning('In try loop data1 is %s', data) data = json.loads(data) logging.warning('In try loop data2 is %s', data) logging.warning('data value is %s', data) results.append(data) results_datapoint_order.append(datapoint) except Exception as exc: print('In Exception path') print('exc: %s', exc) print('%r generated an exception: %s' % (future, exc)) print('Finishing Exception path') else: if datapoint == 'FEEDER DONE': data = future.result() print(data) else: print('%r page is %d bytes' % (datapoint, len(data))) # remove the now completed future del future_to_datapoint[future] datapoints_result_order = [] for item_in_list in results_datapoint_order: datapoints_result = item_in_list['predict_datapoints'] datapoints_result_order.append(datapoints_result[0]) order_list_idx = [] for item_in_list in datapoints_result_order: order_list_idx.append(predict_datapoints.index(item_in_list)) logging.warning('predict_datapoints value is %s', predict_datapoints) logging.warning('results_datapoint_order value is %s', results_datapoint_order) logging.warning('order_list_idx value is %s', order_list_idx) results_ordered = [x for _,x in sorted(zip(order_list_idx,results))] logging.warning('results value is %s', results) logging.warning('results_ordered value is %s', results_ordered) response = { "statusCode": 200, "body": json.dumps(results_ordered, default=lambda x: x.decode('utf-8')) } return response
[ "logging.getLogger", "json.loads", "boto3.client", "json.dumps", "logging.warning", "json.load", "queue.Queue" ]
[((201, 220), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (218, 220), False, 'import logging\n'), ((399, 412), 'queue.Queue', 'queue.Queue', ([], {}), '()\n', (410, 412), False, 'import queue\n'), ((429, 451), 'boto3.client', 'boto3.client', (['"""lambda"""'], {}), "('lambda')\n", (441, 451), False, 'import boto3\n'), ((966, 999), 'json.dumps', 'json.dumps', (['payload_one_item_json'], {}), '(payload_one_item_json)\n', (976, 999), False, 'import json\n'), ((1009, 1109), 'logging.warning', 'logging.warning', (['"""payload_one_item_json from process_one_datapoint is %s"""', 'payload_one_item_json'], {}), "('payload_one_item_json from process_one_datapoint is %s',\n payload_one_item_json)\n", (1024, 1109), False, 'import logging\n'), ((1358, 1443), 'logging.warning', 'logging.warning', (['"""predictions raw from process_one_datapoint is %s"""', 'predictions'], {}), "('predictions raw from process_one_datapoint is %s', predictions\n )\n", (1373, 1443), False, 'import logging\n'), ((1571, 1604), 'json.load', 'json.load', (["predictions['Payload']"], {}), "(predictions['Payload'])\n", (1580, 1604), False, 'import json\n'), ((1609, 1670), 'logging.warning', 'logging.warning', (['"""responseFromChild is %s"""', 'responseFromChild'], {}), "('responseFromChild is %s', responseFromChild)\n", (1624, 1670), False, 'import logging\n'), ((2009, 2062), 'logging.warning', 'logging.warning', (['"""predict_input is %s"""', 'predict_input'], {}), "('predict_input is %s', predict_input)\n", (2024, 2062), False, 'import logging\n'), ((2124, 2173), 'logging.warning', 'logging.warning', (['"""epoch_files is %s"""', 'epoch_files'], {}), "('epoch_files is %s', epoch_files)\n", (2139, 2173), False, 'import logging\n'), ((2332, 2395), 'logging.warning', 'logging.warning', (['"""predict_datapoints is %s"""', 'predict_datapoints'], {}), "('predict_datapoints is %s', predict_datapoints)\n", (2347, 2395), False, 'import logging\n'), ((5613, 5682), 'logging.warning', 'logging.warning', (['"""predict_datapoints value is %s"""', 'predict_datapoints'], {}), "('predict_datapoints value is %s', predict_datapoints)\n", (5628, 5682), False, 'import logging\n'), ((5688, 5767), 'logging.warning', 'logging.warning', (['"""results_datapoint_order value is %s"""', 'results_datapoint_order'], {}), "('results_datapoint_order value is %s', results_datapoint_order)\n", (5703, 5767), False, 'import logging\n'), ((5773, 5834), 'logging.warning', 'logging.warning', (['"""order_list_idx value is %s"""', 'order_list_idx'], {}), "('order_list_idx value is %s', order_list_idx)\n", (5788, 5834), False, 'import logging\n'), ((5922, 5969), 'logging.warning', 'logging.warning', (['"""results value is %s"""', 'results'], {}), "('results value is %s', results)\n", (5937, 5969), False, 'import logging\n'), ((5975, 6038), 'logging.warning', 'logging.warning', (['"""results_ordered value is %s"""', 'results_ordered'], {}), "('results_ordered value is %s', results_ordered)\n", (5990, 6038), False, 'import logging\n'), ((3536, 3601), 'logging.warning', 'logging.warning', (['"""payload_one_item value is %s"""', 'payload_one_item'], {}), "('payload_one_item value is %s', payload_one_item)\n", (3551, 3601), False, 'import logging\n'), ((4002, 4032), 'logging.warning', 'logging.warning', (['"""In try loop"""'], {}), "('In try loop')\n", (4017, 4032), False, 'import logging\n'), ((4053, 4104), 'logging.warning', 'logging.warning', (['"""In try loop future is %s"""', 'future'], {}), "('In try loop future is %s', future)\n", (4068, 4104), False, 'import logging\n'), ((4279, 4327), 'logging.warning', 'logging.warning', (['"""In try loop data1 is %s"""', 'data'], {}), "('In try loop data1 is %s', data)\n", (4294, 4327), False, 'import logging\n'), ((4359, 4375), 'json.loads', 'json.loads', (['data'], {}), '(data)\n', (4369, 4375), False, 'import json\n'), ((4400, 4448), 'logging.warning', 'logging.warning', (['"""In try loop data2 is %s"""', 'data'], {}), "('In try loop data2 is %s', data)\n", (4415, 4448), False, 'import logging\n'), ((4473, 4514), 'logging.warning', 'logging.warning', (['"""data value is %s"""', 'data'], {}), "('data value is %s', data)\n", (4488, 4514), False, 'import logging\n')]
from time import time import rclpy from rclpy.node import Node import json from std_msgs.msg import String, Float32, Int8, Int16 import sailbot.autonomous.p2p as p2p from collections import deque class ControlSystem(Node): # Gathers data from some nodes and distributes it to others def __init__(self): super().__init__('control_system') # Create subcription to serial_rc topic self.serial_rc_subscription = self.create_subscription( String, 'serial_rc', self.serial_rc_listener_callback, 10) self.serial_rc_subscription # Create subscription to airmar_data self.airmar_data_subscription = self.create_subscription( String, 'airmar_data', self.airmar_data_listener_callback, 10) self.airmar_data_subscription # Create subscription to tt_telemetry self.trim_tab_telemetry_subscription = self.create_subscription( Float32, 'tt_telemetry', self.trim_tab_telemetry_listener_callback, 10) self.trim_tab_telemetry_subscription # Create publisher to pwm_control self.pwm_control_publisher_ = self.create_publisher(String, 'pwm_control', 10) # Create publisher to trim_tab_control self.trim_tab_control_publisher_ = self.create_publisher(Int8, 'tt_control', 10) self.trim_tab_angle_publisher_ = self.create_publisher(Int16, 'tt_angle', 10) # Create publisher to ballast_algorithnm_debug self.ballast_algorithnm_debug_publisher_ = self.create_publisher(String, 'ballast_algorithnm_debug', 10) # Create instance vars for subscribed topics to update self.serial_rc = {} self.airmar_data = {} self.trim_tab_status = {} # Create instance var for keeping queue of wind data self.lastWinds = [] self.p2p_alg = None # Create instance var for keeping queue of roll data self.omega = deque(maxlen=4) self.alpha = deque(maxlen=3) self.lastRollAngle = deque(maxlen=4) # self.p2p_alg = None def serial_rc_listener_callback(self, msg): self.get_logger().info('Received msg: "%s"' % msg.data) msg_dict = json.loads(msg.data) for i in msg_dict: self.serial_rc[i] = msg_dict[i] def airmar_data_listener_callback(self, msg): self.get_logger().info('Received msg: "%s"' % msg.data) msg_dict = json.loads(msg.data) for i in msg_dict: self.airmar_data[i] = msg_dict[i] def trim_tab_telemetry_listener_callback(self, msg): self.get_logger().info('Received msg: "%s"' % msg.data) try: self.trim_tab_status['wind_dir'] = msg.data except Exception as e: self.get_logger().error(str(e)) def update_winds(self, relative_wind): # Check we have new wind if len(self.lastWinds) != 0 and relative_wind == self.lastWinds[len(self.lastWinds) -1]: return # First add wind to running list self.lastWinds.append(float(relative_wind)) if len(self.lastWinds) > 10: self.lastWinds.pop(0) # Now find best trim tab state smooth_angle = self.median(self.lastWinds) return smooth_angle def find_trim_tab_state(self, relative_wind): #five states of trim smooth_angle = self.update_winds(relative_wind) msg = Int8() if 45.0 <= smooth_angle < 135: # Max lift port msg.data = (0) elif 135 <= smooth_angle < 180: # Max drag port msg.data = (2) elif 180 <= smooth_angle < 225: # Max drag starboard msg.data = (3) elif 225 <= smooth_angle < 315: # Max lift starboard msg.data = (1) else: # In irons, min lift msg.data = (4) self.trim_tab_control_publisher_.publish(msg) def make_json_string(self, json_msg): json_str = json.dumps(json_msg) message = String() message.data = json_str return message def median(self, lst): n = len(lst) s = sorted(lst) return (sum(s[n//2-1:n//2+1])/2.0, s[n//2])[n % 2] if n else None def ballast_algorithm(self): # Check wind angle, then check current tilt of boat, then adjust ballast accordingly if len(self.lastWinds) == 0: return self.lastRollAngle.append(self.airmar_data["roll"]) smooth_angle = self.median(self.lastWinds) ballast_angle = 0 #print("roll:" + self.airmar_data["roll"]) delta = self.airmar_data["roll"] - self.lastRollAngle[-1] timeDifference = .5 #hypothetically - see main omega_n = delta/timeDifference self.omega.append(omega_n) alpha_n = self.omega[-1]/timeDifference self.alpha.append(alpha_n) #-- Logging ---------------- self.ballast_algorithnm_debug_publisher_.publish("omega: " + str(omega_n) + " -- " + "alpha / acceleration: " + str(alpha_n) + "\n") #Account for a heavy tilt #----------- # Starboard tack if 0 < smooth_angle <= 180: # Go for 20 degrees if float(self.airmar_data["roll"]) > -12: #change to roll acc. #ballast_angle = 110 ballast_angle = omega_n * 2 elif float(self.airmar_data["roll"]) < -20: #change to roll acc. ballast_angle = 80 #----------- # Port tack elif 180 < smooth_angle < 360: if float(self.airmar_data["roll"]) < 12: ballast_angle = 80 elif float(self.airmar_data["roll"]) > 20: ballast_angle = 110 ballast_json = {"channel": "12", "angle": ballast_angle} self.pwm_control_publisher_.publish(self.make_json_string(ballast_json)) def main(args=None): rclpy.init(args=args) control_system = ControlSystem() while rclpy.ok(): rclpy.spin_once(control_system, timeout_sec=.5) # Now we have new vals from subscribers in: # control_system.serial_rc # control_system.airmar_data # control_system.trim_tab_status # Need to publish new values to both control topics based on new values # control_system.pwm_control_publisher_.publish() <----- i think both of these are notes from last year and have since been implemented # control_system.trim_tab_control_publisher_.publish() <----- i think both of these are notes from last year and have since been implemented #TODO ^^implement if len(control_system.serial_rc) < 2: pass # Don't have rc values elif float(control_system.serial_rc["state2"]) > 600: # in RC if float(control_system.serial_rc["state1"]) < 400: # Manual manual_angle = int((float(control_system.serial_rc["manual"]) / 2000) * 100) + 65 state_msg = Int8() state_msg.data = 5 angle_msg = Int16() angle_msg.data = manual_angle control_system.trim_tab_control_publisher_.publish(state_msg) control_system.trim_tab_angle_publisher_.publish(angle_msg) elif "wind-angle-relative" in control_system.airmar_data: # print(control_system.airmar_data["wind-angle-relative"]) try: control_system.find_trim_tab_state(control_system.airmar_data["apparentWind"]["direction"]) except Exception as e: control_system.get_logger().error(str(e)) else: print("No wind angle values") if float(control_system.serial_rc["state1"]) < 800: ballast_angle = 0 if control_system.serial_rc["ballast"] > 1200: ballast_angle = 110 elif control_system.serial_rc["ballast"] < 800: ballast_angle = 80 ballast_json = {"channel" : "12", "angle" : ballast_angle} control_system.pwm_control_publisher_.publish(control_system.make_json_string(ballast_json)) else: control_system.ballast_algorithm() rudder_angle = (float(control_system.serial_rc["rudder"]) / 2000 * 90) + 25 rudder_json = {"channel": "8", "angle": rudder_angle} control_system.pwm_control_publisher_.publish(control_system.make_json_string(rudder_json)) elif float(control_system.serial_rc["state2"]) < 600: destinations = [(42.277055,-71.799924),(42.276692,-71.799912)] if 'Latitude' in control_system.airmar_data and 'Longitude' in control_system.airmar_data: try: if control_system.p2p_alg is None: # Instantiate new control_system.p2p_alg = p2p.P2P((float(control_system.airmar_data['Latitude']), float(control_system.airmar_data['Longitude'])), destinations[0]) wind = control_system.update_winds(control_system.airmar_data["apparentWind"]["direction"]) action = control_system.p2p_alg.getAction(wind, float(control_system.airmar_data["magnetic-sensor-heading"]), float(control_system.airmar_data["track-degrees-true"])) control_system.get_logger().error(str(control_system.p2p_alg.getdistance())) control_system.get_logger().error(str(action)) if action['status'] == 'DONE': if control_system.p2p_alg.dest == destinations[0]: control_system.p2p_alg = p2p.P2P((control_system.airmar_data['Latitude'], control_system.airmar_data['Longitude']), destinations[1]) else: control_system.p2p_alg = p2p.P2P((control_system.airmar_data['Latitude'], control_system.airmar_data['Longitude']), destinations[0]) else: # We have a non-done action (either trim tab or rudders) if 'tt-state' in action: control_system.trim_tab_control_publisher_.publish(int(action['tt-state'])) elif 'rudder-angle' in action: rudder_json = {"channel": "8", "angle": int(action['rudder-angle'])} control_system.pwm_control_publisher_.publish(control_system.make_json_string(rudder_json)) control_system.ballast_algorithm() except Exception as e: control_system.get_logger().error(str(e)) else: control_system.get_logger().error("No latitude and longitude data") # Destroy the node explicitly # (optional - otherwise it will be done automatically # when the garbage collector destroys the node object) control_system.destroy_node() rclpy.shutdown() if __name__ == '__main__': main()
[ "std_msgs.msg.String", "rclpy.ok", "json.loads", "collections.deque", "json.dumps", "std_msgs.msg.Int8", "sailbot.autonomous.p2p.P2P", "rclpy.spin_once", "std_msgs.msg.Int16", "rclpy.init", "rclpy.shutdown" ]
[((6174, 6195), 'rclpy.init', 'rclpy.init', ([], {'args': 'args'}), '(args=args)\n', (6184, 6195), False, 'import rclpy\n'), ((6249, 6259), 'rclpy.ok', 'rclpy.ok', ([], {}), '()\n', (6257, 6259), False, 'import rclpy\n'), ((11225, 11241), 'rclpy.shutdown', 'rclpy.shutdown', ([], {}), '()\n', (11239, 11241), False, 'import rclpy\n'), ((2058, 2073), 'collections.deque', 'deque', ([], {'maxlen': '(4)'}), '(maxlen=4)\n', (2063, 2073), False, 'from collections import deque\n'), ((2095, 2110), 'collections.deque', 'deque', ([], {'maxlen': '(3)'}), '(maxlen=3)\n', (2100, 2110), False, 'from collections import deque\n'), ((2140, 2155), 'collections.deque', 'deque', ([], {'maxlen': '(4)'}), '(maxlen=4)\n', (2145, 2155), False, 'from collections import deque\n'), ((2327, 2347), 'json.loads', 'json.loads', (['msg.data'], {}), '(msg.data)\n', (2337, 2347), False, 'import json\n'), ((2561, 2581), 'json.loads', 'json.loads', (['msg.data'], {}), '(msg.data)\n', (2571, 2581), False, 'import json\n'), ((3564, 3570), 'std_msgs.msg.Int8', 'Int8', ([], {}), '()\n', (3568, 3570), False, 'from std_msgs.msg import String, Float32, Int8, Int16\n'), ((4172, 4192), 'json.dumps', 'json.dumps', (['json_msg'], {}), '(json_msg)\n', (4182, 4192), False, 'import json\n'), ((4211, 4219), 'std_msgs.msg.String', 'String', ([], {}), '()\n', (4217, 4219), False, 'from std_msgs.msg import String, Float32, Int8, Int16\n'), ((6278, 6326), 'rclpy.spin_once', 'rclpy.spin_once', (['control_system'], {'timeout_sec': '(0.5)'}), '(control_system, timeout_sec=0.5)\n', (6293, 6326), False, 'import rclpy\n'), ((7280, 7286), 'std_msgs.msg.Int8', 'Int8', ([], {}), '()\n', (7284, 7286), False, 'from std_msgs.msg import String, Float32, Int8, Int16\n'), ((7350, 7357), 'std_msgs.msg.Int16', 'Int16', ([], {}), '()\n', (7355, 7357), False, 'from std_msgs.msg import String, Float32, Int8, Int16\n'), ((9965, 10077), 'sailbot.autonomous.p2p.P2P', 'p2p.P2P', (["(control_system.airmar_data['Latitude'], control_system.airmar_data[\n 'Longitude'])", 'destinations[1]'], {}), "((control_system.airmar_data['Latitude'], control_system.airmar_data\n ['Longitude']), destinations[1])\n", (9972, 10077), True, 'import sailbot.autonomous.p2p as p2p\n'), ((10156, 10268), 'sailbot.autonomous.p2p.P2P', 'p2p.P2P', (["(control_system.airmar_data['Latitude'], control_system.airmar_data[\n 'Longitude'])", 'destinations[0]'], {}), "((control_system.airmar_data['Latitude'], control_system.airmar_data\n ['Longitude']), destinations[0])\n", (10163, 10268), True, 'import sailbot.autonomous.p2p as p2p\n')]
from dataclasses import dataclass from app import crud from app.schemas import UserCreate, SlackEventHook from app.settings import REACTION_LIST, DAY_MAX_REACTION # about reaction REMOVED_REACTION = 'reaction_removed' ADDED_REACTION = 'reaction_added' APP_MENTION_REACTION = 'app_mention' # about command CREATE_USER_COMMAND = 'create_user' @dataclass class EventDto: type: str # ex: reaction_added user: str # 리액션을 한 유저(slack_id) item: dict # type, channel, ts reaction: str # 리액션(이모지) item_user: str # 리액션을 받은 유저(slack_id) event_ts: str text: str # app mention text def __init__(self, event_data): self.type = event_data.get('type') self.user = event_data.get('user') self.item = event_data.get('item') self.reaction = event_data.get('reaction') self.item_user = event_data.get('item_user') self.event_ts = event_data.get('event_ts') self.text = event_data.get('text') @dataclass class AddUserCommandDto: name: str slack_id: str avatar_url: str def __init__(self, name: str, slack_id: str, avatar_url: str): self.name = name.strip('name=') self.slack_id = slack_id.strip('slack_id=') self.avatar_url = avatar_url.strip('avatar_url=') class SlackService(object): def check_challenge(self, event: SlackEventHook, db) -> dict: # slack Enable Events if 'challenge' in event: return {"challenge": event['challenge']} # check slack event if "event" in event: event_dto = EventDto(event['event']) if event_dto.type in [ADDED_REACTION, REMOVED_REACTION]: # 다른 사람에게만 이모지 줄 수 있음 if event_dto.item_user != event_dto.user: self.assign_emoji(event_dto, db) elif event_dto.type == APP_MENTION_REACTION: self.manage_app_mention(event_dto, db) return {} def assign_emoji(self, event: EventDto, db): """ reaction process """ if event.reaction not in REACTION_LIST: return if event.type == ADDED_REACTION: user = crud.get_user(db, event.user) # 멤버에게 줄 수 있는 나의 reaction 개수 체크 if user.my_reaction > 0: crud.update_my_reaction(db, user, False) crud.update_added_reaction(db=db, type=event.reaction, item_user=event.item_user, user=event.user, is_increase=True) elif event.type == REMOVED_REACTION: user = crud.get_user(db, event.user) # 멤버에게 전달한 reaction을 삭제하는 경우 (이미 하루 최대의 reaction 개수인 경우 더이상 추가하지 않음) if user.my_reaction < DAY_MAX_REACTION: crud.update_my_reaction(db, user, True) crud.update_added_reaction(db=db, type=event.reaction, item_user=event.item_user, user=event.user, is_increase=False) def manage_app_mention(self, event: EventDto, db): """ 명령어를 분기 처리하는 함수 ex: <@ABCDEFG> --create_user --name=JAY --slack_id=ABCDEFG --avatar_url=https://blablac.com/abcd """ event_command = event.text.split('--') event_command.pop(0) # 첫번째 값은 user slack_id if not event_command: return _type = event_command.pop(0).strip(' ') if _type == CREATE_USER_COMMAND: if len(event_command) == 3: add_user_cmd_dto = AddUserCommandDto(event_command[0], event_command[1], event_command[2]) self.add_user(add_user_cmd_dto, db) def add_user(self, add_user_cmd_dto: AddUserCommandDto, db): """ user 추가 명령어 """ db_user = crud.get_user(db, item_user=add_user_cmd_dto.slack_id) if db_user: return user = UserCreate(username=add_user_cmd_dto.name, slack_id=add_user_cmd_dto.slack_id, using_emoji_count=DAY_MAX_REACTION, get_emoji_count=0, avatar_url=add_user_cmd_dto.avatar_url) crud.create_user(db=db, user=user)
[ "app.schemas.UserCreate", "app.crud.update_added_reaction", "app.crud.create_user", "app.crud.update_my_reaction", "app.crud.get_user" ]
[((3752, 3806), 'app.crud.get_user', 'crud.get_user', (['db'], {'item_user': 'add_user_cmd_dto.slack_id'}), '(db, item_user=add_user_cmd_dto.slack_id)\n', (3765, 3806), False, 'from app import crud\n'), ((3862, 4044), 'app.schemas.UserCreate', 'UserCreate', ([], {'username': 'add_user_cmd_dto.name', 'slack_id': 'add_user_cmd_dto.slack_id', 'using_emoji_count': 'DAY_MAX_REACTION', 'get_emoji_count': '(0)', 'avatar_url': 'add_user_cmd_dto.avatar_url'}), '(username=add_user_cmd_dto.name, slack_id=add_user_cmd_dto.\n slack_id, using_emoji_count=DAY_MAX_REACTION, get_emoji_count=0,\n avatar_url=add_user_cmd_dto.avatar_url)\n', (3872, 4044), False, 'from app.schemas import UserCreate, SlackEventHook\n'), ((4096, 4130), 'app.crud.create_user', 'crud.create_user', ([], {'db': 'db', 'user': 'user'}), '(db=db, user=user)\n', (4112, 4130), False, 'from app import crud\n'), ((2171, 2200), 'app.crud.get_user', 'crud.get_user', (['db', 'event.user'], {}), '(db, event.user)\n', (2184, 2200), False, 'from app import crud\n'), ((2298, 2338), 'app.crud.update_my_reaction', 'crud.update_my_reaction', (['db', 'user', '(False)'], {}), '(db, user, False)\n', (2321, 2338), False, 'from app import crud\n'), ((2355, 2476), 'app.crud.update_added_reaction', 'crud.update_added_reaction', ([], {'db': 'db', 'type': 'event.reaction', 'item_user': 'event.item_user', 'user': 'event.user', 'is_increase': '(True)'}), '(db=db, type=event.reaction, item_user=event.\n item_user, user=event.user, is_increase=True)\n', (2381, 2476), False, 'from app import crud\n'), ((2580, 2609), 'app.crud.get_user', 'crud.get_user', (['db', 'event.user'], {}), '(db, event.user)\n', (2593, 2609), False, 'from app import crud\n'), ((2759, 2798), 'app.crud.update_my_reaction', 'crud.update_my_reaction', (['db', 'user', '(True)'], {}), '(db, user, True)\n', (2782, 2798), False, 'from app import crud\n'), ((2815, 2937), 'app.crud.update_added_reaction', 'crud.update_added_reaction', ([], {'db': 'db', 'type': 'event.reaction', 'item_user': 'event.item_user', 'user': 'event.user', 'is_increase': '(False)'}), '(db=db, type=event.reaction, item_user=event.\n item_user, user=event.user, is_increase=False)\n', (2841, 2937), False, 'from app import crud\n')]
""" Creates files for end-to-end tests python util/build_tests.py """ # stdlib import json from dataclasses import asdict # module import avwx def make_metar_test(station: str) -> dict: """ Builds METAR test file for station """ m = avwx.Metar(station) m.update() # Clear timestamp due to parse_date limitations m.data.time = None return { "data": asdict(m.data), "translations": asdict(m.translations), "summary": m.summary, "speech": m.speech, "station_info": asdict(m.station_info), } def make_taf_test(station: str, report: str = None) -> dict: """ Builds TAF test file for station """ t = avwx.Taf(station) t.update(report) data = asdict(t.data) # Clear timestamp due to parse_date limitations for key in ("time", "start_time", "end_time"): data[key] = None for i in range(len(data["forecast"])): for key in ("start_time", "end_time"): data["forecast"][i][key] = None return { "data": data, "translations": asdict(t.translations), "summary": t.summary, "speech": t.speech, "station_info": asdict(t.station_info), } def make_pirep_test(station: str) -> [dict]: """ Builds PIREP test file for station """ p = avwx.Pireps(station) p.update() ret = [] if not p.data: return for report in p.data: # Clear timestamp due to parse_date limitations report.time = None ret.append({"data": asdict(report)}) return {"reports": ret, "station_info": asdict(p.station_info)} if __name__ == "__main__": from pathlib import Path for target in ("metar", "taf", "pirep"): for station in ("KJFK", "KMCO", "PHNL", "EGLL"): data = locals()[f"make_{target}_test"](station) if data: path = Path("tests", target, station + ".json") json.dump(data, path.open("w"), indent=4, sort_keys=True)
[ "dataclasses.asdict", "pathlib.Path", "avwx.Metar", "avwx.Taf", "avwx.Pireps" ]
[((254, 273), 'avwx.Metar', 'avwx.Metar', (['station'], {}), '(station)\n', (264, 273), False, 'import avwx\n'), ((693, 710), 'avwx.Taf', 'avwx.Taf', (['station'], {}), '(station)\n', (701, 710), False, 'import avwx\n'), ((743, 757), 'dataclasses.asdict', 'asdict', (['t.data'], {}), '(t.data)\n', (749, 757), False, 'from dataclasses import asdict\n'), ((1325, 1345), 'avwx.Pireps', 'avwx.Pireps', (['station'], {}), '(station)\n', (1336, 1345), False, 'import avwx\n'), ((393, 407), 'dataclasses.asdict', 'asdict', (['m.data'], {}), '(m.data)\n', (399, 407), False, 'from dataclasses import asdict\n'), ((433, 455), 'dataclasses.asdict', 'asdict', (['m.translations'], {}), '(m.translations)\n', (439, 455), False, 'from dataclasses import asdict\n'), ((539, 561), 'dataclasses.asdict', 'asdict', (['m.station_info'], {}), '(m.station_info)\n', (545, 561), False, 'from dataclasses import asdict\n'), ((1079, 1101), 'dataclasses.asdict', 'asdict', (['t.translations'], {}), '(t.translations)\n', (1085, 1101), False, 'from dataclasses import asdict\n'), ((1185, 1207), 'dataclasses.asdict', 'asdict', (['t.station_info'], {}), '(t.station_info)\n', (1191, 1207), False, 'from dataclasses import asdict\n'), ((1606, 1628), 'dataclasses.asdict', 'asdict', (['p.station_info'], {}), '(p.station_info)\n', (1612, 1628), False, 'from dataclasses import asdict\n'), ((1545, 1559), 'dataclasses.asdict', 'asdict', (['report'], {}), '(report)\n', (1551, 1559), False, 'from dataclasses import asdict\n'), ((1895, 1935), 'pathlib.Path', 'Path', (['"""tests"""', 'target', "(station + '.json')"], {}), "('tests', target, station + '.json')\n", (1899, 1935), False, 'from pathlib import Path\n')]
from micropython import const ADXL345_ADDRESS = const(0x53) # I2C address of adxl345 ADXL345_DEVICE_ID = const(0xe5) # ADXL345_DEVID = const(0x00) # Device ID ADXL345_THESH_TAP = const(0x1d) # Tap threshold ADXL345_OFSX = const(0x1e) # X-axis offset ADXL345_OFSY = const(0x1f) # y-axis offset ADXL345_OFSZ = const(0x20) # z-axis offset ADXL345_DUR = const(0x21) # Tap duration ADXL345_LATENT = const(0x22) # Tap latency ADXL345_WINDOW = const(0x23) # Tap window ADXL345_THRESH_ACT = const(0x24) # Activity threshold ADXL345_THRESH_INACT = const(0x25) # Inactivity threshold ADXL345_TIME_INACT = const(0x26) # Inactivity time ADXL345_ACT_INACT_CTL = const(0x27) # Axis enable for activity and inactivity detection ADXL345_THRESH_FF = const(0x28) # Free-fall threshold ADXL345_TIME_FF = const(0x29) # Free-fall time ADXL345_TAP_AXIS = const(0x2a) # Axis control for single/touble tap ADXL345_ACT_TAP_STATUS = const(0x2b) # Source of single/touble tap ADXL345_BW_RATE = const(0x2c) # Data rate and power mode control ADXL345_POWER_CTL = const(0x2d) # Power-saving features control ADXL345_INT_ENABLE = const(0x2e) # Interrupt enable control ADXL345_INT_MAP = const(0x2f) # Interrupt mapping control ADXL345_INT_SOURCE = const(0x30) # Source of Interrupts ADXL345_DATA_FORMAT = const(0x31) # Data format control ADXL345_DATAAX0 = const(0x32) # X-Axis Data 0 ADXL345_DATAAX1 = const(0x33) # X-Axis Data 1 ADXL345_DATAAY0 = const(0x34) # Y-Axis Data 0 ADXL345_DATAAY1 = const(0x35) # Y-Axis Data 1 ADXL345_DATAAZ0 = const(0x36) # Z-Axis Data 0 ADXL345_DATAAZ1 = const(0x37) # Z-Axis Data 1 ADXL345_FIFO_CTL = const(0x38) # FIFO control ADXL345_FIFO_STATUS = const(0x39) # FIFO status # Bit definitions # ACT_INACT_CTL INACT_Z_EN = const(0) INACT_Y_EN = const(1) INACT_X_EN = const(2) INACT_AC_DC = const(3) ACT_Z_EN = const(4) ACT_Y_EN = const(5) ACT_X_EN = const(6) ACT_AC_DC = const(7) # TAP AXES TAP_X_EN = const(0) TAP_Y_EN = const(1) TAP_Z_EN = const(2) SUPPRESS = const(3) # ACT_TAP_STATUS TAP_Z_SOURCE = const(0) TAP_Y_SOURCE = const(1) TAP_X_SOURCE = const(2) ASLEEP = const(3) ACT_Z_SOURCE = const(4) ACT_Y_SOURCE = const(5) ACT_X_SOURCE = const(6) # BW_RATE RATE = const(3) RATE_SIZE = const(4) LOW_POWER = const(4) LOW_POWER_SIZE = const(2) # POWER_CTL WAKEUP = const(1) WAKEUP_SIZE = const(2) SLEEP = const(2) MEASURE = const(3) AUTO_SLEEP = const(5) AUTO_SLEEP_SIZE = const(2) LINK = const(5) # INT_ENABLE OVERRUN = const(0) WATERMARK = const(1) FREE_FALL = const(2) INACTIVITY = const(3) ACTIVITY = const(4) DOUBLE_TAP = const(5) SINGLE_TAP = const(6) DATA_READY = const(7) # DATA_FORMAT RANGE = const(1) RANGE_SIZE = const(2) JUSTIFY = const(2) FULL_RES = const(3) FULL_RES_SIZE = const(2) INT_INVERT = const(5) SPI = const(6) SELF_TEST = const(7) # FIFO_CTL SAMPLES = const(4) SAMPLES_SIZE = const(5) TRIGGER = const(5) FIFO_TYPE = const(7) FIFO_TYPE_SIZE = const(2) MODE_BYPASS = const(0) MODE_FIFO = const(1) MODE_STREAM = const(2) MODE_TRIGGER = const(3) # FIFO_STATUS FIFO_ENTRIES = const(5) FIFO_ENTRIES_SIZE = const(6) FIFO_TRIG = const(7) # Data rates RATE_3200 = const(0xf) RATE_1600 = const(0xe) RATE_800 = const(0xd) RATE_400 = const(0xc) RATE_200 = const(0xb) RATE_100 = const(0xa) RATE_50 = const(0x9) RATE_25 = const(0x8) RATE_12_5 = const(0x7) RATE_6_25 = const(0x6) RATE_3_13 = const(0x5) RATE_0_78 = const(0x4) RATE_0_39 = const(0x3) RATE_0_20 = const(0x1) RATE_0_10 = const(0x0) # Acceleration full range ACCEL_2G = const(0) ACCEL_4G = const(1) ACCEL_8G = const(2) ACCEL_16G = const(3) # FIFO BYPASS = const(0) FIFO_MODE = const(1) STREAM_MODE = const(2) TRIGGER_MODE = const(3) # POWER_CTL Wakeup frequency WAKE_UP_8_HZ = const(0) WAKE_UP_4_HZ = const(1) WAKE_UP_2_HZ = const(2) WAKE_UP_1_HZ = const(3)
[ "micropython.const" ]
[((62, 71), 'micropython.const', 'const', (['(83)'], {}), '(83)\n', (67, 71), False, 'from micropython import const\n'), ((134, 144), 'micropython.const', 'const', (['(229)'], {}), '(229)\n', (139, 144), False, 'from micropython import const\n'), ((185, 193), 'micropython.const', 'const', (['(0)'], {}), '(0)\n', (190, 193), False, 'from micropython import const\n'), ((244, 253), 'micropython.const', 'const', (['(29)'], {}), '(29)\n', (249, 253), False, 'from micropython import const\n'), ((307, 316), 'micropython.const', 'const', (['(30)'], {}), '(30)\n', (312, 316), False, 'from micropython import const\n'), ((370, 379), 'micropython.const', 'const', (['(31)'], {}), '(31)\n', (375, 379), False, 'from micropython import const\n'), ((433, 442), 'micropython.const', 'const', (['(32)'], {}), '(32)\n', (438, 442), False, 'from micropython import const\n'), ((496, 505), 'micropython.const', 'const', (['(33)'], {}), '(33)\n', (501, 505), False, 'from micropython import const\n'), ((558, 567), 'micropython.const', 'const', (['(34)'], {}), '(34)\n', (563, 567), False, 'from micropython import const\n'), ((619, 628), 'micropython.const', 'const', (['(35)'], {}), '(35)\n', (624, 628), False, 'from micropython import const\n'), ((679, 688), 'micropython.const', 'const', (['(36)'], {}), '(36)\n', (684, 688), False, 'from micropython import const\n'), ((747, 756), 'micropython.const', 'const', (['(37)'], {}), '(37)\n', (752, 756), False, 'from micropython import const\n'), ((817, 826), 'micropython.const', 'const', (['(38)'], {}), '(38)\n', (822, 826), False, 'from micropython import const\n'), ((882, 891), 'micropython.const', 'const', (['(39)'], {}), '(39)\n', (887, 891), False, 'from micropython import const\n'), ((981, 990), 'micropython.const', 'const', (['(40)'], {}), '(40)\n', (986, 990), False, 'from micropython import const\n'), ((1050, 1059), 'micropython.const', 'const', (['(41)'], {}), '(41)\n', (1055, 1059), False, 'from micropython import const\n'), ((1114, 1123), 'micropython.const', 'const', (['(42)'], {}), '(42)\n', (1119, 1123), False, 'from micropython import const\n'), ((1198, 1207), 'micropython.const', 'const', (['(43)'], {}), '(43)\n', (1203, 1207), False, 'from micropython import const\n'), ((1275, 1284), 'micropython.const', 'const', (['(44)'], {}), '(44)\n', (1280, 1284), False, 'from micropython import const\n'), ((1357, 1366), 'micropython.const', 'const', (['(45)'], {}), '(45)\n', (1362, 1366), False, 'from micropython import const\n'), ((1436, 1445), 'micropython.const', 'const', (['(46)'], {}), '(46)\n', (1441, 1445), False, 'from micropython import const\n'), ((1510, 1519), 'micropython.const', 'const', (['(47)'], {}), '(47)\n', (1515, 1519), False, 'from micropython import const\n'), ((1585, 1594), 'micropython.const', 'const', (['(48)'], {}), '(48)\n', (1590, 1594), False, 'from micropython import const\n'), ((1655, 1664), 'micropython.const', 'const', (['(49)'], {}), '(49)\n', (1660, 1664), False, 'from micropython import const\n'), ((1724, 1733), 'micropython.const', 'const', (['(50)'], {}), '(50)\n', (1729, 1733), False, 'from micropython import const\n'), ((1787, 1796), 'micropython.const', 'const', (['(51)'], {}), '(51)\n', (1792, 1796), False, 'from micropython import const\n'), ((1850, 1859), 'micropython.const', 'const', (['(52)'], {}), '(52)\n', (1855, 1859), False, 'from micropython import const\n'), ((1913, 1922), 'micropython.const', 'const', (['(53)'], {}), '(53)\n', (1918, 1922), False, 'from micropython import const\n'), ((1976, 1985), 'micropython.const', 'const', (['(54)'], {}), '(54)\n', (1981, 1985), False, 'from micropython import const\n'), ((2039, 2048), 'micropython.const', 'const', (['(55)'], {}), '(55)\n', (2044, 2048), False, 'from micropython import const\n'), ((2102, 2111), 'micropython.const', 'const', (['(56)'], {}), '(56)\n', (2107, 2111), False, 'from micropython import const\n'), ((2164, 2173), 'micropython.const', 'const', (['(57)'], {}), '(57)\n', (2169, 2173), False, 'from micropython import const\n'), ((2261, 2269), 'micropython.const', 'const', (['(0)'], {}), '(0)\n', (2266, 2269), False, 'from micropython import const\n'), ((2302, 2310), 'micropython.const', 'const', (['(1)'], {}), '(1)\n', (2307, 2310), False, 'from micropython import const\n'), ((2343, 2351), 'micropython.const', 'const', (['(2)'], {}), '(2)\n', (2348, 2351), False, 'from micropython import const\n'), ((2384, 2392), 'micropython.const', 'const', (['(3)'], {}), '(3)\n', (2389, 2392), False, 'from micropython import const\n'), ((2425, 2433), 'micropython.const', 'const', (['(4)'], {}), '(4)\n', (2430, 2433), False, 'from micropython import const\n'), ((2466, 2474), 'micropython.const', 'const', (['(5)'], {}), '(5)\n', (2471, 2474), False, 'from micropython import const\n'), ((2507, 2515), 'micropython.const', 'const', (['(6)'], {}), '(6)\n', (2512, 2515), False, 'from micropython import const\n'), ((2548, 2556), 'micropython.const', 'const', (['(7)'], {}), '(7)\n', (2553, 2556), False, 'from micropython import const\n'), ((2601, 2609), 'micropython.const', 'const', (['(0)'], {}), '(0)\n', (2606, 2609), False, 'from micropython import const\n'), ((2642, 2650), 'micropython.const', 'const', (['(1)'], {}), '(1)\n', (2647, 2650), False, 'from micropython import const\n'), ((2683, 2691), 'micropython.const', 'const', (['(2)'], {}), '(2)\n', (2688, 2691), False, 'from micropython import const\n'), ((2724, 2732), 'micropython.const', 'const', (['(3)'], {}), '(3)\n', (2729, 2732), False, 'from micropython import const\n'), ((2784, 2792), 'micropython.const', 'const', (['(0)'], {}), '(0)\n', (2789, 2792), False, 'from micropython import const\n'), ((2825, 2833), 'micropython.const', 'const', (['(1)'], {}), '(1)\n', (2830, 2833), False, 'from micropython import const\n'), ((2866, 2874), 'micropython.const', 'const', (['(2)'], {}), '(2)\n', (2871, 2874), False, 'from micropython import const\n'), ((2907, 2915), 'micropython.const', 'const', (['(3)'], {}), '(3)\n', (2912, 2915), False, 'from micropython import const\n'), ((2948, 2956), 'micropython.const', 'const', (['(4)'], {}), '(4)\n', (2953, 2956), False, 'from micropython import const\n'), ((2989, 2997), 'micropython.const', 'const', (['(5)'], {}), '(5)\n', (2994, 2997), False, 'from micropython import const\n'), ((3030, 3038), 'micropython.const', 'const', (['(6)'], {}), '(6)\n', (3035, 3038), False, 'from micropython import const\n'), ((3082, 3090), 'micropython.const', 'const', (['(3)'], {}), '(3)\n', (3087, 3090), False, 'from micropython import const\n'), ((3123, 3131), 'micropython.const', 'const', (['(4)'], {}), '(4)\n', (3128, 3131), False, 'from micropython import const\n'), ((3164, 3172), 'micropython.const', 'const', (['(4)'], {}), '(4)\n', (3169, 3172), False, 'from micropython import const\n'), ((3205, 3213), 'micropython.const', 'const', (['(2)'], {}), '(2)\n', (3210, 3213), False, 'from micropython import const\n'), ((3259, 3267), 'micropython.const', 'const', (['(1)'], {}), '(1)\n', (3264, 3267), False, 'from micropython import const\n'), ((3300, 3308), 'micropython.const', 'const', (['(2)'], {}), '(2)\n', (3305, 3308), False, 'from micropython import const\n'), ((3341, 3349), 'micropython.const', 'const', (['(2)'], {}), '(2)\n', (3346, 3349), False, 'from micropython import const\n'), ((3382, 3390), 'micropython.const', 'const', (['(3)'], {}), '(3)\n', (3387, 3390), False, 'from micropython import const\n'), ((3423, 3431), 'micropython.const', 'const', (['(5)'], {}), '(5)\n', (3428, 3431), False, 'from micropython import const\n'), ((3464, 3472), 'micropython.const', 'const', (['(2)'], {}), '(2)\n', (3469, 3472), False, 'from micropython import const\n'), ((3505, 3513), 'micropython.const', 'const', (['(5)'], {}), '(5)\n', (3510, 3513), False, 'from micropython import const\n'), ((3560, 3568), 'micropython.const', 'const', (['(0)'], {}), '(0)\n', (3565, 3568), False, 'from micropython import const\n'), ((3601, 3609), 'micropython.const', 'const', (['(1)'], {}), '(1)\n', (3606, 3609), False, 'from micropython import const\n'), ((3642, 3650), 'micropython.const', 'const', (['(2)'], {}), '(2)\n', (3647, 3650), False, 'from micropython import const\n'), ((3683, 3691), 'micropython.const', 'const', (['(3)'], {}), '(3)\n', (3688, 3691), False, 'from micropython import const\n'), ((3724, 3732), 'micropython.const', 'const', (['(4)'], {}), '(4)\n', (3729, 3732), False, 'from micropython import const\n'), ((3765, 3773), 'micropython.const', 'const', (['(5)'], {}), '(5)\n', (3770, 3773), False, 'from micropython import const\n'), ((3806, 3814), 'micropython.const', 'const', (['(6)'], {}), '(6)\n', (3811, 3814), False, 'from micropython import const\n'), ((3847, 3855), 'micropython.const', 'const', (['(7)'], {}), '(7)\n', (3852, 3855), False, 'from micropython import const\n'), ((3903, 3911), 'micropython.const', 'const', (['(1)'], {}), '(1)\n', (3908, 3911), False, 'from micropython import const\n'), ((3944, 3952), 'micropython.const', 'const', (['(2)'], {}), '(2)\n', (3949, 3952), False, 'from micropython import const\n'), ((3985, 3993), 'micropython.const', 'const', (['(2)'], {}), '(2)\n', (3990, 3993), False, 'from micropython import const\n'), ((4026, 4034), 'micropython.const', 'const', (['(3)'], {}), '(3)\n', (4031, 4034), False, 'from micropython import const\n'), ((4067, 4075), 'micropython.const', 'const', (['(2)'], {}), '(2)\n', (4072, 4075), False, 'from micropython import const\n'), ((4108, 4116), 'micropython.const', 'const', (['(5)'], {}), '(5)\n', (4113, 4116), False, 'from micropython import const\n'), ((4149, 4157), 'micropython.const', 'const', (['(6)'], {}), '(6)\n', (4154, 4157), False, 'from micropython import const\n'), ((4190, 4198), 'micropython.const', 'const', (['(7)'], {}), '(7)\n', (4195, 4198), False, 'from micropython import const\n'), ((4243, 4251), 'micropython.const', 'const', (['(4)'], {}), '(4)\n', (4248, 4251), False, 'from micropython import const\n'), ((4284, 4292), 'micropython.const', 'const', (['(5)'], {}), '(5)\n', (4289, 4292), False, 'from micropython import const\n'), ((4325, 4333), 'micropython.const', 'const', (['(5)'], {}), '(5)\n', (4330, 4333), False, 'from micropython import const\n'), ((4366, 4374), 'micropython.const', 'const', (['(7)'], {}), '(7)\n', (4371, 4374), False, 'from micropython import const\n'), ((4407, 4415), 'micropython.const', 'const', (['(2)'], {}), '(2)\n', (4412, 4415), False, 'from micropython import const\n'), ((4449, 4457), 'micropython.const', 'const', (['(0)'], {}), '(0)\n', (4454, 4457), False, 'from micropython import const\n'), ((4490, 4498), 'micropython.const', 'const', (['(1)'], {}), '(1)\n', (4495, 4498), False, 'from micropython import const\n'), ((4531, 4539), 'micropython.const', 'const', (['(2)'], {}), '(2)\n', (4536, 4539), False, 'from micropython import const\n'), ((4572, 4580), 'micropython.const', 'const', (['(3)'], {}), '(3)\n', (4577, 4580), False, 'from micropython import const\n'), ((4628, 4636), 'micropython.const', 'const', (['(5)'], {}), '(5)\n', (4633, 4636), False, 'from micropython import const\n'), ((4669, 4677), 'micropython.const', 'const', (['(6)'], {}), '(6)\n', (4674, 4677), False, 'from micropython import const\n'), ((4710, 4718), 'micropython.const', 'const', (['(7)'], {}), '(7)\n', (4715, 4718), False, 'from micropython import const\n'), ((4765, 4774), 'micropython.const', 'const', (['(15)'], {}), '(15)\n', (4770, 4774), False, 'from micropython import const\n'), ((4808, 4817), 'micropython.const', 'const', (['(14)'], {}), '(14)\n', (4813, 4817), False, 'from micropython import const\n'), ((4851, 4860), 'micropython.const', 'const', (['(13)'], {}), '(13)\n', (4856, 4860), False, 'from micropython import const\n'), ((4894, 4903), 'micropython.const', 'const', (['(12)'], {}), '(12)\n', (4899, 4903), False, 'from micropython import const\n'), ((4937, 4946), 'micropython.const', 'const', (['(11)'], {}), '(11)\n', (4942, 4946), False, 'from micropython import const\n'), ((4980, 4989), 'micropython.const', 'const', (['(10)'], {}), '(10)\n', (4985, 4989), False, 'from micropython import const\n'), ((5023, 5031), 'micropython.const', 'const', (['(9)'], {}), '(9)\n', (5028, 5031), False, 'from micropython import const\n'), ((5066, 5074), 'micropython.const', 'const', (['(8)'], {}), '(8)\n', (5071, 5074), False, 'from micropython import const\n'), ((5109, 5117), 'micropython.const', 'const', (['(7)'], {}), '(7)\n', (5114, 5117), False, 'from micropython import const\n'), ((5152, 5160), 'micropython.const', 'const', (['(6)'], {}), '(6)\n', (5157, 5160), False, 'from micropython import const\n'), ((5195, 5203), 'micropython.const', 'const', (['(5)'], {}), '(5)\n', (5200, 5203), False, 'from micropython import const\n'), ((5238, 5246), 'micropython.const', 'const', (['(4)'], {}), '(4)\n', (5243, 5246), False, 'from micropython import const\n'), ((5281, 5289), 'micropython.const', 'const', (['(3)'], {}), '(3)\n', (5286, 5289), False, 'from micropython import const\n'), ((5324, 5332), 'micropython.const', 'const', (['(1)'], {}), '(1)\n', (5329, 5332), False, 'from micropython import const\n'), ((5367, 5375), 'micropython.const', 'const', (['(0)'], {}), '(0)\n', (5372, 5375), False, 'from micropython import const\n'), ((5437, 5445), 'micropython.const', 'const', (['(0)'], {}), '(0)\n', (5442, 5445), False, 'from micropython import const\n'), ((5478, 5486), 'micropython.const', 'const', (['(1)'], {}), '(1)\n', (5483, 5486), False, 'from micropython import const\n'), ((5519, 5527), 'micropython.const', 'const', (['(2)'], {}), '(2)\n', (5524, 5527), False, 'from micropython import const\n'), ((5560, 5568), 'micropython.const', 'const', (['(3)'], {}), '(3)\n', (5565, 5568), False, 'from micropython import const\n'), ((5609, 5617), 'micropython.const', 'const', (['(0)'], {}), '(0)\n', (5614, 5617), False, 'from micropython import const\n'), ((5650, 5658), 'micropython.const', 'const', (['(1)'], {}), '(1)\n', (5655, 5658), False, 'from micropython import const\n'), ((5691, 5699), 'micropython.const', 'const', (['(2)'], {}), '(2)\n', (5696, 5699), False, 'from micropython import const\n'), ((5732, 5740), 'micropython.const', 'const', (['(3)'], {}), '(3)\n', (5737, 5740), False, 'from micropython import const\n'), ((5803, 5811), 'micropython.const', 'const', (['(0)'], {}), '(0)\n', (5808, 5811), False, 'from micropython import const\n'), ((5844, 5852), 'micropython.const', 'const', (['(1)'], {}), '(1)\n', (5849, 5852), False, 'from micropython import const\n'), ((5885, 5893), 'micropython.const', 'const', (['(2)'], {}), '(2)\n', (5890, 5893), False, 'from micropython import const\n'), ((5926, 5934), 'micropython.const', 'const', (['(3)'], {}), '(3)\n', (5931, 5934), False, 'from micropython import const\n')]
import random global_mutation = 0.002 encodings = {'0': '00000', '1': '00001', '2': '00010', '3': '00011', '4': '00100', '5': '00101', 'A': '00110', 'B': '00111', 'C': '01000', 'D': '01001', 'E': '01010', 'F': '01011', 'G': '01100', 'H': '01101', 'I': '01110', 'J': '01111', 'K': '10000', 'L': '10001', 'M': '10010', 'N': '10011', 'O': '10100', 'P': '10101', 'Q': '10110', 'R': '10111', 'S': '11000', 'T': '11001', 'U': '11010', 'V': '11011', 'W': '11100', 'X': '11101', 'Y': '11110', 'Z': '11111'} decodings = dict([(value, key) for key, value in encodings.items()]) def untangle(gene): sequence = '' for char in gene: sequence += encodings[char] return sequence def mutate(sequence): sequence = list(sequence) if global_mutation > random.random(): i = random.randrange(0, len(sequence)) sequence[i] = '1' if sequence[i] == '0' else '0' return ''.join(sequence) def tangle(sequence): gene = [] [gene.append(decodings[sequence[i:i+5]]) for i in range(0, len(sequence), 5)] return ''.join(gene) def bin_to_float(string): num1 = sum([int(string[1 + i]) * 2 ** (10 - i) for i in range(11)]) num2 = sum([int(string[12 + i]) * 2 ** -(1 + i) for i in range(0,11)]) return num1 + num2 if string[0] == '0' else -(num1 + num2) def bin_to_rgb_illum(string): #8 bit each for r,g,b. 1 bit for illumination(yes/no). #ex- 'ZZZZZ' -> (255,255,255,True) r = sum([int(string[i]) * 2 ** (7 - i) for i in range(8)]) g = sum([int(string[8 + i]) * 2 ** (7 - i) for i in range(8)]) b = sum([int(string[16 + i]) * 2 ** (7 - i) for i in range(8)]) i = string[-1] == '1' return (r,g,b,i) def split_seq(utg): source = utg[0] # input or hidden source_id = utg[1:8] # address of either input or hidden sink_type = utg[8] # sink/aka the output. output neuron or hidden neuron sink_id = utg[9:16] # id of output neuron or output hidden neuron recurrent = utg[16] # if the neuron has memory weight = utg[17:]# value of weight's first bit represents the sign(0:+ve,1:-ve) # weight = [sign] [11 bits] [.] [11 bits]. ex- 1 11111111111 . 11111111111 -> -2047.99951171875 ##lr = utg[40:] sequence of 5 bits return source, source_id, sink_type, sink_id, recurrent, weight def main(): gene = 'AX0W1ZXX' #<- how gene is stored(in memory) and displayed(to user) color = '0X0A0' #print(gene, untangle(gene)) #print(color, untangle(color)) for i in range(5000): utg = untangle(gene) #<- gene is untangled to a binary sequence to be used by the cell utg = mutate(utg) #<- during reproduction, there is a small chance(global_mutation factor) that a bit gets flipped in the untangled binary gene sequence. gene = tangle(utg) #<- After reproduction, the gene is tangled and stored in memory. utg2 = untangle(color) utg2 = mutate(utg2) color = tangle(utg2) if((i+1) % 50 == 0): #print(gene, untangle(gene)) source, source_id, sink_type, sink_id, recurrent, weight = split_seq(utg) #print(source, source_id, sink_type, sink_id, recurrent, weight) print('weight:', bin_to_float(weight)) #print(color,untangle(color)) print('color:',bin_to_rgb_illum(untangle(color))) #%% if __name__ == '__main__': main() # Neuron gene -> 40 bits # Color gene -> 24 bits (r,g,b) + 1 unused bit # Vital gene (Max dv, Max Energy, Current Energy, Food Type(Self/Generator(Photo or Thermal),Predator,Scavenger,Paracitic,Combination), Preferred food color(only if cell is predator or both), # reproduction style(uni,2 parent, both), ...)
[ "random.random" ]
[((871, 886), 'random.random', 'random.random', ([], {}), '()\n', (884, 886), False, 'import random\n')]
# ============================================================================ # FILE: func.py # AUTHOR: <NAME> <<EMAIL>> # License: MIT license # ============================================================================ # pylint: disable=E0401,C0411 import os import subprocess from denite import util from .base import Base def _find_root(path): while True: if path == '/' or os.path.ismount(path): return None p = os.path.join(path, 'package.json') if os.access(p, os.R_OK): return path path = os.path.dirname(path) def run_command(commands, cwd, stdin=None): try: p = subprocess.run(commands, cwd=cwd, input=stdin, encoding="utf8", stdout=subprocess.PIPE, stderr=subprocess.STDOUT) except subprocess.CalledProcessError: return [] return p.stdout.split('\n') class Source(Base): def __init__(self, vim): super().__init__(vim) self.name = 'func' self.kind = 'file' def on_init(self, context): cwd = os.path.normpath(self.vim.call('getcwd')) context['__root'] = _find_root(cwd) def highlight(self): self.vim.command('highlight default link deniteSource_funcFile Comment') self.vim.command('highlight default link deniteSource_funcLinenr LineNR') def define_syntax(self): self.vim.command(r'syntax match deniteSource_funcHeader /^.*$/ ' r'containedin=' + self.syntax_name) self.vim.command(r'syntax match deniteSource_funcFile /[^:]*: / ' r'contained containedin=deniteSource_funcHeader') self.vim.command(r'syntax match deniteSource_funcLinenr /\s*\d\+: / ' r'contained containedin=deniteSource_funcHeader') self.vim.command(r'syntax match deniteSource_funcSeparator /:/ conceal ' r'contained containedin=deniteSource_funcHeader') def gather_candidates(self, context): if not context['__root']: util.error(self.vim, 'package.json not found') return [] root = context['__root'] args = dict(enumerate(context['args'])) t = args.get(0, '') cmds = [self.vim.eval('g:npm_parsefunc_command')] curpath = os.path.normpath(self.vim.call('expand', '%:p')) relpath = os.path.relpath(curpath, root) if t == 't': cmds += ['-m', 'this'] elif t == 'm': name = args.get(1, '') if name: cmds += ['-m', name] else: cmds += ['-a'] elif t == 'r': cmds += ['-r', relpath] elif t == 'e': cmds += ['-m', relpath] else: cmds += [relpath] candidates = [] if not len(t): stdin = "\n".join(self.vim.call('getline', 1, '$')) lines = run_command(cmds, root, stdin) else: lines = run_command(cmds, root) for line in lines: if not line: continue parts = line.split(':') filepath = relpath if parts[0] == 'stdin' else parts[0] if parts[0] == 'stdin': actionpath = curpath abbr = os.path.basename(curpath) elif os.path.isabs(parts[0]): actionpath = parts[0] abbr = os.path.relpath(filepath, os.path.join(root, 'node_modules')) else: actionpath = os.path.join(root, parts[0]) abbr = os.path.relpath(actionpath, root) candidates.append({ 'word': parts[2], 'abbr': '%s: %s: %s' % (abbr, parts[1], parts[2]), 'action__path': actionpath, 'action__line': parts[1], }) return candidates
[ "os.path.isabs", "os.path.ismount", "denite.util.error", "os.access", "os.path.join", "subprocess.run", "os.path.dirname", "os.path.basename", "os.path.relpath" ]
[((453, 487), 'os.path.join', 'os.path.join', (['path', '"""package.json"""'], {}), "(path, 'package.json')\n", (465, 487), False, 'import os\n'), ((499, 520), 'os.access', 'os.access', (['p', 'os.R_OK'], {}), '(p, os.R_OK)\n', (508, 520), False, 'import os\n'), ((561, 582), 'os.path.dirname', 'os.path.dirname', (['path'], {}), '(path)\n', (576, 582), False, 'import os\n'), ((649, 767), 'subprocess.run', 'subprocess.run', (['commands'], {'cwd': 'cwd', 'input': 'stdin', 'encoding': '"""utf8"""', 'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.STDOUT'}), "(commands, cwd=cwd, input=stdin, encoding='utf8', stdout=\n subprocess.PIPE, stderr=subprocess.STDOUT)\n", (663, 767), False, 'import subprocess\n'), ((2480, 2510), 'os.path.relpath', 'os.path.relpath', (['curpath', 'root'], {}), '(curpath, root)\n', (2495, 2510), False, 'import os\n'), ((394, 415), 'os.path.ismount', 'os.path.ismount', (['path'], {}), '(path)\n', (409, 415), False, 'import os\n'), ((2159, 2205), 'denite.util.error', 'util.error', (['self.vim', '"""package.json not found"""'], {}), "(self.vim, 'package.json not found')\n", (2169, 2205), False, 'from denite import util\n'), ((3392, 3417), 'os.path.basename', 'os.path.basename', (['curpath'], {}), '(curpath)\n', (3408, 3417), False, 'import os\n'), ((3435, 3458), 'os.path.isabs', 'os.path.isabs', (['parts[0]'], {}), '(parts[0])\n', (3448, 3458), False, 'import os\n'), ((3630, 3658), 'os.path.join', 'os.path.join', (['root', 'parts[0]'], {}), '(root, parts[0])\n', (3642, 3658), False, 'import os\n'), ((3682, 3715), 'os.path.relpath', 'os.path.relpath', (['actionpath', 'root'], {}), '(actionpath, root)\n', (3697, 3715), False, 'import os\n'), ((3547, 3581), 'os.path.join', 'os.path.join', (['root', '"""node_modules"""'], {}), "(root, 'node_modules')\n", (3559, 3581), False, 'import os\n')]
import logging from .model.orm import ( Check, Host, Instance, ) from .alerting import ( bootstrap_checks, check_specs, ) logger = logging.getLogger(__name__) def merge_agent_info(session, host_info, instances_info): """Update the host, instance and database information with the data received from the agent.""" try: # Try to get host_id, based on hostname host_info['host_id'] = get_host_id(session, host_info['hostname']) except Exception: # host not found pass host = Host.from_dict(host_info) # Insert or update host information session.merge(host) session.flush() session.commit() # Get host_id in any case host_id = get_host_id(session, host_info['hostname']) for instance_info in instances_info: # Only process instances marked as available, since only those # have complete information if instance_info['available']: try: # Try to get instance_id instance_info['instance_id'] = get_instance_id( session, host_id, instance_info['port'] ) except Exception: # instance not found pass instance_info['host_id'] = host_id inst = Instance.from_dict(instance_info) # Insert or update instance information session.merge(inst) session.flush() session.commit() return host def get_host_id(session, hostname): """ Get host_id from the hostname. """ query = """ SELECT host_id FROM monitoring.hosts WHERE hostname = :hostname """ result = session.execute(query, {"hostname": hostname}) try: return result.fetchone()[0] except Exception: raise Exception("Can't find host_id for \"%s\"" " in monitoring.hosts table." % hostname) def get_instance_id(session, host_id, port): """ Get instance from host_id and port. """ query = """ SELECT instance_id FROM monitoring.instances WHERE host_id = :host_id AND port = :port """ result = session.execute(query, {"host_id": host_id, "port": port}) try: return result.fetchone()[0] except Exception: raise Exception("Can't find instance_id for \"%s/%s\" " "in monitoring.instances table." % (host_id, port)) def check_agent_key(session, hostname, pg_data, pg_port, agent_key): query = """ SELECT agent_key FROM application.instances WHERE hostname = :hostname AND pg_data=:pgdata AND pg_port = :pgport LIMIT 1 """ result = session.execute( query, {"hostname": hostname, "pgdata": pg_data, "pgport": pg_port}) try: row = result.fetchone() if row[0] == agent_key: return except Exception: raise Exception("Can't find the instance \"%s\" " "in application.instances table." % hostname) raise Exception("Can't check agent's key.") def check_host_key(session, hostname, agent_key): query = """ SELECT agent_key FROM application.instances WHERE hostname = :hostname """ result = session.execute(query, {"hostname": hostname}) try: for row in result.fetchall(): if row[0] == agent_key: return except Exception: raise Exception("Can't find the instance \"%s\" " "in application.instances table." % hostname) raise Exception("Can't check agent's key.") def insert_metrics(session, host, agent_data, logger, hostname, port): try: # Find host_id & instance_id host_id = get_host_id(session, hostname) instance_id = get_instance_id(session, host_id, port) except Exception as e: logger.info("Unable to find host & instance IDs") logger.debug(agent_data) logger.exception(str(e)) session.rollback() return cur = session.connection().connection.cursor() for metric in agent_data.keys(): # Do not try to insert empty lines if len(agent_data[metric]) == 0: continue try: # Insert data if metric == 'sessions': for metric_data in agent_data['sessions']: query = """ INSERT INTO monitoring.metric_sessions_current VALUES (%s, %s, %s, %s) """ cur.execute( query, ( metric_data['datetime'], instance_id, metric_data['dbname'], ( None, metric_data['active'], metric_data['waiting'], metric_data['idle'], metric_data['idle_in_xact'], metric_data['idle_in_xact_aborted'], metric_data['fastpath'], metric_data['disabled'], metric_data['no_priv'] ) ) ) elif metric == 'xacts': for metric_data in agent_data['xacts']: query = """ INSERT INTO monitoring.metric_xacts_current VALUES (%s, %s, %s, %s) """ cur.execute( query, ( metric_data['datetime'], instance_id, metric_data['dbname'], ( None, str(metric_data['measure_interval']), metric_data['n_commit'], metric_data['n_rollback'] ) ) ) elif metric == 'locks': for metric_data in agent_data['locks']: query = """ INSERT INTO monitoring.metric_locks_current VALUES (%s, %s, %s, %s) """ cur.execute( query, ( metric_data['datetime'], instance_id, metric_data['dbname'], ( None, metric_data['access_share'], metric_data['row_share'], metric_data['row_exclusive'], metric_data['share_update_exclusive'], metric_data['share'], metric_data['share_row_exclusive'], metric_data['exclusive'], metric_data['access_exclusive'], metric_data['siread'], metric_data['waiting_access_share'], metric_data['waiting_row_share'], metric_data['waiting_row_exclusive'], metric_data['waiting_share_update_exclusive'], metric_data['waiting_share'], metric_data['waiting_share_row_exclusive'], metric_data['waiting_exclusive'], metric_data['waiting_access_exclusive'] ) ) ) elif metric == 'blocks': for metric_data in agent_data['blocks']: query = """ INSERT INTO monitoring.metric_blocks_current VALUES (%s, %s, %s, %s) """ cur.execute( query, ( metric_data['datetime'], instance_id, metric_data['dbname'], ( None, str(metric_data['measure_interval']), metric_data['blks_read'], metric_data['blks_hit'], metric_data['hitmiss_ratio'] ) ) ) elif metric == 'bgwriter': for metric_data in agent_data['bgwriter']: query = """ INSERT INTO monitoring.metric_bgwriter_current VALUES (%s, %s, %s) """ cur.execute( query, ( metric_data['datetime'], instance_id, ( None, str(metric_data['measure_interval']), metric_data['checkpoints_timed'], metric_data['checkpoints_req'], metric_data['checkpoint_write_time'], metric_data['checkpoint_sync_time'], metric_data['buffers_checkpoint'], metric_data['buffers_clean'], metric_data['maxwritten_clean'], metric_data['buffers_backend'], metric_data['buffers_backend_fsync'], metric_data['buffers_alloc'], metric_data['stats_reset'] ) ) ) elif metric == 'db_size': for metric_data in agent_data['db_size']: query = """ INSERT INTO monitoring.metric_db_size_current VALUES (%s, %s, %s, %s) """ cur.execute( query, ( metric_data['datetime'], instance_id, metric_data['dbname'], ( None, metric_data['size'] ) ) ) elif metric == 'tblspc_size': for metric_data in agent_data['tblspc_size']: query = """ INSERT INTO monitoring.metric_tblspc_size_current VALUES (%s, %s, %s, %s) """ cur.execute( query, ( metric_data['datetime'], instance_id, metric_data['spcname'], ( None, metric_data['size'] ) ) ) elif metric == 'filesystems_size': for metric_data in agent_data['filesystems_size']: query = """ INSERT INTO monitoring.metric_filesystems_size_current VALUES (%s, %s, %s, %s) """ cur.execute( query, ( metric_data['datetime'], host_id, metric_data['mount_point'], ( None, metric_data['used'], metric_data['total'], metric_data['device'] ) ) ) elif metric == 'temp_files_size_tblspc': for metric_data in agent_data['temp_files_size_tblspc']: query = """ INSERT INTO monitoring.metric_temp_files_size_tblspc_current VALUES (%s, %s, %s, %s) """ cur.execute( query, ( metric_data['datetime'], instance_id, metric_data['spcname'], ( None, metric_data['size'] ) ) ) elif metric == 'temp_files_size_db': for metric_data in agent_data['temp_files_size_db']: query = """ INSERT INTO monitoring.metric_temp_files_size_db_current VALUES (%s, %s, %s, %s) """ cur.execute( query, ( metric_data['datetime'], instance_id, metric_data['dbname'], ( None, metric_data['size'] ) ) ) elif metric == 'wal_files': for metric_data in agent_data['wal_files']: query = """ INSERT INTO monitoring.metric_wal_files_current VALUES (%s, %s, %s) """ cur.execute( query, ( metric_data['datetime'], instance_id, ( None, str(metric_data['measure_interval']), metric_data['written_size'], metric_data['current_location'], metric_data['total'], metric_data['archive_ready'], metric_data['total_size'] ) ) ) elif metric == 'cpu': for metric_data in agent_data['cpu']: query = """ INSERT INTO monitoring.metric_cpu_current VALUES (%s, %s, %s, %s) """ cur.execute( query, ( metric_data['datetime'], host_id, metric_data['cpu'], ( None, str(metric_data['measure_interval']), metric_data['time_user'], metric_data['time_system'], metric_data['time_idle'], metric_data['time_iowait'], metric_data['time_steal'] ) ) ) elif metric == 'process': for metric_data in agent_data['process']: query = """ INSERT INTO monitoring.metric_process_current VALUES (%s, %s, %s) """ cur.execute( query, ( metric_data['datetime'], host_id, ( None, str(metric_data['measure_interval']), metric_data['context_switches'], metric_data['forks'], metric_data['procs_running'], metric_data['procs_blocked'], metric_data['procs_total'] ) ) ) elif metric == 'memory': for metric_data in agent_data['memory']: query = """ INSERT INTO monitoring.metric_memory_current VALUES (%s, %s, %s) """ cur.execute( query, ( metric_data['datetime'], host_id, ( None, metric_data['mem_total'], metric_data['mem_used'], metric_data['mem_free'], metric_data['mem_buffers'], metric_data['mem_cached'], metric_data['swap_total'], metric_data['swap_used'] ) ) ) elif metric == 'loadavg': for metric_data in agent_data['loadavg']: query = """ INSERT INTO monitoring.metric_loadavg_current VALUES (%s, %s, %s) """ cur.execute( query, ( metric_data['datetime'], host_id, ( None, metric_data['load1'], metric_data['load5'], metric_data['load15'] ) ) ) elif metric == 'vacuum_analyze': for metric_data in agent_data['vacuum_analyze']: query = """ INSERT INTO monitoring.metric_vacuum_analyze_current VALUES (%s, %s, %s, %s) """ cur.execute( query, ( metric_data['datetime'], instance_id, metric_data['dbname'], ( None, str(metric_data['measure_interval']), metric_data['n_vacuum'], metric_data['n_analyze'], metric_data['n_autovacuum'], metric_data['n_autoanalyze'] ) ) ) elif metric == 'replication': for metric_data in agent_data['replication']: query = """ INSERT INTO monitoring.metric_replication_current VALUES (%s, %s, %s) """ cur.execute( query, ( metric_data['datetime'], instance_id, ( None, metric_data['receive_location'], metric_data['replay_location'] ) ) ) session.connection().connection.commit() except Exception as e: logger.info("Metric data not inserted for '%s' type" % (metric)) logger.debug(agent_data[metric]) logger.exception(str(e)) session.connection().connection.rollback() def get_host_checks(session, host_id): # Returns enabled alerting checks as list of tuples: # (name, warning threshold, critical threshold) checks = session.query(Check).filter(Check.host_id == host_id) return [(c.name, c.warning, c.critical) for c in checks if c.enabled] def populate_host_checks(session, host_id, instance_id, hostinfo): # Populate checks table with bootstraped checks if needed q = session.query(Check) n = q.filter(Check.host_id == host_id).count() if n != 0: return specs = check_specs for bc in bootstrap_checks(hostinfo): c = Check(host_id=host_id, instance_id=instance_id, name=bc[0], enabled=True, warning=bc[1], critical=bc[2], description=specs.get(bc[0]).get('description')) session.add(c) session.commit()
[ "logging.getLogger" ]
[((154, 181), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (171, 181), False, 'import logging\n')]
#!/usr/bin/env python3 #=============================================================================== # Copyright (c) 2020 <NAME> # Lab of Dr. <NAME> and Dr. <NAME> # University of Michigan #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. #============================================================================ ############################ ##### IMPORT MODULES ####### ########################### import os import sys import sqlite3 import rsidx import argparse import gzip ########################### ##### PARSE ARGUMENTS #### ########################### def get_settings(): parser = argparse.ArgumentParser(description="Convert weights files with just rsIDs to ones with chromosomes and coordinates too\n") parser.add_argument("-v","--vcf",help="bgzipped and tabixed vcf file",type=str,required=True) parser.add_argument("-r","--rsidx",help="rsidx file",type=str) parser.add_argument("-w","--weights",help="weights file. assumes one header. will skip lines with #",type=str,required=True) parser.add_argument("-c","--col",help="0-based column in weights file that rsID is in",type=int,default=0) parser.add_argument("-p","--prefix",help="Prefix for output file, including path",type=str,required=True) args=parser.parse_args() return args ############################### ######## SUB ROUTINES ######### ############################### def open_zip(f): if ".gz" in f: command=gzip.open(f,"rt") print("Opening gzipped file %s\n" % f,file=sys.stderr) elif f == "-": command=sys.stdin() else: command=open(f,"rt") print("Opening file %s\n" % f,file=sys.stderr) return command def index(vcf): with sqlite3.connect('myidx.db') as dbconn, open(vcf, 'r') as vcffh: rsidx.index.index(dbconn, vcffh) # rsidx index 00-All.vcf.gz 00-All.vcf.rsidx def search(rsidlist,vcf,index): print("Querying markers from weights file in VCF\n",file=sys.stderr) in_len=len(rsidlist) rsid_dict={} with sqlite3.connect(index) as dbconn: for line in rsidx.search.search(rsidlist, dbconn, vcf): ls=line.rstrip() lineList=ls.split("\t") rsid_dict[lineList[2]]=lineList[:5] #assumes VCF is chr, pos, rsID, REF, ALT out_len=len(rsid_dict.keys()) if in_len!=out_len: diff=int(in_len)-int(out_len) print("Not all rsIDs from weights file could be found in the VCF. Missing %d of %d\n" % (diff,in_len),file=sys.stderr) else: print("All %d rsIDs from weights file could be found in the VCF.\n" % in_len,file=sys.stderr) return rsid_dict def rsid_from_weights(weights,col): print("Getting rsIDs from weights file %s\n" %weights, file=sys.stderr) command=open_zip(weights) rsid_list=[] header_count=0 with command as f: for line in f: ls=line.rstrip() if ls[0] != "#": if header_count==0: #skip first header after any lines with # header_count+=1 next else: lineList=ls.split() rsid_list.append(lineList[col]) return rsid_list def merge(weights,col,rsid_dict,prefix): command=open_zip(weights) header_count=0 output=prefix + "_reformat.txt" print("Writing new weights file %s\n" %output, file=sys.stderr) with open(output,"w") as o: with command as f: for line in f: ls=line.rstrip() if ls[0] == "#": o.write(ls+"\n") elif header_count==0: lineList=ls.split() o.write("\t".join(lineList+["CHR","POS","REF","ALT"])+"\n") #write header header_count+=1 else: lineList=ls.split() try: from_vcf=rsid_dict[lineList[col]] #look up from dictionary from vcf ## handle occurence of multiple alt alleles by printing each potential entry as a newline for alt_allele in from_vcf[4].split(","): o.write("\t".join(lineList+from_vcf[0:2]+[from_vcf[3]]+[alt_allele])+"\n") except KeyError: o.write("\t".join(lineList+["NA"]*4)+"\n") #rsid not in VCF f.close() o.close() os.system("gzip "+output) #ystem call to gzip return 0 ######################### ########## MAIN ######### ######################### def main(): #get arguments args = get_settings() print(args) #github package https://github.com/bioforensics/rsidx if not os.path.exists(args.vcf): sys.exit("VCF does not exist\n") if not os.path.exists(args.rsidx): sys.exit("RSIDX does not exist\n") #index(args.vcf) #get rsids from weights file rsid_list=rsid_from_weights(args.weights,args.col) #search vcf rsid_dict=search(rsid_list,args.vcf,args.rsidx) #merge new info with weights file merge(args.weights,args.col,rsid_dict,args.prefix) #call main if __name__ == "__main__": main() 111
[ "os.path.exists", "sys.exit", "sqlite3.connect", "argparse.ArgumentParser", "gzip.open", "sys.stdin", "rsidx.index.index", "os.system", "rsidx.search.search" ]
[((1591, 1727), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Convert weights files with just rsIDs to ones with chromosomes and coordinates too\n"""'}), '(description=\n """Convert weights files with just rsIDs to ones with chromosomes and coordinates too\n"""\n )\n', (1614, 1727), False, 'import argparse\n'), ((5410, 5437), 'os.system', 'os.system', (["('gzip ' + output)"], {}), "('gzip ' + output)\n", (5419, 5437), False, 'import os\n'), ((2426, 2444), 'gzip.open', 'gzip.open', (['f', '"""rt"""'], {}), "(f, 'rt')\n", (2435, 2444), False, 'import gzip\n'), ((2693, 2720), 'sqlite3.connect', 'sqlite3.connect', (['"""myidx.db"""'], {}), "('myidx.db')\n", (2708, 2720), False, 'import sqlite3\n'), ((2765, 2797), 'rsidx.index.index', 'rsidx.index.index', (['dbconn', 'vcffh'], {}), '(dbconn, vcffh)\n', (2782, 2797), False, 'import rsidx\n'), ((3016, 3038), 'sqlite3.connect', 'sqlite3.connect', (['index'], {}), '(index)\n', (3031, 3038), False, 'import sqlite3\n'), ((3070, 3112), 'rsidx.search.search', 'rsidx.search.search', (['rsidlist', 'dbconn', 'vcf'], {}), '(rsidlist, dbconn, vcf)\n', (3089, 3112), False, 'import rsidx\n'), ((5698, 5722), 'os.path.exists', 'os.path.exists', (['args.vcf'], {}), '(args.vcf)\n', (5712, 5722), False, 'import os\n'), ((5732, 5764), 'sys.exit', 'sys.exit', (['"""VCF does not exist\n"""'], {}), "('VCF does not exist\\n')\n", (5740, 5764), False, 'import sys\n'), ((5776, 5802), 'os.path.exists', 'os.path.exists', (['args.rsidx'], {}), '(args.rsidx)\n', (5790, 5802), False, 'import os\n'), ((5812, 5846), 'sys.exit', 'sys.exit', (['"""RSIDX does not exist\n"""'], {}), "('RSIDX does not exist\\n')\n", (5820, 5846), False, 'import sys\n'), ((2542, 2553), 'sys.stdin', 'sys.stdin', ([], {}), '()\n', (2551, 2553), False, 'import sys\n')]
# encoding: UTF-8 from distutils.core import setup from Cython.Build import cythonize import numpy setup( name = 'crrCython', ext_modules = cythonize("crrCython.pyx"), include_dirs = [numpy.get_include()] )
[ "Cython.Build.cythonize", "numpy.get_include" ]
[((146, 172), 'Cython.Build.cythonize', 'cythonize', (['"""crrCython.pyx"""'], {}), "('crrCython.pyx')\n", (155, 172), False, 'from Cython.Build import cythonize\n'), ((192, 211), 'numpy.get_include', 'numpy.get_include', ([], {}), '()\n', (209, 211), False, 'import numpy\n')]
# coding: utf-8 """ App Center Client Microsoft Visual Studio App Center API # noqa: E501 OpenAPI spec version: preview Contact: <EMAIL> Project Repository: https://github.com/b3nab/appcenter-sdks """ from __future__ import absolute_import import unittest import appcenter_sdk from ReleaseUpdateError.clsReleaseUpdateError import ReleaseUpdateError # noqa: E501 from appcenter_sdk.rest import ApiException class TestReleaseUpdateError(unittest.TestCase): """ReleaseUpdateError unit test stubs""" def setUp(self): pass def tearDown(self): pass def testReleaseUpdateError(self): """Test ReleaseUpdateError""" # FIXME: construct object with mandatory attributes with example values # model = appcenter_sdk.models.clsReleaseUpdateError.ReleaseUpdateError() # noqa: E501 pass if __name__ == '__main__': unittest.main()
[ "unittest.main" ]
[((902, 917), 'unittest.main', 'unittest.main', ([], {}), '()\n', (915, 917), False, 'import unittest\n')]
from ftplib import FTP from datetime import * from tkinter import * def interval(): now = date.today() yourDay = int(input("Vous êtes né quel jour ? ")) yourMonth = int(input("Vous êtes né quel mois ? ")) yourYear = int(input("Vous êtes né quelle année ? ")) birthday = date(yourYear, yourMonth, yourDay) daysPassed = now - birthday import os clear = lambda: os.system('clear') clear() endOfString = str(daysPassed).index(" ") print("Tu as " + str(daysPassed)[:endOfString] + " jours !") def calculate(): global result global response try: result.destroy() except: print("no") now = date.today() yourDay = int(day.get('1.0', END)) yourMonth = int(month.get('1.0', END)) yourYear = int(year.get('1.0', END)) birthday = date(yourYear, yourMonth, yourDay) daysPassed = now - birthday endOfString = str(daysPassed).index(" ") response = str(daysPassed)[:endOfString] result = Label(root, text="Félicitations ! Tu as exactement: " + response + " jours !!!") result.pack() root = Tk() root.minsize(width=640, height=480) root.maxsize(width=640, height=480) root.wm_title("A Day Calculator") Label(root, text="A Day Calculator calcule ton nombre de jours passés depuis ta naissance !").pack() calc = Button(root, text="Calculer", command=calculate) calc.pack() Label(root, text="Jour de naissance").pack() day = Text(root, width="4", height="2", background="gray") day.pack() Label(root, text="Mois de naissance").pack() month = Text(root, width="4", height="2", background="gray") month.pack() Label(root, text="Année de naissance").pack() year = Text(root, width="4", height="2", background="gray") year.pack() Label(root, text="-----------------").pack() root.mainloop()
[ "os.system" ]
[((370, 388), 'os.system', 'os.system', (['"""clear"""'], {}), "('clear')\n", (379, 388), False, 'import os\n')]
#!/usr/bin/env python3 from setuptools import setup setup( name="deeplator", version="0.0.7", description="Wrapper for DeepL translator.", long_description="Deeplator is a library enabling translation via the DeepL translator.", author="uinput", author_email="<EMAIL>", license="MIT", url="https://github.com/uinput/deeplator", keywords=["deepl", "translation", "translate", "language"], python_requires=">=3", packages=["deeplator"], py_modules=["deeplator"], classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3" ] )
[ "setuptools.setup" ]
[((54, 664), 'setuptools.setup', 'setup', ([], {'name': '"""deeplator"""', 'version': '"""0.0.7"""', 'description': '"""Wrapper for DeepL translator."""', 'long_description': '"""Deeplator is a library enabling translation via the DeepL translator."""', 'author': '"""uinput"""', 'author_email': '"""<EMAIL>"""', 'license': '"""MIT"""', 'url': '"""https://github.com/uinput/deeplator"""', 'keywords': "['deepl', 'translation', 'translate', 'language']", 'python_requires': '""">=3"""', 'packages': "['deeplator']", 'py_modules': "['deeplator']", 'classifiers': "['Development Status :: 4 - Beta', 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3']"}), "(name='deeplator', version='0.0.7', description=\n 'Wrapper for DeepL translator.', long_description=\n 'Deeplator is a library enabling translation via the DeepL translator.',\n author='uinput', author_email='<EMAIL>', license='MIT', url=\n 'https://github.com/uinput/deeplator', keywords=['deepl', 'translation',\n 'translate', 'language'], python_requires='>=3', packages=['deeplator'],\n py_modules=['deeplator'], classifiers=['Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3'])\n", (59, 664), False, 'from setuptools import setup\n')]
import sys import logging as log from ..common import parsers, helpers, retrievers, data_handlers from ..common.data_models import Taxon from typing import List def run_taiga(infile: str, email: str, gb_mode: int = 0, tid: bool = False, correction: bool = False, retries: int = 5, silent: bool = False) -> List[Taxon]: """ Wrapper for all of TaIGa's main functionalities Required Parameters: infile (str): Full path to input file email (str): Valid user e-mail Optional Parameters: gb_mode (int): An integer representing the reading mode for the input file. Options are: 0: a plain text file, which is not handled by this function (Default) 1: Genbank file with multiple records from different organisms 2: Genbank file with a single record from a single organism 3: Genbank file with multiple records from the same organism tid (bool: Default = False): Tells if TaIGa should expect a input file with Taxon IDs correction (bool: Default = False): Activates the name correction function. retries (int: Default = 5): How many time TaIGa should retry after a bad response. silent (bool: Default = False): Tells if TaIGa should stop printing and create a log file Returns: None """ # Ouput and input paths input_path = infile # Providing the email when doing requests through E-Utils is recommended user_email = email # Minor config variables for some of TaIGa's functionalities retries = retries create_log = silent name_correction = correction # The switches for TaIGa's execution modes, either for Taxon IDs or Genbank files taxid = tid mode = gb_mode # A list to hold Taxon objects taxon_list: List[Taxon] = [] # Inital configuration for the logging module # At this point, the output may be set to verbose or not helpers.config_log(create_log) log.info(""" ********************************************* * * * TaIGa - Taxonomy Information Gatherer * * * *********************************************""") # Checking if TaIGa is being run on Taxon ID mode with the '-c' argument # This is needed because, when run with '--tid', TaIGa never actually tries to correct spelling # as the retrieved name is assumed to be correct if taxid and name_correction: log.error("\nERROR: Please, when running TaIGa with the '--tid' option, don't use the '-c' " "option as TaIGa already skips the name correction\n") sys.exit() # Check if input mode is for a Genbank format file or a text file and then parse the input if not (mode == 0): taxon_list = parsers.parse_gb(input_path, mode) else: taxon_list = parsers.parse_txt(input_path, taxid) log.info("\n> Searching for taxonomic information...") # Checking the type of input (Taxon ID or names) and fetching the rest of the information if tid: retrievers.retrieve_from_taxid(taxon_list, user_email, retries) else: retrievers.retrieve_from_names( taxon_list, user_email, name_correction, retries) # Calling the wrapper function to fetch for the taxonomic information for all organisms retrievers.retrieve_taxonomy(taxon_list, user_email, retries) log.info( "\n> Successfuly created taxa metadata Dataframe. You can manipulate or save it!\n") # Calling a function to handle the fetched data and convert it to a Pandas DataFrame return taxon_list
[ "logging.info", "logging.error", "sys.exit" ]
[((2038, 2314), 'logging.info', 'log.info', (['"""\n *********************************************\n * *\n * TaIGa - Taxonomy Information Gatherer *\n * *\n *********************************************"""'], {}), '(\n """\n *********************************************\n * *\n * TaIGa - Taxonomy Information Gatherer *\n * *\n *********************************************"""\n )\n', (2046, 2314), True, 'import logging as log\n'), ((3012, 3069), 'logging.info', 'log.info', (['"""\n> Searching for taxonomic information..."""'], {}), '("""\n> Searching for taxonomic information...""")\n', (3020, 3069), True, 'import logging as log\n'), ((3522, 3627), 'logging.info', 'log.info', (['"""\n> Successfuly created taxa metadata Dataframe. You can manipulate or save it!\n"""'], {}), '(\n """\n> Successfuly created taxa metadata Dataframe. You can manipulate or save it!\n"""\n )\n', (3530, 3627), True, 'import logging as log\n'), ((2578, 2734), 'logging.error', 'log.error', (['"""\nERROR: Please, when running TaIGa with the \'--tid\' option, don\'t use the \'-c\' option as TaIGa already skips the name correction\n"""'], {}), '(\n """\nERROR: Please, when running TaIGa with the \'--tid\' option, don\'t use the \'-c\' option as TaIGa already skips the name correction\n"""\n )\n', (2587, 2734), True, 'import logging as log\n'), ((2752, 2762), 'sys.exit', 'sys.exit', ([], {}), '()\n', (2760, 2762), False, 'import sys\n')]
from django.shortcuts import render def HomeView(request): return render(request , 'site_home.html') def AboutView(request): return render(request, 'about.html')
[ "django.shortcuts.render" ]
[((71, 104), 'django.shortcuts.render', 'render', (['request', '"""site_home.html"""'], {}), "(request, 'site_home.html')\n", (77, 104), False, 'from django.shortcuts import render\n'), ((142, 171), 'django.shortcuts.render', 'render', (['request', '"""about.html"""'], {}), "(request, 'about.html')\n", (148, 171), False, 'from django.shortcuts import render\n')]
import pandas as pd import pandas import numpy as np #provide local path testfile='../input/test.csv' data = open(testfile).readlines() sequences={} #(key, value) = (id , sequence) for i in range(1,len(data)): line=data[i] line =line.replace('"','') line = line[:-1].split(',') id = int(line[0]) sequence=[int(x) for x in line[1:]]; sequences[id]=sequence # In[ ]: def checkRecurrence(seq, order= 2, minlength = 7): """ :type seq: List[int] :type order: int :type minlength: int :rtype: List[int] Check whether the input sequence is a recurrence sequence with given order. If it is, return the coefficients for the recurrenec relation. If not, return None. """ if len(seq)< max((2*order+1), minlength): return None ################ Set up the system of equations A,b = [], [] for i in range(order): A.append(seq[i:i+order]) b.append(seq[i+order]) A,b =np.array(A), np.array(b) try: if np.linalg.det(A)==0: return None except TypeError: return None ############# Solve for the coefficients (c0, c1, c2, ...) coeffs = np.linalg.inv(A).dot(b) ############ Check if the next terms satisfy recurrence relation for i in range(2*order, len(seq)): predict = np.sum(coeffs*np.array(seq[i-order:i])) if abs(predict-seq[i])>10**(-2): return None return list(coeffs) def predictNextTerm(seq, coeffs): """ :type seq: List[int] :type coeffs: List[int] :rtype: int Given a sequence and coefficienes, compute the next term for the sequence. """ order = len(coeffs) predict = np.sum(coeffs*np.array(seq[-order:])) return int(round(predict)) # ## Example: ## # * Given a sequence [1,5,11,21,39,73,139,269,527]. # * We verify if it's 3rd order recurrence sequence and find the coefficients (2,-5,4). # * We then predict the next term using the last 3 terms and the relation $a_{n+3} = 2a_{n}-5a_{n+1}+4a_{n+2}$. # In[ ]: seq = [1,5,11,21,39,73,139,269,527] print (checkRecurrence(seq,3)) print (predictNextTerm(seq, [2,-5,4])) # # Find 2nd order sequeneces in the test set # # In[ ]: order2Seq={} #(key, value) = (sequence id, [prediction, coefficients]) for id in sequences: seq = sequences[id] coeff = checkRecurrence(seq,2) if coeff!=None: predict = predictNextTerm(seq, coeff) order2Seq[id]=(predict,coeff) print ("We found %d sequences\n" %len(order2Seq)) print ("Some examples\n") print ("ID, Prediction, Coefficients") for key in sorted(order2Seq)[0:5]: value = order2Seq[key] print ("%s, %s, %s" %(key, value[0], [int(round(x)) for x in value[1]])) # # Find 3rd order sequeneces in the test set # # In[ ]: order3Seq={} for id in sequences: if id in order2Seq: continue seq = sequences[id] coeff = checkRecurrence(seq,3) if coeff!=None: predict = predictNextTerm(seq, coeff) order3Seq[id]=(predict,coeff) print ("We found %d sequences\n" %len(order3Seq)) print ("Some examples\n") print ("ID, Prediction, Coefficients") for key in sorted(order3Seq)[0:5]: value = order3Seq[key] print ("%s, %s, %s" %(key, value[0], [int(round(x)) for x in value[1]])) # # Find 4th order sequeneces in the test set # # In[ ]: order4Seq={} for id in sequences: if id in order2Seq or id in order3Seq: continue seq = sequences[id] coeff = checkRecurrence(seq,4) if coeff!=None: predict = predictNextTerm(seq, coeff) order4Seq[id]=(predict,coeff) print ("We found %d sequences \n" %len(order4Seq)) print ("Some examples\n") print ("ID, Prediction, Coefficients") for key in sorted(order4Seq)[4:5]: value = order4Seq[key] print ("%s, %s, %s" %(key, value[0], [int(round(x)) for x in value[1]])) print (sequences[239][0:17]) # ## Recurrence relations not included in OEIS ## # In the previous cells, # * We find that Sequence 239 is a 4th order sequence and predict the next term as 5662052980. # * We check OEIS https://oeis.org/A000773, which confirms the prediction is correct. # * We observe that this recurrence relation is not described in OEIS. (There are more such sequences.) # In[ ]: print("Conclusion:") print("Number of sequences in the test set:", len(sequences)) print("Number of 2nd order sequences:", len(order2Seq)) print("Number of 3rd order sequences:", len(order3Seq)) print("Number of 4th order sequences:", len(order4Seq))
[ "numpy.array", "numpy.linalg.inv", "numpy.linalg.det" ]
[((1019, 1030), 'numpy.array', 'np.array', (['A'], {}), '(A)\n', (1027, 1030), True, 'import numpy as np\n'), ((1032, 1043), 'numpy.array', 'np.array', (['b'], {}), '(b)\n', (1040, 1043), True, 'import numpy as np\n'), ((1067, 1083), 'numpy.linalg.det', 'np.linalg.det', (['A'], {}), '(A)\n', (1080, 1083), True, 'import numpy as np\n'), ((1241, 1257), 'numpy.linalg.inv', 'np.linalg.inv', (['A'], {}), '(A)\n', (1254, 1257), True, 'import numpy as np\n'), ((1816, 1838), 'numpy.array', 'np.array', (['seq[-order:]'], {}), '(seq[-order:])\n', (1824, 1838), True, 'import numpy as np\n'), ((1417, 1443), 'numpy.array', 'np.array', (['seq[i - order:i]'], {}), '(seq[i - order:i])\n', (1425, 1443), True, 'import numpy as np\n')]
#!/usr/bin/env python # coding: utf-8 # Copyright 2014 The Crashpad 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. import argparse import os import re import subprocess import sys def FixUserImplementation(implementation): """Rewrites a MIG-generated user implementation (.c) file. Rewrites the file at |implementation| by adding “__attribute__((unused))” to the definition of any structure typedefed as “__Reply” by searching for the pattern unique to those structure definitions. These structures are in fact unused in the user implementation file, and this will trigger a -Wunused-local-typedefs warning in gcc unless removed or marked with the “unused” attribute. """ file = open(implementation, 'r+') contents = file.read() pattern = re.compile('^(\t} __Reply);$', re.MULTILINE) contents = pattern.sub(r'\1 __attribute__((unused));', contents) file.seek(0) file.truncate() file.write(contents) file.close() def FixServerImplementation(implementation): """Rewrites a MIG-generated server implementation (.c) file. Rewrites the file at |implementation| by replacing “mig_internal” with “mig_external” on functions that begin with “__MIG_check__”. This makes these functions available to other callers outside this file from a linkage perspective. It then returns, as a list of lines, declarations that can be added to a header file, so that other files that include that header file will have access to these declarations from a compilation perspective. """ file = open(implementation, 'r+') contents = file.read() # Find interesting declarations. declaration_pattern = \ re.compile('^mig_internal (kern_return_t __MIG_check__.*)$', re.MULTILINE) declarations = declaration_pattern.findall(contents) # Remove “__attribute__((__unused__))” from the declarations, and call them # “mig_external” or “extern” depending on whether “mig_external” is defined. attribute_pattern = re.compile(r'__attribute__\(\(__unused__\)\) ') declarations = ['#ifdef mig_external\nmig_external\n#else\nextern\n#endif\n' + attribute_pattern.sub('', x) + ';\n' for x in declarations] # Rewrite the declarations in this file as “mig_external”. contents = declaration_pattern.sub(r'mig_external \1', contents); # Crashpad never implements the mach_msg_server() MIG callouts. To avoid # needing to provide stub implementations, set KERN_FAILURE as the RetCode # and abort(). routine_callout_pattern = re.compile( r'OutP->RetCode = (([a-zA-Z0-9_]+)\(.+\));') routine_callouts = routine_callout_pattern.findall(contents) for routine in routine_callouts: contents = contents.replace(routine[0], 'KERN_FAILURE; abort()') # Include the header for abort(). contents = '#include <stdlib.h>\n' + contents file.seek(0) file.truncate() file.write(contents) file.close() return declarations def FixHeader(header, declarations=[]): """Rewrites a MIG-generated header (.h) file. Rewrites the file at |header| by placing it inside an “extern "C"” block, so that it declares things properly when included by a C++ compilation unit. |declarations| can be a list of additional declarations to place inside the “extern "C"” block after the original contents of |header|. """ file = open(header, 'r+') contents = file.read() declarations_text = ''.join(declarations) contents = '''\ #ifdef __cplusplus extern "C" { #endif %s %s #ifdef __cplusplus } #endif ''' % (contents, declarations_text) file.seek(0) file.truncate() file.write(contents) file.close() def main(args): parser = argparse.ArgumentParser() parser.add_argument('--developer-dir', help='Path to Xcode') parser.add_argument('--sdk', help='Path to SDK') parser.add_argument('--include', default=[], action='append', help='Additional include directory') parser.add_argument('defs') parser.add_argument('user_c') parser.add_argument('server_c') parser.add_argument('user_h') parser.add_argument('server_h') parsed = parser.parse_args(args) command = ['mig', '-user', parsed.user_c, '-server', parsed.server_c, '-header', parsed.user_h, '-sheader', parsed.server_h, ] if parsed.developer_dir is not None: os.environ['DEVELOPER_DIR'] = parsed.developer_dir if parsed.sdk is not None: command.extend(['-isysroot', parsed.sdk]) for include in parsed.include: command.extend(['-I' + include]) command.append(parsed.defs) subprocess.check_call(command) FixUserImplementation(parsed.user_c) server_declarations = FixServerImplementation(parsed.server_c) FixHeader(parsed.user_h) FixHeader(parsed.server_h, server_declarations) if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
[ "subprocess.check_call", "argparse.ArgumentParser", "re.compile" ]
[((1296, 1340), 're.compile', 're.compile', (['"""^(\t} __Reply);$"""', 're.MULTILINE'], {}), "('^(\\t} __Reply);$', re.MULTILINE)\n", (1306, 1340), False, 'import re\n'), ((2177, 2251), 're.compile', 're.compile', (['"""^mig_internal (kern_return_t __MIG_check__.*)$"""', 're.MULTILINE'], {}), "('^mig_internal (kern_return_t __MIG_check__.*)$', re.MULTILINE)\n", (2187, 2251), False, 'import re\n'), ((2504, 2554), 're.compile', 're.compile', (['"""__attribute__\\\\(\\\\(__unused__\\\\)\\\\) """'], {}), "('__attribute__\\\\(\\\\(__unused__\\\\)\\\\) ')\n", (2514, 2554), False, 'import re\n'), ((3057, 3113), 're.compile', 're.compile', (['"""OutP->RetCode = (([a-zA-Z0-9_]+)\\\\(.+\\\\));"""'], {}), "('OutP->RetCode = (([a-zA-Z0-9_]+)\\\\(.+\\\\));')\n", (3067, 3113), False, 'import re\n'), ((4182, 4207), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (4205, 4207), False, 'import argparse\n'), ((5151, 5181), 'subprocess.check_call', 'subprocess.check_call', (['command'], {}), '(command)\n', (5172, 5181), False, 'import subprocess\n')]
from setuptools import setup # with open("../README.md", "r") as fh: # long_description = fh.read() setup(name='pulzar-pkg', version='21.4.1', author='<NAME>', author_email='<EMAIL>', description='Distributed database and jobs', # long_description=long_description, # long_description_content_type="text/markdown", # data_files=[('/var/lib/pulzar/data', [])], url='http://github.com/cleve/pulzar', packages=['pulzarcore', 'pulzarutils'], classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: POSIX :: Linux" ], python_requires='>=3.6', )
[ "setuptools.setup" ]
[((105, 492), 'setuptools.setup', 'setup', ([], {'name': '"""pulzar-pkg"""', 'version': '"""21.4.1"""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'description': '"""Distributed database and jobs"""', 'url': '"""http://github.com/cleve/pulzar"""', 'packages': "['pulzarcore', 'pulzarutils']", 'classifiers': "['Programming Language :: Python :: 3',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: POSIX :: Linux']", 'python_requires': '""">=3.6"""'}), "(name='pulzar-pkg', version='21.4.1', author='<NAME>', author_email=\n '<EMAIL>', description='Distributed database and jobs', url=\n 'http://github.com/cleve/pulzar', packages=['pulzarcore', 'pulzarutils'\n ], classifiers=['Programming Language :: Python :: 3',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: POSIX :: Linux'], python_requires='>=3.6')\n", (110, 492), False, 'from setuptools import setup\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Sample 10^6 particles from anisotropic Hernquist DF. Created: February 2021 Author: <NAME> """ import sys from emcee import EnsembleSampler as Sampler import numpy as np sys.path.append("../src") from constants import G, M_sun, kpc from hernquist import calc_DF_aniso def hernquist_df_aniso(theta, M, a): """ Evaluate anisotropic Hernquist distribution function. Calculates log-probability of given phase space position theta. Functional form is Eq. (44) in Naik et al., (2020). Parameters ---------- theta: array-like, shape (6,) Array containing phase space position (x, y, z, vx, vy, vz). UNITS: metres and metres/second for positions/velocities respectively. M: float Total mass of Hernquist blob. UNITS: kilograms. a: float Scale radius of Hernquist blob. UNITS: metres. Returns ------- lnf: float Unnormalised ln-probability associated with phase space position. """ q = theta[:3] p = theta[3:] f = calc_DF_aniso(q, p, M, a) if f == 0: return -1e+20 else: lnf = np.log(f) return lnf def sample(N, M, a): """ Sample N particles from isotropic Hernquist distribution function. Takes either isotropic or anisotropic DF, parametrised by mass M and scale radius a. Sampler uses 50 MCMC walkers, each taking N iterations (after burn-in). These samples are then thinned by an interval of 50, giving N quasi-independent samples. Parameters ---------- N: int Number of particles to sample. Note: this needs to be a multiple of 50. M: float Total mass of Hernquist blob. UNITS: kilograms. a: float Scale radius of Hernquist blob. UNITS: metres. Returns ------- pos: (N, 3) array Positions of sampled particles, in Cartesian coordinates. UNITS: metres. vel: (N, 3) array Velocities of sampled particles, in Cartesian coordinates. UNITS: metres/second. """ # set up sampler df_function = hernquist_df_aniso nwalkers, ndim = 100, 6 n_burnin = 1000 assert N % nwalkers == 0 n_iter = N s = Sampler(nwalkers, ndim, df_function, args=[M, a]) # set up initial walker positions v_sig = 0.5 * np.sqrt(G * M / a) / np.sqrt(3) sig = np.array([0.3 * a, 0.3 * a, 0.3 * a, v_sig, v_sig, v_sig]) p0 = -sig + 2 * sig * np.random.rand(nwalkers, ndim) # burn in print("\nBurning in...", flush=True) s.run_mcmc(p0, n_burnin, progress=True) # take final sample p0 = s.chain[:, -1, :] s.reset() print("\n\nTaking final sample...", flush=True) s.run_mcmc(p0, n_iter, progress=True, thin=100) pos = s.flatchain[:, :3] vel = s.flatchain[:, 3:] return pos, vel def downsample(pos, vel, a, x_truncation): """Downsample from truncated Hernquist.""" r = np.linalg.norm(pos, axis=-1) allowed = np.where(r < x_truncation * a)[0] inds = np.random.choice(allowed, size=N) pos = pos[inds] vel = vel[inds] return pos, vel if __name__ == '__main__': M = 1e+10 * M_sun a = 5 * kpc N = 1000000 pos, vel = sample(2 * N, M, a) pos, vel = downsample(pos, vel, a, x_truncation=200) np.savez("hq_aniso_orig", pos=pos, vel=vel)
[ "numpy.savez", "numpy.sqrt", "numpy.random.rand", "numpy.random.choice", "numpy.where", "numpy.log", "emcee.EnsembleSampler", "numpy.array", "numpy.linalg.norm", "hernquist.calc_DF_aniso", "sys.path.append" ]
[((223, 248), 'sys.path.append', 'sys.path.append', (['"""../src"""'], {}), "('../src')\n", (238, 248), False, 'import sys\n'), ((1068, 1093), 'hernquist.calc_DF_aniso', 'calc_DF_aniso', (['q', 'p', 'M', 'a'], {}), '(q, p, M, a)\n', (1081, 1093), False, 'from hernquist import calc_DF_aniso\n'), ((2235, 2284), 'emcee.EnsembleSampler', 'Sampler', (['nwalkers', 'ndim', 'df_function'], {'args': '[M, a]'}), '(nwalkers, ndim, df_function, args=[M, a])\n', (2242, 2284), True, 'from emcee import EnsembleSampler as Sampler\n'), ((2384, 2442), 'numpy.array', 'np.array', (['[0.3 * a, 0.3 * a, 0.3 * a, v_sig, v_sig, v_sig]'], {}), '([0.3 * a, 0.3 * a, 0.3 * a, v_sig, v_sig, v_sig])\n', (2392, 2442), True, 'import numpy as np\n'), ((2949, 2977), 'numpy.linalg.norm', 'np.linalg.norm', (['pos'], {'axis': '(-1)'}), '(pos, axis=-1)\n', (2963, 2977), True, 'import numpy as np\n'), ((3037, 3070), 'numpy.random.choice', 'np.random.choice', (['allowed'], {'size': 'N'}), '(allowed, size=N)\n', (3053, 3070), True, 'import numpy as np\n'), ((3314, 3357), 'numpy.savez', 'np.savez', (['"""hq_aniso_orig"""'], {'pos': 'pos', 'vel': 'vel'}), "('hq_aniso_orig', pos=pos, vel=vel)\n", (3322, 3357), True, 'import numpy as np\n'), ((1155, 1164), 'numpy.log', 'np.log', (['f'], {}), '(f)\n', (1161, 1164), True, 'import numpy as np\n'), ((2363, 2373), 'numpy.sqrt', 'np.sqrt', (['(3)'], {}), '(3)\n', (2370, 2373), True, 'import numpy as np\n'), ((2992, 3022), 'numpy.where', 'np.where', (['(r < x_truncation * a)'], {}), '(r < x_truncation * a)\n', (3000, 3022), True, 'import numpy as np\n'), ((2342, 2360), 'numpy.sqrt', 'np.sqrt', (['(G * M / a)'], {}), '(G * M / a)\n', (2349, 2360), True, 'import numpy as np\n'), ((2469, 2499), 'numpy.random.rand', 'np.random.rand', (['nwalkers', 'ndim'], {}), '(nwalkers, ndim)\n', (2483, 2499), True, 'import numpy as np\n')]
# Generated by Django 3.0.5 on 2020-05-26 13:58 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='RepositoryDetails', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=200)), ('url', models.CharField(max_length=512)), ('deploy_key_path', models.CharField(default='', max_length=128, null='')), ('deploy_key_priv', models.CharField(default='', max_length=2048, null='')), ('deploy_key_pub', models.CharField(default='', max_length=2048, null='')), ('details_json', models.TextField(max_length=2048)), ], ), migrations.CreateModel( name='Skillet', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=200, unique=True)), ('skillet_json', models.TextField(default='', max_length=2048)), ('repository', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='cnc.RepositoryDetails')), ], ), ]
[ "django.db.models.TextField", "django.db.models.AutoField", "django.db.models.CharField", "django.db.models.ForeignKey" ]
[((346, 439), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (362, 439), False, 'from django.db import migrations, models\n'), ((463, 495), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)'}), '(max_length=200)\n', (479, 495), False, 'from django.db import migrations, models\n'), ((522, 554), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(512)'}), '(max_length=512)\n', (538, 554), False, 'from django.db import migrations, models\n'), ((593, 646), 'django.db.models.CharField', 'models.CharField', ([], {'default': '""""""', 'max_length': '(128)', 'null': '""""""'}), "(default='', max_length=128, null='')\n", (609, 646), False, 'from django.db import migrations, models\n'), ((685, 739), 'django.db.models.CharField', 'models.CharField', ([], {'default': '""""""', 'max_length': '(2048)', 'null': '""""""'}), "(default='', max_length=2048, null='')\n", (701, 739), False, 'from django.db import migrations, models\n'), ((777, 831), 'django.db.models.CharField', 'models.CharField', ([], {'default': '""""""', 'max_length': '(2048)', 'null': '""""""'}), "(default='', max_length=2048, null='')\n", (793, 831), False, 'from django.db import migrations, models\n'), ((867, 900), 'django.db.models.TextField', 'models.TextField', ([], {'max_length': '(2048)'}), '(max_length=2048)\n', (883, 900), False, 'from django.db import migrations, models\n'), ((1033, 1126), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (1049, 1126), False, 'from django.db import migrations, models\n'), ((1150, 1195), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)', 'unique': '(True)'}), '(max_length=200, unique=True)\n', (1166, 1195), False, 'from django.db import migrations, models\n'), ((1231, 1276), 'django.db.models.TextField', 'models.TextField', ([], {'default': '""""""', 'max_length': '(2048)'}), "(default='', max_length=2048)\n", (1247, 1276), False, 'from django.db import migrations, models\n'), ((1310, 1405), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""cnc.RepositoryDetails"""'}), "(on_delete=django.db.models.deletion.CASCADE, to=\n 'cnc.RepositoryDetails')\n", (1327, 1405), False, 'from django.db import migrations, models\n')]
# coding: utf-8 import os, pickle, csv, json import subprocess from typing import NamedTuple, List, TextIO, Tuple, Dict, Optional, Union, Iterable, Hashable import numpy as np import pandas as pd from scipy import stats from itertools import product, groupby, takewhile from collections import namedtuple, Counter import multiprocessing import logging import string import matplotlib matplotlib.use("Agg") # pids with missing data (i.e., pdbs missing for either sid, eid, and/or gid) pids_missing_data = {'2000524', '2001234', '2001249', '2001255', '2001287', '2001291', '2001306', '2001308', '2001311', '2002239', '2002243', '2002247', '2002255', '2002713', '2002963', '2002990', '2002992', '2003008', '2003011', '2003015', '997529', '996023'} unfetched_pids = {'2000659', '2001302', '2002102', '2002465', '2002809', '2002833', '2002850', '2003001', '2003047', '2003059', '2003078', '2003126', '2003183', '996313', '996492', '996508', '997542', '997940', '998465', '998529', '998574'} # fetched, but corrupt bad_pids = {'1998935', '2000659', '2001302', '2002102', '2002465', '2002809', '2002833', '2002850', '2003078', '2003126', '2003183', '2003763', '2003832', '997766'} # stopped early due to crashes or errors stopped_pids = {'2003699', '2003183', '2002494', '2002247', '2002912', '2003801'} # restarted version of stopped puzzle restarted_pids = {'2003704', '2002499', '2002255', '2002914', '2003806'} pids_missing_energies = {'996547'} pids_missing_pdl_actions = {'998071', '1998729', '998219'} skip_pids = pids_missing_energies.union(pids_missing_pdl_actions).union(bad_pids) class EnergyComponent(NamedTuple): name: str weight: float energy: float class PDB_Info(NamedTuple): sid: str pid: str uid: str gid: str sharing_gid: str scoretype: str pdl: Dict energy: float energy_components: List[EnergyComponent] timestamp: int parent_sid: Optional[str] tmscore: float deviations: np.ndarray class SnapshotDelta(NamedTuple): sid: str parent_sid: Optional[str] timestamp: int action_diff: Counter macro_diff: Counter action_count: int energy_diff: float class SolvingLineVariant(NamedTuple): action_count: int time: int indices: List[int] class SolvingLine(NamedTuple): action_count: int time: int pdb_infos: List[PDB_Info] variants: List[SolvingLineVariant] @property def energies(self): return [x.energy for x in self.pdb_infos] class EvolvingLine(NamedTuple): source: Dict pdb_infos: List[PDB_Info] @property def energies(self): return [x.energy for x in self.pdb_infos] class PuzzleMeta(NamedTuple): pid: str best_tmscores: Dict pfront: np.ndarray upload_baseline: float energy_baseline: float structure: Dict class PatternInstance(NamedTuple): cid: int uid: str pid: str start_idx: int end_idx: int class PatternInstanceExt(NamedTuple): cid: int uid: str pid: str start_idx: int end_idx: int start_pdb: PDB_Info end_pdb: PDB_Info pre_best: PDB_Info post_best: PDB_Info class SubPatternInstance(NamedTuple): p: PatternInstance label: str start_idx: int end_idx: int class SubLookup(NamedTuple): clusters: Dict[str, Dict[int, Dict[int, Dict[int, np.ndarray]]]] # (user to k to cid to sub_k to cluster labels) mrfs: Dict[str, Dict[int, Dict[int, Dict[int, Dict[int, np.ndarray]]]]] # (user to k to cid to sub_k to mrf dictionary (cluster label to mrf)) models: Dict[str, Dict[int, Dict[int, Dict[int, Dict]]]] # (user to k to cid to sub_k to dict of ticc model parameters) bics: Dict[str, Dict[int, Dict[int, Dict[int, float]]]] # (user to k to cid to sub_k to bic) class SubSeriesLookup(NamedTuple): patterns: Dict[Hashable, np.ndarray] # e.g., (uid, pid, start index) -> series for that pattern series: np.ndarray idx_lookup: Dict[Hashable, Tuple[int, int]] class SubclusterSeries(NamedTuple): labels: List[str] series: np.ndarray # type aliases SubClusters = Dict[int, Dict[int, Dict[int, np.ndarray]]] SubMRFs = Dict[int, Dict[int, Dict[int, Dict[int, np.ndarray]]]] PatternLookup = Union[Dict[str, Iterable[PatternInstance]], Dict[int, Dict[int, Iterable[PatternInstance]]]] @pd.api.extensions.register_series_accessor("foldit") class FolditSeriesAccessor: def __init__(self, pandas_obj: pd.Series): self._validate(pandas_obj) self._obj = pandas_obj @staticmethod def _validate(obj: pd.Series): # verify there is a column latitude and a column longitude if ('lines' not in obj.index or 'evol_lines' not in obj.index) and (obj.name != "lines" and obj.name != "evol_lines"): raise AttributeError("Must have 'lines' and 'evol_lines'.") @property def solo_pdbs(self): return [p for l in self._obj.lines for p in l.pdb_infos] if self._obj.lines else [] @property def evol_pdbs(self): return [p for l in self._obj.evol_lines for p in l.pdb_infos] if self._obj.evol_lines else [] @property def solo_energies(self): return [p.energy for p in self._obj.foldit.solo_pdbs] @property def evol_energies(self): return [p.energy for p in self._obj.foldit.evol_pdbs] @pd.api.extensions.register_dataframe_accessor("foldit") class FolditAccessor: def __init__(self, pandas_obj: pd.Series): self._validate(pandas_obj) self._obj = pandas_obj @staticmethod def _validate(obj: pd.Series): # verify there is a column latitude and a column longitude if 'lines' not in obj.columns or 'evol_lines' not in obj.columns: raise AttributeError("Must have 'lines' and 'evol_lines'.") @property def solo_pdbs(self): return self._obj.apply(lambda r: r.foldit.solo_pdbs, axis=1) @property def evol_pdbs(self): return self._obj.apply(lambda r: r.foldit.evol_pdbs, axis=1) @property def solo_energies(self): return self._obj.apply(lambda r: r.foldit.solo_energies, axis=1) @property def evol_energies(self): return self._obj.apply(lambda r: r.foldit.evol_energies, axis=1) # @property # def pdbs(self): ROOT_NID = ('00000000-0000-0000-0000-000000000000', 0) category_lookup = { 'overall': '992758', 'beginner': '992759', 'prediction': '992760', 'design': '992761', 'electron': '994237', 'contacts': '997946', 'symmetry': '992769', 'casp10': '992762', 'casp11': '997398', 'casp_roll': '993715', 'hand_folding': '994890', 'small_molecule_design': '2002074', "pilot": "2004148", 'all': 'all', # dummy to allow select of all categorized puzzles } action_types = { 'optimize': {'ActionGlobalMinimize', 'ActionGlobalMinimizeBackbone', 'ActionGlobalMinimizeSidechains', 'ActionLocalMinimize', 'ActionRepack'}, 'hybrid': {'ActionLocalMinimizePull', 'LoopHash', 'ActionBuild', 'ActionPullSidechain', 'ActionTweak', 'ActionRebuild'}, 'manual': {'ActionSetPhiPsi', 'ActionJumpWidget', 'ActionRotamerCycle', 'ActionRotamerSelect'}, 'guiding': {'ActionInsertCut', 'ActionLockToggle', 'ActionCopyToggle', 'ActionSecStructAssignHelix', 'ActionSecStructAssignLoop', 'ActionSecStructAssignSheet', 'ActionSecStructDSSP', 'ActionSecStructDrag', 'ActionBandAddAtomAtom', 'ActionBandAddDrag', 'ActionBandAddResRes', 'ActionBandDrag', 'ActionBandLength', 'ActionBandStrength'}, } action_types['deliberate'] = action_types['hybrid'].union(action_types['manual']).union(action_types['guiding']) def rmse(predictions, targets): return np.sqrt(((predictions - targets) ** 2).mean()) def iden(x): return x def get_ranks(datafile): puzzles = {} with open("{}.csv".format(datafile)) as fp: ranks_in = csv.DictReader(fp) for row in ranks_in: row['energy'] = float(row['best_score']) row['best_score'] = max(float(row['best_score']) * -10 + 8000, 0) pid = row['pid'] if pid not in puzzles: puzzles[pid] = { 'groups': {}, 'soloists': [], 'evolvers': [], 'categories': [] } if row['gid'] == '0': row['gid'] = 'NULL' # no sense in having both 0 and NULL for no group gid = row['gid'] if gid != 'NULL': gs = puzzles[pid]['groups'] if gid not in gs: gs[gid] = { 'score': row['best_score'], 'type': row['type'], 'gid': gid, 'uid': row['uid'], } if gs[gid]['score'] < row['best_score']: gs[gid]['score'] = row['best_score'] gs[gid]['type'] = row['type'] gs[gid]['uid'] = row['uid'] if row['type'] == '1': puzzles[pid]['soloists'].append(row) if row['type'] == '2': puzzles[pid]['evolvers'].append(row) for pid in puzzles: p = puzzles[pid] p['groups'] = list(p['groups'].values()) # reverse sorts to put them in descending order (top ranked should be first) p['groups'].sort(key=lambda x: x['score'], reverse=True) for i, g in enumerate(p['groups']): g['rank'] = i g['norm_rank'] = i / len(p['groups']) p['soloists'].sort(key=lambda x: x['best_score'], reverse=True) for i, s in enumerate(p['soloists']): s['rank'] = i s['norm_rank'] = i / len(p['soloists']) p['evolvers'].sort(key=lambda x: x['best_score'], reverse=True) for i, e in enumerate(p['evolvers']): e['rank'] = i e['norm_rank'] = i / len(p['evolvers']) return puzzles def get_ranks_labeled(): puzzles = get_ranks("data/rprp_puzzle_ranks_latest") with open("data/puzzle_categories_latest.csv") as fp: cat_in = csv.DictReader(fp) for r in cat_in: pid = r['nid'] if pid in puzzles: puzzles[pid]['categories'] = r['categories'].split(',') puzzles[pid]['categories'].append('all') with open("data/puzzle_labels_latest.json") as fp: lab_in = json.load(fp) for r in lab_in: pid = r['pid'] if pid in puzzles: assert r['title'] is not None puzzles[pid]['title'] = r['title'] if r['desc'] is not None: puzzles[pid]['desc'] = r['desc'] return puzzles def add_pdbs_to_ranks(puzzles): print("loading pdbs") with open("data/top_pdbs.pickle", 'rb') as pdb_fp: pdbs = pickle.load(pdb_fp) pdbs = [p for p in pdbs if 'PID' in p and len(p['PDL']) > 0] print("grouping pdbs") pdbs_by_pid = {pid: list(g) for pid, g in groupby(pdbs, lambda p: p['PID'])} for pid in pids_missing_data.union(unfetched_pids): pid in puzzles and puzzles.pop(pid) for pid in puzzles.copy(): pid not in pdbs_by_pid and puzzles.pop(pid) for pid, ps in pdbs_by_pid.items(): if pid in puzzles: puzzles[pid]['pdbs'] = ps def sig_test(a, b, fstr="{} (n={}) {} (n={})", normal=False, thresholds=frozenset()): if normal: t, p = stats.ttest_ind(a, b, equal_var=False) else: U2, p = stats.mannwhitneyu(np.array(a), np.array(b), use_continuity=True, alternative='two-sided') U = min(U2, len(a) * len(b) - U2) N = len(a) * len(b) f = len(list(filter(lambda xy: xy[0] > xy[1], product(a, b)))) / N u = len(list(filter(lambda xy: xy[0] < xy[1], product(a, b)))) / N if ('p' not in thresholds or p < thresholds['p']) and ('r' not in thresholds or abs(f - u) > thresholds['r']): print(fstr.format("mean={:.6f}, median={:.6f}, std={:.6f}".format(np.mean(a), np.median(a), np.std(a)), len(a), "mean={:.6f}, median={:.6f}, std={:.6f}".format(np.mean(b), np.median(b), np.std(b)), len(b))) if normal: print("test statistic t: {:.6f}".format(t)) else: print("<NAME> U: {:.6f}".format(U)) print("significance (two-tailed): {:.6f}".format(p)) print("rank-biserial correlation: {:.3f}".format(f - u)) return p, f - u def get_atoms(pdb): raw = [[float(x) for x in s.strip(' "[]').split(" ")] for s in pdb['ca'].split(",")] if all(k == 0 for k in raw[-1]): return np.array(raw[:-1]) # remove spurious atom at 0 0 0 that appears at the end of each of these return np.array(raw) def rmsd(X, Y): # center of mass X = X - X.mean(axis=0) Y = Y - Y.mean(axis=0) # covariance matrix R = np.dot(X.T, Y) V, S, Wt = np.linalg.svd(R) d = (np.linalg.det(V) * np.linalg.det(Wt)) < 0.0 if d: S[-1] = -S[-1] V[:, -1] = -V[:, -1] U = np.dot(V, Wt) Xp = np.dot(X, U) deviations = np.linalg.norm(Xp - Y, axis=1) return (deviations ** 2).sum() ** 0.5, deviations # https://github.com/charnley/rmsd # https://www.ncbi.nlm.nih.gov/pmc/articles/PMC1471868/ # https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4321859/ def weighted_rmsd(X, Y, p=50): weights = np.array([[1]] * len(Y)) wrmsd = 0 wrmsd_old = float('inf') i = 0 # there may be rare cases where this doesn't converge, so limit to 1000 iterations just in case while abs(wrmsd - wrmsd_old) > 1e-6 and i < 1000: i += 1 wrmsd_old = wrmsd # weighted center of mass X = X - (weights * X).mean(axis=0) Y = Y - (weights * Y).mean(axis=0) # weighted covariance matrix R = np.dot(X.T, weights * Y) V, S, Wt = np.linalg.svd(R) d = (np.linalg.det(V) * np.linalg.det(Wt)) < 0.0 if d: S[-1] = -S[-1] V[:, -1] = -V[:, -1] U = np.dot(V, Wt) Xp = np.dot(X, U) deviations = np.linalg.norm(Xp - Y, axis=1) wrmsd = ((weights.flatten() * deviations ** 2).sum() / weights.sum()) ** 0.5 dp = np.percentile(deviations, p) weights = np.exp(-deviations ** 2 / dp ** 2).reshape((len(deviations), 1)) return wrmsd, weights, deviations # take in index i and series of Unix-style timestamps # return indices start, end representing the period containing i with no gaps of size break_threshold or larger # break_threshold given in seconds def expand_seed(i, timestamps, break_threshold=900): start = end = i i = end + 1 while i < len(timestamps) and timestamps[i] - timestamps[end] < break_threshold: end = i i += 1 return start, end # takes in list of Unix-style timestamps def get_sessions(timestamps): sessions = [] i = 0 while i < len(timestamps): sessions.append(expand_seed(i, timestamps)) i = sessions[-1][1] + 1 return sessions def time_splits_helper(timestamps, chunk, splits): sessions = get_sessions(timestamps) start_idx = end_idx = 0 time_left = chunk session_idx = 0 ret = [] times = [] for i in range(splits): logging.debug('split {}'.format(i)) while time_left > 0 and session_idx < len(sessions): logging.debug('time left {}'.format(time_left)) ses = sessions[session_idx] session_start, session_end = ses if session_duration(ses, timestamps) <= time_left: logging.debug('session {} {} fits'.format(session_idx, sessions[session_idx])) end_idx = session_end time_left -= session_duration(ses, timestamps) session_idx += 1 if session_idx == len(sessions): logging.debug('adding {} to the end'.format(start_idx)) ret.append((start_idx, len(timestamps))) times.append(sum(session_duration((s, e), timestamps) for s, e in sessions if s >= start_idx)) logging.debug('time: {}'.format(times[-1])) else: ns, ne = sessions[session_idx] minimal_addition = session_duration((ns, ne), timestamps) if ns == ne else timestamps[ns + 1] - \ timestamps[ns] # the minimum we could add to the current split would put us further away than we currently are if abs(time_left - minimal_addition) > abs(time_left): times.append(session_duration((session_start, end_idx), timestamps) + sum( session_duration((s, e), timestamps) for s, e in sessions if s >= start_idx and e < session_start)) if start_idx == end_idx: end_idx += 1 logging.debug("close as we can get, adding {} up to {}".format(start_idx, end_idx)) ret.append((start_idx, end_idx)) logging.debug('time: {}'.format(times[-1])) start_idx = end_idx time_left = 0 else: if session_start == session_end: end_idx = session_end else: end_idx = session_start + 1 while session_duration((session_start, end_idx), timestamps) < time_left: end_idx += 1 if abs(time_left - (timestamps[end_idx] - timestamps[session_start])) > abs( time_left - ( timestamps[end_idx - 1] - timestamps[session_start])) and end_idx > start_idx + 1: end_idx -= 1 logging.debug('splitting session at {}'.format(end_idx)) sessions[session_idx] = (end_idx, session_end) times.append(session_duration((session_start, end_idx), timestamps) + sum( session_duration((s, e), timestamps) for s, e in sessions if s >= start_idx and e < session_start)) if start_idx == end_idx: end_idx += 1 logging.debug('adding {} up to {}'.format(start_idx, end_idx)) ret.append((start_idx, end_idx)) logging.debug('time: {}'.format(times[-1])) start_idx = end_idx time_left = 0 time_left = chunk return ret, times def get_time_splits(time, timestamps, splits): chunk = time / splits ret, times = time_splits_helper(timestamps, chunk, splits) while len(ret) < splits - 1 and len(timestamps) >= 2 * splits: chunk *= 0.9 logging.debug("bad split possibly due to degenerate chunk size, trying with {}".format(chunk)) ret, times = time_splits_helper(timestamps, chunk, splits) if len(ret) == splits - 1 and any(e - s > 0 for s, e in ret): idx = np.argmax([t if s != e else 0 for (s, e), t in zip(ret, times)]) shifted = ret[:idx] + [(ret[idx][0], ret[idx][1] - 1)] + [(s - 1, e - 1) for s, e in ret[idx + 1:]] + [ (ret[-1][1] - 1, ret[-1][1])] logging.debug("short one slice, shifting everything to make another ({} to {})".format(ret, shifted)) ret = shifted if ret[-1][1] < len(timestamps): logging.debug("extending final slice to the end ({} to {})".format(ret[-1][1], len(timestamps))) ret = ret[:-1] + [(ret[-1][0], len(timestamps))] assert len(ret) == splits or len(timestamps) < 2 * splits, "{} -- wanted {} splits, got {}".format(ret, splits, len(ret)) # assert len(ret) == splits or splits > 12, "{} -- wanted {} splits, got {}".format(ret, splits, len(ret)) assert all(e1 == s2 for (s1, e1), (s2, e2) in zip(ret, ret[1:])) covered_timestamps = np.concatenate([np.arange(s, e) for s, e in ret]) assert all(x in covered_timestamps for x in range(len(timestamps))), \ "{} -- not all timestamp indices accounted for: {}".format(ret, [x for x in range(len(timestamps)) if x not in covered_timestamps]) # allowed_deviation = max([max(np.diff(timestamps[s:e]), default=0) for s, e in get_sessions(timestamps) if s != e], default=300) / 2 # assert all(abs(t - chunk) < max(allowed_deviation, chunk * 0.1) for t in times[:-1]) or len(timestamps) <= 2 * splits, \ # "{} -- splits deviate too far from target size ({} ± {}): {}".format(ret, chunk, max(allowed_deviation, chunk * 0.1), times) return ret def session_duration(session, timestamps): st, en = session if st == en: # assume 5 minutes of work where we have just a single snapshot for the session, based on standard upload rate return 300 return timestamps[en] - timestamps[st] def time_played(timestamps): return sum(session_duration(ses, timestamps) for ses in get_sessions(timestamps)) def align_timestamps(timestamps): sessions = [slice(s, e + 1) for s, e in get_sessions(timestamps)] ts_aligned = timestamps for ses1, ses2 in zip(sessions, sessions[1:]): adjustment = ts_aligned[ses2.start] - ts_aligned[ses1.stop - 1] ts_aligned = np.concatenate((ts_aligned[:ses2.start], ts_aligned[ses2.start:] - adjustment + 900)) assert (np.diff(ts_aligned) <= 900).all() return ts_aligned def get_children(nid, history): uuid, count = nid main = list(filter(lambda x: x['uuid'] == uuid, history[nid])) if nid in history else [] if len(main) == 0 and count != 0: main = list(filter(lambda x: x['uuid'] == uuid and x['count'] > count, history[(uuid, 0)])) other = list( filter(lambda x: x['uuid'] != uuid and x['parent_count'] == count, history[nid])) if nid in history else [] children = [] if len(main) > 0: c = min(main, key=lambda x: x['count']) children.append((c['uuid'], c['count'])) for r in other: children.append((r['uuid'], r['count'])) return children def get_nid(s): return (s['uuid'], int(s['count'])) def output_atoms(atoms: np.ndarray, fp: TextIO) -> None: i = 1 for ca in atoms: fp.write("ATOM {:6d} CA XXX A {:3d} {:8.3f}{:8.3f}{:8.3f} 1.00 0.00\n".format(i, i, *ca)) i += 1 def tmscore(pairs: List[Tuple[str, str]], tmp_input_name: str, atoms_lookup: Dict) -> Dict: if len(pairs) == 0: return {} logging.debug("{}: batch computing {} tmscores".format(tmp_input_name, len(pairs))) if not os.path.exists(tmp_input_name): os.makedirs(tmp_input_name) # write the necessary atom files sids = {s for ss in pairs for s in ss} for sid in sids: with open("{}/{}.atoms".format(tmp_input_name, sid), 'w') as fp: output_atoms(atoms_lookup[sid], fp) # empirically derived formula for chunksize to equalize batch time and spawning time # based on estimates that batches run 100 scores in ~1.5s, and Python starts ~6 batches per second chunksize = max(100, (len(pairs) / 0.09) ** 0.5) if len(pairs) // chunksize > (multiprocessing.cpu_count() / 4): chunksize = len(pairs) / ( multiprocessing.cpu_count() / 4) # avoid spawning huge numbers of batches as this kills the performance splits = np.array_split(pairs, len(pairs) // chunksize if len(pairs) > chunksize else 1) ps = [] for i, split in enumerate(splits): input_name = "{}/{}.tmscore_input".format(tmp_input_name, i) with open(input_name, 'w') as fp: for a, b in split: fp.write("{} {}\n".format(a, b)) ps.append((subprocess.Popen(['./tmscore_batch.zsh', input_name], stdout=subprocess.PIPE, encoding='utf-8'), input_name)) scores = [] for p, fname in ps: scores.extend([s.split() for s in p.communicate()[0].splitlines()]) subprocess.run(['rm', fname]) subprocess.run(["rsync", "-a", "--delete", "tmp_data/empty_dir/", "{}/".format(tmp_input_name)]) return {(a, b): float(s) for a, b, s in scores} def get_overlap(segment, target): seg_sessions = get_sessions(segment) tar_sessions = get_sessions(target) tar_adj = [] for s, e in tar_sessions: cands = [ses for ses in seg_sessions if target[s] < segment[ses[1]] and target[e] > segment[ses[0]]] if len(cands) > 0: start = s while all(target[start] < segment[cs] for cs, ce in cands): start += 1 # assert start < e end = e while all(target[end] > segment[ce] for cs, ce in cands): end -= 1 # assert end >= start if start <= end: tar_adj.append((start, end)) return tar_adj def load_frame(datafile): df = pd.read_hdf(datafile, 'df') bts = pd.read_hdf(datafile, 'bts') puz = pd.read_hdf(datafile, 'puz').iloc[0] # tuple gets wrapped in a pandas data structure, so unwrap it here logging.debug(datafile) return df, bts, puz def collect_pdl_entries(soln): entries = list(takewhile(lambda x: x['header']['uid'] == soln.uid, soln.pdl[::-1])) actions = {} macros = {} for e in entries: for a, c in e['actions'].items(): actions[a] = actions.get(a, 0) + c for m, c in e['macros'].items(): macros[m] = macros.get(m, 0) + c return actions, macros def get_data_value(uid, pid, key, data): r = data[(data.uid == uid) & (data.pid == pid)] return r[key].iloc[0] def get_action_labels(): return ['band', 'build', 'cut', 'global_min', 'idealize', 'local_min', 'lock', 'rebuild', 'repack', 'assign_loop', 'save', 'reset', 'ss_load', 'ss_save'] def get_action_keys(): """ index: action type 0: banding 1: build 2: cuts 3: global minimize 4: idealize 5: local minimize 6: locking 7: rebuild 8: repack 9: assign secondary structure loop 10: quicksave 11: reset recent best 12: load secondary structure 12: save secondary structure """ actionset_band = {'ActionBandAddAtomAtom', 'ActionBandAddDrag', 'ActionBandAddResRes', 'ActionBandDrag', 'ActionBandLength', 'ActionBandStrength', 'ActionBandDelete', 'ActionBandDisableToggle'} actionset_cut = {'ActionDeleteCut', 'ActionInsertCut'} actionset_global = {'ActionGlobalMinimize', 'ActionGlobalMinimizeBackbone', 'ActionGlobalMinimizeSidechains'} actionset_save = {'ActionStandaloneQuicksave', 'ActionNoviceQuicksave'} actionset_load = {'ActionStandaloneResetRecentBest', 'ActionNoviceResetRecentBest'} actionset_ss_save = {'ActionStandaloneSecstructSave', 'ActionNoviceSecstructSave'} actionset_ss_load = {'ActionStandaloneSecstructLoad', 'ActionNoviceSecstructLoad'} return [actionset_band, {'ActionBuild'}, actionset_cut, actionset_global, {'ActionIdealize'}, {'ActionLocalMinimize'}, {'ActionLockToggle'}, {'ActionRebuild'}, {'ActionRepack'}, {'ActionSecStructAssignLoop'}, actionset_save, actionset_load, actionset_ss_load, actionset_ss_save] def get_action_stream(action_diff: Counter): keys = get_action_keys() return [sum(action_diff.get(a, 0) for a in k) for k in keys] def get_pattern_label(p, cid, sub_k): if sub_k == 0: assert p.cid == cid return str(cid) return str(cid) + string.ascii_uppercase[p.cid]
[ "csv.DictReader", "logging.debug", "multiprocessing.cpu_count", "numpy.array", "scipy.stats.ttest_ind", "numpy.linalg.norm", "pandas.api.extensions.register_series_accessor", "numpy.arange", "os.path.exists", "numpy.mean", "subprocess.Popen", "subprocess.run", "itertools.product", "numpy.d...
[((386, 407), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (400, 407), False, 'import matplotlib\n'), ((5594, 5646), 'pandas.api.extensions.register_series_accessor', 'pd.api.extensions.register_series_accessor', (['"""foldit"""'], {}), "('foldit')\n", (5636, 5646), True, 'import pandas as pd\n'), ((6597, 6652), 'pandas.api.extensions.register_dataframe_accessor', 'pd.api.extensions.register_dataframe_accessor', (['"""foldit"""'], {}), "('foldit')\n", (6642, 6652), True, 'import pandas as pd\n'), ((14076, 14089), 'numpy.array', 'np.array', (['raw'], {}), '(raw)\n', (14084, 14089), True, 'import numpy as np\n'), ((14215, 14229), 'numpy.dot', 'np.dot', (['X.T', 'Y'], {}), '(X.T, Y)\n', (14221, 14229), True, 'import numpy as np\n'), ((14245, 14261), 'numpy.linalg.svd', 'np.linalg.svd', (['R'], {}), '(R)\n', (14258, 14261), True, 'import numpy as np\n'), ((14385, 14398), 'numpy.dot', 'np.dot', (['V', 'Wt'], {}), '(V, Wt)\n', (14391, 14398), True, 'import numpy as np\n'), ((14408, 14420), 'numpy.dot', 'np.dot', (['X', 'U'], {}), '(X, U)\n', (14414, 14420), True, 'import numpy as np\n'), ((14438, 14468), 'numpy.linalg.norm', 'np.linalg.norm', (['(Xp - Y)'], {'axis': '(1)'}), '(Xp - Y, axis=1)\n', (14452, 14468), True, 'import numpy as np\n'), ((26446, 26473), 'pandas.read_hdf', 'pd.read_hdf', (['datafile', '"""df"""'], {}), "(datafile, 'df')\n", (26457, 26473), True, 'import pandas as pd\n'), ((26484, 26512), 'pandas.read_hdf', 'pd.read_hdf', (['datafile', '"""bts"""'], {}), "(datafile, 'bts')\n", (26495, 26512), True, 'import pandas as pd\n'), ((26632, 26655), 'logging.debug', 'logging.debug', (['datafile'], {}), '(datafile)\n', (26645, 26655), False, 'import logging\n'), ((9203, 9221), 'csv.DictReader', 'csv.DictReader', (['fp'], {}), '(fp)\n', (9217, 9221), False, 'import os, pickle, csv, json\n'), ((11456, 11474), 'csv.DictReader', 'csv.DictReader', (['fp'], {}), '(fp)\n', (11470, 11474), False, 'import os, pickle, csv, json\n'), ((11759, 11772), 'json.load', 'json.load', (['fp'], {}), '(fp)\n', (11768, 11772), False, 'import os, pickle, csv, json\n'), ((12197, 12216), 'pickle.load', 'pickle.load', (['pdb_fp'], {}), '(pdb_fp)\n', (12208, 12216), False, 'import os, pickle, csv, json\n'), ((12801, 12839), 'scipy.stats.ttest_ind', 'stats.ttest_ind', (['a', 'b'], {'equal_var': '(False)'}), '(a, b, equal_var=False)\n', (12816, 12839), False, 'from scipy import stats\n'), ((13969, 13987), 'numpy.array', 'np.array', (['raw[:-1]'], {}), '(raw[:-1])\n', (13977, 13987), True, 'import numpy as np\n'), ((15159, 15183), 'numpy.dot', 'np.dot', (['X.T', '(weights * Y)'], {}), '(X.T, weights * Y)\n', (15165, 15183), True, 'import numpy as np\n'), ((15203, 15219), 'numpy.linalg.svd', 'np.linalg.svd', (['R'], {}), '(R)\n', (15216, 15219), True, 'import numpy as np\n'), ((15363, 15376), 'numpy.dot', 'np.dot', (['V', 'Wt'], {}), '(V, Wt)\n', (15369, 15376), True, 'import numpy as np\n'), ((15390, 15402), 'numpy.dot', 'np.dot', (['X', 'U'], {}), '(X, U)\n', (15396, 15402), True, 'import numpy as np\n'), ((15424, 15454), 'numpy.linalg.norm', 'np.linalg.norm', (['(Xp - Y)'], {'axis': '(1)'}), '(Xp - Y, axis=1)\n', (15438, 15454), True, 'import numpy as np\n'), ((15553, 15581), 'numpy.percentile', 'np.percentile', (['deviations', 'p'], {}), '(deviations, p)\n', (15566, 15581), True, 'import numpy as np\n'), ((22856, 22945), 'numpy.concatenate', 'np.concatenate', (['(ts_aligned[:ses2.start], ts_aligned[ses2.start:] - adjustment + 900)'], {}), '((ts_aligned[:ses2.start], ts_aligned[ses2.start:] -\n adjustment + 900))\n', (22870, 22945), True, 'import numpy as np\n'), ((24161, 24191), 'os.path.exists', 'os.path.exists', (['tmp_input_name'], {}), '(tmp_input_name)\n', (24175, 24191), False, 'import os, pickle, csv, json\n'), ((24201, 24228), 'os.makedirs', 'os.makedirs', (['tmp_input_name'], {}), '(tmp_input_name)\n', (24212, 24228), False, 'import os, pickle, csv, json\n'), ((25532, 25561), 'subprocess.run', 'subprocess.run', (["['rm', fname]"], {}), "(['rm', fname])\n", (25546, 25561), False, 'import subprocess\n'), ((26732, 26799), 'itertools.takewhile', 'takewhile', (["(lambda x: x['header']['uid'] == soln.uid)", 'soln.pdl[::-1]'], {}), "(lambda x: x['header']['uid'] == soln.uid, soln.pdl[::-1])\n", (26741, 26799), False, 'from itertools import product, groupby, takewhile\n'), ((12357, 12390), 'itertools.groupby', 'groupby', (['pdbs', "(lambda p: p['PID'])"], {}), "(pdbs, lambda p: p['PID'])\n", (12364, 12390), False, 'from itertools import product, groupby, takewhile\n'), ((12885, 12896), 'numpy.array', 'np.array', (['a'], {}), '(a)\n', (12893, 12896), True, 'import numpy as np\n'), ((12898, 12909), 'numpy.array', 'np.array', (['b'], {}), '(b)\n', (12906, 12909), True, 'import numpy as np\n'), ((14271, 14287), 'numpy.linalg.det', 'np.linalg.det', (['V'], {}), '(V)\n', (14284, 14287), True, 'import numpy as np\n'), ((14290, 14307), 'numpy.linalg.det', 'np.linalg.det', (['Wt'], {}), '(Wt)\n', (14303, 14307), True, 'import numpy as np\n'), ((21460, 21475), 'numpy.arange', 'np.arange', (['s', 'e'], {}), '(s, e)\n', (21469, 21475), True, 'import numpy as np\n'), ((24731, 24758), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (24756, 24758), False, 'import multiprocessing\n'), ((26523, 26551), 'pandas.read_hdf', 'pd.read_hdf', (['datafile', '"""puz"""'], {}), "(datafile, 'puz')\n", (26534, 26551), True, 'import pandas as pd\n'), ((15233, 15249), 'numpy.linalg.det', 'np.linalg.det', (['V'], {}), '(V)\n', (15246, 15249), True, 'import numpy as np\n'), ((15252, 15269), 'numpy.linalg.det', 'np.linalg.det', (['Wt'], {}), '(Wt)\n', (15265, 15269), True, 'import numpy as np\n'), ((15600, 15634), 'numpy.exp', 'np.exp', (['(-deviations ** 2 / dp ** 2)'], {}), '(-deviations ** 2 / dp ** 2)\n', (15606, 15634), True, 'import numpy as np\n'), ((22954, 22973), 'numpy.diff', 'np.diff', (['ts_aligned'], {}), '(ts_aligned)\n', (22961, 22973), True, 'import numpy as np\n'), ((24820, 24847), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (24845, 24847), False, 'import multiprocessing\n'), ((25279, 25379), 'subprocess.Popen', 'subprocess.Popen', (["['./tmscore_batch.zsh', input_name]"], {'stdout': 'subprocess.PIPE', 'encoding': '"""utf-8"""'}), "(['./tmscore_batch.zsh', input_name], stdout=subprocess.\n PIPE, encoding='utf-8')\n", (25295, 25379), False, 'import subprocess\n'), ((13073, 13086), 'itertools.product', 'product', (['a', 'b'], {}), '(a, b)\n', (13080, 13086), False, 'from itertools import product, groupby, takewhile\n'), ((13144, 13157), 'itertools.product', 'product', (['a', 'b'], {}), '(a, b)\n', (13151, 13157), False, 'from itertools import product, groupby, takewhile\n'), ((13355, 13365), 'numpy.mean', 'np.mean', (['a'], {}), '(a)\n', (13362, 13365), True, 'import numpy as np\n'), ((13367, 13379), 'numpy.median', 'np.median', (['a'], {}), '(a)\n', (13376, 13379), True, 'import numpy as np\n'), ((13381, 13390), 'numpy.std', 'np.std', (['a'], {}), '(a)\n', (13387, 13390), True, 'import numpy as np\n'), ((13475, 13485), 'numpy.mean', 'np.mean', (['b'], {}), '(b)\n', (13482, 13485), True, 'import numpy as np\n'), ((13487, 13499), 'numpy.median', 'np.median', (['b'], {}), '(b)\n', (13496, 13499), True, 'import numpy as np\n'), ((13501, 13510), 'numpy.std', 'np.std', (['b'], {}), '(b)\n', (13507, 13510), True, 'import numpy as np\n')]
import os import tempfile import shutil import argparse import networkx as nx from tqdm import tqdm from joblib import Parallel, delayed from collections import defaultdict, Counter import math import numpy as np from .isvalid import * from .__init__ import __version__ from .cdhit import run_cdhit from .clean_network import collapse_families, collapse_paralogs from .generate_output import * def make_list(inp): if not type(inp) == list: inp = [inp] return inp def load_graphs(graph_files, n_cpu=1): graphs = [] for graph_file in graph_files: if not os.path.isfile(graph_file): print("Missing:", graph_file) raise RuntimeError("Missing graph file!") graphs = [nx.read_gml(graph_file) for graph_file in tqdm(graph_files)] return graphs def cluster_centroids(graphs, outdir, len_dif_percent=0.95, identity_threshold=0.95, n_cpu=1): # create the files we will need temp_input_file = tempfile.NamedTemporaryFile(delete=False, dir=outdir) temp_input_file.close() temp_output_file = tempfile.NamedTemporaryFile(delete=False, dir=outdir) temp_output_file.close() # create input for cdhit with open(temp_input_file.name, 'w') as outfile: for i, G in enumerate(graphs): for node in G.nodes(): outfile.write(">" + str(i) + "_" + node + '\n') seqs = G.nodes[node]["protein"].split(";") seqs = [s for s in seqs if "*" not in s] outfile.write(max(seqs, key=len) + "\n") # Run cd-hit run_cdhit(temp_input_file.name, temp_output_file.name, id=identity_threshold, s=len_dif_percent, accurate=True, n_cpu=n_cpu) # Process output clusters = [] with open(temp_output_file.name + ".clstr", 'rU') as infile: c = [] for line in infile: if line[0] == ">": clusters.append(c) c = [] else: temp = line.split(">")[1].split("...")[0].split("_") centroid = (int(temp[0]), temp[1]) c.append(centroid) clusters.append(c) clusters = clusters[1:] # remove temporary files os.remove(temp_input_file.name) os.remove(temp_output_file.name) os.remove(temp_output_file.name + ".clstr") # need to add new centroidsssss!!! return clusters def simple_merge_graphs(graphs, clusters): # Here, we only merge nodes that don't conflict # first rename each graphs nodes in preperation for merge # get mapping mapping = defaultdict(dict) nnodes = 0 reverse_mapping = defaultdict(list) merge_centroids = {} centroid_context = defaultdict(list) for c, cluster in enumerate(clusters): c = str(c) nnodes += 1 graph_clust_count = Counter() for n in cluster: graph_clust_count[n[0]] += 1 non_conflicting_nodes = [ n for n in cluster if graph_clust_count[n[0]] < 2 ] conflicting_nodes = [n for n in cluster if graph_clust_count[n[0]] > 1] for n in non_conflicting_nodes: mapping[n[0]][n[1]] = nnodes merge_centroids[nnodes] = c reverse_mapping[nnodes].append((n[0], nnodes)) for n in conflicting_nodes: nnodes += 1 mapping[n[0]][n[1]] = nnodes merge_centroids[nnodes] = c centroid_context[c].append([nnodes, n[0]]) reverse_mapping[nnodes].append((n[0], nnodes)) # rename for i, G in enumerate(graphs): nx.relabel_nodes(G, mapping[i], copy=False) # merge graphs merged_G = nx.compose_all(graphs) # fix up node attributes for node in merged_G.nodes(): size = 0 members = set() lengths = [] centroid = [] seqIDs = set() protein = [] dna = [] annotation = [] description = [] paralog = False hasEnd = False mergedDNA = False for prev in reverse_mapping[node]: size += graphs[prev[0]].nodes[prev[1]]['size'] members |= set([ str(prev[0]) + "_" + str(m) for m in make_list(graphs[prev[0]].nodes[prev[1]]['members']) ]) lengths += make_list(graphs[prev[0]].nodes[prev[1]]['lengths']) centroid += [ str(prev[0]) + "_" + str(m) for m in make_list(graphs[ prev[0]].nodes[prev[1]]['centroid'].split(";")) ] seqIDs |= set([ str(prev[0]) + "_" + d for d in make_list(graphs[prev[0]].nodes[prev[1]]['seqIDs']) ]) protein += make_list( graphs[prev[0]].nodes[prev[1]]['protein'].split(";")) dna += make_list(graphs[prev[0]].nodes[prev[1]]['dna'].split(";")) annotation += make_list( graphs[prev[0]].nodes[prev[1]]['annotation']) description += make_list( graphs[prev[0]].nodes[prev[1]]['description']) paralog = (paralog or graphs[prev[0]].nodes[prev[1]]['paralog']) hasEnd = (paralog or graphs[prev[0]].nodes[prev[1]]['hasEnd']) mergedDNA = (paralog or graphs[prev[0]].nodes[prev[1]]['mergedDNA']) merged_G.nodes[node]['size'] = size merged_G.nodes[node]['members'] = set(members) merged_G.nodes[node]['lengths'] = lengths merged_G.nodes[node]['prevCentroids'] = str( merge_centroids[node]) #";".join(centroid) merged_G.nodes[node]['seqIDs'] = set(seqIDs) merged_G.nodes[node]['hasEnd'] = hasEnd merged_G.nodes[node]['dna'] = [max(dna, key=len)] merged_G.nodes[node]['protein'] = [max(protein, key=len)] merged_G.nodes[node]['annotation'] = ";".join(annotation) merged_G.nodes[node]['description'] = ";".join(description) merged_G.nodes[node]['paralog'] = paralog merged_G.nodes[node]['mergedDNA'] = mergedDNA merged_G.nodes[node]['centroid'] = [str(merge_centroids[node])] # fix longcentroid if len(merged_G.nodes[node]['centroid']) != len( merged_G.nodes[node]['protein']): print(merged_G.nodes[node]['protein']) print(merged_G.nodes[node]['centroid']) raise RuntimeError("protein/centroid count mismatch!") for node in merged_G.nodes(): merged_G.nodes[node]['longCentroidID'] = max([ (len(s), sid) for s, sid in zip(merged_G.nodes[node]['protein'], merged_G.nodes[node]['centroid']) ]) merged_G.nodes[node]['maxLenId'] = max([ (len(s), index) for s, index in zip(merged_G.nodes[node]['dna'], range(len(merged_G.nodes[node]['dna']))) ])[1] # fix up edge attributes for edge in merged_G.edges(): merged_G[edge[0]][edge[1]]['weight'] = 0 merged_G[edge[0]][edge[1]]['members'] = set() for prev1 in reverse_mapping[edge[0]]: for prev2 in reverse_mapping[edge[1]]: if prev1[0] == prev2[0]: #same graph if graphs[prev1[0]].has_edge(prev1[1], prev2[1]): merged_G[edge[0]][edge[1]]['weight'] += 1 merged_G[edge[0]][edge[1]]['members'] |= set([ str(prev1[0]) + "_" + str(m) for m in graphs[ prev1[0]][prev1[1]][prev2[1]]['members'] ]) return merged_G, centroid_context def get_options(): import argparse description = 'Merge independent runs of Panaroo' parser = argparse.ArgumentParser(description=description, prog='panaroo_merge_graphs') io_opts = parser.add_argument_group('Input/output') io_opts.add_argument( "-d", "--directories", dest="directories", required=True, help="Location of seperate Panaroo output directories", nargs='+') io_opts.add_argument("-o", "--out_dir", dest="output_dir", required=True, help="location of a new output directory", type=lambda x: is_valid_folder(parser, x)) matching = parser.add_argument_group('Matching') matching.add_argument("-c", "--threshold", dest="id", help="sequence identity threshold (default=0.95)", default=0.95, type=float) matching.add_argument( "-f", "--family_threshold", dest="family_threshold", help="protein family sequence identity threshold (default=0.7)", default=0.7, type=float) matching.add_argument("--len_dif_percent", dest="len_dif_percent", help="length difference cutoff (default=0.95)", default=0.95, type=float) parser.add_argument( "--min_edge_support_sv", dest="min_edge_support_sv", help=( "minimum edge support required to call structural variants" + " in the presence/absence sv file (default=max(2, 0.01*n_samples))" ), type=int) # Other options parser.add_argument("-t", "--threads", dest="n_cpu", help="number of threads to use (default=1)", type=int, default=1) parser.add_argument("--verbose", dest="verbose", help="print additional output", action='store_true', default=False) parser.add_argument('--version', action='version', version='%(prog)s ' + __version__) args = parser.parse_args() return (args) def main(): args = get_options() # make sure trailing forward slash is present args.output_dir = os.path.join(args.output_dir, "") args.directories = [os.path.join(d, "") for d in args.directories] # Create temporary directory temp_dir = os.path.join(tempfile.mkdtemp(dir=args.output_dir), "") print( "Merging graphs is still under active development and may change frequently!" ) # Load graphs print("Loading graphs...") graphs = load_graphs([d + "final_graph.gml" for d in args.directories], n_cpu=args.n_cpu) # cluster centroids print("Clustering centroids...") clusters = cluster_centroids(graphs=graphs, outdir=temp_dir, len_dif_percent=args.len_dif_percent, identity_threshold=args.id, n_cpu=args.n_cpu) # perform initial merge print("Performing inital merge...") G, centroid_contexts = simple_merge_graphs(graphs, clusters) print("Number of nodes in merged graph: ", G.number_of_nodes()) # collapse gene families/paralogs at successively lower thresholds print("Collapsing paralogs...") G = collapse_paralogs(G, centroid_contexts) print("Collapsing at DNA...") G = collapse_families(G, outdir=temp_dir, dna_error_threshold=0.98, correct_mistranslations=True, n_cpu=args.n_cpu, quiet=(not args.verbose))[0] print("Collapsing at families...") G = collapse_families(G, outdir=temp_dir, family_threshold=args.family_threshold, correct_mistranslations=False, n_cpu=args.n_cpu, quiet=(not args.verbose))[0] print("Number of nodes in merged graph: ", G.number_of_nodes()) # Generate output print("Generating output...") # write out roary like gene_presence_absence.csv mems_to_isolates = {} for i, sub_G in enumerate(graphs): for j, iso in enumerate(sub_G.graph['isolateNames']): mems_to_isolates[str(i) + "_" + str(j)] = iso n_samples = len(mems_to_isolates) args.min_edge_support_sv = max(2, math.ceil(0.01 * n_samples)) # get original annotaiton IDs # get original annotaiton IDs, lengts and whether or # not an internal stop codon is present orig_ids = {} ids_len_stop = {} for i, d in enumerate(args.directories): with open(d + "gene_data.csv", 'r') as infile: next(infile) for line in infile: line = line.split(",") orig_ids[str(i) + "_" + line[2]] = line[3] ids_len_stop[str(i) + "_" + line[2]] = (len(line[4]), "*" in line[4][1:-3]) G = generate_roary_gene_presence_absence(G, mems_to_isolates=mems_to_isolates, orig_ids=orig_ids, ids_len_stop=ids_len_stop, output_dir=args.output_dir) # write pan genome reference fasta file generate_pan_genome_reference(G, output_dir=args.output_dir, split_paralogs=False) # write out common structural differences in a matrix format generate_common_struct_presence_absence( G, output_dir=args.output_dir, mems_to_isolates=mems_to_isolates, min_variant_support=args.min_edge_support_sv) # add helpful attributes and write out graph in GML format for node in G.nodes(): G.nodes[node]['size'] = len(G.nodes[node]['members']) G.nodes[node]['genomeIDs'] = ";".join(G.nodes[node]['members']) G.nodes[node]['members'] = list(G.nodes[node]['members']) G.nodes[node]['centroid'] = G.nodes[node]['prevCentroids'] del G.nodes[node]['prevCentroids'] G.nodes[node]['geneIDs'] = ";".join(G.nodes[node]['seqIDs']) G.nodes[node]['seqIDs'] = list(G.nodes[node]['seqIDs']) G.nodes[node]['degrees'] = G.degree[node] sub_graphs = list( set([m.split("_")[0] for m in G.nodes[node]['members']])) G.nodes[node]['subGraphs'] = ";".join(conv_list(sub_graphs)) for edge in G.edges(): G.edges[edge[0], edge[1]]['genomeIDs'] = ";".join(G.edges[edge[0], edge[1]]['members']) G.edges[edge[0], edge[1]]['members'] = list(G.edges[edge[0], edge[1]]['members']) sub_graphs = list( set([ m.split("_")[0] for m in G.edges[edge[0], edge[1]]['members'] ])) G.edges[edge[0], edge[1]]['subGraphs'] = ";".join(conv_list(sub_graphs)) nx.write_gml(G, args.output_dir + "merged_final_graph.gml") # remove temporary directory shutil.rmtree(temp_dir) return if __name__ == '__main__': main()
[ "networkx.relabel_nodes", "math.ceil", "argparse.ArgumentParser", "tqdm.tqdm", "os.path.join", "shutil.rmtree", "collections.Counter", "os.path.isfile", "networkx.write_gml", "collections.defaultdict", "tempfile.mkdtemp", "tempfile.NamedTemporaryFile", "networkx.read_gml", "networkx.compos...
[((1054, 1107), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', ([], {'delete': '(False)', 'dir': 'outdir'}), '(delete=False, dir=outdir)\n', (1081, 1107), False, 'import tempfile\n'), ((1159, 1212), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', ([], {'delete': '(False)', 'dir': 'outdir'}), '(delete=False, dir=outdir)\n', (1186, 1212), False, 'import tempfile\n'), ((2352, 2383), 'os.remove', 'os.remove', (['temp_input_file.name'], {}), '(temp_input_file.name)\n', (2361, 2383), False, 'import os\n'), ((2388, 2420), 'os.remove', 'os.remove', (['temp_output_file.name'], {}), '(temp_output_file.name)\n', (2397, 2420), False, 'import os\n'), ((2425, 2468), 'os.remove', 'os.remove', (["(temp_output_file.name + '.clstr')"], {}), "(temp_output_file.name + '.clstr')\n", (2434, 2468), False, 'import os\n'), ((2722, 2739), 'collections.defaultdict', 'defaultdict', (['dict'], {}), '(dict)\n', (2733, 2739), False, 'from collections import defaultdict, Counter\n'), ((2777, 2794), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (2788, 2794), False, 'from collections import defaultdict, Counter\n'), ((2844, 2861), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (2855, 2861), False, 'from collections import defaultdict, Counter\n'), ((3806, 3828), 'networkx.compose_all', 'nx.compose_all', (['graphs'], {}), '(graphs)\n', (3820, 3828), True, 'import networkx as nx\n'), ((7889, 7966), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'description', 'prog': '"""panaroo_merge_graphs"""'}), "(description=description, prog='panaroo_merge_graphs')\n", (7912, 7966), False, 'import argparse\n'), ((10410, 10443), 'os.path.join', 'os.path.join', (['args.output_dir', '""""""'], {}), "(args.output_dir, '')\n", (10422, 10443), False, 'import os\n'), ((15430, 15489), 'networkx.write_gml', 'nx.write_gml', (['G', "(args.output_dir + 'merged_final_graph.gml')"], {}), "(G, args.output_dir + 'merged_final_graph.gml')\n", (15442, 15489), True, 'import networkx as nx\n'), ((15528, 15551), 'shutil.rmtree', 'shutil.rmtree', (['temp_dir'], {}), '(temp_dir)\n', (15541, 15551), False, 'import shutil\n'), ((730, 753), 'networkx.read_gml', 'nx.read_gml', (['graph_file'], {}), '(graph_file)\n', (741, 753), True, 'import networkx as nx\n'), ((2972, 2981), 'collections.Counter', 'Counter', ([], {}), '()\n', (2979, 2981), False, 'from collections import defaultdict, Counter\n'), ((3727, 3770), 'networkx.relabel_nodes', 'nx.relabel_nodes', (['G', 'mapping[i]'], {'copy': '(False)'}), '(G, mapping[i], copy=False)\n', (3743, 3770), True, 'import networkx as nx\n'), ((10468, 10487), 'os.path.join', 'os.path.join', (['d', '""""""'], {}), "(d, '')\n", (10480, 10487), False, 'import os\n'), ((10577, 10614), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {'dir': 'args.output_dir'}), '(dir=args.output_dir)\n', (10593, 10614), False, 'import tempfile\n'), ((12684, 12711), 'math.ceil', 'math.ceil', (['(0.01 * n_samples)'], {}), '(0.01 * n_samples)\n', (12693, 12711), False, 'import math\n'), ((591, 617), 'os.path.isfile', 'os.path.isfile', (['graph_file'], {}), '(graph_file)\n', (605, 617), False, 'import os\n'), ((772, 789), 'tqdm.tqdm', 'tqdm', (['graph_files'], {}), '(graph_files)\n', (776, 789), False, 'from tqdm import tqdm\n')]
import os import re import yaml for root, dirs, files in os.walk("."): for file in files: njk = os.path.join(root, file) if njk.endswith(".njk"): with open(njk, "r") as file: lines = file.read().split("\n") if not(lines[0].startswith("---")): continue end = 1 while not(lines[end].startswith("---")): end += 1 meta = yaml.safe_load("\n".join(lines[1:end])) field = "ogDescription" if not(field in meta) or not("shortTitle" in meta): continue meta[field] = (meta["shortTitle"] + " is a famous and most played DOS game that now is available to play in browser. With virtual" + " mobile controls you also can play in " + meta["shortTitle"] + " on mobile. On DOS.Zone " + meta["shortTitle"] + " available to play for free without registration.") meta = yaml.dump(meta, default_flow_style=False, allow_unicode=True) lines = [lines[0]] + meta.split("\n") + lines[end:] with open(njk, "w") as file: file.write("\n".join(lines))
[ "os.path.join", "os.walk", "yaml.dump" ]
[((58, 70), 'os.walk', 'os.walk', (['"""."""'], {}), "('.')\n", (65, 70), False, 'import os\n'), ((109, 133), 'os.path.join', 'os.path.join', (['root', 'file'], {}), '(root, file)\n', (121, 133), False, 'import os\n'), ((1022, 1083), 'yaml.dump', 'yaml.dump', (['meta'], {'default_flow_style': '(False)', 'allow_unicode': '(True)'}), '(meta, default_flow_style=False, allow_unicode=True)\n', (1031, 1083), False, 'import yaml\n')]
# project libraries imports: # instruments: from GenericScript import TestScript class Test(TestScript): def __init__(self): TestScript.__init__(self) self.Name = 'Modulated photocurrent frequency spectrum' self.Description = """Measurement of the modulation frequency spectrum of photocurrent""" return def init_parameters(self): """ create the list of the parameter and initialize some basic values """ #voltages, acquizDelay=0.1, voltStepDelay=5 self.generate_parameter(Name='Tested wavelength', Unit='nm', Type='float', Iterable = False, Limits = [ 1200, 200, None], Description='Wavelengths to irradiate the sample with') self.set_parameter_value('Tested wavelength', 800) self.generate_parameter(Name='Tested frequencies', Unit='Hz', Type='float', Iterable = True, Limits = [ 1e5, 0.01, None], Description='Light chopper modulation frequencies') #self.set_parameter_value('Tested frequencies', 64) self.generate_parameter(Name='Lamp voltage', Unit='Volts', Type='float', Iterable = False, Limits = [ 20, 0.0, None], Description='Voltage to be applied to the light source (Tungsten Lamp, or LED)') self.set_parameter_value('Lamp voltage', 20.0) self.generate_parameter(Name='Lamp voltage offset', Unit='Volts', Type='float', Iterable = False, Limits = [ 5, 0.0, None], Description='Offset voltage to be applied to the LED light source in case of Agilent Waveform generator is used') self.set_parameter_value('Lamp voltage offset', 0.0) self.generate_parameter(Name='Acquisition delay', Unit='Seconds', Type='float', Iterable = False, Limits = [ None, None, [0.01, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0]], Description='delay of the data acquizition loop in seconds') self.set_parameter_value('Acquisition delay', 2.0) self.generate_parameter(Name='Settle time frequency', Unit='Seconds', Type='float', Iterable = False, Limits = [ None, 0.001, None], Description='Delay to settle signal at each frequency in seconds') self.set_parameter_value('Settle time frequency', 5.0) self.generate_parameter(Name='Settle time DC volts', Unit='Seconds', Type='float', Iterable = False, Limits = [ None, 0.001, None], Description='Delay before the irradiation starts, with applied voltage to settle the current (in seconds)') self.set_parameter_value('Settle time DC volts', 5.0) self.generate_parameter(Name='DC voltage', Unit='Volts', Type='float', Iterable = False, Limits = [ 10.5, -10.5, None], Description='DC voltage to be applied to the sample from AUX OUT 1 of the LockIn Apmlifier') self.set_parameter_value('DC voltage', 0.0) self.generate_parameter(Name='Chopper device', Unit='', Type='name', Iterable = False, Limits = [ None, None, ['Wheel chopper SR530','Agilent 33220A Waveform generator']], Description="""Device to provide modulation of irradiation. In case of Wheel chopper, the wavelength will be adjusted by monochromator and chopper frequency will be adjusted by LockIn AUX OUT 2 (0.6 - 10.5 V) connected to the control voltage input of the wheel controler. In case of Agilent 33220A Waveform generator, the set frequencies will be selected on the output terminal of the device, e.g. to feed LED""") self.set_parameter_value('Chopper device', 'Wheel chopper SR530') return def init_devices(self): from Devices import Clock, Thermometer, PowerSource,\ Monochromator, LockIn,\ HamamatsuPhotodiode, GeneratorSquare self.Channel = LockIn() self.append_active_devices_list(self.Channel) deviceName = self.get_parameter_value('Chopper device') if deviceName == 'Wheel chopper SR530': self.Filter = Monochromator() self.append_active_devices_list(self.Filter) self.Lamp = PowerSource() self.append_active_devices_list(self.Lamp) if deviceName == 'Agilent 33220A Waveform generator': self.Filter = Monochromator() self.append_active_devices_list(self.Filter) self.Chopper = GeneratorSquare() self.append_active_devices_list(self.Chopper) #from instruments.Keithley import Electrometer617 #from instruments.Agilent import A34401_4ohm ################################################################ ## Here begins the initialization of devices ################## ################################################################ # define and ACTIVATE the instruments #PeltierP = PID_CBdriver(TCchannel=1, count=20) #PeltierP.Activate() self.LightMeter = HamamatsuPhotodiode() self.append_active_devices_list(self.LightMeter) self.Stopwatch = Clock() self.append_active_devices_list(self.Stopwatch) self.Temper = Thermometer() self.append_active_devices_list(self.Temper) def _run(self): """ simple current-voltage characteristics measurement """ ################################################################ ## Here begins the experimetal part ########################### ################################################################ deviceName = self.get_parameter_value('Chopper device') Wavelength = self.get_parameter_value('Tested wavelength') Frequencies = self.get_parameter_value('Tested frequencies') DCvoltage = self.get_parameter_value('DC voltage') LampVolt = self.get_parameter_value('Lamp voltage') LampOffset = self.get_parameter_value('Lamp voltage offset') WaitDC = self.get_parameter_value('Settle time DC volts') WaitWL = self.get_parameter_value('Settle time frequency') WaitDAQ = self.get_parameter_value('Acquisition delay') # parameters for recalcualtion of the frequencies to the voltages: WheelChopperVoltageCoeff = 0.005 WheelChopperVoltageOffset = 0.0 self.datastore.report('Using device "%(device)s" for modulation' % \ {'device':deviceName}) # initializing the measurement for given instrument: if deviceName == 'Wheel chopper SR530': self.Filter.close_shutter() self.Filter.set_wave(Wavelength) self.Lamp.set_volts(LampVolt) self.Lamp.set_amperes_limit(10) self.Lamp.set_output_on() # calculate the voltages set to regulate frequencies self.Channel.set_aux_output(2, 1.0) self.Filter.open_shutter() self.Stopwatch.Wait(3) # initializing the measurement for given instrument: if deviceName == 'Agilent 33220A Waveform generator': self.Filter.close_shutter() self.Filter.set_wave(Wavelength) self.Chopper.set_duty_cycle(50) self.Chopper.set_freq(1000) LEDamplitude = LampVolt - LampOffset LEDoffset = LampOffset self.Chopper.set_amplitude_vrms(LEDamplitude) self.Chopper.set_offset(LEDoffset) self.Chopper.set_output_on() self.Filter.open_shutter() self.Stopwatch.Wait(3) # apply DC voltage to the sample and # measure during 1kHz irradiation self.datastore.report('Stabilizing the DC voltage at the sample, irradiation modulation at 1 kHz' ) self.Channel.set_aux_output(channel=1, voltage=DCvoltage) self.datastore.report('Irradiation wavelength %0.1f nm' % Wavelength ) self.observe(WaitDC,WaitDAQ) #self.datastore.report ('estimation of LockIn amplifier gain for desired Frequencies:') self.datastore.report('Starting the modulated photocurrent spectra measurement from %(from)f to %(to)f Hz' % \ {'from':Frequencies[0], 'to':Frequencies[-1]}) self.datastore.report ('Starting Frequency scanning:') for freq in Frequencies: if deviceName == 'Wheel chopper SR530': ChopperVoltage = freq * WheelChopperVoltageCoeff + WheelChopperVoltageOffset self.Channel.set_aux_output(channel=2, voltage=ChopperVoltage) if deviceName == 'Agilent 33220A Waveform generator': self.Chopper.set_freq(freq) self.Stopwatch.Wait(0.1) self.datastore.report ('Set New frequency: %0.1f' % freq) if freq > 9.99: gain = self.Channel.auto_gain() self.datastore.report('Found new Lock-In Amplifier GAIN: %d' % gain) else: gain = self.Channel.get_gain() self.datastore.report('Kept old Lock-In Amplifier GAIN: %d' % gain) minimumWait = WaitWL + 10/freq self.observe(WaitWL, WaitDAQ) self.datastore.separateData() self.datastore.report ('Experiment finished') self.Channel.set_aux_output(channel=1, voltage=0.0) if deviceName == 'Wheel chopper SR530': #self.Lamp.set_output_off() #self.Filter.close_shutter() self.Channel.set_aux_output(channel=2, voltage=1.0) if deviceName == 'Agilent 33220A Waveform generator': #self.Chopper.set_output_off() pass #self.datastore.report('finished the Modulated frequency photocurrent spectrum measurement') return from AllScripts import ScriptsBase ScriptsBase.add_script(Test, 'Photoconductivity')
[ "Devices.Thermometer", "Devices.Monochromator", "GenericScript.TestScript.__init__", "AllScripts.ScriptsBase.add_script", "Devices.LockIn", "Devices.PowerSource", "Devices.Clock", "Devices.HamamatsuPhotodiode", "Devices.GeneratorSquare" ]
[((11413, 11462), 'AllScripts.ScriptsBase.add_script', 'ScriptsBase.add_script', (['Test', '"""Photoconductivity"""'], {}), "(Test, 'Photoconductivity')\n", (11435, 11462), False, 'from AllScripts import ScriptsBase\n'), ((138, 163), 'GenericScript.TestScript.__init__', 'TestScript.__init__', (['self'], {}), '(self)\n', (157, 163), False, 'from GenericScript import TestScript\n'), ((5412, 5420), 'Devices.LockIn', 'LockIn', ([], {}), '()\n', (5418, 5420), False, 'from Devices import Clock, Thermometer, PowerSource, Monochromator, LockIn, HamamatsuPhotodiode, GeneratorSquare\n'), ((6549, 6570), 'Devices.HamamatsuPhotodiode', 'HamamatsuPhotodiode', ([], {}), '()\n', (6568, 6570), False, 'from Devices import Clock, Thermometer, PowerSource, Monochromator, LockIn, HamamatsuPhotodiode, GeneratorSquare\n'), ((6653, 6660), 'Devices.Clock', 'Clock', ([], {}), '()\n', (6658, 6660), False, 'from Devices import Clock, Thermometer, PowerSource, Monochromator, LockIn, HamamatsuPhotodiode, GeneratorSquare\n'), ((6739, 6752), 'Devices.Thermometer', 'Thermometer', ([], {}), '()\n', (6750, 6752), False, 'from Devices import Clock, Thermometer, PowerSource, Monochromator, LockIn, HamamatsuPhotodiode, GeneratorSquare\n'), ((5622, 5637), 'Devices.Monochromator', 'Monochromator', ([], {}), '()\n', (5635, 5637), False, 'from Devices import Clock, Thermometer, PowerSource, Monochromator, LockIn, HamamatsuPhotodiode, GeneratorSquare\n'), ((5719, 5732), 'Devices.PowerSource', 'PowerSource', ([], {}), '()\n', (5730, 5732), False, 'from Devices import Clock, Thermometer, PowerSource, Monochromator, LockIn, HamamatsuPhotodiode, GeneratorSquare\n'), ((5876, 5891), 'Devices.Monochromator', 'Monochromator', ([], {}), '()\n', (5889, 5891), False, 'from Devices import Clock, Thermometer, PowerSource, Monochromator, LockIn, HamamatsuPhotodiode, GeneratorSquare\n'), ((5976, 5993), 'Devices.GeneratorSquare', 'GeneratorSquare', ([], {}), '()\n', (5991, 5993), False, 'from Devices import Clock, Thermometer, PowerSource, Monochromator, LockIn, HamamatsuPhotodiode, GeneratorSquare\n')]
from django.conf import settings from django.contrib.sites.models import Site from django.db import models from django.utils.translation import pgettext_lazy from .constants import REDIRECT_TYPE_CHOICES, REDIRECT_301 from .fields import MultipleChoiceArrayField __all__ = ( 'Redirect', ) LANGUAGES = getattr(settings, 'LANGUAGES', []) class Redirect(models.Model): site = models.ForeignKey( Site, models.CASCADE, verbose_name=pgettext_lazy("ok:redirects", 'site') ) old_path = models.CharField( pgettext_lazy("ok:redirects", 'redirect from'), max_length=250, db_index=True, help_text=pgettext_lazy( "ok:redirects", "This should be an absolute path, " "excluding the domain name. Example: '/events/search/'." ), ) languages = MultipleChoiceArrayField( models.CharField( max_length=2, choices=LANGUAGES, blank=True ), blank=True, default=[lang[0] for lang in LANGUAGES] if LANGUAGES else list, verbose_name=pgettext_lazy("ok:redirects", "Languages to check redirect") ) is_ignore_get_params = models.BooleanField( pgettext_lazy("ok:redirects", 'Ignore GET parameters'), default=True ) new_path = models.CharField( pgettext_lazy("ok:redirects", 'redirect to'), blank=True, max_length=250, help_text=pgettext_lazy( "ok:redirects", "This can be either an absolute path (as above) " "or a full URL starting with 'http://'." ), ) to_language = models.CharField( pgettext_lazy("ok:redirects", 'to language'), blank=True, choices=LANGUAGES, max_length=5, help_text=pgettext_lazy( "ok:redirects", "Leave blank to redirect to the current language on the site" ), ) status_code = models.PositiveSmallIntegerField( db_index=True, choices=REDIRECT_TYPE_CHOICES, default=REDIRECT_301, verbose_name=pgettext_lazy("ok:redirects", 'Status code'), help_text=pgettext_lazy( "ok:redirects", 'The redirect http status code.' ) ) counter = models.PositiveIntegerField( blank=True, default=0, verbose_name=pgettext_lazy("ok:redirects", 'Counter'), ) is_active = models.BooleanField( pgettext_lazy("ok:redirects", 'Is active'), default=True, db_index=True, ) class Meta: db_table = 'ok_redirects' ordering = ('old_path',) unique_together = (('site', 'old_path'),) verbose_name = pgettext_lazy("ok:redirects", 'redirect') verbose_name_plural = pgettext_lazy("ok:redirects", 'redirects') def __str__(self): return ( f"{pgettext_lazy('ok:redirects', 'Redirect')} " f"{self.status_code}: " f"`{self.old_path}` ---> `{self.new_path}`" )
[ "django.db.models.CharField", "django.utils.translation.pgettext_lazy" ]
[((548, 594), 'django.utils.translation.pgettext_lazy', 'pgettext_lazy', (['"""ok:redirects"""', '"""redirect from"""'], {}), "('ok:redirects', 'redirect from')\n", (561, 594), False, 'from django.utils.translation import pgettext_lazy\n'), ((888, 949), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(2)', 'choices': 'LANGUAGES', 'blank': '(True)'}), '(max_length=2, choices=LANGUAGES, blank=True)\n', (904, 949), False, 'from django.db import models\n'), ((1233, 1287), 'django.utils.translation.pgettext_lazy', 'pgettext_lazy', (['"""ok:redirects"""', '"""Ignore GET parameters"""'], {}), "('ok:redirects', 'Ignore GET parameters')\n", (1246, 1287), False, 'from django.utils.translation import pgettext_lazy\n'), ((1357, 1401), 'django.utils.translation.pgettext_lazy', 'pgettext_lazy', (['"""ok:redirects"""', '"""redirect to"""'], {}), "('ok:redirects', 'redirect to')\n", (1370, 1401), False, 'from django.utils.translation import pgettext_lazy\n'), ((1684, 1728), 'django.utils.translation.pgettext_lazy', 'pgettext_lazy', (['"""ok:redirects"""', '"""to language"""'], {}), "('ok:redirects', 'to language')\n", (1697, 1728), False, 'from django.utils.translation import pgettext_lazy\n'), ((2480, 2522), 'django.utils.translation.pgettext_lazy', 'pgettext_lazy', (['"""ok:redirects"""', '"""Is active"""'], {}), "('ok:redirects', 'Is active')\n", (2493, 2522), False, 'from django.utils.translation import pgettext_lazy\n'), ((2732, 2773), 'django.utils.translation.pgettext_lazy', 'pgettext_lazy', (['"""ok:redirects"""', '"""redirect"""'], {}), "('ok:redirects', 'redirect')\n", (2745, 2773), False, 'from django.utils.translation import pgettext_lazy\n'), ((2804, 2846), 'django.utils.translation.pgettext_lazy', 'pgettext_lazy', (['"""ok:redirects"""', '"""redirects"""'], {}), "('ok:redirects', 'redirects')\n", (2817, 2846), False, 'from django.utils.translation import pgettext_lazy\n'), ((463, 500), 'django.utils.translation.pgettext_lazy', 'pgettext_lazy', (['"""ok:redirects"""', '"""site"""'], {}), "('ok:redirects', 'site')\n", (476, 500), False, 'from django.utils.translation import pgettext_lazy\n'), ((661, 790), 'django.utils.translation.pgettext_lazy', 'pgettext_lazy', (['"""ok:redirects"""', '"""This should be an absolute path, excluding the domain name. Example: \'/events/search/\'."""'], {}), '(\'ok:redirects\',\n "This should be an absolute path, excluding the domain name. Example: \'/events/search/\'."\n )\n', (674, 790), False, 'from django.utils.translation import pgettext_lazy\n'), ((1110, 1170), 'django.utils.translation.pgettext_lazy', 'pgettext_lazy', (['"""ok:redirects"""', '"""Languages to check redirect"""'], {}), "('ok:redirects', 'Languages to check redirect')\n", (1123, 1170), False, 'from django.utils.translation import pgettext_lazy\n'), ((1465, 1592), 'django.utils.translation.pgettext_lazy', 'pgettext_lazy', (['"""ok:redirects"""', '"""This can be either an absolute path (as above) or a full URL starting with \'http://\'."""'], {}), '(\'ok:redirects\',\n "This can be either an absolute path (as above) or a full URL starting with \'http://\'."\n )\n', (1478, 1592), False, 'from django.utils.translation import pgettext_lazy\n'), ((1817, 1913), 'django.utils.translation.pgettext_lazy', 'pgettext_lazy', (['"""ok:redirects"""', '"""Leave blank to redirect to the current language on the site"""'], {}), "('ok:redirects',\n 'Leave blank to redirect to the current language on the site')\n", (1830, 1913), False, 'from django.utils.translation import pgettext_lazy\n'), ((2116, 2160), 'django.utils.translation.pgettext_lazy', 'pgettext_lazy', (['"""ok:redirects"""', '"""Status code"""'], {}), "('ok:redirects', 'Status code')\n", (2129, 2160), False, 'from django.utils.translation import pgettext_lazy\n'), ((2180, 2243), 'django.utils.translation.pgettext_lazy', 'pgettext_lazy', (['"""ok:redirects"""', '"""The redirect http status code."""'], {}), "('ok:redirects', 'The redirect http status code.')\n", (2193, 2243), False, 'from django.utils.translation import pgettext_lazy\n'), ((2387, 2427), 'django.utils.translation.pgettext_lazy', 'pgettext_lazy', (['"""ok:redirects"""', '"""Counter"""'], {}), "('ok:redirects', 'Counter')\n", (2400, 2427), False, 'from django.utils.translation import pgettext_lazy\n'), ((2903, 2944), 'django.utils.translation.pgettext_lazy', 'pgettext_lazy', (['"""ok:redirects"""', '"""Redirect"""'], {}), "('ok:redirects', 'Redirect')\n", (2916, 2944), False, 'from django.utils.translation import pgettext_lazy\n')]
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.2' # jupytext_version: 0.8.6 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %% {"slideshow": {"slide_type": "skip"}} # %load_ext autoreload # %autoreload 2 # %matplotlib inline # %% {"slideshow": {"slide_type": "skip"}} import os import sys from typing import Tuple from dataclasses import dataclass if '' in sys.path: sys.path.remove('') module_path = os.path.abspath(os.path.join('../python')) if module_path not in sys.path: sys.path.append(module_path) import networkx as nx from graphPlot import drawGraph, setCanvas from const import * setCanvas() # %% [markdown] {"slideshow": {"slide_type": "slide"}} # ## G-ConvNet # # $$f_+(y) = <A_{ug} \circ f(x), w_0(x)> _x$$ # # - this implies bijection/isomorphism $y \longleftrightarrow A_{ug}$ # - ... and high-level features usually have more dimensions $\{x\} \subset \{y\}$ # # --- # # All of the followings are concrete subclasses: # # # Augmentation types | Answer # --- | --- # 2d translation | ConvNet # **others** | **G-ConvNet** # - 2d translation + 90$^{\circ}$ rotation | Group Equivariant CNNs # - 2d translation + rotation | Harmonic Net # - 3d rotation | Spherical CNNs # - 3d translation + rotation | Tensor Field Net # # # %% [markdown] {"slideshow": {"slide_type": "slide"}} # ## ConvNet # # | - | Input $f(x)$ | High-level $f_+(y)$, $f_{++}(z)$, ... | Augmentation $A_{ug}$, $U_{ga}$, ... # | ---|---------------|----------------|------------------------------- # | domain | $R^2$ | $R^2$ | $R^2$ (translation only) # # --- # # - First of its kind but not the last # - A rare case when high-level feature domain $\{y\} = \{x\}$, in all other cases $\{y\} \supset \{x\}$ # # <img src="assets/alexnet.png"> # # %% [markdown] {"slideshow": {"slide_type": "slide"}} # ## ConvNet # %% {"slideshow": {"slide_type": "-"}} g = nx.DiGraph(directed=True) nodes = [ "$f: R^2$", "$f_+: R^2$", "$f_{++}: R^2$", "$f_{+++}: R^2$" ] for i in range(0, len(nodes) - 1): g.add_edge(nodes[i], nodes[i + 1], text="conv") drawGraph(g) plt.show() # %% [markdown] {"slideshow": {"slide_type": "slide"}} # ## Group Equivariant CNNs (ICML 2016*) # # | - | Input $f(x)$ | High-level $f_+(y)$, $f_{++}(z)$, ... | Augmentation $A_{ug}$, $U_{ga}$, ... # | --- |---|---|--- # | domain | $R^2$ | $R^2 \times p4$ | $R^2 \times p4$ (translation, rotation $\pm 90^{\circ}$) # # --- # # - change looks trivial # # <img src="assets/r2p4.png" width="500"> # # --- # # [*] <NAME> and <NAME>, “Group Equivariant Convolutional Networks,” ICML 2016. # %% [markdown] {"slideshow": {"slide_type": "slide"}} # ## Group Equivariant CNNs (ICML 2016*) # %% {"slideshow": {"slide_type": "-"}} g = nx.DiGraph(directed=True) tail = "$f: R^2$" angles = [-90, 0, 90, 180] def regularize(v: int) -> int: if v > 180: return regularize(v - 360) elif v <= -180: return regularize(v + 360) else: return v def repr(v: int) -> str: r = regularize(v) if r > 0: return f"+{str(r)}^{{\circ}}" else: return f"{str(r)}^{{\circ}}" sub = "+" subPlus = "" for i in angles: node = f"$f_{{{sub}}} | {repr(i)}$" g.add_edge(tail, node, text=f"${repr(i)}$") for epoch in range(1, 3): subPlus = f"{sub}+" for i in angles: for j in angles: prev = f"$f_{{{sub}}} | {repr(i)}$" node = f"$f_{{{subPlus}}} | {repr(j)}$" g.add_edge(prev, node, text=f"${repr(j - i)}$") sub = subPlus drawGraph(g, font='humor sans', label_pos=0.8) plt.show() # %% [markdown] {"slideshow": {"slide_type": "slide"}} # ## Group Equivariant CNNs (ICML 2016*) - Alternatively # # | - | Input $f(x)$ | High-level $f_+(y)$, $f_{++}(z)$, ... | Augmentation $A_{ug}$, $U_{ga}$, ... # | --- |---|---|--- # | domain | $R^2$ | $R^2 \times p4m$ | $R^2 \times p4m$ (translation, rotation $\pm 90^{\circ}$, flipping) # # --- # # - Size of filter bank start to become annoying, but still acceptable. # # <img src="assets/r2p4m.png" width="500"> # # --- # # [*] <NAME> and <NAME>, “Group Equivariant Convolutional Networks,” ICML 2016.
[ "networkx.DiGraph", "os.path.join", "graphPlot.setCanvas", "sys.path.remove", "sys.path.append", "graphPlot.drawGraph" ]
[((774, 785), 'graphPlot.setCanvas', 'setCanvas', ([], {}), '()\n', (783, 785), False, 'from graphPlot import drawGraph, setCanvas\n'), ((2042, 2067), 'networkx.DiGraph', 'nx.DiGraph', ([], {'directed': '(True)'}), '(directed=True)\n', (2052, 2067), True, 'import networkx as nx\n'), ((2246, 2258), 'graphPlot.drawGraph', 'drawGraph', (['g'], {}), '(g)\n', (2255, 2258), False, 'from graphPlot import drawGraph, setCanvas\n'), ((2898, 2923), 'networkx.DiGraph', 'nx.DiGraph', ([], {'directed': '(True)'}), '(directed=True)\n', (2908, 2923), True, 'import networkx as nx\n'), ((3692, 3738), 'graphPlot.drawGraph', 'drawGraph', (['g'], {'font': '"""humor sans"""', 'label_pos': '(0.8)'}), "(g, font='humor sans', label_pos=0.8)\n", (3701, 3738), False, 'from graphPlot import drawGraph, setCanvas\n'), ((543, 562), 'sys.path.remove', 'sys.path.remove', (['""""""'], {}), "('')\n", (558, 562), False, 'import sys\n'), ((594, 619), 'os.path.join', 'os.path.join', (['"""../python"""'], {}), "('../python')\n", (606, 619), False, 'import os\n'), ((657, 685), 'sys.path.append', 'sys.path.append', (['module_path'], {}), '(module_path)\n', (672, 685), False, 'import sys\n')]
from django.conf.urls import url, include from driver import views # from djgeojson.views import GeoJSONLayerView # from driver.models import Points urlpatterns = [ url(r'^new/driver$', views.create_driver_profile, name='new-driver-profile'), url(r'^new/car$', views.submit_car, name='new-car'), ]
[ "django.conf.urls.url" ]
[((170, 245), 'django.conf.urls.url', 'url', (['"""^new/driver$"""', 'views.create_driver_profile'], {'name': '"""new-driver-profile"""'}), "('^new/driver$', views.create_driver_profile, name='new-driver-profile')\n", (173, 245), False, 'from django.conf.urls import url, include\n'), ((252, 302), 'django.conf.urls.url', 'url', (['"""^new/car$"""', 'views.submit_car'], {'name': '"""new-car"""'}), "('^new/car$', views.submit_car, name='new-car')\n", (255, 302), False, 'from django.conf.urls import url, include\n')]
import numpy as np import tensorflow as tf from utils import fc_block from params import* class Model(): def __init__(self, input_dim=INPUT_DIM, output_dim=OUTPUT_DIM, dim_hidden=DIM_HIDDEN, latent_dim=LATENT_DIM, update_lr=LEARNING_RATE, scope='model'): self.input_dim = input_dim self.output_dim = 2 self.dim_hidden = dim_hidden self.latent_dim = latent_dim self.update_lr = update_lr self.scope = scope self.flag = 0 def construct_weights(self, scope=''): weights = {} weights['w1'] = tf.Variable(tf.random_normal([self.input_dim, 128], stddev=0.1), name=scope+'w1') weights['b1'] = tf.Variable(tf.zeros([128]), name=scope+'b1') weights['w2'] = tf.Variable(tf.random_normal([128, self.dim_hidden], stddev=0.1), name=scope+'w2') weights['b2'] = tf.Variable(tf.zeros([self.dim_hidden]), name=scope+'b2') weights['w5'] = tf.Variable(tf.random_normal([self.dim_hidden, self.dim_hidden], stddev=0.1), name=scope+'w5') weights['b5'] = tf.Variable(tf.zeros([self.dim_hidden]), name=scope+'b5') weights['w3'] = tf.Variable(tf.random_normal([self.dim_hidden, 64], stddev=0.1), name=scope+'w3') weights['b3'] = tf.Variable(tf.zeros([64]), name=scope+'b3') weights['w4'] = tf.Variable(tf.random_normal([64,self.output_dim], stddev=0.1), name=scope+'w4') return weights def forward(self, inp, weights, prob, reuse=False, scope='', is_training=True): hidden = fc_block(inp, weights['w1'], weights['b1'], prob, reuse, scope+'0', is_training=is_training) hidden = fc_block(hidden, weights['w2'], weights['b2'], prob, reuse, scope+'1', is_training=is_training) hidden = fc_block(hidden, weights['w5'], weights['b5'], prob, reuse, scope+'3', is_training=is_training) hidden = fc_block(hidden, weights['w3'], weights['b3'], prob, reuse, scope+'2', is_training=is_training) return tf.matmul(hidden, weights['w4']) def construct_model(self, input_var, target_var, prob, decay_lr, is_training): batch_size = tf.shape(input_var)[0] input_var = tf.one_hot(input_var, self.input_dim, axis=-1) input_var = tf.reduce_sum(input_var, axis=1) self.input_var = input_var with tf.variable_scope(self.scope, reuse=None) as training_scope: if 'weights' in dir(self): training_scope.reuse_variables() weights = self.weights else: self.weights = weights = self.construct_weights() if not 'check' in dir(self): self.check=1 self.forward(input_var, weights, prob, False) output = self.forward(input_var, weights, prob, True, is_training=is_training) self.output = tf.nn.softmax(output, axis=1) _, regularizer1 = tf.nn.moments(tf.expand_dims(output[:,1], axis=1), axes=0) self.loss = tf.reduce_mean(tf.losses.mean_squared_error(predictions=output, labels=target_var)) if self.flag == 0: self.op = tf.train.AdamOptimizer(decay_lr).minimize(self.loss + 0.5 - 0.5*tf.log(regularizer1+1e-1), var_list=weights) else: self.op = tf.train.AdamOptimizer(decay_lr).minimize(self.loss + 0.5 - 0.5*tf.log(regularizer1+1e-1), var_list=weights['w4','w3','b3'])
[ "tensorflow.one_hot", "tensorflow.random_normal", "utils.fc_block", "tensorflow.shape", "tensorflow.variable_scope", "tensorflow.reduce_sum", "tensorflow.matmul", "tensorflow.nn.softmax", "tensorflow.expand_dims", "tensorflow.train.AdamOptimizer", "tensorflow.losses.mean_squared_error", "tenso...
[((1553, 1651), 'utils.fc_block', 'fc_block', (['inp', "weights['w1']", "weights['b1']", 'prob', 'reuse', "(scope + '0')"], {'is_training': 'is_training'}), "(inp, weights['w1'], weights['b1'], prob, reuse, scope + '0',\n is_training=is_training)\n", (1561, 1651), False, 'from utils import fc_block\n'), ((1664, 1765), 'utils.fc_block', 'fc_block', (['hidden', "weights['w2']", "weights['b2']", 'prob', 'reuse', "(scope + '1')"], {'is_training': 'is_training'}), "(hidden, weights['w2'], weights['b2'], prob, reuse, scope + '1',\n is_training=is_training)\n", (1672, 1765), False, 'from utils import fc_block\n'), ((1778, 1879), 'utils.fc_block', 'fc_block', (['hidden', "weights['w5']", "weights['b5']", 'prob', 'reuse', "(scope + '3')"], {'is_training': 'is_training'}), "(hidden, weights['w5'], weights['b5'], prob, reuse, scope + '3',\n is_training=is_training)\n", (1786, 1879), False, 'from utils import fc_block\n'), ((1892, 1993), 'utils.fc_block', 'fc_block', (['hidden', "weights['w3']", "weights['b3']", 'prob', 'reuse', "(scope + '2')"], {'is_training': 'is_training'}), "(hidden, weights['w3'], weights['b3'], prob, reuse, scope + '2',\n is_training=is_training)\n", (1900, 1993), False, 'from utils import fc_block\n'), ((2004, 2036), 'tensorflow.matmul', 'tf.matmul', (['hidden', "weights['w4']"], {}), "(hidden, weights['w4'])\n", (2013, 2036), True, 'import tensorflow as tf\n'), ((2189, 2235), 'tensorflow.one_hot', 'tf.one_hot', (['input_var', 'self.input_dim'], {'axis': '(-1)'}), '(input_var, self.input_dim, axis=-1)\n', (2199, 2235), True, 'import tensorflow as tf\n'), ((2257, 2289), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['input_var'], {'axis': '(1)'}), '(input_var, axis=1)\n', (2270, 2289), True, 'import tensorflow as tf\n'), ((604, 655), 'tensorflow.random_normal', 'tf.random_normal', (['[self.input_dim, 128]'], {'stddev': '(0.1)'}), '([self.input_dim, 128], stddev=0.1)\n', (620, 655), True, 'import tensorflow as tf\n'), ((711, 726), 'tensorflow.zeros', 'tf.zeros', (['[128]'], {}), '([128])\n', (719, 726), True, 'import tensorflow as tf\n'), ((782, 834), 'tensorflow.random_normal', 'tf.random_normal', (['[128, self.dim_hidden]'], {'stddev': '(0.1)'}), '([128, self.dim_hidden], stddev=0.1)\n', (798, 834), True, 'import tensorflow as tf\n'), ((890, 917), 'tensorflow.zeros', 'tf.zeros', (['[self.dim_hidden]'], {}), '([self.dim_hidden])\n', (898, 917), True, 'import tensorflow as tf\n'), ((973, 1037), 'tensorflow.random_normal', 'tf.random_normal', (['[self.dim_hidden, self.dim_hidden]'], {'stddev': '(0.1)'}), '([self.dim_hidden, self.dim_hidden], stddev=0.1)\n', (989, 1037), True, 'import tensorflow as tf\n'), ((1093, 1120), 'tensorflow.zeros', 'tf.zeros', (['[self.dim_hidden]'], {}), '([self.dim_hidden])\n', (1101, 1120), True, 'import tensorflow as tf\n'), ((1176, 1227), 'tensorflow.random_normal', 'tf.random_normal', (['[self.dim_hidden, 64]'], {'stddev': '(0.1)'}), '([self.dim_hidden, 64], stddev=0.1)\n', (1192, 1227), True, 'import tensorflow as tf\n'), ((1283, 1297), 'tensorflow.zeros', 'tf.zeros', (['[64]'], {}), '([64])\n', (1291, 1297), True, 'import tensorflow as tf\n'), ((1353, 1404), 'tensorflow.random_normal', 'tf.random_normal', (['[64, self.output_dim]'], {'stddev': '(0.1)'}), '([64, self.output_dim], stddev=0.1)\n', (1369, 1404), True, 'import tensorflow as tf\n'), ((2145, 2164), 'tensorflow.shape', 'tf.shape', (['input_var'], {}), '(input_var)\n', (2153, 2164), True, 'import tensorflow as tf\n'), ((2342, 2383), 'tensorflow.variable_scope', 'tf.variable_scope', (['self.scope'], {'reuse': 'None'}), '(self.scope, reuse=None)\n', (2359, 2383), True, 'import tensorflow as tf\n'), ((2889, 2918), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['output'], {'axis': '(1)'}), '(output, axis=1)\n', (2902, 2918), True, 'import tensorflow as tf\n'), ((2964, 3000), 'tensorflow.expand_dims', 'tf.expand_dims', (['output[:, 1]'], {'axis': '(1)'}), '(output[:, 1], axis=1)\n', (2978, 3000), True, 'import tensorflow as tf\n'), ((3049, 3116), 'tensorflow.losses.mean_squared_error', 'tf.losses.mean_squared_error', ([], {'predictions': 'output', 'labels': 'target_var'}), '(predictions=output, labels=target_var)\n', (3077, 3116), True, 'import tensorflow as tf\n'), ((3177, 3209), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['decay_lr'], {}), '(decay_lr)\n', (3199, 3209), True, 'import tensorflow as tf\n'), ((3332, 3364), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['decay_lr'], {}), '(decay_lr)\n', (3354, 3364), True, 'import tensorflow as tf\n'), ((3241, 3267), 'tensorflow.log', 'tf.log', (['(regularizer1 + 0.1)'], {}), '(regularizer1 + 0.1)\n', (3247, 3267), True, 'import tensorflow as tf\n'), ((3396, 3422), 'tensorflow.log', 'tf.log', (['(regularizer1 + 0.1)'], {}), '(regularizer1 + 0.1)\n', (3402, 3422), True, 'import tensorflow as tf\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- """The setup script.""" from setuptools import setup, find_packages requirements = [ "xarray>=0.14", "numpy>=1.11", "scikit-learn>=0.22", "fsspec>=0.6.2", "pyyaml>=5.1.2", "tensorflow>=2.2.0", "tensorflow-addons>=0.11.2", "typing_extensions>=3.7.4.3", "dacite>=1.6.0", "wandb>=0.12.1", # fv3fit also depends on fv3gfs-util>=0.6.0, but pip-compile does not work # for packages not hosted on pypi. ] setup_requirements = [] test_requirements = ["pytest"] setup( author="Vulcan Technologies LLC", author_email="<EMAIL>", python_requires=">=3.6.9", classifiers=[ "Development Status :: 2 - Pre-Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Natural Language :: English", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", ], description="FV3Fit is used to train machine learning models.", install_requires=requirements, dependency_links=["../loaders/", "../vcm/"], extras_require={}, license="BSD license", long_description="FV3Fit is used to train machine learning models.", include_package_data=True, keywords="fv3fit", name="fv3fit", packages=find_packages(include=["fv3fit", "fv3fit.*"]), setup_requires=setup_requirements, test_suite="tests", tests_require=test_requirements, url="https://github.com/VulcanClimateModeling/fv3fit", version="0.1.0", zip_safe=False, )
[ "setuptools.find_packages" ]
[((1367, 1412), 'setuptools.find_packages', 'find_packages', ([], {'include': "['fv3fit', 'fv3fit.*']"}), "(include=['fv3fit', 'fv3fit.*'])\n", (1380, 1412), False, 'from setuptools import setup, find_packages\n')]
# -*- coding: utf-8 -*- """Dupa Set of tools handy during working, debuging and testing the code.""" __version__ = '0.0.1' __author__ = '<NAME> <<EMAIL>>' import time from functools import wraps from dupa.fixturize import fixturize def debug(func): """Print the function signature and return value""" @wraps(func) def wrapper_debug(*args, **kwargs): args_repr = [repr(a) for a in args] kwargs_repr = [f"{k}={v!r}" for k, v in kwargs.items()] signature = ", ".join(args_repr + kwargs_repr) print(f"Signature:\n{func.__name__}({signature})") value = func(*args, **kwargs) print(f"{func.__name__} RETURN:\n{value!r}\n") return value return wrapper_debug def print_wrap(func): @wraps(func) def wrap(*args, **kwargs): print("DUPA Start: %s" % func.__name__) out = func(*args, **kwargs) print("DUPA End: %s" % func.__name__) return out return wrap DUPA_COUNTER = 1 def dupa(marker=None): if marker: print(f"DUPA {marker}") return None global DUPA_COUNTER print(f"DUPA {DUPA_COUNTER}") DUPA_COUNTER += 1 def fart(marker=None): def closure(func): """A decorator around a function.""" @wraps(func) def wrapper(*args, **kwargs): dupa(marker) return func(*args, **kwargs) return wrapper return closure
[ "functools.wraps" ]
[((315, 326), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (320, 326), False, 'from functools import wraps\n'), ((760, 771), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (765, 771), False, 'from functools import wraps\n'), ((1266, 1277), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (1271, 1277), False, 'from functools import wraps\n')]
from django.contrib.sites.models import Site from django.shortcuts import render_to_response from django.template.context import RequestContext from htmlmin.decorators import not_minified_response from dss import localsettings from spa.forms import UserForm __author__ = 'fergalm' @not_minified_response def get_template(request, template_name): return render_to_response( 'views/%s.html' % template_name, context_instance=RequestContext(request)) @not_minified_response def get_template_ex(request, template_name): html = render_to_response( 'views/%s.html' % template_name, context_instance=RequestContext(request, {'form': UserForm()})) return html @not_minified_response def get_embed_codes_dialog(request, slug): payload = { 'embed_code': 'http://%s/embed/mix/%s' % (Site.objects.get_current().domain, slug) } return render_to_response( 'views/dlg/EmbedCodes.html', payload, context_instance=RequestContext(request)) @not_minified_response def get_dialog(request, dialog_name, **kwargs): return render_to_response( 'views/dlg/%s.html' % dialog_name, context_instance=RequestContext(request)) def get_javascript(request, template_name): localsettings.JS_SETTINGS.update({ 'CURRENT_USER_ID': request.user.get_profile().id if not request.user.is_anonymous() else -1, 'CURRENT_USER_NAME': request.user.get_profile().get_nice_name() if not request.user.is_anonymous() else -1, 'CURRENT_USER_URL': request.user.get_profile().get_profile_url() if not request.user.is_anonymous() else -1, 'CURRENT_USER_SLUG': request.user.get_profile().slug if not request.user.is_anonymous() else -1, 'CURRENT_USER_CANHOMEPAGE': request.user.has_perm('spa.mix_add_homepage') or request.user.is_staff if not request.user.is_anonymous() else False, 'AVATAR_IMAGE': request.user.get_profile().get_small_profile_image() if not request.user.is_anonymous() else "" }) return render_to_response( 'javascript/%s.js' % template_name, localsettings.JS_SETTINGS, context_instance=RequestContext(request), mimetype="text/javascript")
[ "django.template.context.RequestContext", "django.contrib.sites.models.Site.objects.get_current", "spa.forms.UserForm" ]
[((460, 483), 'django.template.context.RequestContext', 'RequestContext', (['request'], {}), '(request)\n', (474, 483), False, 'from django.template.context import RequestContext\n'), ((1025, 1048), 'django.template.context.RequestContext', 'RequestContext', (['request'], {}), '(request)\n', (1039, 1048), False, 'from django.template.context import RequestContext\n'), ((1229, 1252), 'django.template.context.RequestContext', 'RequestContext', (['request'], {}), '(request)\n', (1243, 1252), False, 'from django.template.context import RequestContext\n'), ((2209, 2232), 'django.template.context.RequestContext', 'RequestContext', (['request'], {}), '(request)\n', (2223, 2232), False, 'from django.template.context import RequestContext\n'), ((692, 702), 'spa.forms.UserForm', 'UserForm', ([], {}), '()\n', (700, 702), False, 'from spa.forms import UserForm\n'), ((863, 889), 'django.contrib.sites.models.Site.objects.get_current', 'Site.objects.get_current', ([], {}), '()\n', (887, 889), False, 'from django.contrib.sites.models import Site\n')]
import os import argparse import numpy as np import scipy import imageio import matplotlib.pyplot as plt from sklearn.cluster import KMeans import graphkke.generate_graphs.graph_generation as graph_generation import graphkke.generate_graphs.generate_SDE as generate_SDE parser = argparse.ArgumentParser() parser.add_argument('--input_dir', type=str, default='/home/katerynam/work/data/artificial/test/') parser.add_argument('--n_graphs', type=int, default=500) parser.add_argument('--n_nodes', type=int, default=300) parser.add_argument('--radius', type=float, default=0.6) parser.add_argument('--n_wells', type=int, default=3) parser.add_argument('--out_state', type=int, default=0.1) parser.add_argument('--if_plot', type=bool, default=True) parser.add_argument('--seed', type=int, default=7) args = parser.parse_args() def randb(n, b): return b[0] + (b[1] - b[0]) * scipy.rand(1, n) def rand(n, bounds, boxes): d = boxes.size x = np.zeros([d, n]) for i in range(d): x[i, :] = randb(n, bounds[i, :]) return x if __name__ == '__main__': lm = generate_SDE.LemonSlice2D([0.9, 0.9], args.n_graphs, 2, args.n_wells) x = rand(1, np.asarray([[-0.5, 0.5], [-0.5, 0.5]]), np.asarray([10, 10])) sde_traj = np.asarray(lm.sim_determ_system(x[:, 0])) k_means = KMeans(n_clusters=args.n_wells).fit(sde_traj) graph_states = k_means.labels_ # sde_traj = np.load(args.input_dir + 'traj.npy') # graph_states = np.load(args.input_dir + 'graph_states.npy') plt.scatter(sde_traj[:, 0], sde_traj[:, 1], c=graph_states) plt.show() sim_graph = graph_generation.LemonGraph(args.radius, args.n_graphs, args.n_nodes, graph_states) graphs, images, node_points = sim_graph.create_adj_matrix(sde_traj, args.out_state, args.if_plot) for i, image in enumerate(images): imageio.imwrite(args.input_dir + f'/traj_{i}.png', image) imageio.mimsave(args.input_dir + '/anim.gif', images, fps=2) np.save(os.path.join(args.input_dir + 'traj.npy'), sde_traj) np.save(os.path.join(args.input_dir + 'graphs.npy'), graphs) np.save(os.path.join(args.input_dir + 'graph_states.npy'), graph_states) np.save(os.path.join(args.input_dir + 'node_points.npy'), node_points)
[ "sklearn.cluster.KMeans", "graphkke.generate_graphs.generate_SDE.LemonSlice2D", "argparse.ArgumentParser", "imageio.imwrite", "numpy.asarray", "os.path.join", "numpy.zeros", "graphkke.generate_graphs.graph_generation.LemonGraph", "matplotlib.pyplot.scatter", "imageio.mimsave", "scipy.rand", "m...
[((282, 307), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (305, 307), False, 'import argparse\n'), ((1114, 1130), 'numpy.zeros', 'np.zeros', (['[d, n]'], {}), '([d, n])\n', (1122, 1130), True, 'import numpy as np\n'), ((1246, 1315), 'graphkke.generate_graphs.generate_SDE.LemonSlice2D', 'generate_SDE.LemonSlice2D', (['[0.9, 0.9]', 'args.n_graphs', '(2)', 'args.n_wells'], {}), '([0.9, 0.9], args.n_graphs, 2, args.n_wells)\n', (1271, 1315), True, 'import graphkke.generate_graphs.generate_SDE as generate_SDE\n'), ((1674, 1733), 'matplotlib.pyplot.scatter', 'plt.scatter', (['sde_traj[:, 0]', 'sde_traj[:, 1]'], {'c': 'graph_states'}), '(sde_traj[:, 0], sde_traj[:, 1], c=graph_states)\n', (1685, 1733), True, 'import matplotlib.pyplot as plt\n'), ((1738, 1748), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1746, 1748), True, 'import matplotlib.pyplot as plt\n'), ((1766, 1853), 'graphkke.generate_graphs.graph_generation.LemonGraph', 'graph_generation.LemonGraph', (['args.radius', 'args.n_graphs', 'args.n_nodes', 'graph_states'], {}), '(args.radius, args.n_graphs, args.n_nodes,\n graph_states)\n', (1793, 1853), True, 'import graphkke.generate_graphs.graph_generation as graph_generation\n'), ((2106, 2166), 'imageio.mimsave', 'imageio.mimsave', (["(args.input_dir + '/anim.gif')", 'images'], {'fps': '(2)'}), "(args.input_dir + '/anim.gif', images, fps=2)\n", (2121, 2166), False, 'import imageio\n'), ((1333, 1371), 'numpy.asarray', 'np.asarray', (['[[-0.5, 0.5], [-0.5, 0.5]]'], {}), '([[-0.5, 0.5], [-0.5, 0.5]])\n', (1343, 1371), True, 'import numpy as np\n'), ((1373, 1393), 'numpy.asarray', 'np.asarray', (['[10, 10]'], {}), '([10, 10])\n', (1383, 1393), True, 'import numpy as np\n'), ((2044, 2101), 'imageio.imwrite', 'imageio.imwrite', (["(args.input_dir + f'/traj_{i}.png')", 'image'], {}), "(args.input_dir + f'/traj_{i}.png', image)\n", (2059, 2101), False, 'import imageio\n'), ((2180, 2221), 'os.path.join', 'os.path.join', (["(args.input_dir + 'traj.npy')"], {}), "(args.input_dir + 'traj.npy')\n", (2192, 2221), False, 'import os\n'), ((2245, 2288), 'os.path.join', 'os.path.join', (["(args.input_dir + 'graphs.npy')"], {}), "(args.input_dir + 'graphs.npy')\n", (2257, 2288), False, 'import os\n'), ((2310, 2359), 'os.path.join', 'os.path.join', (["(args.input_dir + 'graph_states.npy')"], {}), "(args.input_dir + 'graph_states.npy')\n", (2322, 2359), False, 'import os\n'), ((2387, 2435), 'os.path.join', 'os.path.join', (["(args.input_dir + 'node_points.npy')"], {}), "(args.input_dir + 'node_points.npy')\n", (2399, 2435), False, 'import os\n'), ((1040, 1056), 'scipy.rand', 'scipy.rand', (['(1)', 'n'], {}), '(1, n)\n', (1050, 1056), False, 'import scipy\n'), ((1467, 1498), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': 'args.n_wells'}), '(n_clusters=args.n_wells)\n', (1473, 1498), False, 'from sklearn.cluster import KMeans\n')]
import sys try: import uos as os except ImportError: import os if not hasattr(os, "unlink"): print("SKIP") sys.exit() # cleanup in case testfile exists try: os.unlink("testfile") except OSError: pass try: f = open("testfile", "r+b") print("Unexpectedly opened non-existing file") except OSError: print("Expected OSError") pass f = open("testfile", "w+b") f.write(b"1234567890") f.seek(0) print(f.read()) f.close() # Open with truncation f = open("testfile", "w+b") f.write(b"abcdefg") f.seek(0) print(f.read()) f.close() # Open without truncation f = open("testfile", "r+b") f.write(b"1234") f.seek(0) print(f.read()) f.close() # cleanup try: os.unlink("testfile") except OSError: pass
[ "os.unlink", "sys.exit" ]
[((124, 134), 'sys.exit', 'sys.exit', ([], {}), '()\n', (132, 134), False, 'import sys\n'), ((179, 200), 'os.unlink', 'os.unlink', (['"""testfile"""'], {}), "('testfile')\n", (188, 200), False, 'import os\n'), ((694, 715), 'os.unlink', 'os.unlink', (['"""testfile"""'], {}), "('testfile')\n", (703, 715), False, 'import os\n')]
import json import re import datetime import scrapy import yaml import munch import pathlib from appdirs import user_config_dir config_path = list(pathlib.Path(__file__).parent.parent.parent.resolve().glob('config.yml'))[0] class YtchSpider(scrapy.Spider): name = "ytch" start_urls = list( munch.Munch.fromDict( yaml.safe_load( ( ( config_path ).read_text() ) ) ).channels.values() ) start_urls = [x + "/live" for x in start_urls] def parse(self, response): """Parse live stream details if channel is streaming.""" res = [ re.findall(r'(".*?"):(".*?"|\[.*?\]|true|false)', x) for x in re.findall(r'videoDetails":{(.*?)}', response.text) ] if not res: return res = res[0] res = "{%s}" % ",".join([":".join(x) for x in res][:-1]) res = json.loads(res) res["keywords"] = ", ".join(res["keywords"]) res["scraped_time"] = datetime.datetime.now() res = dict(table="youtube_streams", value=res, key="videoId") return res
[ "re.findall", "datetime.datetime.now", "json.loads", "pathlib.Path" ]
[((986, 1001), 'json.loads', 'json.loads', (['res'], {}), '(res)\n', (996, 1001), False, 'import json\n'), ((1085, 1108), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (1106, 1108), False, 'import datetime\n'), ((711, 764), 're.findall', 're.findall', (['"""(".*?"):(".*?"|\\\\[.*?\\\\]|true|false)"""', 'x'], {}), '(\'(".*?"):(".*?"|\\\\[.*?\\\\]|true|false)\', x)\n', (721, 764), False, 'import re\n'), ((785, 835), 're.findall', 're.findall', (['"""videoDetails":{(.*?)}"""', 'response.text'], {}), '(\'videoDetails":{(.*?)}\', response.text)\n', (795, 835), False, 'import re\n'), ((149, 171), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (161, 171), False, 'import pathlib\n')]
import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from mpl_finance import candlestick_ohlc # import matplotlib as mpl then mpl.use('TkAgg') import pandas as pd import numpy as np from datetime import datetime df = pd.read_csv('BitMEX-OHLCV-1d.csv') df.columns = ['date', 'open', 'high', 'low', 'close', 'volume'] chart_figure = plt.figure(figsize=(10, 5)) chart_figure.set_facecolor('w') chart_gridspec = gridspec.GridSpec(2, 1, height_ratios=[3, 1]) axes = [] axes.append(plt.subplot(chart_gridspec[0])) axes.append(plt.subplot(chart_gridspec[1], sharex=axes[0])) axes[0].get_xaxis().set_visible(False) x = np.arange(len(df.index)) ohlc = df[['open', 'high', 'low', 'close']].astype(int).values dohlc = np.hstack((np.reshape(x, (-1, 1)), ohlc)) candlestick_ohlc(axes[0], dohlc, width=0.5, colorup='r', colordown='b') axes[1].bar(x, df.volume, color='k', width=0.6, align='center') plt.tight_layout() plt.show()
[ "mpl_finance.candlestick_ohlc", "numpy.reshape", "pandas.read_csv", "matplotlib.pyplot.figure", "matplotlib.gridspec.GridSpec", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.subplot", "matplotlib.pyplot.show" ]
[((236, 270), 'pandas.read_csv', 'pd.read_csv', (['"""BitMEX-OHLCV-1d.csv"""'], {}), "('BitMEX-OHLCV-1d.csv')\n", (247, 270), True, 'import pandas as pd\n'), ((351, 378), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 5)'}), '(figsize=(10, 5))\n', (361, 378), True, 'import matplotlib.pyplot as plt\n'), ((428, 473), 'matplotlib.gridspec.GridSpec', 'gridspec.GridSpec', (['(2)', '(1)'], {'height_ratios': '[3, 1]'}), '(2, 1, height_ratios=[3, 1])\n', (445, 473), True, 'import matplotlib.gridspec as gridspec\n'), ((770, 841), 'mpl_finance.candlestick_ohlc', 'candlestick_ohlc', (['axes[0]', 'dohlc'], {'width': '(0.5)', 'colorup': '"""r"""', 'colordown': '"""b"""'}), "(axes[0], dohlc, width=0.5, colorup='r', colordown='b')\n", (786, 841), False, 'from mpl_finance import candlestick_ohlc\n'), ((908, 926), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (924, 926), True, 'import matplotlib.pyplot as plt\n'), ((927, 937), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (935, 937), True, 'import matplotlib.pyplot as plt\n'), ((496, 526), 'matplotlib.pyplot.subplot', 'plt.subplot', (['chart_gridspec[0]'], {}), '(chart_gridspec[0])\n', (507, 526), True, 'import matplotlib.pyplot as plt\n'), ((540, 586), 'matplotlib.pyplot.subplot', 'plt.subplot', (['chart_gridspec[1]'], {'sharex': 'axes[0]'}), '(chart_gridspec[1], sharex=axes[0])\n', (551, 586), True, 'import matplotlib.pyplot as plt\n'), ((739, 761), 'numpy.reshape', 'np.reshape', (['x', '(-1, 1)'], {}), '(x, (-1, 1))\n', (749, 761), True, 'import numpy as np\n')]