seq_id
stringlengths
7
11
text
stringlengths
156
1.7M
repo_name
stringlengths
7
125
sub_path
stringlengths
4
132
file_name
stringlengths
4
77
file_ext
stringclasses
6 values
file_size_in_byte
int64
156
1.7M
program_lang
stringclasses
1 value
lang
stringclasses
38 values
doc_type
stringclasses
1 value
stars
int64
0
24.2k
dataset
stringclasses
1 value
pt
stringclasses
1 value
442805106
import tensorflow as tf from PIL import Image import cv2 import numpy as np import uuid import os from .admin import model_path, label_path from .utility import load_image_into_numpy_array, calculate_area, delete_and_create_folder, shortest_longest_area import sys sys.path.append("../models/research") from object_detection.utils import label_map_util from object_detection.utils import visualization_utils as vis_util # define a class brand object that will take the video input, make predictions and calculate the KPI metrics class BrandObjectService: def __init__(self, video_path): self.video_path = video_path self.save_path = "./save_path" self.predicted_path = './predicted_frames' delete_and_create_folder(self.save_path) delete_and_create_folder(self.predicted_path) def predict(self): NUM_CLASSES = 7 KPIs_dict = dict() #Load a (frozen) Tensorflow model into memory. detection_graph = tf.Graph() with detection_graph.as_default(): od_graph_def = tf.GraphDef() with tf.gfile.GFile(model_path, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name='') # Loading label map label_map = label_map_util.load_labelmap(label_path) categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True) category_index = label_map_util.create_category_index(categories) # Size, in inches, of the output images. IMAGE_SIZE = (500, 500) count = 0 frame_number = 0 cap = cv2.VideoCapture(self.video_path) with detection_graph.as_default(): with tf.Session(graph=detection_graph) as sess: while cap.isOpened(): frame_number += 1 ret, frame = cap.read() filename = str(uuid.uuid4()) + ".jpg" fullpath = os.path.join(self.save_path, filename) cv2.imwrite(fullpath, frame) count += 1 ### for testing script... if count == 50: break image = Image.open(fullpath) image_np = load_image_into_numpy_array(image) image_np_expanded = np.expand_dims(image_np, axis=0) image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') boxes = detection_graph.get_tensor_by_name('detection_boxes:0') scores = detection_graph.get_tensor_by_name('detection_scores:0') classes = detection_graph.get_tensor_by_name('detection_classes:0') num_detections = detection_graph.get_tensor_by_name('num_detections:0') (boxes, scores, classes, num_detections) = sess.run( [boxes, scores, classes, num_detections], feed_dict={image_tensor: image_np_expanded}) # Visualization of the results of a detection image, box_to_display_str_map = vis_util.visualize_boxes_and_labels_on_image_array( image_np, np.squeeze(boxes), np.squeeze(classes).astype(np.int32), np.squeeze(scores), category_index, use_normalized_coordinates=True, line_thickness=8) image_pil = Image.fromarray(np.uint8(image_np)).convert('RGB') im_width, im_height = image_pil.size area_whole = im_width * im_height for key, value in box_to_display_str_map.items(): ymin, xmin, ymax, xmax = key (left, right, top, bottom) = ( xmin * im_width, xmax * im_width, ymin * im_height, ymax * im_height) area = calculate_area(top, left, bottom, right) percent_area = round(area / area_whole, 2) rindex = value[0].rfind(':') brand_name = value[0][:rindex] if brand_name in KPIs_dict.keys(): KPIs_dict[brand_name]['count'] += 1 KPIs_dict[brand_name]['area'].append(percent_area) KPIs_dict[brand_name]['frames'].append(frame_number) else: KPIs_dict[brand_name] = {"count": 1} KPIs_dict[brand_name].update({"area": [percent_area]}) KPIs_dict[brand_name].update({"frames": [frame_number]}) full_predicted_path = os.path.join(self.predicted_path, str(uuid.uuid4()) + ".jpg") cv2.imwrite(full_predicted_path, image) KPIs_dict = self.process_kpi(KPIs_dict) return KPIs_dict # define a function that will return the dictonary with KPI metrics per logo def process_kpi(self, KPIs_dict): for each_brand, analytics_dict in KPIs_dict.items(): area = analytics_dict['area'] response = shortest_longest_area(area) KPIs_dict[each_brand].update(response) return KPIs_dict
krishnakaushik25/Forecasting-Business-KPI
modular_code/src/ML_Pipeline/predict.py
predict.py
py
5,576
python
en
code
0
github-code
6
32102340399
from typing import List class Solution: def canJump(self, nums: List[int]) -> bool: if not nums or len(nums) < 2: return True max_arrive = nums[0] for i in range(1, len(nums)): if max_arrive < i: return False max_arrive = max(max_arrive, i + nums[i]) return True nums = [0,1] print(Solution().canJump(nums))
Eleanoryuyuyu/LeetCode
python/Greedy/55. 跳跃游戏.py
55. 跳跃游戏.py
py
398
python
en
code
3
github-code
6
34290631186
""" 1.Cambia el valor 10 en x a 15. Una vez que haya terminado, x ahora debería ser [[5,2,3], [15,8,9]]. 2.Cambia el apellido del primer alumno de 'Jordan' a 'Bryant' 3.En el directorio sports_directory, cambia 'Messi' a 'Andres' 4.Cambia el valor 20 en z a 30 """ """ x = [ [5,2,3], [10,8,9] ] x [1][0] = 15 print(x) """ """ students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'} ] students[0]['last_name'] = 'Bryant' print(students) """ """ sports_directory = { 'basketball' : ['Kobe', 'Jordan', 'James', 'Curry'], 'soccer' : ['Messi', 'Ronaldo', 'Rooney'] } sports_directory ['soccer'][0] = 'Andres' """ """ z = [ {'x': 10, 'y': 20} ] z [0]['y'] = 30 print(z) """ """ students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] def iterateDictionarycopy(some_list): stringReturn = '' for val in some_list: stringReturn += f"first_name - {val['first_name']}, last_name - {val['last_name']}\n" return stringReturn iterateDictionarycopy(students) """ """ students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] def iterateDictionary2(key_name, some_list): stringReturn = '' for val in some_list: stringReturn += f"{val[key_name]}\n" return stringReturn print(iterateDictionary2('first_name',students)) print(iterateDictionary2('last_name',students)) """ dojo = { 'locations': ['San Jose', 'Seattle', 'Dallas', 'Chicago', 'Tulsa', 'DC', 'Burbank'], 'instructors': ['Michael', 'Amy', 'Eduardo', 'Josh', 'Graham', 'Patrick', 'Minh', 'Devon'] } """ def printInfo(my_dictionary): for key in my_dictionary: print(f"{len(my_dictionary[key])} {key.upper()}") for val in my_dictionary[key]: print(val) print("") printInfo(dojo) """
Dominique-HL/python_fundamentals
funciones_intermediasII.py
funciones_intermediasII.py
py
2,138
python
en
code
0
github-code
6
33585071155
__author__ = 'Vivek' #Search for a target element in rotated array , if element present then return index otherwise -1 def binSearch(A, B) : """ Binary Search Algorithm """ low = 0 high = len(A) - 1 result = -1 while low <= high : mid = (low + high)/2 if A[mid] == B : return mid elif B > A[mid] : low = mid + 1 else : high = mid - 1 return -1 def findMin(A): """ Find the index of minimum element in a rotated array """ low = 0 high = len(A) - 1 N = len(A) while low <= high : mid = (low + high)/2 next = (mid + 1)%N prev = (mid + N - 1)%N if A[low] < A[high] : return low elif A[mid] <= A[next] and A[mid] <= A[prev] : return mid elif A[mid] <= A[high] : high = mid - 1 elif A[mid] >= A[low] : low = mid + 1 def search(A, B) : minIndex = findMin(A) if minIndex == 0 or minIndex == len(A) - 1 : return binSearch(A, B) else : res1 = binSearch(A[:minIndex], B) res2 = binSearch(A[minIndex:], B) if res1 == -1 and res2 == -1 : return -1 if res1 == -1 : return res2 + minIndex elif res2 == -1 : return res1
viveksyngh/InterviewBit
Binary Search/SEARCHROTATED.py
SEARCHROTATED.py
py
1,515
python
en
code
3
github-code
6
16128682047
def get_dist(start): # BFSで距離を計算する global N, D d = [1e9] * (N + 1) q = [start] d[start] = 0 while len(q) > 0: p = q.pop(0) for t in D[p]: if d[t] == 1e9: d[t] = d[p] + 1 q.append(t) return d N = int(input()) D = [[] for _ in range(N + 1)] for _ in range(N - 1): a, b = map(int, input().split()) D[a].append(b) D[b].append(a) dist = get_dist(1) max_n = -1 max_i = 0 for i in range(1, N + 1): if max_n < dist[i]: max_n = dist[i] max_i = i dist_max = get_dist(max_i) max2 = -1 for i in range(1, N + 1): max2 = max(max2, dist_max[i]) print(max2 + 1)
keimoriyama/Atcoder
Tenkei/003.py
003.py
py
692
python
en
code
0
github-code
6
24905708193
import cadquery as cq import cadquery.selectors as cqs import logging import importlib import utilities # TODO: Change to a relative import ".utilities" to preempt name clashes. from types import SimpleNamespace as Measures from math import sin, cos, radians # A parametric cover that can be hooked to the top edge of an eyeglasses lens. # # You might want to reduce the amount of light reaching the eye even more for practical use. For # that, you can drill chains of small holes through the top face and the inclined face at the # bottom and then sew flexible black material there. Cut the material so that it seals well against # the user's face. # # To use this design, you need Python, CadQuery (https://cadquery.readthedocs.io/en/latest/) and # ideally also CQ-Editor, the CadQuery IDE (https://github.com/CadQuery/CQ-editor). # # License: Unlicence and Creative Commons Public Domain Dedication (CC-0). # # Tasks for now # TODO: Rework the design so that it consists of a sweep operation along a single path, with wires # automatically swept orthogonal to the path. Wires are then defined as a parametrized hook # profile together with a position along that path in percent or millimeters from both ends. # In addition, the type of transition (ruled or round) between wires should be defined. The # problem is of course that sweeps always interpolate between wires with splines. So probably # lofting should be used, and the rounded path is only there to place the wires exactly, not to # sweep them along. The rounding is achieved by choosing round transition for lofting. # TODO: Replace the upper hook bar over the lens with two narrow hooks, also a bit shorter than now. # TODO: Remove the hook along the current stem cover part, keeping the hook infill though. This # should help attaching and detaching the lens cover. # TODO: Round the lower back corner, so it cannot poke into the head. This can be done by using # three profiles with "round" transition for lofting. # TODO: Cut off the lower right corner according to the manually cut prototype. This can be done # by using three profiles with "round" transition for lofting. # TODO: Add a top surface light blocker, carved according to the face contour. The shape should be # an arc, with the distance between arc and outer corner being 25 mm. Can be created from the # lens cover path and this arc, then extruding that face by 1.6 mm. Since this can easily be # 3D printed, there is no reason to use other material. # # Tasks for later # TODO: Add documentation for all methods. # TODO: Reduce the size of this script by a lot by replacing all the *_start_wire() and *_end_wire() # methods with calls to a more general method. This requires proper specification of position # and rotation at once, possibly also by combining multiple other such positions and rotations. # In CadQuery, the Location type is for that (or maybe it has a different name, but there is one). # TODO: Add the general edge chamfering. That's very impractical though for a design like this, # as edge selection is very difficult here. # TODO: Add sewing holes along the upper horizontal surface and on the lower 45° angled surface, # for sewing on flexible parts that block out light entering from below and above the glasses. # TODO: Implement vertical arcing for the outside of the cover. But not really needed in practice. # TODO: Add the chamfers to the lower corner of the lens. # TODO: Improve how space is made for the stem-to-lens frame element of 1.2 mm additional thickness. # TODO: Add a clip that connects to the bottom of the glasses lens. Can be done by # adjusting the shape of the "hook" profile used for the sweep. # TODO: Replace the bent section between lens and stem cover with a spline that smoothly # continues to both the lens and stem cover sections. measures = Measures( part_name = "lens_cover", color = "steelblue", alpha = 0.0, debug = True, side = "left", # "left" or "right". TODO: Implement "right" using mirroring. thickness = 1.6, # For FDM, that's 4 walls with a 0.4 mm nozzle. Corrected from 0.8. edge_smoothing = 0.4, # For all edges, to make them nicer to the touch. lens_cover = Measures( # Lens width 58.3 mm + stem corner width 5.6 mm - stem cover width 6.1 mm. # Corrected from 55.5 mm width = 57.8, height = 35.3, # Corrected from 33.5 vertical_arc_height = 1.7, # TODO: Implement that this is utilized, then reduce hook_depth. horizontal_arc_height = 2.3, # Only small radii possible due to a bug. Cornercase radii may may result in non-manifoldness. lower_corner_radius = 2.0, hook_depth = 4.6, # Lens thickness 2.9 mm, vertical arc height 1.7 mm. hook_height = 8.0, frame_attachment_depth = 1.4, # Provides additional hook depth at outer side of lens, for frame. overhang_angle_start = 45, # Visually adapted to achieve the same lower endpoint position compared to a shape with # frame_attachment_depth = 0. overhang_angle_end = 48, overhang_size_start = 7.0, # Visually adapted to achieve the same lower endpoint position compared to a shape with # frame_attachment_depth = 0. overhang_size_end = 7.5 ), corner_cover = Measures( height = 35.3, hook_depth = 5.0, # Adapted visually to create a corner. Corrected from 7.0. # TODO: Calculate hook_height always automatically as the midpoint between lens cover and # hinge cover height, as when forgetting to do this manually, the interpolation can create # shapes that let the lofts partially fail. hook_height = 8.0, # Midpoint between lens cover and hinge cover hook heights. hook_height_infill = 2.7, # Midpoint between lens cover and stem cover hook heights. Avoids interpolation issues. overhang_angle = 45, overhang_size = 7.0 ), hinge_cover = Measures( depth = 18.0, # Measured from the lens cover back plane. height = 35.3, path_angle = 100, lower_corner_radius = 12.0, hook_depth = 4.5, # Measured glasses stem width is 3.8 mm. hook_height = 8.0, hook_height_infill = 5.4, overhang_angle = 45, overhang_size = 7.0 ), stem_cover = Measures( depth = 22.0, # Measured from the lens cover back plane. height = 35.3, path_angle = 100, lower_corner_radius = 12.0, hook_depth = 4.5, # Measured glasses stem width is 3.8 mm. hook_height = 14.0, hook_height_infill = 5.4, overhang_angle = 45, overhang_size = 7.0 ), ) # Selective reloading to pick up changes made between script executions. # See: https://github.com/CadQuery/CQ-editor/issues/99#issue-525367146 importlib.reload(utilities) class LensCover: def __init__(self, workplane, measures): """ A parametric eye cover that can be hooked to the top edge of eyeglasses. :param workplane: The CadQuery workplane to create the eye cover on. This workplane is assumed to be coplanar with the face of the eyeglass user, with the plane's normal pointing into the "front" direction of the model. :param measures: The measures to use for the parameters of this design. Expects a nested [SimpleNamespace](https://docs.python.org/3/library/types.html#types.SimpleNamespace) object. See example above for the possible attributes. """ self.model = workplane self.measures = measures self.log = logging.getLogger(__name__) m = self.measures # Points on the sweep path that we'll need repeatedly. m.lens_startpoint = (0, 0) # We create a space for the rounded edge that is 60-70% of the wrap radius, to achieve a # smooth shape transition for angles slightly larger than 90°. m.lens_endpoint = (-m.lens_cover.width, 0) m.hinge_startpoint = (-m.lens_cover.width, -m.lens_cover.hook_depth - 2 * m.thickness) # toTuple() yields a (x,y,z) coordinate, but we only want (x,y) here. # When slicing in Python "[0:2]", the specified end element (index 2) will not be in the result. m.stem_startpoint =self.hinge_path().val().positionAt(1).toTuple()[0:2] self.build() def profile_wire(self, height, hook_depth, hook_height, hook_height_infill = 0.1, overhang_angle = 90, overhang_size = 0.1, debug_name = None ): """ Object of class Wire, representing the base shape of the hook. A multi-section sweep requires wires placed along the path to use for the shape-adapted sweeping. These wires should be orthogonal to the path to get the desired shape. """ # hook_height_infill is by default 0.1 just because the CAD kernel cannot handle 0 here. # TODO: Create a profile with a curved section. Proposal: Use swipe() and # convert a face of the resulting 3D shape back into a wire. m = self.measures # Remember that translate() uses global (!) coordinates. wire = ( cq.Workplane("YZ") # Covering outer element of the profile. .rect(m.thickness, height, forConstruction = True) .translate((0, -0.5 * m.thickness, -0.5 * height)) .toPending() # Horizontal element of the hook, including hook infill if any. .copyWorkplane(cq.Workplane("YZ")) .rect(hook_depth + 2 * m.thickness, m.thickness + hook_height_infill, forConstruction = True) .translate((0, -0.5 * (hook_depth + 2 * m.thickness), -0.5 * (m.thickness + hook_height_infill))) .toPending() # Vertical element of the hook with the tip. .copyWorkplane(cq.Workplane("YZ")) .rect(m.thickness, hook_height + m.thickness, forConstruction = True) # -0.499 instead of -0.5 due to a malfunction of union_pending() when having a complete # intersection in this corner. Strangely, only for this corner. .translate((0, -hook_depth - 1.5 * m.thickness, -0.499 * (hook_height + m.thickness))) .toPending() # Overhang at the bottom of the profile shape. .copyWorkplane(cq.Workplane("YZ")) .rect(m.thickness, overhang_size, forConstruction = True) # 0.499 because otherwise union_pending() cannot create a correct result. This happens due to # the CAD kernel limitations of unioning shapes that share one corner exactly. .translate((0, -0.5 * m.thickness, -height - 0.499 * overhang_size)) .rotate((1, 0, -height), (-1, 0, -height), overhang_angle) .toPending() .union_pending() .ctx.pendingWires[0] ) if m.debug and debug_name is not None: showable_wire = cq.Workplane().newObject([wire]).wires().val() show_object(showable_wire, name = debug_name) return wire # Wire at the start of the sweep, defining the lens cover cross-section next to the nose. def lens_start_wire(self): m = self.measures wire = ( cq.Workplane().newObject([ self.profile_wire( height = m.lens_cover.height, hook_depth = m.lens_cover.hook_depth, hook_height = m.lens_cover.hook_height, overhang_angle = m.lens_cover.overhang_angle_start, overhang_size = m.lens_cover.overhang_size_start ) ]) .wires() .val() ) if m.debug: show_object(wire, name = "lens_start_wire") return wire # Wire at the end of the lens / start of the bent section. # Position is slightly approximate as it treats the path as made from straight lines. def lens_end_wire(self): m = self.measures wire = ( cq.Workplane().newObject([self.profile_wire( height = m.lens_cover.height, hook_depth = m.lens_cover.hook_depth + m.lens_cover.frame_attachment_depth, hook_height = m.lens_cover.hook_height, overhang_angle = m.lens_cover.overhang_angle_end, overhang_size = m.lens_cover.overhang_size_end )]) .translate((*m.lens_endpoint, 0)) .translate((0, 1.4, 0)) # TODO: Make this parametric. .val() ) if m.debug: show_object(wire, name = "lens_end_wire") return wire # Wire at the end of the lens / start of the bent section. # Position is slightly approximate as it treats the path as made from straight lines. def corner_center_wire(self): m = self.measures wire = ( cq.Workplane().newObject([self.profile_wire( height = m.corner_cover.height, hook_depth = m.corner_cover.hook_depth, hook_height = m.corner_cover.hook_height, hook_height_infill = m.corner_cover.hook_height_infill, overhang_angle = m.corner_cover.overhang_angle, overhang_size = m.corner_cover.overhang_size )]) # Move the wire to the +y part so we can rotate around origin to rotate around the # back edge. .translate((0, m.corner_cover.hook_depth + 2 * m.thickness, 0)) # Rotate around the back edge of the initial wire, now at origin. # Rotate by half the angle that the hinge start wire will have. .rotate((0, 0, 1), (0, 0, -1), 0.5 * (-90 + (m.hinge_cover.path_angle - 90))) # Bring the wire into its final position. .translate((*m.lens_endpoint, 0)) .translate((0, -m.lens_cover.hook_depth - 2 * m.thickness, 0)) .val() ) if m.debug: show_object(wire, name = "corner_center_wire") return wire # Wire at the start of the stem cover / end of the bent section. # Position is slightly approximate as it treats the path as made from straight lines. def hinge_start_wire(self): m = self.measures wire = ( cq.Workplane().newObject([self.profile_wire( height = m.hinge_cover.height, hook_depth = m.hinge_cover.hook_depth, hook_height = m.hinge_cover.hook_height, hook_height_infill = m.hinge_cover.hook_height_infill, overhang_angle = m.hinge_cover.overhang_angle, overhang_size = m.hinge_cover.overhang_size )]) .wires() # Rotate around the back (-y) edge of the initial wire. .rotate( (0, -m.hinge_cover.hook_depth - 2 * m.thickness, 1), (0, -m.hinge_cover.hook_depth - 2 * m.thickness, -1), -90 + (m.hinge_cover.path_angle - 90) ) # Move so that the original back edge is at the origin, to prepare the move along the path. .translate((0, m.hinge_cover.hook_depth + 2 * m.thickness, 0)) # Easiest to find the point at the very start of the path is via positionAt(0) .translate(self.hinge_path().val().positionAt(0).toTuple()) .val() ) if m.debug: show_object(wire, name = "hinge_start_wire") return wire def hinge_end_wire(self): m = self.measures wire = ( cq.Workplane().newObject([self.profile_wire( height = m.hinge_cover.height, hook_depth = m.hinge_cover.hook_depth, hook_height = m.hinge_cover.hook_height, hook_height_infill = m.hinge_cover.hook_height_infill, overhang_angle = m.hinge_cover.overhang_angle, overhang_size = m.hinge_cover.overhang_size )]) .wires() # Rotate around the back (-y) edge of the initial wire. .rotate( (0, -m.hinge_cover.hook_depth - 2 * m.thickness, 1), (0, -m.hinge_cover.hook_depth - 2 * m.thickness, -1), -90 + (m.hinge_cover.path_angle - 90) ) # Move so that the original back edge is at the origin, to prepare the move along the path. .translate((0, m.hinge_cover.hook_depth + 2 * m.thickness, 0)) # Easiest to find the point at the very end of the path is via positionAt(1) .translate(self.hinge_path().val().positionAt(1).toTuple()) .val() ) if m.debug: show_object(wire, name = "hinge_end_wire") return wire def stem_start_wire(self): m = self.measures wire = ( cq.Workplane().newObject([self.profile_wire( height = m.stem_cover.height, hook_depth = m.stem_cover.hook_depth, hook_height = m.stem_cover.hook_height, hook_height_infill = m.stem_cover.hook_height_infill, overhang_angle = m.stem_cover.overhang_angle, overhang_size = m.stem_cover.overhang_size )]) .wires() # Rotate around the back (-y) edge of the initial wire. .rotate( (0, -m.stem_cover.hook_depth - 2 * m.thickness, 1), (0, -m.stem_cover.hook_depth - 2 * m.thickness, -1), -90 + (m.stem_cover.path_angle - 90) ) # Move so that the original back edge is at the origin, to prepare the move along the path. .translate((0, m.stem_cover.hook_depth + 2 * m.thickness, 0)) # Easiest to find the point at the very beginning of the path is via positionAt(0) # But not exactly at the beginning as that would place the wire into the same position # as the hinge end wire, and we can't loft wires in the same position. .translate(self.stem_path().val().positionAt(0.01).toTuple()) .val() ) if m.debug: show_object(wire, name = "stem_end_wire") return wire def stem_end_wire(self): m = self.measures wire = ( cq.Workplane().newObject([self.profile_wire( height = m.stem_cover.height, hook_depth = m.stem_cover.hook_depth, hook_height = m.stem_cover.hook_height, hook_height_infill = m.stem_cover.hook_height_infill, overhang_angle = m.stem_cover.overhang_angle, overhang_size = m.stem_cover.overhang_size )]) .wires() # Rotate around the back (-y) edge of the initial wire. .rotate( (0, -m.stem_cover.hook_depth - 2 * m.thickness, 1), (0, -m.stem_cover.hook_depth - 2 * m.thickness, -1), -90 + (m.stem_cover.path_angle - 90) ) # Move so that the original back edge is at the origin, to prepare the move along the path. .translate((0, m.stem_cover.hook_depth + 2 * m.thickness, 0)) # Easiest to find the point at the very end of the path is via positionAt(1) .translate(self.stem_path().val().positionAt(1).toTuple()) .val() ) if m.debug: show_object(wire, name = "stem_end_wire") return wire def lens_path(self): """ The sweeping path follows the planar upper edge of the eye cover shape. Points are defined in the XY plane, drawing a cover for the left lens from origin to -x. """ m = self.measures path = ( cq .Workplane("XY") .moveTo(*m.lens_startpoint) .sagittaArc(m.lens_endpoint, -m.lens_cover.horizontal_arc_height) .wire() # Since we don't want a closed wire, close() will not create the wire. We have to. ) if m.debug: show_object(path, name = "lens_path") return path def hinge_path(self): m = self.measures path = ( cq .Workplane("XY") .moveTo(*m.hinge_startpoint) .polarLine(m.hinge_cover.depth, 360 - m.hinge_cover.path_angle) .wire() # Since we don't want a closed wire, close() will not create the wire. We have to. ) if m.debug: show_object(path, name = "hinge_path") return path def stem_path(self): m = self.measures path = ( cq .Workplane("XY") .moveTo(*m.stem_startpoint) .polarLine(m.stem_cover.depth, 360 - m.stem_cover.path_angle) .wire() # Since we don't want a closed wire, close() will not create the wire. We have to. ) if m.debug: show_object(path, name = "stem_path") return path def build(self): cq.Workplane.union_pending = utilities.union_pending m = self.measures # Sweeping along the path sections. # Due to CadQuery issue #808 (https://github.com/CadQuery/cadquery/issues/808), we cannot # simply do one multi-section sweep along a single path with all six wires along it. # And, the default transition = "right" would crash CadQuery-Editor due to a CAD kernel bug. lens_cover = cq.Workplane("YZ") lens_cover.ctx.pendingWires.extend([ self.lens_start_wire(), self.lens_end_wire() ]) lens_cover = lens_cover.sweep( self.lens_path(), multisection = True, transition = "round" ) corner_cover = cq.Workplane("YZ") corner_cover.ctx.pendingWires.extend([ self.lens_end_wire(), self.corner_center_wire(), self.hinge_start_wire() ]) corner_cover = corner_cover.loft() hinge_and_stem_cover = cq.Workplane("YZ") hinge_and_stem_cover.ctx.pendingWires.extend([ self.hinge_start_wire(), self.hinge_end_wire(), self.stem_start_wire(), self.stem_end_wire() ]) hinge_and_stem_cover = hinge_and_stem_cover.loft(ruled = True) # The internal combine function of loft() and sweep() is a bit fragile, so instead to obtain # a singel solid we created the individual parts first and then union() them together here. self.model = ( cq.Workplane("YZ") .union(lens_cover) .union(corner_cover) .union(hinge_and_stem_cover) ) # Rounding the lower corners. # TODO: Reimplement this, as it does not work when having the 45° overhang at the bottom. # self.model = ( # self.model # # # Rounding the lower corner of the lens cover. # .faces(">X") # .edges("<Z") # # TODO: Fix that only small radii are possible here. This is probably because the part # # is curved. # .fillet(m.lens_cover.lower_corner_radius) # # # Rounding the lower corner of the stem cover. # .faces("<Y") # .edges("<Z") # .fillet(m.stem_cover.lower_corner_radius) # ) # ============================================================================= # Part Creation # ============================================================================= part = LensCover(cq.Workplane(), measures) show_options = {"color": measures.color, "alpha": measures.alpha} show_object(part.model, name = measures.part_name, options = show_options)
tanius/cadquery-models
lenscover/lens_cover.py
lens_cover.py
py
23,912
python
en
code
11
github-code
6
41524463636
def print_main_menu(menu): """ Given a dictionary with the menu, prints the keys and values as the formatted options. Adds additional prints for decoration and outputs a question "What would you like to do?" """ print('==========================') print('What would you like to do?') for key, value in menu.items(): print(f'{key} - {value}') print('==========================') def get_written_date(date_format): """ The function gets a list of integers that corresponds to a date and formats it into a written format but for this final project, the date_list will be a string fomatted like MM/DD/YYYY """ month_names = { 1: "January", 2: "February", 3: "March", 4: "April", 5: "May", 6: "June", 7: "July", 8: "August", 9: "September", 10: "October", 11: "November", 12: "December", } month = int(date_format[0]) day = int(date_format[1]) year = int(date_format[2]) month1 = month_names[month] date = month1 + ' ' + str(day) + ', ' + str(year) return date def get_selection(action, suboptions, to_upper = True, go_back = False): """ param: action (string) - the action that the user would like to perform; printed as part of the function prompt param: suboptions (dictionary) - contains suboptions that are listed underneath the function prompt. param: to_upper (Boolean) - by default, set to True, so the user selection is converted to upper-case. If set to False, then the user input is used as-is. param: go_back (Boolean) - by default, set to False. If set to True, then allows the user to select the option M to return back to the main menu The function displays a submenu for the user to choose from. Asks the user to select an option using the input() function. Re-prints the submenu if an invalid option is given. Prints the confirmation of the selection by retrieving the description of the option from the suboptions dictionary. returns: the option selection (by default, an upper-case string). The selection be a valid key in the suboptions or a letter M, if go_back is True. """ selection = None if go_back: if 'm' in suboptions or 'M' in suboptions: print("Invalid submenu, which contains M as a key.") return None while selection not in suboptions: print(f"::: What would you like to {action.lower()}?") for key in suboptions: print(f"{key} - {suboptions[key]}") if go_back == True: selection = input(f"::: Enter your selection " f"or press 'm' to return to the main menu\n> ") else: selection = input("::: Enter your selection\n> ") if to_upper: selection = selection.upper() # to allow us to input lower- or upper-case letters if go_back and selection.upper() == 'M': return 'M' if to_upper: print(f"You selected |{selection}| to", f"{action.lower()} |{suboptions[selection].lower()}|.") else: print(f"You selected |{selection}| to", f"{action.lower()} |{suboptions[selection]}|.") return selection def print_task(task, priority_map, name_only = False): """ param: task (dict) - a dictionary object that is expected to have the following string keys: - "name": a string with the task's name - "info": a string with the task's details/description (the field is not displayed if the value is empty) - "priority": an integer, representing the task's priority (defined by a dictionary priority_map) - "duedate": a valid date-string in the US date format: <MM>/<DD>/<YEAR> (displayed as a written-out date) - "done": a string representing whether a task is completed or not param: priority_map (dict) - a dictionary object that is expected to have the integer keys that correspond to the "priority" values stored in the task; the stored value is displayed for the priority field, instead of the numeric value. param: name_only (Boolean) - by default, set to False. If True, then only the name of the task is printed. Otherwise, displays the formatted task fields. returns: None; only prints the task values Helper functions: - get_written_date() to display the 'duedate' field """ if name_only == False: print(task["name"]) if task["info"] != "": print(f' * {task["info"]}') print(f' * Due: {get_written_date(task["duedate"].split("/"))} (Priority: {priority_map[task["priority"]]})') print(f' * Completed? {task["done"]}') if name_only == True: print(task["name"]) def print_tasks(task_list, priority_map, name_only = False, show_idx = False, start_idx = 0, completed = "all"): """ param: task_list (list) - a list containing dictionaries with the task data param: priority_map (dict) - a dictionary object that is expected to have the integer keys that correspond to the "priority" values stored in the task; the stored value is displayed for the priority field, instead of the numeric value. param: name_only (Boolean) - by default, set to False. If True, then only the name of the task is printed. Otherwise, displays the formatted task fields. Passed as an argument into the helper function. param: show_idx (Boolean) - by default, set to False. If False, then the index of the task is not displayed. Otherwise, displays the "{idx + start_idx}." before the task name. param: start_idx (int) - by default, set to 0; an expected starting value for idx that gets displayed for the first task, if show_idx is True. param: completed (str) - by default, set to "all". By default, prints all tasks, regardless of their completion status ("done" field status). Otherwise, it is set to one of the possible task's "done" field's values in order to display only the tasks with that completion status. returns: None; only prints the task values from the task_list Helper functions: - print_task() to print individual tasks """ print("-"*42) for task in task_list: # go through all tasks in the list if show_idx: # if the index of the task needs to be displayed print(f"{task_list.index(task)+1}.", end=" ") if completed == "all": print_task(task, priority_map, name_only) elif task["done"] == completed: print_task(task, priority_map, name_only) def is_valid_index(idx, in_list, start_idx = 0): """ param: idx (str) - a string that is expected to contain an integer index to validate param: in_list - a list that the idx indexes param: start_idx (int) - an expected starting value for idx (default is 0); gets subtracted from idx for 0-based indexing The function checks if the input string contains only digits and verifies that (idx - start_idx) is >= 0, which allows to retrieve an element from in_list. returns: - True, if idx is a numeric index >= start_idx that can retrieve an element from in_list. - False if idx is not a string that represents an integer value, if int(idx) is < start_idx, or if it exceeds the size of in_list. """ if (type(idx) == str) and (idx.isdigit() == True) and (int(idx) >= start_idx) and ((int(idx) - start_idx) < len(in_list)): return True else: return False def delete_item(in_list, idx, start_idx = 0): """ param: in_list - a list from which to remove an item param: idx (str) - a string that is expected to contain a representation of an integer index of an item in the provided list param: start_idx (int) - by default, set to 0; an expected starting value for idx that gets subtracted from idx for 0-based indexing The function first checks if the input list is empty. The function then calls is_valid_index() to verify that the provided index idx is a valid positive index that can access an element from info_list. On success, the function saves the item from info_list and returns it after it is deleted from in_list. returns: If the input list is empty, return 0. If idx is not of type string or start_idx is not an int, return None. If is_valid_index() returns False, return -1. Otherwise, on success, the function returns the element that was just removed from the input list. Helper functions: - is_valid_index() """ if in_list == []: return 0 if (type(idx) != str) or (type(start_idx) != int): return None if is_valid_index(idx, in_list, start_idx) == False: return -1 else: return in_list[int(idx) -start_idx] del in_list[int(idx) - start_idx] def is_valid_name(name): """ param1- a string returns: - true if the string is between 3 and 25 characters inclusive - false otherwise """ if 3 <= len(name) <= 25: return True else: return False def is_valid_priority(priority_value, priority_map): """ param1- a string that should contain an integer priority value param2- a dictionary that contains the mapping between the integer priority value to its representation returns: - true if the string contains an integer value that maps to a key in the dictionary - false otherwise """ if (type(priority_value) == str) and (priority_value.isdigit() == True) and (int(priority_value) in priority_map): return True else: return False def is_valid_month(date_list): """ The function returns true if the month in the string is valid and false otherwise """ if len(date_list) == 3: for j in date_list: if type(j) != str: return False if date_list[0].isdigit(): month = int(date_list[0]) if (month > 0) and (month < 13): return True return False def is_valid_day(date_list): """ The function returns true if the day in the list is valid and false otherwise helper function: is_valid_month() """ num_days = { 1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31 } if is_valid_month(date_list): if date_list[1].isdigit(): month = int(date_list[0]) day = int(date_list[1]) if (day > 0) and (day <= num_days[month]): return True return False def is_valid_year(date_list): """ The function returns true if the year in the list is valid and false otherwise """ if len(date_list) == 3: for j in date_list: if type(j) != str: return False if date_list[2].isdigit(): year = int(date_list[2]) if year > 1000: return True return False def is_valid_date(date_string): """ param1- a string that should contain a date in the format (MM/DD/YYYY) validates each date component returns: - true if string is valid date in correct format - false otherwise helper_functions: is_valid_month() is_valid_day() is_valid_year() """ date_list = date_string.split('/') if (is_valid_month(date_list) == True) and (is_valid_day(date_list) == True) and (is_valid_year(date_list) == True): return True else: return False def is_valid_completion(completion): """ param1- a string that should be either 'yes' or 'no' if string either, the function will return true and if otherwise the function will return false """ if completion == 'yes' or completion == 'no': return True else: return False def get_new_task(new_task, priority_map): """ param1: a list with 5 strings (check) param2: dictionary containing mapping between the integer priority value returns: - integer size of list if the size of list is not correct - tuple with ("type", <value>) if any of the elements on the list are not of type string - if size and str is correct, but validation fails, returns tuple with name of parameter and corresponding value/parameter that failed - if all passes, returns new dictionary with task keys set to provided parameters helper functions: is_valid_name() is_valid_priority() is_valid_date() is_valid_completion() """ if len(new_task) != 5: return len(new_task) for element in new_task: if type(element) != str: return "type", element new_entry = {} if (is_valid_name(new_task[0]) == True) and (is_valid_priority(new_task[2], priority_map) == True) and (is_valid_date(new_task[3]) == True) and (is_valid_completion(new_task[4]) == True): new_entry["name"] = new_task[0] new_entry["info"] = new_task[1] new_entry["priority"] = int(new_task[2]) new_entry["duedate"] = new_task[3] new_entry["done"] = new_task[4] return new_entry elif is_valid_name(new_task[0]) == False: return "name", new_task[0] elif (is_valid_priority(new_task[2], priority_map) == False): return "priority", (new_task[2]) elif is_valid_date(new_task[3]) == False: return "duedate", new_task[3] elif is_valid_completion(new_task[4]) == False: return "done", new_task[4] def load_tasks_from_csv(filename, in_list, priority_map): """ param: filename (str) - A string variable which represents the name of the file from which to read the contents. param: in_list (list) - A list of task dictionary objects to which the tasks read from the provided filename are appended. If in_list is not empty, the existing tasks are not dropped. param: priority_map (dict) - a dictionary that contains the mapping between the integer priority value (key) to its representation (e.g., key 1 might map to the priority value "Highest" or "Low") Needed by the helper function. The function ensures that the last 4 characters of the filename are '.csv'. The function requires the `import csv` and `import os`. If the file exists, the function will use the `with` statement to open the `filename` in read mode. For each row in the csv file, the function will proceed to create a new task using the `get_new_task()` function. - If the function `get_new_task()` returns a valid task object, it gets appended to the end of the `in_list`. - If the `get_new_task()` function returns an error, the 1-based row index gets recorded and added to the NEW list that is returned. E.g., if the file has a single row, and that row has invalid task data, the function would return [1] to indicate that the first row caused an error; in this case, the `in_list` would not be modified. If there is more than one invalid row, they get excluded from the in_list and their indices will be appended to the new list that's returned. returns: * -1, if the last 4 characters in `filename` are not '.csv' * None, if `filename` does not exist. * A new empty list, if the entire file is successfully read from `in_list`. * A list that records the 1-based index of invalid rows detected when calling get_new_task(). Helper functions: - get_new_task() """ import os import csv if filename[-4:] != '.csv': return -1 if not os.path.exists(filename): return None else: new_list = [] with open(filename, 'r') as csvfile: file_reader = csv.reader(csvfile, delimiter = ',') row_num = 1 for row in file_reader: if type(get_new_task(row, priority_map)) == dict: in_list.append(row) return [] if type(get_new_task(row, priority_map)) != dict: new_list.append(row_num) row_num += 1 return new_list def save_tasks_to_csv(tasks_list, filename): """ param: tasks_list - The list of the tasks stored as dictionaries param: filename (str) - A string that ends with '.csv' which represents the name of the file to which to save the tasks. This file will be created if it is not present, otherwise, it will be overwritten. The function ensures that the last 4 characters of the filename are '.csv'. The function requires the `import csv`. The function will use the `with` statement to open the file `filename`. After creating a csv writer object, the function uses a `for` loop to loop over every task in the list and creates a new list containing only strings - this list is saved into the file by the csv writer object. The order of the elements in the list is: * `name` field of the task dictionary * `info` field of the task dictionary * `priority` field of the task as a string (i.e, "5" or "3", NOT "Lowest" or "Medium") * `duedate` field of the task as written as string (i.e, "06/06/2022", NOT "June 6, 2022") * `done` field of the task dictionary returns: -1 if the last 4 characters in `filename` are not '.csv' None if we are able to successfully write into `filename` """ import csv file_list = [] if filename[-4:] != '.csv': return -1 else: with open(filename, 'w', newline='') as csvfile: file_reader = csv.reader(csvfile) for file_tasks in tasks_list: for file_value in file_tasks.items(): file_list.append(str(file_value)) def update_task(info_list, idx, priority_map, field_key, field_info, start_idx = 0): """ param: info_list - a list that contains task dictionaries param: idx (str) - a string that is expected to contain an integer index of an item in the input list param: start_idx (int) - by default is set to 0; an expected starting value for idx that gets subtracted from idx for 0-based indexing param: priority_map (dict) - a dictionary that contains the mapping between the integer priority value (key) to its representation (e.g., key 1 might map to the priority value "Highest" or "Low") Needed if "field_key" is "priority" to validate its value. param: field_key (string) - a text expected to contain the name of a key in the info_list[idx] dictionary whose value needs to be updated with the value from field_info param: field_info (string) - a text expected to contain the value to validate and with which to update the dictionary field info_list[idx][field_key]. The string gets stripped of the whitespace and gets converted to the correct type, depending on the expected type of the field_key. The function first calls one of its helper functions to validate the idx and the provided field. If validation succeeds, the function proceeds with the update. return: If info_list is empty, return 0. If the idx is invalid, return -1. If the field_key is invalid, return -2. If validation passes, return the dictionary info_list[idx]. Otherwise, return the field_key. Helper functions: The function calls the following helper functions: - is_valid_index() Depending on the field_key, it also calls: - is_valid_name() - is_valid_priority() - is_valid_date() - is_valid_completion() """ if info_list == []: return 0 if is_valid_index(idx, info_list, start_idx) == False: return -1 if field_key == 'name': if is_valid_name(field_info) == True: info_list[int(idx)-1][field_key] = field_info return info_list[int(idx)-1] else: return field_key if field_key == 'info': info_list[int(idx)-1][field_key] = field_info return info_list[int(idx)-1] if field_key == 'priority': if is_valid_priority(field_info, priority_map) == True: info_list[int(idx)-1][field_key] = int(field_info) return info_list[int(idx)-1] else: return field_key if field_key == 'duedate': if is_valid_date(field_info) == True: info_list[int(idx)-1][field_key] = field_info return info_list[int(idx)-1] else: return field_key if field_key == 'done': if is_valid_completion(field_info) == True: info_list[int(idx)-1][field_key] = field_info return info_list[int(idx)-1] else: return field_key else: return -2
katieli3/task-organizer
task_functions.py
task_functions.py
py
22,169
python
en
code
0
github-code
6
21499361084
import importlib import matplotlib import matplotlib.pyplot as plt import numpy as np import os import pandas as pd import re import seaborn as sns import shutil from datetime import timedelta from file_read_backwards import FileReadBackwards from functools import partial from getpass import getuser from openpyxl import load_workbook from openpyxl.styles import Font, PatternFill, Alignment, Border, Side from openpyxl.utils import get_column_letter from pathlib import Path from prettytable import PrettyTable from scipy.fft import fft, fftfreq from socket import gethostname from statistics import stdev, mean from tqdm import tqdm from warnings import warn import utils.find as find import utils.fetch as fetch import utils.constants as cst # * =================================================================================================== def issteady(run: str) -> bool: log_file = find.find_logs(find.find_runs(run)[0])[0] with FileReadBackwards(log_file) as frb: for line in frb: if line.startswith("Time ="): if line.split()[-1].isdigit(): return True else: return False # * =================================================================================================== def ncol(handles: list) -> int: max_text_length = 60 nhandles = len(handles) total_length = sum(len(text) for text in handles) + 3 * nhandles if total_length > max_text_length: if nhandles > 6: ncol = 4 else: ncol = max(int(nhandles / 2), int((nhandles + 1) / 2)) row_index = range(0, nhandles - ncol, ncol) for i in row_index: words_in_row = [handles[k] for k in range(i, i + ncol)] if sum(len(word) for word in words_in_row) > max_text_length: ncol -= 1 break else: ncol = nhandles return ncol # * =================================================================================================== def print_header(run_dirs: list[Path]) -> None: # Check project is unique if not len({r.parent.name for r in run_dirs}) == 1: raise ValueError("Multiple project directories found.") # If unique project project = f'{cst.bmag}{run_dirs[0].parent.name}{cst.bcyan}' runs_num = [k.name for k in run_dirs] format_runs = f'{cst.bmag}{f"{cst.reset}, {cst.bmag}".join(sorted(runs_num))}{cst.bcyan}' title_df = pd.DataFrame({f'{cst.reset}{cst.bold}PROJECT{cst.bcyan}': project, f'{cst.reset}{cst.bold}RUN(S){cst.bcyan}': format_runs}, index=['Data']) # Create a prettytable object pt = PrettyTable() for col in title_df.columns: pt.add_column(col, title_df[col].values) pt.align[col] = 'c' pt.min_width[col] = int(shutil.get_terminal_size().columns / 2) - 4 # print the table print(cst.bcyan) print(pt, end=f'{cst.reset}') print('') # * =================================================================================================== def get_avg(df: pd.DataFrame, *, rng: int, type_avg: str = 'final', **kwargs) -> dict: # Select all the columns except 'Time' by default columns = list(df.columns)[1:] # If one or more columns are specified with 'usecols' if 'usecols' in kwargs: usecols = kwargs.get('usecols') columns = [col for col in list(df.columns)[1:] if re.search(re.compile(usecols), col)] # Return a dict of the mean value of each column over rng iterations if type_avg == 'final': return {c: df.loc[:, c].tail(rng).mean() for c in columns} # Get the window of series of observations of rng size for each column elif type_avg == 'moving': windows = {c: df.loc[:, c].rolling(rng) for c in columns} # Create a series of moving averages of each window for each column moving_avgs = {k: windows.get(k).mean().tolist() for k in windows} # Remove null entries final_dict = {k: moving_avgs.get(k)[rng - 1:] for k in moving_avgs} return final_dict # * =================================================================================================== def _format_excel(file_path): # Load the Excel file workbook = load_workbook(file_path) sheet = workbook.active # Set font styles header_font = Font(name="Calibri", bold=True, size=14) content_font = Font(name="Calibri", size=12) # Set alignment alignment = Alignment(horizontal="center", vertical="center") # Set fill color fill_main = PatternFill(start_color="C7D1E0", end_color="C7D1E0", fill_type="solid") fill_data = PatternFill(start_color="F2F2F2", end_color="F2F2F2", fill_type="solid") # Set border border_color = "FF0000" thin_border = Border(top=Side(style=None), right=Side(style=None), bottom=Side(style=None), left=Side(style=None)) # Format header row for cell in sheet[1]: cell.font = header_font cell.alignment = alignment cell.fill = fill_main cell.border = thin_border cell.value = cell.value.upper() # Format content rows for row in sheet.iter_rows(min_row=2): for cell in row: cell.font = content_font cell.alignment = alignment cell.fill = fill_data cell.border = thin_border if isinstance(cell.value, (int, float)): if cell.coordinate >= 'K': cell.number_format = '0.00E+00' # Scientific notation format code # Increase header row height sheet.row_dimensions[1].height = 40 for row in sheet.iter_rows(min_row=2): sheet.row_dimensions[row[0].row].height = 20 # Calculate the maximum text length in each column max_text_lengths = {} print(sheet.column_dimensions['G'].width) for row in sheet.iter_rows(min_row=1, values_only=True): for column_index, cell_value in enumerate(row, start=1): column_letter = get_column_letter(column_index) text_length = len(str(cell_value)) if column_letter not in max_text_lengths or text_length > max_text_lengths[column_letter]: max_text_lengths[column_letter] = text_length # Set the column width as 1.2 times the maximum text length for column_letter, max_length in max_text_lengths.items(): column_width = (max_length * 1.2) + 2 # Add some extra padding sheet.column_dimensions[column_letter].width = column_width # Save the modified Excel file workbook.save(file_path)
vicmcl/postpro
utils/misc.py
misc.py
py
6,902
python
en
code
0
github-code
6
9752254935
import functools from flask_login import current_user, LoginManager from flask import session from src.model import UserModel login_manager = LoginManager() def roles_allowed(func=None, roles=None): """ Check if the user has at least one required role :param func: the function to decorate :param roles: an array of allowed roles """ if not func: return functools.partial(roles_allowed, roles=roles) @functools.wraps(func) def f(*args, **kwargs): role = session.get("ROLE") if not any(role in s for s in roles): return login_manager.unauthorized() return func(*args, **kwargs) return f @login_manager.user_loader def load_user(user_id): # user = User.query.get(user_id) if "current_user" in session: user = UserModel() user.fill_from_json(session["current_user"]) user.set_authenticated(True) return user return None
GreyTeam2020/GoOutSafe_microservice
gateway/src/auth.py
auth.py
py
949
python
en
code
3
github-code
6
25131590072
# /usr/bin/python #**************TOPOLOGY ******************* # H1----------S1------------ # (10.0.1.10\24) \ # \ # H2---------S2---------CORE SWITCH------------S4---------SERVER(10.0.4.10/24) # (10.0.1.20\24) / | # / | # H3---------S3------------- |_____H4(10.0.2.10/24) # (10.0.1.30\24) from mininet.topo import Topo from mininet.net import Mininet from mininet.util import dumpNodeConnections from mininet.log import setLogLevel, info from mininet.cli import CLI from mininet.node import RemoteController class ques2_topo(Topo): def build(self): #add switches print( '*** Add switches to topology') s1 = self.addSwitch('s1') s2 = self.addSwitch('s2') s3 = self.addSwitch('s3') cs12 = self.addSwitch('cs12') #core switch s4 = self.addSwitch('s4') #add hosts by defining their mac address,ip address and default router print( '*** Add hosts to topology') h1 = self.addHost('h1',mac='00:00:00:00:00:01',ip='10.0.1.10/24',defaultRoute='h1-eth0') h2 = self.addHost('h2',mac='00:00:00:00:00:02',ip='10.0.2.20/24',defaultRoute='h2-eth0') h3 = self.addHost('h3',mac='00:00:00:00:00:03',ip='10.0.3.30/24',defaultRoute='h3-eth0') h4 = self.addHost('h4',mac='00:00:00:00:00:05',ip='10.0.2.10/24',defaultRoute='h4-eth0') server = self.addHost('server',mac='00:00:00:00:00:04',ip='10.0.4.10/24',defaultRoute='server-eth0') #add links print( '*** Add links to topology') self.addLink(h1,s1) #link between h1 and s1 self.addLink(h2,s2) #link between h2 and s2 self.addLink(h3,s3) #link between h3 and s3 self.addLink(s1,cs12) #link between s1 and core self.addLink(s2,cs12) #link between s2 and core self.addLink(s3,cs12) #link between s3 and core self.addLink(server,s4) #link between server and s4 self.addLink(cs12,s4) #link between core and s4 self.addLink(h4,cs12) #link between h4 and core print('*** Post configure switches and hosts\n') topos = {'ques2' : ques2_topo} def configure(): topo = ques2_topo() net = Mininet(topo=topo, controller=RemoteController) print( '*** Adding controller to topology ' ) print( '*** Starting network') net.start() CLI(net) net.stop() if __name__ == '__main__': configure()
khyatimehta11/SDN-Mininet-
B part/topo and controller file/topob.py.py
topob.py.py
py
2,384
python
en
code
1
github-code
6
34218162586
# -*- coding: utf-8 -*- """ Created on Tue Feb 8 11:01:20 2022 @author: sonne """ #0. Imports from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure import matplotlib.patches as patches import matplotlib.animation as animation import matplotlib.ticker as ticker import tkinter as Tk #Interface import numpy as np #Numerische Mathematik import itertools #für Iteration import random #Zufallszahlen from scipy.constants import k #Boltzmann-Konstante #1. Dictionaries für die Edelgase Masse = {"Helium" : 6.642e-27, "Neon" : 3.351e-26, "Argon" : 6.634e-26, "Krypton" : 1.392e-25, "Xenon": 2.180e-25} Durchmesser = {"Helium" : 36.58, # 1.4e-10m "Neon" : 44.22, # 1.58e-10m "Argon" : 65.96, # 1.88e-10m "Krypton" : 76.15, # 2.00e-10m "Xenon": 87.07} # 2.18e-10m Farbe = {"Helium" : "blue", "Neon" : "darkblue", "Argon" : "blueviolet", "Krypton" : "purple", "Xenon": "indigo"} LennardJones_epsilon = {"Helium" : 14e-23, "Neon" : 50e-23, "Argon" : 167e-23, "Krypton" : 225e-23, "Xenon": 320e-23} LennardJones_sigma = {"Helium" : 2.56e-10, "Neon" : 2.74e-10, "Argon" : 3.4e-10, "Krypton" : 3.65e-10, "Xenon": 3.98e-10} #2. Figure für Plot erstellen #2.1 für die Simulation fig = Figure(figsize = (6,6)) ax = fig.add_subplot(111) #2.2 für Beschleunigungspfeil arrow = Figure(figsize = (1.5,1.5)) #Zweites Plotfenster für den Beschleunigungsvektor arr = arrow.add_subplot(111) arr.set_xlim(-1,1) arr.set_ylim(-1,1) arr.axes.xaxis.set_visible(False) #Achsen zur Übersichtlichkeit ausgeblendet arr.axes.yaxis.set_visible(False) Inaktiv_text = arr.text(0,0,'Aktiviere \n"Teilchen verfolgen"', ha="center", va = "center", fontsize = 8.) #Text in der Figure zu Beginn Pfeil = patches.Arrow(0, 0, 0, 0) #Pfeilobjekt mit Länge 0 erstellen patch = arr.add_patch(Pfeil) #Pfeil zu Plot hinzufügen #3. Interface mit Tkinter class Interface(): def __init__(self, Teilchentracker_aus = True): self.root = Tk.Toplevel() self.Teilchentracker_aus = Teilchentracker_aus #3.1 Tkinter-Fenster konfigurieren self.root.title("C5 Molecular Dynamics") #Titel des Fensters self.root.geometry("1400x800") #Größe des Fensters in Pixel self.root.config(bg = "white") #weißer Hintergrund self.root.columnconfigure(0, weight=3) self.root.columnconfigure(1, weight=1) self.root.columnconfigure(2, weight =1) self.Ueberschrift = Tk.Label(self.root,text="Thermal motion", font = "Verdana 20 bold", \ bg = "white").grid(column=0, row=0) #3.2 Canvas für die Simulation und für den Beschleunigungspfeil erstellen self.canvas = FigureCanvasTkAgg(fig, master=self.root) #für Simulation self.canvas.get_tk_widget().grid(column=0, row=1, rowspan = 9, sticky = Tk.N) self.Label_Beschleunigungspfeil = Tk.Label(self.root, text = "Acceleration",\ font = "Verdana 10 bold", bg = "white").grid(column = 2, row = 1) self.canvas_arrow = FigureCanvasTkAgg(arrow, master=self.root) #für Pfeil self.canvas_arrow.get_tk_widget().grid(column=2, row =2, rowspan = 2, sticky = Tk.N, pady = 10) #3.2 Schieberegler für Änderung der Temperatur self.Label_Temperatur = Tk.Label(self.root, text = "Temperature in K", font = "Verdana 10 bold",\ bg = "white").grid(column = 1, row =1) self.Slider_Temperatur = Tk.Scale(self.root, from_=1, to=2000, orient = "horizontal",\ bg = "white") #Schieberegler self.Slider_Temperatur.grid(column = 1, row = 2) #Schieberegler platzieren self.Slider_Temperatur.set(300) #Startwert self.Button_Temperatur = Tk.Button(self.root, text="Change temperature", bg= "lightgreen", \ compound = "left", width = 18, command= \ self.update_Temperatur).grid(column = 1, row = 3) #Knopf, ruft Funktion für Temperatur auf #3.3 Schieberegler für Änderung der Teilchenzahl self.Label_Teilchenzahl = Tk.Label(self.root, text = "Number of particles", \ font = "Verdana 10 bold", bg = "white").grid(column = 1, row = 4, sticky= Tk.S) self.Slider_Teilchenzahl = Tk.Scale(self.root, from_=1, to=20,\ orient = "horizontal", bg = "white") #Schieberegler self.Slider_Teilchenzahl.grid(column = 1, row = 5) #Schieberegler platzieren self.Slider_Teilchenzahl.set(5) #Startwert self.Button_Teilchenzahl = Tk.Button(self.root, text="Change number of particles",\ bg = "lightgreen", compound = "left", width = 18,\ command=self.update_Teilchenzahl).grid(column = 1, row = 6) #Knopf, ruft Funktion für Teilchenzahl auf #3.4 Dropdownmenü für Änderung der Teilchenart self.Label_Teilchenart = Tk.Label(self.root, text = "Gas type", font = "Verdana 10 bold",\ bg = "white").grid(column = 1, row = 7, sticky = Tk.S) Edelgase = ["Helium","Neon", "Argon","Krypton","Xenon"] #Liste der Optionen Variable = Tk.StringVar() #Definition des Wert des Widgets, Hält eine Zeichenfolge; Standardwert "" Variable.set(Edelgase[0]) #gibt an welches Element der Liste im Menü angezeigt wird self.dropdown = Tk.OptionMenu(self.root, Variable, *Edelgase, command= \ self.update_Teilchenart).grid(column = 1, row = 8) #Widget für Dropdown-Menü erstellen #3.5 Label mit Informationen zur aktuellen Simulation self.Infos = Tk.Label(self.root, text = "Informationen", bg = "white", font = \ "Verdana 10 bold").grid(column = 2, row = 7, sticky = Tk.S) self.Label_Infos = Tk.Label(self.root, text = "Infos", justify = "left") #Label erstellen self.Label_Infos.grid(column = 2, row = 8) #Label platzieren #3.6 Teilchentracker zum An- und Ausschalten self.Label_Teilchentracker = Tk.Label(self.root, text = "Track particle", font = \ "Verdana 10 bold", bg = "white").grid(column = 2, row = 4, sticky = Tk.S) self.Button_teilchen_verfolgen = Tk.Button(self.root, fg = "darkgreen", text="Teilchen verfolgen", bg = "white",\ height = 2, command=self.teilchen_verfolgen).grid(column = 2, row = 5, \ rowspan = 2, sticky = Tk.N, pady = 12) #Knopf, aktiviert Teilchentracker #3.7 Stopp-Knopf zum Beenden des Programms self.Beenden = Tk.Button(self.root, text = "Interrupt", fg= "white", bg="maroon",\ command = self.stopp, width = 65).grid(column = 1, row = 9, columnspan = 2) #Knopf, ruft Stopp-Funktion auf #Funktionen für Tkinter-Schaltflächen: def update_Temperatur(self): box.Temperatur = self.Slider_Temperatur.get() #Wert des Schiebereglers abrufen box.start_Animation() #Startbedingungen aktualisieren def update_Teilchenzahl(self): box.Teilchenzahl = self.Slider_Teilchenzahl.get() #Wert des Schiebereglers abrufen box.particles = [Particle(i) for i in range(box.Teilchenzahl)] #neue Teilchen erstellen box.start_Animation() #Startbedingungen aktualisieren def update_Teilchenart(self, Variable): partikel.Teilchenart = str(Variable) #Teilchenart als String speichern (für Infolabel) partikel.m = Masse.get(Variable) #Masse im Dictionary nachschlagen und aktualisieren partikel.R = Durchmesser.get(Variable) #Teilchenradius im Dictionary nachschlagen und aktualisieren partikel.color = Farbe.get(Variable) #Farbe im Dictionary nachschlagen und aktualisieren partikel.epsilon = LennardJones_epsilon.get(Variable) #Parameter im Dictionary nachschlagen und aktualisieren partikel.sigma = LennardJones_sigma.get(Variable) #Parameter im Dictionary nachschlagen und aktualisieren box.start_Animation() #Startbedingungen aktualisieren def teilchen_verfolgen(self): #Möglichkeit die Farbe eines Teilchens zu ändern und den Beschleunigungsvektor zu verfolgen global patch, Inaktiv_text if self.Teilchentracker_aus: #wenn noch nicht aktiv Inaktiv_text.remove() #Text aus Plot entfernen arrow.canvas.draw() self.Button_teilchen_verfolgen = Tk.Button(self.root, foreground = "white",\ text="Teilchen entfolgen", bg = "darkgreen", height = 2,\ command=self.teilchen_verfolgen).grid(column = 2, row = 5,\ rowspan = 2, sticky = Tk.N, pady = 12) #Knopf ändert sein Aussehen self.Teilchentracker_aus = False else: #falls schon aktiv Inaktiv_text = arr.text(0,0,'Aktiviere \n"Teilchen verfolgen"', ha="center", va = "center", fontsize = 8.) #Text in Plot einfügen arrow.canvas.draw() self.Button_teilchen_verfolgen = Tk.Button(self.root, foreground = "darkgreen",\ text="Teilchen verfolgen", bg = "white", height = 2,\ command=self.teilchen_verfolgen).grid(column = 2, row = 5,\ rowspan = 2, sticky = Tk.N, pady = 12) #Knopf ändert sein Aussehen patch.remove() #Pfeil entfernen Pfeil = patches.Arrow(0, 0, 0, 0) #einen neuen Pfeil der Länge 0 erstellen patch = arr.add_patch(Pfeil) #Pfeil hinzufügen arrow.canvas.draw() #Pfeil anzeigen self.Teilchentracker_aus = True def stopp(self): self.root.destroy() #Tkinter-Fenster schließen self.root.quit() #Programmausführung stoppen interface = Interface() #auf die Klasse Interface() mit interface zugreifen #4. Beschleunigungspfeil für das erste Teilchen def pfeil(Beschleunigung): global patch if interface.Teilchentracker_aus == False: #nur wenn Teilchentracker aktiv ist Betrag_Beschleunigung = np.sqrt(Beschleunigung[0]**2 + Beschleunigung[1]**2) if Betrag_Beschleunigung != 0: patch.remove() #Pfeil entfernen Pfeil_x = Beschleunigung[0]/np.abs(Beschleunigung[0]) \ * np.log(np.abs(Beschleunigung[0]))/50 #logarithmisch skalierte Beschleunigung, #um die nötigen Größenordnungen abzudecken Pfeil_y = Beschleunigung[1]/np.abs(Beschleunigung[1]) \ * np.log(np.abs(Beschleunigung[1]))/50 #logarithmisch skalierte Beschleunigung Pfeil = patches.FancyArrow(0, 0, Pfeil_x, Pfeil_y, color = "maroon", width = 0.05, overhang = 0.2,\ head_width = 0.25, head_length = 0.3) #Pfeil mit den Komponenten der #Beschleunigung erstellen patch = arr.add_patch(Pfeil) #Pfeil hinzufügen arrow.canvas.draw() #Pfeil anzeigen #5. Kritischer Radius kritischerRadius = 4e-9 # entspricht 40% der Boxgröße, um Rechenaufwand zu reduzieren #6. Teilchen als Klasse: class Particle(): #Ordnet jedem Teilchen einen Radius (R), Masse (m), Farbe (color), #und die Parameter für das Lennard-Jones-Potential (sigma, epsilon) zu def __init__(self, R = 36.58, m = 6.642e-27, color = "blue", epsilon = 14e-23, sigma = 2.56e-10, Teilchenart = "Helium"): self.R, self.m, self.color, self.epsilon, self.sigma, self.Teilchenart = R, m, color, epsilon, sigma, Teilchenart partikel = Particle() #auf Klasse Particle() als partikel zugreifen # 7. Funktionen für die Bewegung der Teilchen in der Box class Box(): #enthält die Funktionen für die Bewegung der Teilchen in der Box def __init__(self, Teilchenzahl = 5, dt=4E-15, Temperatur = 300, Boxgroesse = 1e-8,\ Anfangsgeschwindigkeit = 1367.8, E_gesamt = 3.1e-20): #Default-Werte für Anzahl der Teilchen, Zeitintervall, Temperatur, Boxgröße, Anfangsgeschwindigkeit, Gesamtenergie self.dt, self.Teilchenzahl, self.Temperatur, self.Boxgroesse, self.Anfangsgeschwindigkeit, \ self.E_gesamt = dt, Teilchenzahl, Temperatur, Boxgroesse, Anfangsgeschwindigkeit, E_gesamt self.particles = [Particle(i) for i in range(self.Teilchenzahl)] #für jedes Teilchen eine Instanz der Particle-Klasse erstellen #7.1 Startbedingungen für die Simulation berechnen und festlegen def start_Animation(self): self.scatter = ax.scatter([],[], s= partikel.R) #Streudiagramm mit Teilchen als Marker, Größe entsprechend des Teilchenradius self.Anfangsgeschwindigkeit = self.mittlere_Geschwindigkeit(self.Temperatur) #Anfangsgeschwindigkeit aus Temperatur berechnen self.E_gesamt = self.gesamtenergie(self.Teilchenzahl, self.Anfangsgeschwindigkeit) #Gesamtenergie aus kinetischer Energie bestimmen Infos = "Edelgas: " + partikel.Teilchenart + \ "\nMasse: %10.3e kg \nGesamtenergie: %10.3e J \nMittlere Geschwindigkeit: %8.2f m/s" \ % (partikel.m, box.E_gesamt, box.Anfangsgeschwindigkeit) #Text für das Info-Label interface.Label_Infos.configure(text = Infos) #Labelinhalt aktualisieren box.startpositionen() #Startpositionen-Funktion aufrufen for particle in self.particles: angle = random.uniform(-1, 1) #zufälliger Winkel für Richtung der Geschwindigkeit particle.v = np.array([(np.cos(angle * np.pi/2)), (np.sin(angle * np.pi/2))]) \ * self.Anfangsgeschwindigkeit #Anfangsgeschwindigkeit als Array definieren particle.a = np.zeros(2) #Beschleunigung zum Zeitpunkt t=0 ist Null #7.1.1 Anfangsgeschwindigkeit der Teilchen als mittlere Geschwindigkeit festlegen def mittlere_Geschwindigkeit(self, T): return np.sqrt(3*k*T/partikel.m) #Als mittlere Geschwindigkeit über Temperatur berechnen #7.1.2 Gesamtenergie aller Teilchen berechnen def gesamtenergie(self, Teilchenzahl, v): return Teilchenzahl * 0.5 * partikel.m * v**2 #Summe der kinetischen Energie #7.1.3 Startpostitionen der Teilchen zufällig bestimmen def startpositionen(self): for particle in self.particles: particle.r = 100*np.random.uniform(0, self.Boxgroesse/100, size=2) #Startposition zufällig #innerhalb des Kastens festlegen #Wiederholung der zufälligen Teilchenverteilung bei Überlappung von 2 Teilchen zu Beginn der Animation for particle, particle2 in itertools.combinations(self.particles, 2): #für jedes Teilchenpaar # Abstand berechnen x_diff = particle.r[0] - particle2.r[0] y_diff = particle.r[1] - particle2.r[1] Abstand = np.sqrt(x_diff**2 + y_diff**2) if Abstand < 1.12*partikel.sigma: #wenn Abstand kleiner abstoßende Wechselwirkunegn box.startpositionen() #neue Startpositionen berechnen #7.2 Trajektorien der Teilchen über Velocity-Verlet-Algorithmus bestimmen def zeitliche_Entwicklung(self, particles, Boxgroesse, dt, E_gesamt): box.kollision_Box(particles, Boxgroesse) #elastische Stöße mit Wand berücksichtigen for particle in particles: particle.r += dt * particle.v + dt**2*particle.a #Ort nach Velocity-Verlet-Algorithmus bestimmen particle.a_vorher = particle.a #Wert für die Beschleunigung für nächsten Zeitschritt speichern particle.a = np.zeros(2) #Beschleunigung wieder auf Null setzen vor neuer Evaluation des Potentials box.beschleunigung(particles) #Beschleunigung aus dem Potential berechnen particle.v = (particle.v + dt/2 * (particle.a + particle.a_vorher)) \ * box.normierung(particles, E_gesamt) #Geschwindigkeit nach Velocity-Verlet-Algorithmus bestimmen und normieren pfeil(box.particles[0].a) #Beschleunigungspfeil updaten #7.2.1 Elastische Stöße mit den Wänden der Box def kollision_Box(self, particles, Boxgroesse): for particle in self.particles: for i in range(0,2): #für x- und y-Koordinate if particle.r[i] >= Boxgroesse: particle.r[i] = Boxgroesse #Verhindert 'Tunneling', wo die Geschwind. eines sehr schnellen # Teilchens vor Rückkehr in den Kasten zweimal gespiegelt wird particle.v[i] *=-1 #Spiegelung der Geschwindigkeit if particle.r[i] <= 0: particle.r[i] = 0 #s.o. particle.v[i] *=-1 #7.2.2 Abstand und Beschleunigung der Teilchen bestimmen def beschleunigung(self, particles): for particle, particle2 in itertools.combinations(self.particles, 2): #über alle Paare von Teilchen iterieren #Abstand berechnen x_diff = particle.r[0] - particle2.r[0] y_diff = particle.r[1] - particle2.r[1] Abstand = np.sqrt(x_diff**2 + y_diff**2) #Wechselwirkung aus Potential berechnen: if Abstand < kritischerRadius: #nur Wechselwirkung bestimmen, wenn innerhalb des kritischen Radius Wechselwirkung = self.lennardJones_Kraft(Abstand) #Abstand in Lennard-Jones-Potential einsetzen particle.a[0] -= 1/(partikel.m) * Wechselwirkung * x_diff/Abstand particle.a[1] -= 1/(partikel.m) * Wechselwirkung * y_diff/Abstand particle2.a[0] += 1/(partikel.m) * Wechselwirkung * x_diff/Abstand particle2.a[1] += 1/(partikel.m) * Wechselwirkung * y_diff/Abstand #7.2.3 Lennard-Jones-Potential def lennardJones_Kraft(self, Distanz): #Kraft als Gradient des LennardJones-Potentials in Abhängigkeit #vom Abstand der Teilchen return (-24 * partikel.epsilon) * (2 *(partikel.sigma**12 / Distanz**13) -(partikel.sigma**6 / Distanz**7)) #7.2.4 Geschwindigkeiten für Energieerhaltung normieren def normierung(self, particles, E_gesamt): Summe_v=0 for particle in particles: Summe_v += particle.v**2 #alle Geschwindigkeitsquadrate aufaddieren return np.sqrt(E_gesamt /(0.5*Particle().m*Summe_v)) #neue Gesamtenergie bestimmen und Skalierungsfaktor zurückgeben #7.3 Position der Teilchen zurückgeben def position(self, particles): #Funktion um den Ort jedes Teilchens an die Animation zu übergeben return [particle.r for particle in particles] box = Box() #auf die Klasse Box() als box zugreifen #8. Animation starten und Programm ausführen def particle_Farbe(particles): for particle in box.particles: particle.color = partikel.color #jedem Teilchen die Farbe des Edelgases aus der Particle-Klasse zuweisen if interface.Teilchentracker_aus == False: #wenn Teiclhentracker aktiviert box.particles[0].color = "red" #erstes Teilchen wird rot eingefärbt return [particle.color for particle in box.particles] #Farben zurückgeben def init(): #Box darstellen ax.set_xlim (0, box.Boxgroesse) #Boxgröße einstellen ax.set_ylim (0, box.Boxgroesse) ax.xaxis.set_major_locator(ticker.FixedLocator(np.arange(0,12e-9, 2e-9))) #Ticklabels einstellen ax.yaxis.set_major_locator(ticker.FixedLocator(np.arange(0,12e-9, 2e-9))) ax.xaxis.set_ticklabels(np.arange(0,11,2)) #Beschriftungen in nm festlegen ax.yaxis.set_ticklabels(np.arange(0,11,2)) ax.set_xlabel("Boxbreite in nm") #Achsenbeschriftung return box.scatter, def update(frame): #Funktion für die Animation (FunAn) box.zeitliche_Entwicklung(box.particles, box.Boxgroesse, box.dt, box.E_gesamt) #Funktion für zetilche Entwicklung aufrufen box.scatter.set_offsets(np.array(box.position(box.particles))) #neuen Ort der Marker übernehmen box.scatter.set_color(particle_Farbe(box.particles)) #Farbe der Teilchen ggf. ändern return box.scatter, box.start_Animation() #Funktion für Startbedingungen aufrufen ani = animation.FuncAnimation(fig, update , frames=range(10000), init_func = init, blit=True,\ interval = 1/2000, repeat = True) #Animation abrufen Tk.mainloop() #Tkinter-Fenster aufrufen
tappelnano/molecular_dynamics
2022_02_13_C5_Molekulardynamik.py
2022_02_13_C5_Molekulardynamik.py
py
22,402
python
de
code
0
github-code
6
11961734737
#!/usr/bin/env python import unittest import rospy import rostest from pprint import pprint from rospy_message_transporter.msg import HeartbeatMessage from rospy_message_transporter.JsonFormatter import JsonFormatter class TestMessageFormatter(unittest.TestCase): def test_json_formatter_instanciation(self): expected_msg_typ_attr_name = 'messageType' msg_typ_info = {} msg_typ_info['HelloMessage'] = 'rospy_message_transporter' msg_typ_info['HeartbeatMessage'] = 'rospy_message_transporter' message_formatter = JsonFormatter(expected_msg_typ_attr_name,msg_typ_info) self.assertEqual(message_formatter.msg_typ_attr_name, expected_msg_typ_attr_name) self.assertEqual(message_formatter.msg_typ_info, msg_typ_info) def test_json_format_from_ros_msg(self): msg_typ_info = {} msg_typ_info['HelloMessage'] = 'rospy_message_transporter' msg_typ_info['HeartbeatMessage'] = 'rospy_message_transporter' message_formatter = JsonFormatter('messageType',msg_typ_info) msg = HeartbeatMessage() msg.droneID = "UAV123" msg.sessionID = "SE123" msg.batteryLevel = 0.7 msg.status = 0 msg.latitude = 40 msg.longitude = 40 msg.altitude = 40 json = message_formatter.format_from_ros_msg(msg) expected_json = '{"status": 0, "droneID": "UAV123", "altitude": 40, "longitude": 40, "sessionID": "SE123", "messageType": "", "latitude": 40, "batteryLevel": 0.7}' self.assertEqual(json, expected_json) def test_json_formatter_to_ros_msg(self): msg_typ_info = {} msg_typ_info['HelloMessage'] = 'rospy_message_transporter' msg_typ_info['HeartbeatMessage'] = 'rospy_message_transporter' message_formatter = JsonFormatter('messageType',msg_typ_info) json = '{"status": 0, "droneID": "UAV123", "altitude": 40, "longitude": 40, "sessionID": "SE123", "latitude": 40, "batteryLevel": 0.7, "messageType": "HeartbeatMessage"}' msg = message_formatter.format_to_ros_msg(json) expected_msg = HeartbeatMessage() expected_msg.droneID = "UAV123" expected_msg.sessionID = "SE123" expected_msg.batteryLevel = 0.7 expected_msg.status = 0 expected_msg.latitude = 40 expected_msg.longitude = 40 expected_msg.altitude = 40 expected_msg.messageType = "HeartbeatMessage" self.assertEqual(msg, expected_msg) self.assertTrue(isinstance(msg, HeartbeatMessage)) PKG = 'rospy_message_transporter' NAME = 'rospy_message_transporter' if __name__ == '__main__': rostest.unitrun(PKG, NAME, TestMessageFormatter)
mfsriti/rospy_message_transporter
test/test_message_formatter.py
test_message_formatter.py
py
2,690
python
en
code
0
github-code
6
12260712099
#!/usr/bin/env python # -*- coding:utf-8 -*- import pymysql money_all=56.75+2+938.7+83.2 money_all_str=str(money_all) print(money_all_str) money_real=int(money_all) print(str(money_real)) print(7/3) print(7//5) print(35<54) def sort(x): return x['price'] mydb=pymysql.connect( host="localhost", user='root', password="123456", ) cursor=mydb.cursor() sqltext='show databases' cursor.execute(sqltext) for row in cursor: print(row)
hedychium/python_learning
erase_zero.py
erase_zero.py
py
459
python
en
code
0
github-code
6
3037493070
import sys input = sys.stdin.readline n, m = map(int, input().split()) arr = sorted([int(input()) for _ in range(n)]) def sol(m): i = 1 # 불가능한 시간의 최댓값 M = m*arr[0] # 가능한 시간의 최댓값 if len(arr)== 1: return M while M-i>=2: j = (i+M)//2 # 중간값 s = 0 # 심사 받은 인원의 수 for a in arr: if s < m: # 현재 m명 미만 검사했으면 계속 검사 s += j//a else: # 현재 m명 이상 검사 가능하면 그만 break if s >= m: # m명보다 더 검사했으면 시간의 최댓값 M을 중간값 j로 교체 M = j else: # m명보다 더 적게 검사했으면 시간의 최솟값 i를 중간값 j로 교체 i = j return M print(sol(m))
sunyeongchoi/sydsyd_challenge
argorithm/3079_gw.py
3079_gw.py
py
877
python
ko
code
1
github-code
6
71243441147
import random import string #Image:一个画布 #ImageDraw:一个画笔 #ImageFont:画笔的字体 from PIL import Image,ImageDraw,ImageFont #Captcha验证码 class Captcha(object): #生成几位验证码 number = 4 #验证码图片的宽度和高度 size = (100,30) #验证码字体大小 fontsize = 25 #加入干扰线的条数 line_number = 2 # 构建一个验证码源文件 SOURCE = list(string.ascii_letters) for index in range(0,10): SOURCE.append(str(index)) #随机生成颜色 @classmethod def __gene_random_color(cls,start=0,end=255): random.seed() return (random.randint(start,end),random.randint(start,end),random.randint(start,end)) #随机产生一个字体 @classmethod def __gene_random_font(cls): fonts=[ 'cambriaz.ttf', 'consola.ttf', # 'modern.fon', # 'smalle.fon' ] #随机从列表中取一个元素 font = random.choice(fonts) return 'tool/captcha/'+font #随机生成一个字符串(包括英文和数字) @classmethod def gene_text(cls,number): #number是生成验证码的位数 return ''.join(random.sample(cls.SOURCE,number)) #生成干扰线 @classmethod def __gene_line(cls,draw,width,height): begin = (random.randint(0,width),random.randint(0,height)) end = (random.randint(0,width),random.randint(0,height)) draw.line([begin,end],fill=cls.__gene_random_color(),width=2) #绘制干扰点 @classmethod def __gene_points(cls,draw,point_chance,width,height): chance = min(100,max(0,int(point_chance))) #大小限制在[0,100] for w in range(width): for h in range(height): tmp = random.randint(0,100) if tmp > 100 - chance: draw.point((w,h),fill=cls.__gene_random_color()) #生成验证码 @classmethod def gene_captcha(cls): #验证码图片的宽和高 width,height = cls.size #创建图片(画板) image = Image.new('RGBA',(width,height),cls.__gene_random_color(0,100)) #验证码的字体 font = ImageFont.truetype(cls.__gene_random_font(),cls.fontsize) #创建画笔 draw = ImageDraw.Draw(image) # 生成字符串 text = cls.gene_text(cls.number) #获取字体的尺寸 font_width,font_height = font.getsize(text) #填充字符串 draw.text(((width - font_width) / 2,(height - font_height) / 2),text,font=font,fill=cls.__gene_random_color(150,255)) #绘制干扰线 for x in range(0,cls.line_number): cls.__gene_line(draw,width,height) #绘制噪点 cls.__gene_points(draw,10,width,height) # with open('captcha.png','wb') as fp: # image.save(fp) return (image,text)
lubocsu/BBS
tool/captcha/__init__.py
__init__.py
py
2,943
python
en
code
23
github-code
6
39249799524
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right ans = [] def inorder(root): if root is not None: if root.left: inorder(root.left) ans.append(root.val) if root.right: inorder(root.right)
midnightbot/snapalgo
snapalgo/template_generator/inorder.py
inorder.py
py
369
python
en
code
2
github-code
6
21884337737
""" Series of galactic operations (doesn't that sound cool?!). ...as in converting coordinates, calculating DM etc. """ from datetime import timedelta import ctypes as C import math import numpy as np import os import pandas as pd import random from frbpoppy.paths import paths # Import fortran libraries uni_mods = os.path.join(paths.models(), 'universe/') dm_mods = os.path.join(paths.models(), 'ne2001/') loc = os.path.join(dm_mods, 'libne2001.so') ne2001lib = C.CDLL(loc) ne2001lib.dm_.restype = C.c_float def frac_deg(ra, dec): """Convert coordinates expressed in hh:mm:ss to fractional degrees.""" # Inspired by Joe Filippazzo calculator rh, rm, rs = [float(r) for r in ra.split(':')] ra = rh*15 + rm/4 + rs/240 dd, dm, ds = [float(d) for d in dec.split(':')] if dd < 0: sign = -1 else: sign = 1 dec = dd + sign*dm/60 + sign*ds/3600 return ra, dec def lb_to_xyz(gl, gb, dist): """ Convert galactic coordinates to galactic XYZ. Args: l (float): Galactic longitude [fractional degrees] b (float): Galactic latitude [fractional degrees] dist (float): Distance to source [Gpc] Returns: gx, gy, gz: Galactic XYZ [Gpc] """ rsun = 8.5e-6 # Gpc L = np.radians(gl) B = np.radians(gb) gx = dist * np.cos(B) * np.sin(L) gy = rsun - dist * np.cos(B) * np.cos(L) gz = dist * np.sin(B) return gx, gy, gz def lb_to_radec(l, b): """ Convert galactic coordinates to RA, Dec. Formulas from 'An Introduction to Modern Astrophysics (2nd Edition)' by Bradley W. Carroll, Dale A. Ostlie (Eq. 24.19 onwards). NOTE: This function is not as accurate as the astropy conversion, nor as the Javascript calculators found online. However, as using astropy was prohibitively slow while running over large populations, frbpoppy uses this function. While this function is not as accurate, the under/over estimations of the coordinates are equally distributed meaning the errors cancel each other in the limit of large populations. Args: l (float): Galactic longitude [fractional degrees] b (float): Galactic latitude [fractional degrees] Returns: ra, dec (float): Right ascension and declination [fractional degrees] """ gl = np.radians(l) gb = np.radians(b) # Coordinates of the galactic north pole (J2000) a_ngp = np.radians(12.9406333 * 15.) d_ngp = np.radians(27.1282500) l_ngp = np.radians(123.9320000) sd_ngp = np.sin(d_ngp) cd_ngp = np.cos(d_ngp) sb = np.sin(gb) cb = np.cos(gb) # Calculate right ascension y = cb*np.sin(l_ngp - gl) x = cd_ngp*sb - sd_ngp*cb*np.cos(l_ngp - gl) ra = np.arctan2(y, x) + a_ngp ra = np.degrees(ra) % 360 # Calculate declination dec = np.arcsin(sd_ngp*sb + cd_ngp*cb*np.cos(l_ngp - gl)) dec = np.degrees(dec) % 360. dec[dec > 270] = -(360 - dec[dec > 270]) return ra, dec def radec_to_lb(ra, dec, frac=False): """ Convert from ra, dec to galactic coordinates. Formulas from 'An Introduction to Modern Astrophysics (2nd Edition)' by Bradley W. Carroll, Dale A. Ostlie (Eq. 24.16 onwards). NOTE: This function is not as accurate as the astropy conversion, nor as the Javascript calculators found online. However, as using astropy was prohibitively slow while running over large populations, we use this function. While this function is not as accurate, the under/over estimations of the coordinates are equally distributed meaning the errors cancel each other in the limit of large populations. Args: ra (string): Right ascension given in the form '19:06:53' dec (string): Declination given in the form '-40:37:14' frac (bool): Denote whether coordinates are already fractional or not Returns: gl, gb (float): Galactic longitude and latitude [fractional degrees] """ if not frac: ra, dec = frac_deg(ra, dec) a = np.radians(ra) d = np.radians(dec) # Coordinates of the galactic north pole (J2000) a_ngp = np.radians(12.9406333 * 15.) d_ngp = np.radians(27.1282500) l_ngp = np.radians(123.9320000) sd_ngp = np.sin(d_ngp) cd_ngp = np.cos(d_ngp) sd = np.sin(d) cd = np.cos(d) # Calculate galactic longitude y = cd*np.sin(a - a_ngp) x = cd_ngp*sd - sd_ngp*cd*np.cos(a - a_ngp) gl = - np.arctan2(y, x) + l_ngp gl = np.degrees(gl) % 360 # Shift so in range -180 to 180 if isinstance(gl, np.ndarray): gl[gl > 180] = -(360 - gl[gl > 180]) else: if gl > 180: gl = -(360 - gl) # Calculate galactic latitude gb = np.arcsin(sd_ngp*sd + cd_ngp*cd*np.cos(a - a_ngp)) gb = np.degrees(gb) % 360 if isinstance(gb, np.ndarray): gb[gb > 270] = -(360 - gb[gb > 270]) else: if gb > 270: gb = -(360 - gb) return gl, gb def separation(ra_1, dec_1, ra_2, dec_2): """Separation between points on sky [degrees]. Using a special case of the Vincenty formula for an ellipsoid with equal major and minor axes. See https://en.wikipedia.org/wiki/Great-circle_distance for more info. """ # Convert to radians ra_1 = np.deg2rad(ra_1) dec_1 = np.deg2rad(dec_1) ra_2 = np.deg2rad(ra_2) dec_2 = np.deg2rad(dec_2) # Shortcuts sdr = np.sin(ra_2 - ra_1) cdr = np.cos(ra_2 - ra_1) cd1 = np.cos(dec_1) cd2 = np.cos(dec_2) sd1 = np.sin(dec_1) sd2 = np.sin(dec_2) # Calculation upper = np.sqrt((cd2*sdr)**2 + (cd1*sd2 - sd1*cd2*cdr)**2) lower = sd1*sd2 + cd1*cd2*cdr sep = np.arctan2(upper, lower) return np.rad2deg(sep) def ne2001_dist_to_dm(dist, gl, gb): """ Convert position to a dispersion measure using NE2001. Args: dist (float): Distance to source [Gpc]. Distance will be cut at 100kpc, as NE2001 can not cope with larger distances. This value should be more than enough to clear the Milky Way. gl (float): Galactic longitude [fractional degrees] gb (float): Galactic latitude [fractional degrees] Returns: dm (float): Dispersion measure [pc*cm^-3] """ dist *= 1e6 # Convert from Gpc to kpc # NE2001 gives errors if distance input is too large! 100 kpc ought to be # enough to clear the galaxy. if dist > 100: dist = 100 dist = C.c_float(dist) gl = C.c_float(gl) gb = C.c_float(gb) inpath = C.create_string_buffer(dm_mods.encode()) linpath = C.c_int(len(dm_mods)) dm = ne2001lib.dm_(C.byref(dist), C.byref(gl), C.byref(gb), C.byref(C.c_int(4)), C.byref(C.c_float(0.0)), C.byref(inpath), C.byref(linpath) ) return dm def ne2001_get_smtau(dist, gl, gb): """ Use the NE2001 model to calculate scattering measure. Calculations based on work presented in Cordes & Lazio (1991, DOI: 10.1086/170261) Args: dist (array): Distance to source [kpc]. Distance will be cut at 100 kpc as NE2001 can not cope with larger distances. Therefore the calculated scattering will only be that from the Milky Way. gl (array): Galactic longitude [fractional degrees] gb (array): Galactic latitude [fractional degrees] Returns: sm (array): Scattering measure smtau (array): Scattering measure, but unsure why different to sm """ # NE2001 gives errors if distance input is too large! 100 kpc ought to be # enough to clear the galaxy. dist[dist > 100] = 100 sms = np.ones_like(dist) smtaus = np.ones_like(dist) for i, d in enumerate(dist): disti = C.c_float(d) # Note the galactic coordinates need to be given in radians gli = C.c_float(math.radians(gl[i])) gbi = C.c_float(math.radians(gb[i])) ndir = C.c_int(-1) sm = C.c_float(0.) smtau = C.c_float(0.) inpath = C.create_string_buffer(dm_mods.encode()) linpath = C.c_int(len(dm_mods)) ne2001lib.dmdsm_(C.byref(gli), C.byref(gbi), C.byref(ndir), C.byref(C.c_float(0.0)), C.byref(disti), C.byref(C.create_string_buffer(' '.encode())), C.byref(sm), C.byref(smtau), C.byref(C.c_float(0.0)), C.byref(C.c_float(0.0)), C.byref(inpath), C.byref(linpath) ) sms[i], smtaus[i] = sm.value, smtau.value return sms, smtaus def ne2001_scint_time_bw(dist, gl, gb, freq): """ Use the NE2001 model to get the diffractive scintillation timescale. Args: dist (array): Distance to source [Gpc]. Distance will be cut at 100 kpc as NE2001 can not cope with larger distances. Therefore the calculated scintillation timescale will only be that from the Milky Way. gl (array): Galactic longitude [fractional degrees] gb (array): Galactic latitude [fractional degrees] freq (float): Observing frequency [MHz] Returns: scint_time (float): Diffractive scintillation timescale [Hz] scint_bw (float): Scintillation bandwidth [Hz] """ dist *= 1e6 # Convert from Gpc to kpc sm, smtau = ne2001_get_smtau(dist, gl, gb) scint_time = np.ones_like(dist) scint_time[smtau <= 0.] = float('NaN') # Eq. 46 of Cordes & Lazio 1991, ApJ, 376, 123 uses coefficient 3.3 # instead of 2.3. They do this in the code and mention it explicitly, # so I trust it! <- From psrpoppy scint_time[smtau > 0.] = 3.3 * (freq/1e3)**1.2 * smtau**(-0.6) scint_bw = np.ones_like(dist) scint_bw[sm <= 0.] = float('NaN') # (eq. 48) scint_bw[sm > 0.] = 223. * (freq/1e3)**4.4 * sm**(-1.2) / dist return scint_time, scint_bw def scatter_bhat(dm, offset=-6.46, scindex=-3.86, freq=1400.0): """ Calculate scattering timescale (values default to those from Bhat et al. (2004, DOI:10.1086/382680) and to simluate the scatter around this relationship, draw from a Gaussian around this value. Args: dm (array): Dispersion measure [pc*cm^-3] offset (float): Offset of scattering relationship. Defaults to -6.46 scindex (float): Scattering index. Defaults to -3.86 freq (float): Frequency at which to evaluate scattering time [MHz]. Defaults to 1400 MHz Returns: array: Scattering timescale [ms] """ log_t = offset + 0.154*np.log10(dm) + 1.07*np.log10(dm)**2 log_t += scindex*np.log10(freq/1e3) # Width of Gaussian distribution based on values given Lorimer et al (2008) t_scat = 10**np.random.normal(log_t, 0.8) return t_scat def load_T_sky(): """ Read the Haslam sky temperature map into a list. ... from which temperatures can be retrieved. The temperature sky map is given in the weird units of HealPix, and despite looking up info on this coordinate system, I don't have the foggiest idea of how to transform these to galactic coordinates. I have therefore directly copied the following code from psrpoppy in the assumption Sam Bates managed to figure it out. Returns: t_sky_list (list): List of sky temperatures in HealPix? coordinates? """ model = os.path.join(os.path.dirname(__file__), '../data/models/tsky/') path = os.path.join(model, 'haslam_2014.dat') t_sky_list = [] with open(path) as f: for line in f: str_idx = 0 while str_idx < len(line): # each temperature occupies space of 5 chars temp_string = line[str_idx:str_idx+5] try: t_sky_list.append(float(temp_string)) except ValueError: pass str_idx += 5 return t_sky_list class Redshift: """Class for converting redshift to other distance measures.""" def __init__(self, z, H_0=67.74, W_m=0.3089, W_v=0.6911): """ Convert redshift to a various measures. Based on James Schombert's python implementation of Edward L. Wright's cosmology calculator. Args: z (array): Redshift self.H_0 (float, optional): Hubble parameter. self.W_m (float, optional): Omega matter. self.W_v (float, optional): Omega vacuum. Returns: array: One of the distance measures [Gpc], or comoving volume from Earth to the source [Gpc^3] """ self.z = z self.H_0 = H_0 self.W_m = W_m self.W_v = W_v # Initialize constants self.W_r = 0.4165/(self.H_0*self.H_0) # Omega radiation self.W_k = 1.0 - self.W_m - self.W_r - self.W_v # Omega curvature self.c = 299792.458 # Velocity of light [km/sec] self.dcmr = 0. self.az = 1/(1+self.z) # Distance measures self.dc_mpc = None self.dl_mpc = None def dist_co(self): """Calculate the corresponding comoving distance [Gpc].""" n = 1000 for i in range(n): a = self.az+(1-self.az)*(i+0.5)/n s = sum([self.W_k, self.W_m/a, self.W_r/(a*a), self.W_v*a*a]) adot = np.sqrt(s) self.dcmr += 1/(a*adot) self.dcmr = (1.-self.az)*self.dcmr/n self.dc_mpc = (self.c/self.H_0)*self.dcmr # Comoving distance [Mpc] return self.dc_mpc*1e-3 # Convert to Gpc def dist_lum(self): """Calculate the corresponding luminosity distance [Gpc].""" if self.dc_mpc is None: self.dist_co() # Calculate luminosity distance ratio = np.ones_like(self.dcmr) x = np.sqrt(abs(self.W_k))*self.dcmr mask = (x > 0.1) if self.W_k > 0: ratio[mask] = 0.5*(np.exp(x[mask])-np.exp(-x[mask]))/x[mask] else: ratio[mask] = np.sin(x[mask])/x[mask] y = x*x if self.W_k < 0: y = -y ratio[~mask] = 1. + y[~mask]/6. + y[~mask]*y[~mask]/120. dcmt = ratio*self.dcmr da = self.az*dcmt dl = da/(self.az*self.az) self.dl_mpc = (self.c/self.H_0)*dl # Luminosity distance [Mpc] return self.dl_mpc*1e-3 # Covert to Gpc def vol_co(self): """Calculate the corresponding comoving volume [Gpc^3].""" if self.dl_mpc is None: self.dist_lum() ratio = np.ones_like(self.dcmr) x = math.sqrt(abs(self.W_k))*self.dcmr mask = (x > 0.1) if self.W_k > 0: n = (0.125*(np.exp(2.*x[mask])-np.exp(-2.*x[mask]))-x[mask]/2.) ratio[mask] = n/(x[mask]**3/3) else: ratio[mask] = (x[mask]/2. - np.sin(2.*x[mask])/4.)/(x[mask]**3/3) y = x*x if self.W_k < 0: y = -y ratio[~mask] = 1. + y[~mask]/5. + (2./105.)*y[~mask]*y[~mask] v_cm = ratio*self.dcmr**3/3 self.v_gpc = 4.*math.pi*((1e-3*self.c/self.H_0)**3)*v_cm return self.v_gpc def z_to_d_approx(z, H_0=67.74): """ Calculate distance in Gpc from a redshift. Only holds for z <= 2. Formulas from 'An Introduction to Modern Astrophysics (2nd Edition)' by Bradley W. Carroll, Dale A. Ostlie. (Eq. 27.7) Args: z (float): Redshift H_0 (float, optional): Hubble parameter. Defaults to 67.74 Returns: dist (float): Associated distance [Gpc] """ c = 299792.458 # Velocity of light [km/sec] zsq = (z+1)**2 dist = c/H_0 * (zsq - 1)/(zsq + 1) dist /= 1e3 # Mpc -> Gpc return dist def dist_to_z(dist, H_0=67.74): """ Calculate redshift from a distance in Gpc. Only holds for z <= 2. Formulas from 'An Introduction to Modern Astrophysics (2nd Edition)' by Bradley W. Carroll, Dale A. Ostlie. (Eq. 27.7) Args: dist (float): Distance [Gpc]. H_0 (float, optional): Hubble parameter. Defaults to 67.74 Returns: z (float): Associated redshift """ c = 299792.458 # Velocity of light [km/sec] dist *= 1e3 # Gpc -> Mpc dhc = dist*H_0/c det = math.sqrt(1 - dhc**2) z = -(det + dhc - 1)/(dhc - 1) return z def datetime_to_julian(date): """Convert a datetime object into julian float. See https://aa.usno.navy.mil/faq/docs/JD_Formula.php for more info. Args: date (datetime-object): Date in question Returns: float: Julian calculated datetime. """ # Add support for numpy arrays of datetime64 if np.issubdtype(date.dtype, np.datetime64): date = pd.to_datetime(date) # Define terms y = date.year m = date.month d = date.day h = date.hour min = date.minute sec = date.second # Calculate julian day number jdn = 367*y - ((7*(y + ((m+9)/12).astype(int)))/4).astype(int) jdn += ((275*m)/9).astype(int) + d + 1721013.5 # Add fractional day jd = jdn + h/24 + min/1440 + sec/86400 # Convert to a numpy array if isinstance(jd, pd.Float64Index): jd = jd.values return jd def datetime_to_gmst(date): """Calculate Greenwich Mean Sidereal Time. See https://aa.usno.navy.mil/faq/docs/GAST.php for more info. """ jd = datetime_to_julian(date) return ((18.697374558 + 24.06570982441908*(jd - 2451545))*15) % 360 def random_date(start, end): """Generate a random datetime between two datetime objects.""" delta = end - start int_delta = (delta.days * 24 * 60 * 60) + delta.seconds random_second = random.randrange(int_delta) return start + timedelta(seconds=random_second) def coord_to_offset(xref, yref, x, y): """ Convert point (x, y) to projected offset from reference (xref, yref). Makes use of a gnomonic projection: see both https://github.com/LSSTDESC/Coord/blob/master/coord/celestial.py http://mathworld.wolfram.com/GnomonicProjection.html Args: xref (array): Reference RA or Az [rad] yref (array): Reference Dec or Alt [rad] x (array): Target RA or Az [rad] y (array): Target Dec or Alt [rad] Returns: array, array: x and y offset [rad] """ # Define convenience numbers sinxref = np.sin(xref) sinx = np.sin(x) cosxref = np.cos(xref) cosx = np.cos(x) sinyref = np.sin(yref) siny = np.sin(y) cosyref = np.cos(yref) cosy = np.cos(y) # Sine and cosine of shift in x cosdx = (cosxref * cosx) + (sinxref * sinx) sindx = (cosxref * sinx) - (sinxref * cosx) # Projection effect cosine cosc = sinyref * siny + cosyref * cosy * cosdx # Projected offsets dx = (cosy * sindx) / cosc dy = (cosyref * siny - sinyref * cosy * cosdx) / cosc if isinstance(cosc, np.ndarray): dx[cosc < 0] = np.nan dy[cosc < 0] = np.nan elif cosc < 0: dx, dy = np.nan, np.nan return dx, dy def hadec_to_azalt(ha, dec, lat): """ Convert hour angle and declination to azimuth and altitude. Args: ha (array): Hour angle [rad] dec (array): Declination [rad] lat (float): Latitude [rad] Returns: array, array: az, alt [rad] """ # Ha and dec should be same type assert type(ha) == type(dec) # Altitude sinalt = np.sin(dec) * np.sin(lat) + np.cos(dec) * np.cos(lat) * np.cos(ha) alt = np.arcsin(sinalt) # Azimuth (note this uses altitude) cosaz = (np.sin(dec)-np.sin(alt)*np.sin(lat)) / (np.cos(alt)*np.cos(lat)) convert_to_float = False if isinstance(cosaz, float): cosaz = np.array([cosaz]) convert_to_float = True # Numerical instability can cause cosaz > 1 cosaz[cosaz > 1] = 1 cosaz[cosaz < -1] = -1 az = np.arccos(cosaz) # Sign of azimuth is lost, but can be recovered using the input hour angle mask = np.sin(ha) > 0 az[mask] = 2*np.pi - az[mask] # Convert back to float if input was float if convert_to_float: az = float(az) return az, alt def in_region(ra, dec, gl, gb, ra_min=0, ra_max=360, dec_min=-90, dec_max=90, gl_min=-180, gl_max=180, gb_min=-90, gb_max=90): """ Check if the given frbs are within the survey region. Args: ra, dec, gl, gb (float): Coordinates to check whether in region Returns: array: Boolean mask denoting whether frbs are within survey region """ # Create mask with False mask = np.ones_like(ra, dtype=bool) # Ensure in correct format gl[gl > 180.] -= 360. # Create region masks gl_limits = (gl > gl_max) | (gl < gl_min) gb_limits = (gb > gb_max) | (gb < gb_min) ra_limits = (ra > ra_max) | (ra < ra_min) dec_limits = (dec > dec_max) | (dec < dec_min) mask[gl_limits] = False mask[gb_limits] = False mask[ra_limits] = False mask[dec_limits] = False return mask def calc_sky_radius(area): """Determine the radius [deg] along the sky of an area [sq. degrees].""" # Check whether the full sky if np.allclose(area, 4*np.pi*(180/np.pi)**2): return 180 else: cos_r = (1 - (area*np.pi)/(2*180**2)) # Suppressing warnings when cos_r is invalid (will nan anyway) with np.errstate(invalid='ignore'): return np.rad2deg(np.arccos(cos_r)) def calc_sky_area(radius): """Determine the area [sq. degree] of a radius [deg] along the sky.""" return (1 - np.cos(np.deg2rad(radius)))*(2*180**2)/np.pi
TRASAL/frbpoppy
frbpoppy/galacticops.py
galacticops.py
py
22,052
python
en
code
26
github-code
6
72739113148
from reportlab.lib import colors from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import A4 from reportlab.platypus import Paragraph from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.enums import TA_JUSTIFY def generate_prescription(patient_name, doctor_name, medicine_list, logo_path, rx_path, signature_path, prescription_no, consultation_no, doctor_email, medconnect_id, reg_no, doctor_location, patient_id, patient_location, date, remarks, doctor_title): # Create a file named after the patient filename = f"{patient_name}_prescription.pdf" c = canvas.Canvas(filename, pagesize=A4, bottomup=1) # MedConnect Logo c.setFillColor(colors.white) c.drawImage(logo_path, 12, 759 - 16, width=169, height=83.12) # Rx logo c.drawImage(rx_path, 595-60-12, 759 - 4, width=60, height=60) # Document Nos. c.setFillColor(colors.black) c.setFont("Courier", 13) c.drawRightString(525, 735 , "Prescription No:") c.setFont("Courier", 13) c.drawRightString(570, 735, f"#{prescription_no}") c.drawRightString(525, 720 , "Consultation No:") c.setFont("Courier", 13) c.drawRightString(570, 720, f"#{consultation_no}") #Doctor Details c.setFillColor(colors.black) c.setFont("Courier", 13) c.drawRightString(570, 680 , "+917738118110") c.drawRightString(570, 665 , f"{doctor_email}") c.drawRightString(450, 650 , "MedConnect Id.: ") c.setFont("Courier", 13) c.drawRightString(570, 650 , f"{medconnect_id}") c.drawRightString(450, 635 , "Reg. No.: ") c.setFont("Courier", 13) c.drawRightString(570, 635 , f"{reg_no}") #Doctor Headers c.setFont("Courier-Bold", 21) c.drawString(12, 680, f"Dr. {doctor_name}") c.setFont("Courier", 13) c.drawString(12, 665 , f"{doctor_location}") # Patient Details c.setFont("Courier", 13) c.drawString(12, 620 , "Patient Id:") c.drawString(100, 620 , f"# {patient_id}") c.drawString(12, 605 , "Patient:") c.setFont("Courier-Bold", 13) c.drawString(100, 605 , f"{patient_name}") c.setFont("Courier", 13) c.drawString(100, 590 , f"{patient_location}") c.drawString(12, 575 , "Date:") c.drawString(100, 575 , f"{date}") c.setFont("Courier-Bold", 18) c.drawString(12, 530 , "Treatment Advised") # Add a table with the medicine list c.setFont("Courier-Bold", 13) c.drawString(12, 500, "Type") c.drawString(97, 500, "Medicine") c.drawString(242, 500, "Power") c.drawString(346, 500, "Frequency") c.drawString(440, 500, "Remarks") c.setStrokeColor(colors.grey) c.line(12, 490, 570, 490) c.setFont("Courier", 13) for i, medicine in enumerate(medicine_list): c.drawString(12, 475 - i * 25, medicine[0]) c.drawString(97, 475 - i * 25, medicine[1]) c.drawString(242, 475 - i * 25, medicine[2]) c.drawString(346, 475 - i * 25, medicine[3]) c.drawString(440, 475 - i * 25, medicine[4]) c.setFont("Courier-Bold", 18) c.drawString(12, 280 , "Next Investigation / Other Remarks") style = getSampleStyleSheet()["Normal"] style.fontName = "Courier" style.fontSize = 12 style.alignment = TA_JUSTIFY p = Paragraph(remarks, style) p.wrapOn(c, 558, 100) p.drawOn(c, 12, 140) c.drawImage(signature_path, 456, 66, width=86, height=39) c.setFont("Courier-Bold", 13) c.drawRightString(570, 47 , f"{doctor_name}") c.setFont("Courier", 10) c.drawRightString(570, 33 , f"{doctor_title}") c.line(12, 18, 570, 18) c.setFont("Courier", 10) c.drawString(12, 5, "Thank you for choosing MedConnect. Have a Healthy Day!") # Save the PDF c.save() medicine_list = [ ("Tablet","Paracetamol", "500 mg", "1-0-1", "-"), ("Tablet","Dolo", "10 mg", "0-1-0", "-"), ] remarks = "Take rest. Do not work more." generate_prescription("Prem Kothawle", "Dr. Shubham Saroj", medicine_list, "medconnect_logo.jpg", "rx_logo.jpg", "Shubham_Sign.jpeg", "1258", "1279", "[email protected]", "86438648464", "123454321234", "Thane, India", "2547", "Nere, India", "10 February 2023", remarks, "M.B.B.S") # patient_name, doctor_name, medicine_list, logo_path, rx_path, signature_path, prescription_no, consultation_no, doctor_email, medconnect_id, reg_no, doctor_location, patient_id, patient_location, date, remarks, doctor_title
kothawleprem/MedConnect
templates/main.py
main.py
py
4,423
python
en
code
0
github-code
6
42197867431
from django.test import TestCase from feedback.forms import FeedbackForm class TestForms(TestCase): def test_feedback_form_valid_data(self): form = FeedbackForm(data={ 'titolo': 'Recensione', 'descrizione': 'Una descrizione', 'voto': 5 }) self.assertTrue(form.is_valid()) def test_user_form_no_data(self): form = FeedbackForm(data={}) self.assertFalse(form.is_valid()) self.assertEquals(len(form.errors), 3)
lucacasarotti/CineDate
feedback/tests/test_forms.py
test_forms.py
py
506
python
en
code
0
github-code
6
35729401904
#!/usr/bin/python # -*- coding: UTF-8 -*- # from multiprocessing.pool import ThreadPool import threading from time import sleep import requests from selenium import webdriver from bs4 import BeautifulSoup import output as op class FlaskScraper: # groupName: webUrl dictOfNameAndWebUrl = {} # weburl: webCont dictOfNameAndWebCont = {} # weburl: webCOnt without mark dictOfNameAndWebContWithoutMk = {} # initialize def __init__(self, chatBot, dictOfNameAndWebsite): for key in dictOfNameAndWebsite: web = dictOfNameAndWebsite[key] if(key in FlaskScraper.dictOfNameAndWebUrl.keys()): FlaskScraper.dictOfNameAndWebUrl[key] = web # if(not web in FlaskScraper.dictOfNameAndWebCont.keys()): FlaskScraper.dictOfNameAndWebCont.setdefault(web, ['null']) FlaskScraper.dictOfNameAndWebContWithoutMk.setdefault(web, ['null']) # FlaskScraper.dictOfNameAndWebCont.setdefault(web, self.ScraperFromFlaskByCheck(key)) else: FlaskScraper.dictOfNameAndWebUrl.setdefault(key, web) # if(not web in FlaskScraper.dictOfNameAndWebCont.keys()): FlaskScraper.dictOfNameAndWebCont.setdefault(web, ['null']) FlaskScraper.dictOfNameAndWebContWithoutMk.setdefault(web, ['null']) # FlaskScraper.dictOfNameAndWebCont.setdefault(web, self.ScraperFromFlaskByCheck(key)) self.MultiClientController(chatBot, {key : web}) # self.UpdateWebsiteUrl(chatBot, dictOfNameAndWebsite) # self.UpdateWebsiteCont(dictOfNameAndWebsite) def Scraper(weburl): driver = webdriver.Chrome("/usr/local/share/chromedriver") driver.get(weburl) try: driver.find_element_by_xpath("//a[contains(text(),'Show all completed tasks')]").click() except: pass # driver.find_element_by_id() # print("------------", driver.page_source) sleep(2) soup = BeautifulSoup(driver.page_source, "html.parser") spanlist = soup.find_all('span', attrs={'class':'best_in_place'}) driver.quit() return spanlist # bind group name with url & bind group name with web content def UpdateWebsiteUrl(self, chatBot, key, web): # for key in incDicOfNameAndWebsite: # web = incDicOfNameAndWebsite[key] # print(1) if(web in FlaskScraper.dictOfNameAndWebUrl.values()): return "fail" # print(2) if(key in FlaskScraper.dictOfNameAndWebUrl.keys()): FlaskScraper.dictOfNameAndWebUrl[key] = web # if(not web in FlaskScraper.dictOfNameAndWebCont.keys()): FlaskScraper.dictOfNameAndWebCont.setdefault(web, ['null']) FlaskScraper.dictOfNameAndWebContWithoutMk.setdefault(web, ['null']) # FlaskScraper.dictOfNameAndWebCont.setdefault(web, self.ScraperFromFlaskByCheck(key)) else: FlaskScraper.dictOfNameAndWebUrl.setdefault(key, web) # if(not web in FlaskScraper.dictOfNameAndWebCont.keys()): FlaskScraper.dictOfNameAndWebCont.setdefault(web, ['null']) FlaskScraper.dictOfNameAndWebContWithoutMk.setdefault(web, ['null']) # FlaskScraper.dictOfNameAndWebCont.setdefault(web, self.ScraperFromFlaskByCheck(key)) self.MultiClientController(chatBot, {key : web}) return "succeed" # multiple clients generator def MultiClientController(self, chatBot, nameOfGrp): for k in nameOfGrp: try: thread = threading.Thread(target=ScraperTimeController, args=(k, chatBot, )) thread.start() except: print ("Error: unable to start thread for %s !" %(k)) # check command def ScraperFromFlaskByCheck(self, nameOfGrp): # print(dictOfNameAndWebsite.value[0]) # html = requests.get(dictOfNameAndWebsite.values()[0]).content thisKey = FlaskScraper.dictOfNameAndWebUrl[nameOfGrp] # html = requests.get(thisKey).content # driver.get(thisKey) # driver.find_element_by_xpath("//a[contains(text(),'Show all completed tasks')]").click() # sleep(2) # soup = BeautifulSoup(driver.page_source, "html.parser") # spanlist = soup.find_all('span', attrs={'class':'best_in_place'}) spanlist = FlaskScraper.Scraper(thisKey) # print("before") MessageWithoutMk, Message = op.ChangeFormatOfOutput(spanlist) # print("in") if (Message != FlaskScraper.dictOfNameAndWebCont[thisKey]): # print("in if") FlaskScraper.dictOfNameAndWebCont[thisKey] = Message # print("in if 2") FlaskScraper.dictOfNameAndWebContWithoutMk[thisKey] = MessageWithoutMk # print("in if 3") # print("after") # Message = [] # for i in range(1,len(spanlist)): # checkbox=str(spanlist[i].find_previous_sibling('input')) # if 'checked' in checkbox: # Message.append(spanlist[i].text+'-completed') # else: # Message.append(spanlist[i].text+'-uncompleted') # if (Message != FlaskScraper.dictOfNameAndWebCont[thisKey]): # FlaskScraper.dictOfNameAndWebCont[thisKey] = Message return Message # time controller, send news to users def ScraperTimeController(key, chatBot): while True: weburl = FlaskScraper.dictOfNameAndWebUrl[key] Message = ScraperFromFlaskByTime(weburl) if(Message != ['null']): # News=weburl + '\n' +'Update: \n' News = "" for strMessage in Message: News = News + strMessage + '\n' News = News + weburl my_friend = chatBot.search(puid=key)[0] my_friend.send(News) sleep(3) # listen to the website, return news def ScraperFromFlaskByTime(weburl): spanlist = FlaskScraper.Scraper(weburl) print("test1") # driver.get(thisKey) # driver.find_element_by_xpath("//a[contains(text(),'Show all completed tasks')]").click() # sleep(2) # soup = BeautifulSoup(driver.page_source, "html.parser") # spanlist = soup.find_all('span', attrs={'class':'best_in_place'}) # html = requests.get(weburl).content # soup = BeautifulSoup(html,"html.parser") # spanlist = soup.find_all('span',attrs={'class':'best_in_place'}) MessageWithoutMk, Message = op.ChangeFormatOfOutput(spanlist) oldContent = [] for v in FlaskScraper.dictOfNameAndWebContWithoutMk[weburl]: oldContent.append(v) # first time to log if (FlaskScraper.dictOfNameAndWebCont[weburl] == ['null'] and \ Message != FlaskScraper.dictOfNameAndWebCont[weburl]): FlaskScraper.dictOfNameAndWebCont[weburl] = Message FlaskScraper.dictOfNameAndWebContWithoutMk[weburl] = MessageWithoutMk return Message elif (Message != FlaskScraper.dictOfNameAndWebCont[weburl]): print(Message) print(MessageWithoutMk) print(oldContent) print(FlaskScraper.dictOfNameAndWebContWithoutMk[weburl]) # print("Message",Message) # print("FlaskScraper.dictOfNameAndWebCont[weburl])", FlaskScraper.dictOfNameAndWebCont[weburl]) tmplist = [] cnt = 0 for i in range(len(MessageWithoutMk)): if MessageWithoutMk[i] in oldContent: if Message[i] not in FlaskScraper.dictOfNameAndWebCont[weburl]: print("Message[%d]" %(i), Message[i]) print("oldContent index", oldContent.index(MessageWithoutMk[i])) print("oldCOntent", oldContent) print("cont",FlaskScraper.dictOfNameAndWebCont[weburl]) tmplist.append("\u2713 " + MessageWithoutMk[i]) # finished oldContent.remove(MessageWithoutMk[i]) cnt = cnt + 1 else: # print("not in MessageWithoutMk[%d]" %(i), MessageWithoutMk[i]) # print("oldContent", oldContent) # print("tmplist[0]", MessageWithoutMk[i]) print("--------------------------------") tmplist.append("\u2610 " + MessageWithoutMk[i]) # added for i in range(len(oldContent)): tmplist.append("\u2717 " + oldContent[i]) # delete print("final",tmplist) if(tmplist != []): FlaskScraper.dictOfNameAndWebCont[weburl] = Message FlaskScraper.dictOfNameAndWebContWithoutMk[weburl] = MessageWithoutMk return tmplist else: return ['null'] # cnt = 0 else: return ['null'] # newContent = [] # Message = [] # oldContent = FlaskScraper.dictOfNameAndWebCont[weburl] # dictOldContent = {} # for cont in oldContent: # if cont.find('-completed') > 0: # dictOldContent[cont[:cont.find('-completed')]] ='-completed' # elif cont.find('-uncompleted') > 0: # dictOldContent[cont[:cont.find('-uncompleted')]] ='-uncompleted' # for i in range(1,len(spanlist)): # checkbox=str(spanlist[i].find_previous_sibling('input')) # if 'checked' in checkbox: # newContent.append(spanlist[i].text+'-completed') # if spanlist[i].text in dictOldContent.keys(): # if dictOldContent[spanlist[i].text] == '-uncompleted': # Message.append('completed: '+spanlist[i].text) # dictOldContent[spanlist[i].text] = '-checked' # else: # Message.append('add: '+spanlist[i].text) # else: # newContent.append(spanlist[i].text+'-uncompleted') # if spanlist[i].text in dictOldContent.keys(): # if dictOldContent[spanlist[i].text] == '-completed': # Message.append('uncompleted: '+spanlist[i].text) # dictOldContent[spanlist[i].text] = '-checked' # else: # Message.append('add: '+spanlist[i].text) # for cont in dictOldContent: # if dictOldContent[cont] != '-checked': # Message.append('delete: ' + cont) # if Message !=[]: # FlaskScraper.dictOfNameAndWebCont[weburl]=newContent # return Message # else: # return ['null']
clamli/fdatanotice
scraper.py
scraper.py
py
8,975
python
en
code
0
github-code
6
26826438134
#! /usr/bin/env python import sys import copy import rospy import actionlib import moveit_commander import moveit_msgs.msg import geometry_msgs.msg import numpy as np from std_msgs.msg import Int32 from policies.policies import Policy, PositionPolicy, GripperCurrentPolicy, TactilePolicy from tams_tactile_sensor_array.msg import TactileSensorArrayData from geometry_msgs.msg import Twist from sensor_msgs.msg import Joy, JointState from controller_manager_msgs.srv import SwitchController from diana7_msgs.srv import SetControlMode, SetControlModeRequest, SetImpedance, SetImpedanceRequest from diana7_msgs.msg import CartesianState from fabric_grasping.msg import GraspAction, GraspResult, GraspFeedback, GraspGoal class GraspServer: def __init__(self): moveit_commander.roscpp_initialize(sys.argv) rospy.init_node("diana7_grasp_server") self.action_name = 'grasp' self.max_grasp_torque_2 = 200 self.max_grasp_torque_3 = 100 self.max_pressure = 15 self.pressure_threshold = 5 # pressure hysteresis when approaching table self.approach_speed = 0.04 self.retreat_speed = 0.01 self.fine_speed = 0.005 self.gripper_goal = 0.2 # self.policy = PositionPolicy(gripper_goal=1.0) # self.policy = GripperCurrentPolicy(gripper_current_goal=600) # self.policy = GripperCurrentPolicy(gripper_current_goal=1000) self.policy = TactilePolicy(cell_active_threshold=900, max_gripper_current=1800, max_cell_loss=2) self.policy.gripper_goal_cb(self.gripper_goal) self.current = False self.new_tactile_data = False self.last_tactile_sensor_data_1 = None self.last_tactile_sensor_data_2 = None self.forces = None self.torques_2 = np.array([]) self.torques_3 = np.array([]) self.cartesian_state = None self.robot = moveit_commander.RobotCommander() self.scene = moveit_commander.PlanningSceneInterface(synchronous=True) self.arm_group = moveit_commander.MoveGroupCommander('arm') self.gripper_group = moveit_commander.MoveGroupCommander('gripper') rospy.wait_for_service('/controller_manager/switch_controller') self.switch_controllers = rospy.ServiceProxy('/controller_manager/switch_controller', SwitchController) rospy.wait_for_service('/diana7_hardware_interface/set_control_mode') self.set_mode = rospy.ServiceProxy('/diana7_hardware_interface/set_control_mode', SetControlMode) rospy.wait_for_service('/diana7_hardware_interface/set_cartesian_impedance') self.set_cart_imp = rospy.ServiceProxy('/diana7_hardware_interface/set_cartesian_impedance', SetImpedance) rospy.wait_for_service('/diana7_hardware_interface/set_joint_impedance') self.set_joint_imp = rospy.ServiceProxy('/diana7_hardware_interface/set_joint_impedance', SetImpedance) self.forces_sub = rospy.Subscriber("/diana_gripper/forces_raw", Joy, self.forces_cb) self.torques_sub = rospy.Subscriber("/diana_gripper/torques", Joy, self.torques_cb) self.joint_state_sub = rospy.Subscriber("/current", Int32, self.current_cb) self.cartesian_state_sub = rospy.Subscriber("cartesian_state_controller/cartesian_state", CartesianState, self.cartesian_state_cb) self.tactile_sensor_sub_1 = rospy.Subscriber("tactile_sensor_data/1", TactileSensorArrayData, self.tactile_sensor_cb) self.tactile_sensor_sub_2 = rospy.Subscriber("tactile_sensor_data/2", TactileSensorArrayData, self.tactile_sensor_cb) self.gripper_goal_pub = rospy.Publisher('diana_gripper/simple_goal', JointState, queue_size=10) self.arm_vel_pub = rospy.Publisher('/cartesian_twist_controller/command', Twist, queue_size=10) self.grasp_action_server = actionlib.SimpleActionServer(self.action_name, GraspAction, execute_cb=self.grasp_cb, auto_start = False) self.grasp_action_server.start() def grasp_cb(self, goal: GraspGoal): self.load_twist_controller() print('start control loop.') self.policy.reset() self.gripper_goal = 0.2 grasp_finished = False first_contact = False backdrive = 0 r = rospy.Rate(50) # 50hz while not grasp_finished and not rospy.is_shutdown(): # contact with the piece (towards the table) has been made, slightly retracting and switching to impedance mode... if backdrive > 0: self.move_up(self.retreat_speed) backdrive -= 1 if backdrive == 0: self.unload_controllers() self.to_impedance_mode() self.load_twist_controller() # not in backdrive mode, acting normally. else: pressure = self.cartesian_state.wrench.linear.z print(pressure) if pressure > self.pressure_threshold: # if not in impedance mode already if not first_contact: # move slightly back and switch to impedance mode first_contact = True backdrive = 25 # move up in case the maximal pressure was surpassed if pressure > self.max_pressure + self.pressure_threshold: print('up') self.move_up(self.approach_speed) # move down if the pressure is too low elif pressure < self.max_pressure - self.pressure_threshold: print('down') # move slowly when first contact was made as collision is imminent. if first_contact: self.move_down(self.fine_speed) else: self.move_down(self.approach_speed) # pressure towards the table is in desired zone else: self.stop() print('stop') # if len(self.torques_2) and self.torques_2.mean() < self.max_grasp_torque_2: self.apply_policy() self.send_gripper_goal() if self.policy.finished(): # self.torques_2.mean() > self.max_grasp_torque_2 or self.torques_3.mean() > self.max_grasp_torque_3: grasp_finished = True r.sleep() self.grasp_action_server.set_succeeded(GraspResult()) def move_down(self, speed=0.004): speed = -abs(speed) msg = Twist() msg.linear.z = speed self.arm_vel_pub.publish(msg) def current_cb(self, msg): self.current = msg.data self.policy.gripper_current_cb(self.current) def move_up(self, speed=0.004): speed = abs(speed) msg = Twist() msg.linear.z = speed self.arm_vel_pub.publish(msg) def stop(self): msg = Twist() self.arm_vel_pub.publish(msg) def load_position_controller(self): print('loading position controller') try: self.switch_controllers(['joint_position_trajectory_controller'], ['cartesian_twist_controller'], 1, False, 0) except rospy.ServiceException as e: print("Service did not process request: " + str(e)) def load_twist_controller(self): print('loading twist controller') try: self.switch_controllers(['cartesian_twist_controller'], ['joint_position_trajectory_controller'], 1, False, 0) except rospy.ServiceException as e: print("Service did not process request: " + str(e)) def unload_controllers(self): try: self.switch_controllers([], ['cartesian_twist_controller', 'joint_position_trajectory_controller'], 1, False, 0) except rospy.ServiceException as e: print("Service did not process request: " + str(e)) def move_to_init(self): self.load_position_controller() print("moving to init pose.") # self.move_gripper_to_named_target('wide_open_parallel') # self.set_gripper_goal_position(-0.5) self.set_gripper_goal_position(0.2) self.send_gripper_goal() self.move_arm_to_named_target('idle_user_high') def forces_cb(self, msg): self.forces = msg self.policy.force_cb(msg) def torques_cb(self, msg): # self.torques_2 = np.concatenate((self.torques_2, [msg.axes[2]]))[-10:] # self.torques_3 = np.concatenate((self.torques_3, [msg.axes[3]]))[-10:] self.policy.torque_cb(msg) def tactile_sensor_cb(self, msg): self.policy.tactile_cb(msg) if msg.sensor_id == 1: self.last_tactile_sensor_data_1 = msg.data if msg.sensor_id == 2: self.last_tactile_sensor_data_2 = msg.data def cartesian_state_cb(self, msg): self.policy.state_cb(msg) self.cartesian_state = msg def set_gripper_goal_position(self, pos): self.gripper_goal = pos self.policy.gripper_goal_cb(self.gripper_goal) def apply_policy(self): self.change_gripper_goal_position(self.policy.decide_action() * self.policy.gripper_move_speed) def change_gripper_goal_position(self, chng): self.gripper_goal += chng self.policy.gripper_goal_cb(self.gripper_goal) def send_gripper_goal(self): self.send_gripper_command(self.gripper_goal, 0, 0.06) def send_gripper_command(self, angle, proximal, distal): goal_msg = JointState() goal_msg.name = ['parallel_gripper_angle', 'parallel_gripper_proximal_tilt', 'parallel_gripper_distal_tilt'] goal_msg.position = [angle, proximal, distal] self.gripper_goal_pub.publish(goal_msg) def to_impedance_mode(self): print("switching to impedance mode...") self.unload_controllers() try: resp1 = self.set_mode(1) print(resp1) r2 = SetImpedanceRequest() r2.stiffness = [2000, 2000, 1700, 1700, 1000, 100, 700] r2.damping = [30, 30, 20, 20, 9, 2, 6] resp2 = self.set_joint_imp(r2) # r2.stiffness = [3000, 3000, 3000, 500, 500, 500] # r2.damping = [30, 30, 30, 5, 5, 5] # resp2 = self.set_cart_imp(r2) print(resp2) except rospy.ServiceException as e: print("Service did not process request: " + str(e)) def to_position_mode(self): print("switching to position mode...") try: resp1 = self.set_mode(0) print(resp1) # input('mode changed?') except rospy.ServiceException as e: print("Service did not process request: " + str(e)) def move_gripper_to_named_target(self, target_name): t = rospy.Duration(1) max_i = 2 self.gripper_group.set_named_target(target_name) success = False i = 0 while not success: success = self.gripper_group.go(wait=True) if i > max_i: x = input() if len(x) > 0: sys.exit() print(f"retrying gripper motion to \"{target_name}\"") i += 1 rospy.sleep(t) def move_arm_to_named_target(self, target_name): t = rospy.Duration(1) max_i = 2 self.arm_group.set_named_target(target_name) success = False i = 0 while not success: success = self.arm_group.go(wait=True) if i > max_i: x = input() if len(x) > 0: sys.exit() print(f"retrying arm motion to \"{target_name}\"") i += 1 rospy.sleep(t) if __name__ == '__main__': try: g = GraspServer() except KeyboardInterrupt: g.stop() print( "Received control-c, stopping..." ) exit( 0 ) except rospy.ROSInterruptException: pass
TAMS-Group/tams_fabric_grasping
src/grasp_action_server.py
grasp_action_server.py
py
12,057
python
en
code
1
github-code
6
27267958481
from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from django.http.response import JsonResponse from viteproject.models import DesignSave from viteproject.serializers import DesignSaveSerializer from django.core.files.storage import default_storage # Create your views here. @csrf_exempt def save_designAPI(request,id=0): if request.method == 'GET': designSave = DesignSave.objects.all() designSaveSerializer = DesignSaveSerializer(designSave,many=True) return JsonResponse(designSaveSerializer.data,safe=False) elif request.method == 'POST': designSave_data = JSONParser().parse(request) designSaveSerializer = DesignSaveSerializer(data=designSave_data) if designSaveSerializer.is_valid(): designSaveSerializer.save() return JsonResponse("Added Successfully",safe=False) return JsonResponse("Failed to Add",safe=False) elif request.method == 'PUT': designSave_data = JSONParser().parse(request) designSave = DesignSave.objects.get(DesignId = designSave_data['DesignId']) designSaveSerializer = DesignSaveSerializer(designSave,data=designSave_data) if designSaveSerializer.is_valid(): designSaveSerializer.save() return JsonResponse("Update Successfully",safe=False) return JsonResponse("Fail Update") elif request.method=='DELETE': designSave = DesignSave.objects.get(DesignId=id) designSave.delete() return JsonResponse("Delete Successfully",safe=False) @csrf_exempt def SaveFile(request): file=request.FILES['file'] file_name = default_storage.save(file.name,file) return JsonResponse(file_name,safe=False)
SurajBhosale003/Osdag-React-Django
backend/viteproject/views.py
views.py
py
1,795
python
en
code
0
github-code
6
9805159119
import multiprocessing # Gunicorn app # Tell Gunicorn which application to run wsgi_app = "django_examples.asgi:application" # Requests # Restart workers after so many requests, with some variability. max_requests = 1000 max_requests_jitter = 50 # Logging # Use stdout for logging log_file = "-" # Workers bind = "0.0.0.0:8000" workers = multiprocessing.cpu_count() * 2 + 1 worker_class = "uvicorn.workers.UvicornWorker"
andrewguest/django-alpine-htmx
gunicorn.conf.py
gunicorn.conf.py
py
425
python
en
code
0
github-code
6
27264200550
""" Plot.py Created 21/12/2021 """ from juzzyPython.generic.Tuple import Tuple from juzzyPython.generalType2zSlices.sets.GenT2MF_Interface import GenT2MF_Interface from juzzyPython.type1.sets.T1MF_Interface import T1MF_Interface from juzzyPython.generalType2zSlices.sets.GenT2MF_Triangular import GenT2MF_Triangular from juzzyPython.intervalType2.sets.IntervalT2MF_Interface import IntervalT2MF_Interface from juzzyPython.generalType2zSlices.sets.GenT2MF_Trapezoidal import GenT2MF_Trapezoidal import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from typing import List plt.rcParams.update({'figure.max_open_warning': 0}) class Plot: """ Class Plot: Uses the matplotlib to plot various graphs Parameters: None Funtions: plotControlSurface show figure title legend discretize plotMF """ def __init__(self) -> None: self.colorList = ['tab:blue','tab:orange','tab:green','tab:red','tab:purple','tab:brown','tab:pink','tab:gray','tab:olive','tab:cyan'] def show(self): """Show all the figures created""" plt.show() def figure(self): """Create a new plot to draw upon""" self.fig = plt.figure() def figure3d(self): """Create a new 3d plot to draw upon""" self.fig, self.ax = plt.subplots(subplot_kw={"projection": "3d"}) def title(self,title: str): """Set the title of the current figure""" plt.title(title) def legend(self): """Add legend to the current figure""" plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.tight_layout() def plotControlSurface(self,x: List[float],y: List[float],z: List[List[float]],xLabel: str,yLabel: str,zLabel: str) -> None: """Plot a 3D surface showcasing the relationship between input (x,y) and output z""" fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) x,y = np.meshgrid(x,y) ax.plot_surface(np.asarray(x), np.asarray(y),np.asarray(z)) ax.set_xlabel(xLabel) ax.set_ylabel(yLabel) ax.set_zlabel(zLabel) plt.title("Control Surface") def plotMF2(self,xaxis: str,name: str,sets: IntervalT2MF_Interface,xDisc: int,addExtraEndPoints: bool) -> None: x = self.discretize(sets.getSupport(),xDisc) y1 = [0] * xDisc y2 = [0] * xDisc for i in range(xDisc): temp = sets.getFS(x[i]) y1[i] = temp.getRight() y2[i] = temp.getLeft() if addExtraEndPoints: x2 = [0.0] * (len(x)+2) y1b = [0.0] * (len(y1)+2) y2b = [0.0] * (len(y2)+2) x2[0] = sets.getSupport().getLeft() x2[-1] = sets.getSupport().getRight() y1b[0] = 0.0 y1b[len(y1)-1] = 0.0 y2b[0] = 0.0 y2b[len(y2)-1] = 0.0 for i in range(len(x)): x2[i+1] = x[i] y1b[i+1] = y1[i] y2b[i+1] = y2[i] x = x2 y1 = y1b y2 = y2b ax = plt.gca() color = next(ax._get_lines.prop_cycler)['color'] plt.plot(x,y1,label=name+"_upper", color = color) plt.plot(x,y2,label=name+"_lower", color = color, alpha=0.5) #plt.xlim(xAxisRange.getLeft(),xAxisRange.getRight()) #plt.ylim(yAxisRange.getLeft(),yAxisRange.getRight()) plt.ylabel("μ") plt.xlabel(xaxis) def plotMF(self,xaxis: str,name: str,sets: T1MF_Interface,xDisc: int,xAxisRange: Tuple,yAxisRange: Tuple,addExtraEndPoints: bool) -> None: """Plot a membership function on the current figure""" x = self.discretize(sets.getSupport(),xDisc) y = [0] * xDisc for i in range(xDisc): y[i] = sets.getFS(x[i]) if addExtraEndPoints: x2 = [0.0] * (len(x)+2) y2 = [0.0] * (len(y)+2) x2[0] = sets.getSupport().getLeft() x2[-1] = sets.getSupport().getRight() for i in range(len(x)): x2[i+1] = x[i] y2[i+1] = y[i] x = x2 y = y2 plt.plot(x,y,label=name) plt.xlim(xAxisRange.getLeft(),xAxisRange.getRight()) plt.ylim(yAxisRange.getLeft(),yAxisRange.getRight()) plt.ylabel("μ") plt.xlabel(xaxis) def plotMFasLines(self,sets: GenT2MF_Interface,xDisc: int) -> None: self.ax.set_xlabel("x") self.ax.set_ylabel("y") self.ax.set_zlabel("z") x = self.discretize(sets.getSupport(),xDisc) y1 = [[0 for c in range(xDisc)] for r in range(sets.getNumberOfSlices())] y2 = [[0 for c in range(xDisc)] for r in range(sets.getNumberOfSlices())] z1 = [[0 for c in range(xDisc)] for r in range(sets.getNumberOfSlices())] z2 = [[0 for c in range(xDisc)] for r in range(sets.getNumberOfSlices())] for zLevel in range(sets.getNumberOfSlices()): for i in range(xDisc): temp = sets.getZSlice(zLevel).getFS(x[i]) y1[zLevel][i] = temp.getRight() y2[zLevel][i] = temp.getLeft() if zLevel==0: z1[zLevel][i] = 0.0 else: z1[zLevel][i] = sets.getZValue(zLevel-1) z2[zLevel][i] = sets.getZValue(zLevel) for zLevel in range(sets.getNumberOfSlices()): self.ax.plot3D(x,y1[zLevel],z1[zLevel],label=sets.getName()+"_upper",color= self.colorList[zLevel%10]) self.ax.plot3D(x,y2[zLevel],z1[zLevel],label=sets.getName()+"_lower",color= self.colorList[zLevel%10]) self.ax.plot3D(x,y1[zLevel],z2[zLevel],label=sets.getName()+"_upper",color= self.colorList[zLevel%10]) self.ax.plot3D(x,y2[zLevel],z2[zLevel],label=sets.getName()+"_lower",color= self.colorList[zLevel%10]) def turnOnInteraction(self): plt.ion() def closeAllFigures(self): plt.close('all') def plotMFasSurface(self,plotName: str,sets: GenT2MF_Interface,xAxisRange: Tuple,xDisc: int,addExtraPoints: bool): self.ax.set_xlabel("X-Axis") self.ax.set_ylabel("Z-Axis") self.ax.set_zlabel("Y-Axis") if isinstance(sets,GenT2MF_Triangular): for zLevel in range(sets.getNumberOfSlices()): xUpper = [sets.getZSlice(zLevel).getUMF().getStart(), sets.getZSlice(zLevel).getUMF().getPeak(),sets.getZSlice(zLevel).getUMF().getEnd()] zUpper = None yUpper = [[0 for i in range(3)] for j in range(2)] if zLevel == 0: zUpper = [0.0,sets.getZValue(zLevel)] else: zUpper = [sets.getZValue(zLevel-1),sets.getZValue(zLevel)] for xD in range(3): yUpper[0][xD] = sets.getZSlice(zLevel).getFS(xUpper[xD]).getRight() yUpper[1][xD] = yUpper[0][xD] xLower = [sets.getZSlice(zLevel).getLMF().getStart(), sets.getZSlice(zLevel).getLMF().getPeak(),sets.getZSlice(zLevel).getLMF().getEnd()] zLower = None yLower = [[0 for i in range(3)] for j in range(2)] if zLevel == 0: zLower = [0.0,sets.getZValue(zLevel)] else: zLower = [sets.getZValue(zLevel-1),sets.getZValue(zLevel)] for xD in range(3): yLower[0][xD] = sets.getZSlice(zLevel).getFS(xLower[xD]).getLeft() yLower[1][xD] = yLower[0][xD] x,y = np.meshgrid(xUpper,zUpper) self.ax.plot_surface(np.asarray(x), np.asarray(y),np.asarray(yUpper),alpha = 0.5,color=self.colorList[zLevel%10]) x,y = np.meshgrid(xLower,zLower) self.ax.plot_surface(np.asarray(x), np.asarray(y),np.asarray(yLower),alpha = 0.5,color=self.colorList[zLevel%10]) elif isinstance(sets,GenT2MF_Trapezoidal): for zLevel in range(sets.getNumberOfSlices()): xUpper = [sets.getZSlice(zLevel).getUMF().getA(), sets.getZSlice(zLevel).getUMF().getB(),sets.getZSlice(zLevel).getUMF().getC(),sets.getZSlice(zLevel).getUMF().getD()] zUpper = None yUpper = [[0 for i in range(4)] for j in range(2)] if zLevel == 0: zUpper = [0.0,sets.getZValue(zLevel)] else: zUpper = [sets.getZValue(zLevel-1),sets.getZValue(zLevel)] for xD in range(4): yUpper[0][xD] = sets.getZSlice(zLevel).getFS(xUpper[xD]).getRight() yUpper[1][xD] = yUpper[0][xD] xLower = [sets.getZSlice(zLevel).getLMF().getA(), sets.getZSlice(zLevel).getLMF().getB(),sets.getZSlice(zLevel).getLMF().getC(),sets.getZSlice(zLevel).getLMF().getD()] zLower = None yLower = [[0 for i in range(4)] for j in range(2)] if zLevel == 0: zLower = [0.0,sets.getZValue(zLevel)] else: zLower = [sets.getZValue(zLevel-1),sets.getZValue(zLevel)] for xD in range(4): yLower[0][xD] = sets.getZSlice(zLevel).getFS(xLower[xD]).getLeft() yLower[1][xD] = yLower[0][xD] x,y = np.meshgrid(xUpper,zUpper) self.ax.plot_surface(np.asarray(x), np.asarray(y),np.asarray(yUpper),alpha = 0.5,color=self.colorList[zLevel%10]) x,y = np.meshgrid(xLower,zLower) self.ax.plot_surface(np.asarray(x), np.asarray(y),np.asarray(yLower),alpha = 0.5,color=self.colorList[zLevel%10]) else: for zLevel in range(sets.getNumberOfSlices()): xUpper = self.discretize(xAxisRange,xDisc) zUpper = None yUpper = [[0 for i in range(xDisc)] for j in range(2)] if zLevel == 0: zUpper = [0.0,sets.getZValue(zLevel)] else: zUpper = [sets.getZValue(zLevel-1),sets.getZValue(zLevel)] for xD in range(xDisc): yUpper[0][xD] = sets.getZSlice(zLevel).getFS(xUpper[xD]).getRight() yUpper[1][xD] = yUpper[0][xD] xLower = self.discretize(xAxisRange,xDisc) zLower = None yLower = [[0 for i in range(xDisc)] for j in range(2)] if zLevel == 0: zLower = [0.0,sets.getZValue(zLevel)] else: zLower = [sets.getZValue(zLevel-1),sets.getZValue(zLevel)] for xD in range(xDisc): yLower[0][xD] = sets.getZSlice(zLevel).getFS(xLower[xD]).getLeft() yLower[1][xD] = yLower[0][xD] if addExtraPoints: x_upper2 = [0.0] * (len(xUpper) + 2) y_upper2 = [[0.0 for i in range(len(yUpper[0]) + 2)] for j in range(2)] x_Lower2 = [0.0] * (len(xLower) + 2) y_Lower2 = [[0.0 for i in range(len(yLower[0]) + 2)] for j in range(2)] x_upper2[0] = sets.getSupport().getLeft() x_upper2[-1] = sets.getSupport().getRight() x_Lower2[0] = x_upper2[0] x_Lower2[-1] = x_upper2[-1] for i in range(len(xUpper)): x_upper2[i + 1] = xUpper[i] x_Lower2[i + 1] = xLower[i] y_upper2[0][i + 1] = yUpper[0][i] y_Lower2[0][i + 1] = yLower[0][i] y_upper2[1][i + 1] = yUpper[1][i] y_Lower2[1][i + 1] = yLower[1][i] xUpper = x_upper2 xLower = x_Lower2 yUpper = y_upper2 yLower = y_Lower2 x,y = np.meshgrid(xUpper,zUpper) self.ax.plot_surface(np.asarray(x), np.asarray(y),np.asarray(yUpper),alpha = 0.5,color=self.colorList[zLevel%10]) x,y = np.meshgrid(xLower,zLower) self.ax.plot_surface(np.asarray(x), np.asarray(y),np.asarray(yLower),alpha = 0.5,color=self.colorList[zLevel%10]) def discretize(self,support: Tuple,discLevel: int) -> List[float]: """Discretize the support values""" d = [0] * discLevel stepSize = (support.getSize())/(discLevel-1.0) d[0] = support.getLeft() d[-1] = support.getRight() for i in range(1,discLevel-1): d[i] = support.getLeft()+i*stepSize return d
LUCIDresearch/JuzzyPython
juzzyPython/generic/Plot.py
Plot.py
py
12,826
python
en
code
4
github-code
6
23856995507
from memoizer import Memoizer import re import os import glob from crawl_utils import RAWDATA_PATH R = re.compile MORGUE_BASES = [ [ R(r'cao-.*'), 'http://crawl.akrasiac.org/rawdata' ], [ R(r'cdo.*-0.4$'), 'http://crawl.develz.org/morgues/0.4' ], [ R(r'cdo.*-0.5$'), 'http://crawl.develz.org/morgues/0.5' ], [ R(r'cdo.*-0.6$'), 'http://crawl.develz.org/morgues/0.6' ], [ R(r'cdo.*-0.7'), 'http://crawl.develz.org/morgues/0.7' ], [ R(r'cdo.*-0.8'), 'http://crawl.develz.org/morgues/0.8' ], [ R(r'cdo.*-0.10'), 'http://crawl.develz.org/morgues/0.10' ], [ R(r'cdo.*-svn$'), 'http://crawl.develz.org/morgues/trunk' ], [ R(r'cdo.*-zd$'), 'http://crawl.develz.org/morgues/trunk' ], [ R(r'cdo.*-spr$'), 'http://crawl.develz.org/morgues/sprint' ], [ R(r'rhf.*-0.5$'), 'http://rl.heh.fi/crawl/stuff' ], [ R(r'rhf.*-0.6$'), 'http://rl.heh.fi/crawl-0.6/stuff' ], [ R(r'rhf.*-0.7$'), 'http://rl.heh.fi/crawl-0.7/stuff' ], [ R(r'rhf.*-trunk$'), 'http://rl.heh.fi/trunk/stuff' ], [ R(r'rhf.*-spr$'), 'http://rl.heh.fi/sprint/stuff' ], ] CAO_MORGUE_BASE = 'http://crawl.akrasiac.org/rawdata' CDO_MORGUE_BASE = 'http://crawl.develz.org/morgues/stable' R_MORGUE_TIME = re.compile(r'morgue-\w+-(.*?)\.txt$') def morgue_time_string(raw_time): return raw_time[:8] + "-" + raw_time[8:] def morgue_filename(name, timestr): return RAWDATA_PATH + "/" + name + "/morgue-" + name + "-" + timestr + ".txt" def cao_morgue_url(name, timestr): return "%s/%s/morgue-%s-%s.txt" % (CAO_MORGUE_BASE, name, name, timestr) def cao_morgue_files(name): rawmorgues = glob.glob(morgue_filename(name, '*')) rawmorgues.sort() return rawmorgues def morgue_binary_search(morgues, guess): size = len(morgues) if size == 1: return guess < morgues[0] and morgues[0] s = 0 e = size while e - s > 1: pivot = int((s + e) / 2) if morgues[pivot] == guess: return morgues[pivot] elif morgues[pivot] < guess: s = pivot else: e = pivot return e < size and morgues[e] @Memoizer def find_cao_morgue_link(name, end_time): fulltime = end_time if os.path.exists(morgue_filename(name, fulltime)): return cao_morgue_url(name, fulltime) # Drop seconds for really ancient morgues. parttime = fulltime[:-2] if os.path.exists(morgue_filename(name, parttime)): return cao_morgue_url(name, parttime) # At this point we have no option but to brute-force the search. morgue_list = cao_morgue_files(name) # morgues are sorted. The morgue date should be greater than the # full timestamp. best_morgue = morgue_binary_search(morgue_list, morgue_filename(name, fulltime)) if best_morgue: m = R_MORGUE_TIME.search(best_morgue) if m: return cao_morgue_url(name, m.group(1)) return None def game_is_cao(g): return g['source_file'].find('cao') >= 0 def format_time(time): return "%04d%02d%02d-%02d%02d%02d" % (time.year, time.month, time.day, time.hour, time.minute, time.second) def morgue_link(g): """Given a game dictionary, returns a URL to the game's morgue.""" src = g['source_file'] name = g['name'] stime = format_time( g['end_time'] ) v_regex = R(r'^0\.([0-9]+)') v_search = v_regex.search(g['v']) if not v_search: return '' version = int(v_search.group(1)) if version < 4: if game_is_cao(g): return find_cao_morgue_link(name, stime) # Nothing we can do for anyone else with old games. return '' if version == 9 and not game_is_cao(g): # CDO logs and milestones for 0.9 were placed in the same file as trunk # games, so we need to handle this specially. if stime > "20110819-1740": return "http://crawl.develz.org/morgues/0.9/%s/morgue-%s-%s.txt" % (name, name, stime) for regex, url in MORGUE_BASES: if regex.search(src): return "%s/%s/morgue-%s-%s.txt" % (url, name, name, stime) # Unknown morgue: raise Exception("Unknown source for morgues: %s" % src)
elliptic/dcss_scoring
morgue.py
morgue.py
py
4,018
python
en
code
1
github-code
6
4998438472
import re from odoo import api, fields, models, tools, _ from odoo.exceptions import ValidationError from odoo.osv import expression from odoo.exceptions import UserError, ValidationError import odoo.addons.decimal_precision as dp class ProductCategory(models.Model): _inherit="product.category" @api.model def create(self,vals): seq_list = [] att_list = [] seq_list1 = [] categ_list = [] seq = '' att = '' categ = ' ' seq1 = ' ' name = ' ' name_list = [] count = 1 product_categ_id = super(ProductCategory,self).create(vals) categ_obj = self.env['product.category'].browse(product_categ_id) attribute = self.env['attribute.line'].search([('category_id1','=',categ_obj.id.id)]) for val in attribute: attribute_obj = self.env['attribute.line'].browse(val.id) att_list.append(attribute_obj.attribute_id.id) if att_list: for val3 in att_list: att = val3 count = 1 for val4 in att_list: if att == val4: count = count + 1 else: count = count if count != 2: raise UserError(_('Attribute can not be repeat in Attribute for Grades')) categ_template = self.env['category.template'].search([('category_id1','=',categ_obj.id.id)]) for val in categ_template: categ_template_obj = self.env['category.template'].browse(val.id) seq_list.append(categ_template_obj.seq_no) categ_list.append(categ_template_obj.category_id.id) if categ_list: for val3 in categ_list: categ = val3 count = 1 for val4 in categ_list: if categ == val4: count = count + 1 else: count = count if count != 2: raise UserError(_('Category can not be repeat in Category Template')) if seq_list: for val1 in seq_list: seq = val1 count = 1 for val2 in seq_list: if seq == val2: count = count + 1 else: count = count if count != 2: raise UserError(_('Sequence can not be repeat in Category Template')) spec_template = self.env['specification.line'].search([('category_id1','=',categ_obj.id.id)]) for each in spec_template: spec_template_obj = self.env['specification.line'].browse(each.id) seq_list1.append(spec_template_obj.seq_no) name_list.append(spec_template_obj.name) if seq_list1: for each1 in seq_list1: seq1 = each1 count = 1 for each2 in seq_list1: if seq1 == each2: count = count + 1 else: count = count if count != 2: raise UserError(_('Sequence can not be repeat in Specifications')) if name_list: for each3 in name_list: name = each3 count = 1 for each4 in name_list: if name == each4: count = count + 1 else: count = count if count != 2: raise UserError(_('Name can not be repeat in Specifications')) return product_categ_id numbered = fields.Boolean('Numbered',track_visibility="onchange") can_altered = fields.Boolean('Can Be Altered',track_visibility="onchange") category_template_lines = fields.One2many('category.template','category_id1','Product Category',track_visibility="onchange") prefix = fields.Char('Prefix',track_visibility="onchange") specification_lines = fields.One2many('specification.line','category_id1','Specifications',track_visibility="onchange") attribute_lines = fields.One2many('attribute.line','category_id1','Attribute Value',track_visibility="onchange") class category_template(models.Model): _name="category.template" _inherit = ['mail.thread', 'ir.needaction_mixin'] category_id = fields.Many2one('product.category','Category',track_visibility="onchange") seq_no = fields.Integer('Sequence No',track_visibility="onchange") part_name = fields.Boolean('Part of Name',track_visibility="onchange") mandatory = fields.Boolean('Mandatory',track_visibility="onchange") category_id1 = fields.Many2one('product.category','Category',track_visibility="onchange") class specification_line(models.Model): _name="specification.line" _inherit = ['mail.thread', 'ir.needaction_mixin'] seq_no = fields.Integer('Sequence No',track_visibility="onchange") name = fields.Char('Name',track_visibility="onchange") category_id1 = fields.Many2one('product.category','Category',required="1",track_visibility="onchange") class attribute_line(models.Model): _name="attribute.line" _inherit = ['mail.thread', 'ir.needaction_mixin'] attribute_id = fields.Many2one('product.attribute','Attribute',track_visibility="onchange") category_id1 = fields.Many2one('product.category','Category',required="1",track_visibility="onchange")
odoocjpl/warehouse_custom
models/product_category.py
product_category.py
py
5,581
python
en
code
0
github-code
6
13105799926
class Solution(object): def sortPeople(self, names, heights): """ :type names: List[str] :type heights: List[int] :rtype: List[str] """ dList = [] for i in range(len(heights)): temp = [heights[i], [names[i]]] dList.append(temp) sort = sorted(dList) sort = sort[::-1] nameList = [] for i in range(len(names)): nameList.append(sort[i][1][0]) return nameList
MasoudKarimi4/Leetcode-Submissions
2418-sort-the-people/2418-sort-the-people.py
2418-sort-the-people.py
py
581
python
en
code
0
github-code
6
41562680413
'''Hash Table Description: Are used to store [key-value] pairs, they are like arrays, but the keys are not ordened. Unlike arrays, hash tables are fast for all of the follo wing operations: finding values, adding new values, or removing values. Big O: Average Case Insert: O(1) Deletion: O(1) Access: O(1) ''' WEIRD_PRIME = 31 class HashTable(): def __init__(self, size=53) -> None: self.key_map = [None for _ in range(0, size)] def _hash(self, key): total = 0 for i in range(0, min(len(key), 100)): char = key[i] value = ord(char) - 96 total = (total * WEIRD_PRIME + value) % len(self.key_map) return total def set(self, key, value): idx = self._hash(key) if not self.key_map[idx]: self.key_map[idx] = [] self.key_map[idx].append([key, value]) def get(self, key): idx = self._hash(key) if self.key_map[idx]: for i, v in enumerate(range(0, len(self.key_map[idx]))): if self.key_map[idx][i][0] == key: return self.key_map[idx][i][1] return None def values(self): values = [] for p in self.key_map: if p: for c in p: if c: values.append(c[1]) return values def keys(self): values = [] for p in self.key_map: if p: for c in p: if c: values.append(c[0]) return values ht = HashTable(17) ht.set('maroon', '#800000') ht.set('yellow', '#FFFF00') ht.set('olive', '#808000') ht.set('a', '#809000') ht.set('a', '#807000') print(ht.key_map) print(ht.get('a')) print(ht.keys())
Wainercrb/data-structures
hash-table/main.py
main.py
py
1,787
python
en
code
0
github-code
6
75254285948
#/usr/env/python3 """ This program combines the data directory reference file with a .words file to create a vardial3 format gold file. """ import sys # list of dialects borrowed from ../scripts/eval.py langList=['EGY', 'GLF', 'LAV', 'MSA','NOR'] # first set up hash from metadata to dialect number fr = open('../../reference','r') rdict = dict() for line in fr: sp = line.find(' ') meta = line[:sp] dialect = line[sp+1:sp+2] rdict[meta] = dialect # now read through .words file fin = open(sys.argv[1],'r') for line in fin: line = line.strip() sp = line.find(' ') meta = line[:sp] text = line[sp+1:] standard = rdict[meta] ts = langList[int(standard)-1] # write out line in gold format print(text+'\tQ\t'+ts)
StephenETaylor/vardial4
v17/dialectID/data/reference2gold.py
reference2gold.py
py
764
python
en
code
0
github-code
6
11769598800
#Calculating tax for multiple state from my_functions import conv_numbers while True: order = conv_numbers(input('Enter your order amount :')) if order: break state = input("Enter your state of residence :") state = state.lower() if state == 'wisconsin' or state == 'wi': county = input("""Enter your county of residence (dunn / eau claire) : """) county = county.lower() if county == 'dunn': tax = order * 0.004 else: tax = order * 0.005 total = order + tax total = round(total, 1) print(f"Your tax is : {tax}") print(f"Your total is : {total}") elif state == 'illinois' or state == 'il': tax = order * 0.08 total = order + tax total = round(total,2) print(f"Your tax is : {tax}") print(f"Your total is : {total}")
Kamalabot/Programmers57Challenges
exe20_multiState.py
exe20_multiState.py
py
812
python
en
code
1
github-code
6
75097112828
#Adding Elements to a Queue class Queue: def __init__(self): self.queue = list() def addtoq(self,dataval): # Insert method to add element if dataval not in self.queue: self.queue.insert(0,dataval) return True return False def size(self): return len(self.queue) TheQueue = Queue() TheQueue.addtoq("Mon") TheQueue.addtoq("Tue") TheQueue.addtoq("Wed") print(TheQueue.size()) print("------------------------------------------------------------------------") #removing elements class Queue: def __init__(self): self.queue = list() def addtoq(self,dataval): # Insert method to add element if dataval not in self.queue: self.queue.insert(0,dataval) return True return False # Pop method to remove element def removefromq(self): if len(self.queue)>0: return self.queue.pop() return ("No elements in Queue!") TheQueue = Queue() TheQueue.addtoq("Mon") TheQueue.addtoq("Tue") TheQueue.addtoq("Wed") print(TheQueue.removefromq()) print(TheQueue.removefromq()) print("_--------------------------------------------------------------") # Python program to # demonstrate queue implementation # using list # Initializing a queue queue = [] # Adding elements to the queue queue.append('a') queue.append('b') queue.append('c') print("Initial queue") print(queue) # Removing elements from the queue print("\nElements dequeued from queue") print(queue.pop(0)) print(queue.pop(0)) print(queue.pop(0)) print("\nQueue after removing elements") print(queue) # Uncommenting print(queue.pop(0)) # will raise and IndexError # as the queue is now empty
ishita2108/python_ds
queue.py
queue.py
py
1,661
python
en
code
0
github-code
6
69958752189
import time import pandas as pd # df = pd.read_csv("trades.csv", header=None, names=["num","time","side","lot","sym","o","c","pip","size","pips"]) df = pd.read_csv("FASTWAY.csv") # df = pd.read_csv("FASTWAYINETH.csv") # df = pd.read_csv("NORTHEASTWAYINBTC.csv") df.drop(columns=["num"], inplace=True) pd.to_datetime(df["time"]) df.sort_values(by=["time"], inplace=True) df.set_index(pd.DatetimeIndex(df["time"]), inplace=True) df.drop(columns=["time"], inplace=True) pnl = df["size"].astype(float).sum() deposit_df = df[df["side"]=="DEPOSIT"] deposit = deposit_df["sym"].astype(float).sum() withdraw_df = df[df["side"]=="WITHDRAWAL"] withdraw = withdraw_df["sym"].astype(int).sum() trade_df = df[df["side"]!="DEPOSIT"] trade_df = trade_df[trade_df["side"]!="WITHDRAWAL"] n_trade_df = trade_df[trade_df["size"]<0] p_trade_df = trade_df[trade_df["size"]>0] trade_df["side"].astype(str) monthly_pnl = trade_df["size"].resample("M").sum() monthly_negative_pnl = n_trade_df["size"].resample("M").sum() monthly_positive_pnl = p_trade_df["size"].resample("M").sum() print("********************************************************************trades") print(trade_df) print("********************************************************************deposit") print(deposit_df) print("********************************************************************withdraw") print(withdraw_df) print("********************************************************************negative_pnl") print(monthly_negative_pnl) print("********************************************************************positive_pnl") print(monthly_positive_pnl) print("********************************************************************pnl") print(monthly_pnl) print("********************************************************************pnl") print(pnl) # print(trade_df["2022-02-28":"2022-03-31"]) # print(trade_df.dtypes)
amirayat/Copyfx-Scraper-Analysis
analysis/analysis.py
analysis.py
py
1,943
python
en
code
1
github-code
6
36106930014
import pyperclip import re matchPhone = re.compile(r'''( (\d{3}|\(\d{3}\)) # area code (\s|-|\.) # separator (\d{3}) # first 3 digits (\s|-|\.) # separator (\d{4}) # last 4 digits (\s*(ext|x|ext.)\s*(\d{2,5}))? #extension )''', re.VERBOSE) matchEmail = re.compile(r'''( [a-zA-Z0-9._%+-]+ # address @[a-zA-Z0-9.-]+ # domain name \.(\w*) # domain suffix )''', re.VERBOSE) matchURL = re.compile(r'''( (http://|https://) # prefix (.*) # domain name (\.\w{2,}) # suffix )''', re.VERBOSE) text = pyperclip.paste() matches = [] for match in matchPhone.findall(text): phoneNum = '-'.join([match[1], match[3], match[5]]) if match[8] != '': phoneNum += ' x' + match[8] matches.append(phoneNum) for match in matchEmail.findall(text): matches.append(match[0]) for match in matchURL.findall(text): matches.append(match[0]) print('\n'.join(matches)) pyperclip.copy('\n'.join(matches))
kaisteussy/AtBS
automate_the_boring_stuff/Chapter 7/phoneAndEmail.py
phoneAndEmail.py
py
1,355
python
en
code
0
github-code
6
29358742213
from Qt import QtGui, QtCore, QtWidgets, Qt from ts2.scenery import abstract, helper from ts2 import utils translate = QtWidgets.qApp.translate class TextItem(abstract.TrackItem): """A TextItem is a prop to display simple text on the layout """ def __init__(self, parameters): """Constructor for the TextItem class""" super().__init__(parameters) self._rect = QtCore.QRectF() self.updateBoundingRect() gi = helper.TrackGraphicsItem(self) gi.setPos(self.origin) gi.setToolTip(self.toolTipText) gi.setZValue(0) self._gi[0] = gi def initialize(self, simulation): """Initialize the item after all items are loaded.""" if simulation.context in utils.Context.EDITORS: self._gi[0].setCursor(Qt.PointingHandCursor) else: self._gi[0].setCursor(Qt.ArrowCursor) super().initialize(simulation) @staticmethod def getProperties(): return [ helper.TIProperty("tiTypeStr", translate("TextItem", "Type"), True), helper.TIProperty("tiId", translate("TextItem", "id"), True), helper.TIProperty("text", translate("TextItem", "Text")), helper.TIProperty("originStr", translate("TextItem", "Point 1")) ] @property def text(self): """Returns the text to display""" return self._name @text.setter def text(self, value): """Setter function for the text property""" if self.simulation.context == utils.Context.EDITOR_SCENERY: self.graphicsItem.prepareGeometryChange() self._name = value self.graphicsItem.setToolTip(self.toolTipText) self.updateBoundingRect() self.updateGraphics() def updateBoundingRect(self): """Updates the bounding rectangle of the graphics item""" tl = QtGui.QTextLayout(self.text) tl.beginLayout() tl.createLine() tl.endLayout() self._rect = tl.boundingRect() def graphicsBoundingRect(self, itemId): """This function is called by the owned TrackGraphicsItem to return its bounding rectangle""" if self.text is None or self.text == "": return super().boundingRect() else: if self.tiId.startswith("__EDITOR__"): # Toolbox item return QtCore.QRectF(-36, -15, 100, 50) else: return self._rect def graphicsPaint(self, p, options, itemId, widget=None): """This function is called by the owned TrackGraphicsItem to paint its painter.""" super().graphicsPaint(p, options, itemId, widget) pen = self.getPen() pen.setWidth(0) pen.setColor(Qt.white) p.setPen(pen) p.drawText(self._rect.bottomLeft(), self.text)
ts2/ts2
ts2/scenery/textitem.py
textitem.py
py
2,872
python
en
code
43
github-code
6
15068023113
from os import name from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home"), path('about/', views.about, name="about"), path('join_us/', views.join_us, name="join_us"), path('hotel_detail/<int:hotel_id>/', views.hotel_detail, name="hotel_detail"), path('hotel_detail/<int:hotel_id>/<slug:extra>/', views.hotel_detail, name="hotel_detail"), path('cart/', views.my_cart, name="my_cart"), path('cart/plus', views.plus_cart, name="plus_cart"), path('cart/minus', views.minus_cart, name="minus_cart"), path('verify_payment/', views.verifyPayment, name='verify_payment'), path('order/', views.orders, name="order"), path('search/', views.search_items, name="search"), path('all_hotel/', views.all_hotel, name="all_hotel"), path('all_menu/', views.all_menu, name="all_menu"), path('health/', views.health, name="health"), ]
leenabadgujar/Online_Tiffin_Service
food/urls.py
urls.py
py
935
python
en
code
0
github-code
6
35396164763
import codecs import unittest from asyncssh.asn1 import der_encode, der_decode from asyncssh.asn1 import ASN1EncodeError, ASN1DecodeError from asyncssh.asn1 import BitString, IA5String, ObjectIdentifier from asyncssh.asn1 import RawDERObject, TaggedDERObject, PRIVATE class _TestASN1(unittest.TestCase): """Unit tests for ASN.1 module""" tests = [ (None, '0500'), (False, '010100'), (True, '0101ff'), (0, '020100'), (127, '02017f'), (128, '02020080'), (256, '02020100'), (-128, '020180'), (-129, '0202ff7f'), (-256, '0202ff00'), (b'', '0400'), (b'\0', '040100'), (b'abc', '0403616263'), (127*b'\0', '047f' + 127*'00'), (128*b'\0', '048180' + 128*'00'), ('', '0c00'), ('\0', '0c0100'), ('abc', '0c03616263'), ((), '3000'), ((1,), '3003020101'), ((1, 2), '3006020101020102'), (frozenset(), '3100'), (frozenset({1}), '3103020101'), (frozenset({1, 2}), '3106020101020102'), (frozenset({-128, 127}), '310602017f020180'), (BitString(b''), '030100'), (BitString(b'\0', 7), '03020700'), (BitString(b'\x80', 7), '03020780'), (BitString(b'\x80', named=True), '03020780'), (BitString(b'\x81', named=True), '03020081'), (BitString(b'\x81\x00', named=True), '03020081'), (BitString(b'\x80', 6), '03020680'), (BitString(b'\x80'), '03020080'), (BitString(b'\x80\x00', 7), '0303078000'), (BitString(''), '030100'), (BitString('0'), '03020700'), (BitString('1'), '03020780'), (BitString('10'), '03020680'), (BitString('10000000'), '03020080'), (BitString('10000001'), '03020081'), (BitString('100000000'), '0303078000'), (IA5String(b''), '1600'), (IA5String(b'\0'), '160100'), (IA5String(b'abc'), '1603616263'), (ObjectIdentifier('0.0'), '060100'), (ObjectIdentifier('1.2'), '06012a'), (ObjectIdentifier('1.2.840'), '06032a8648'), (ObjectIdentifier('2.5'), '060155'), (ObjectIdentifier('2.40'), '060178'), (TaggedDERObject(0, None), 'a0020500'), (TaggedDERObject(1, None), 'a1020500'), (TaggedDERObject(32, None), 'bf20020500'), (TaggedDERObject(128, None), 'bf8100020500'), (TaggedDERObject(0, None, PRIVATE), 'e0020500'), (RawDERObject(0, b'', PRIVATE), 'c000') ] encode_errors = [ (range, [1]), # Unsupported type (BitString, [b'', 1]), # Bit count with empty value (BitString, [b'', -1]), # Invalid unused bit count (BitString, [b'', 8]), # Invalid unused bit count (BitString, [b'0c0', 7]), # Unused bits not zero (BitString, ['', 1]), # Unused bits with string (BitString, [0]), # Invalid type (ObjectIdentifier, ['']), # Too few components (ObjectIdentifier, ['1']), # Too few components (ObjectIdentifier, ['-1.1']), # First component out of range (ObjectIdentifier, ['3.1']), # First component out of range (ObjectIdentifier, ['0.-1']), # Second component out of range (ObjectIdentifier, ['0.40']), # Second component out of range (ObjectIdentifier, ['1.-1']), # Second component out of range (ObjectIdentifier, ['1.40']), # Second component out of range (ObjectIdentifier, ['1.1.-1']), # Later component out of range (TaggedDERObject, [0, None, 99]), # Invalid ASN.1 class (RawDERObject, [0, None, 99]), # Invalid ASN.1 class ] decode_errors = [ '', # Incomplete data '01', # Incomplete data '0101', # Incomplete data '1f00', # Incomplete data '1f8000', # Incomplete data '1f0001', # Incomplete data '1f80', # Incomplete tag '0180', # Indefinite length '050001', # Unexpected bytes at end '2500', # Constructed null '050100', # Null with content '2100', # Constructed boolean '010102', # Boolean value not 0x00/0xff '2200', # Constructed integer '2400', # Constructed octet string '2c00', # Constructed UTF-8 string '1000', # Non-constructed sequence '1100', # Non-constructed set '2300', # Constructed bit string '03020800', # Invalid unused bit count '3600', # Constructed IA5 string '2600', # Constructed object identifier '0600', # Empty object identifier '06020080', # Invalid component '06020081' # Incomplete component ] def test_asn1(self): """Unit test ASN.1 module""" for value, data in self.tests: data = codecs.decode(data, 'hex') with self.subTest(msg='encode', value=value): self.assertEqual(der_encode(value), data) with self.subTest(msg='decode', data=data): decoded_value = der_decode(data) self.assertEqual(decoded_value, value) self.assertEqual(hash(decoded_value), hash(value)) self.assertEqual(repr(decoded_value), repr(value)) self.assertEqual(str(decoded_value), str(value)) for cls, args in self.encode_errors: with self.subTest(msg='encode error', cls=cls.__name__, args=args): with self.assertRaises(ASN1EncodeError): der_encode(cls(*args)) for data in self.decode_errors: with self.subTest(msg='decode error', data=data): with self.assertRaises(ASN1DecodeError): der_decode(codecs.decode(data, 'hex'))
ronf/asyncssh
tests/test_asn1.py
test_asn1.py
py
7,788
python
en
code
1,408
github-code
6
71840534267
# coding=utf8 from validate_email import validate_email if __name__ == '__main__': f = open("stargazers_email.txt", "r") emails = f.readlines() emails = [line.rstrip('\n') for line in emails] valid_email = [] for i in range(len(emails)): is_valid = validate_email(emails[i], verify=True) print(is_valid) if is_valid == 'True': valid_email.append(emails[i]) print(len(valid_email)) with open('valid_email.txt', 'w') as f: for item in valid_email: f.write("%s\n" % item)
haoshuai999/Master-project
validate_stargazers_email.py
validate_stargazers_email.py
py
494
python
en
code
0
github-code
6
21139527922
#!/usr/bin/env python3 import time from pymavlink import mavutil from trunk import * #from colored import fg, bg, attr from colored import fg, bg, attr #if get_Setting('mainLoopStatus', 'status.json', 0) == "closed": # print("Warning: Manual override enabled") # set_Setting('mainLoopStatus', 'manual', 'status.json', 1) print("Hello, Launching MavLink viewer...") timer1 = time.time() # Start a connection listening to a UDP port #the_connection = mavutil.mavlink_connection('udpin:localhost:14540') time.sleep(1) print("--->Looking for ports, please wait... Can take up to a minute...") print("") port1 = '/dev/ttyACM1' port2 = '/dev/ttyACM2' current = port1 while 1: try: the_connection = mavutil.mavlink_connection(current) time.sleep(1) the_connection.wait_heartbeat() break except: pass if current == port1: current = port2 elif current == port2: current = port1 time.sleep(1) print("Connected to port: " + current) print("Heartbeat from System %u, Component %u" % (the_connection.target_system, the_connection.target_system)) time.sleep(4) #https://mavlink.io/en/messages/common.html#MAV_DATA_STREAM_EXTENDED_STATUS for i in range(0, 3): the_connection.mav.request_data_stream_send(the_connection.target_system, the_connection.target_component, mavutil.mavlink.MAV_DATA_STREAM_ALL, 4, 1) pevent = mavutil.periodic_event(5) while(1): the_connection.recv_msg() if pevent.trigger(): try: IMU = the_connection.messages['RAW_IMU'] IMU2= the_connection.messages['SCALED_IMU2'] try: IMU3= the_connection.messages['SCALED_IMU3'] except: pass PR1= the_connection.messages['SCALED_PRESSURE'] GPS_RAW= the_connection.messages['GPS_RAW_INT'] #print(IMU) print("\tAx\tAy\tAz\t|Gx\tGy\tGz\t|Mx\tMy\tMz") print(f"0|\t{IMU.xacc:.0f}\t{IMU.yacc:.0f}\t{IMU.zacc:.0f}\t|{IMU.xgyro:.0f}\t{IMU.ygyro:.0f}\t{IMU.zgyro:.0f}\t|{IMU.xmag:.0f}\t{IMU.ymag:.0f}\t{IMU.zmag:.0f}") print(f"1|\t{IMU2.xacc:.0f}\t{IMU2.yacc:.0f}\t{IMU2.zacc:.0f}\t|{IMU2.xgyro:.0f}\t{IMU2.ygyro:.0f}\t{IMU2.zgyro:.0f}\t|{IMU2.xmag:.0f}\t{IMU2.ymag:.0f}\t{IMU2.zmag:.0f}") print(f"2|\t{IMU3.xacc:.0f}\t{IMU3.yacc:.0f}\t{IMU3.zacc:.0f}\t|{IMU3.xgyro:.0f}\t{IMU3.ygyro:.0f}\t{IMU3.zgyro:.0f}\t|{IMU3.xmag:.0f}\t{IMU3.ymag:.0f}\t{IMU3.zmag:.0f}") print(f"Pressure1 Abs: {PR1.press_abs:.2f} \tDif: {PR1.press_diff:.1f} \tTemp: {PR1.temperature:.0f}" + "\tSats in View: " + str(GPS_RAW.satellites_visible)) #print("Sats in View: " + str(GPS_RAW.satellites_visible)) except: print("Error") try: PR2= the_connection.messages['SCALED_PRESSURE2'] print(f"Pressure2 Abs: {PR2.press_abs:.2f} \tDif: {PR2.press_diff:.1f} \tTemp: {PR2.temperature:.0f}") #print(" ") except: print(f"Pressure2 Abs: INOP \tDif: INOP \tTemp: INOP") #print("...Press ctrl+c to exit...") print('%s ...Press ctrl+c to exit... %s' % (fg(3), attr(0))) print(" ") time.sleep(.005) #ALL = the_connection.recv_match(blocking=True) #print(ALL)
j07rdi/controlzero_testing
mavlink_test.py
mavlink_test.py
py
3,092
python
en
code
1
github-code
6
24367084112
import numpy as np import cv2 as cv image = cv.imread('lena.jpg') image = cv.cvtColor(image, cv.COLOR_BGR2GRAY) img = np.array(image) height = image.shape[0] width = image.shape[1] kernel= np.array([[-1, -1, -1],[-1, 8, -1], [-1, -1, -1]]) #print(kernel) m= kernel.shape[0]//2 w=h=3 conv= np.zeros(image.shape) for i in range(m,height-m): for j in range(m, width-m): s=0 for k in range(h): for l in range(w): s=s+img[i-m+k][j-m+l]*kernel[k][l] conv[i][j]=s #print(img) cv.imshow('img', conv) cv.waitKey() #cv.destroyAllWindows()
maximana99/kernel-python
main.py
main.py
py
589
python
en
code
0
github-code
6
11046567215
import urllib.request, json import pytz from datetime import datetime dateTimeStr=datetime.utcnow().replace(tzinfo=pytz.utc) def jsonReaderScooter(urlToOpen): with urllib.request.urlopen(urlToOpen) as url: data = json.loads(url.read().decode()) retStr='lat,lon,isdisabled,time\n' try: with open('outputDataUpdated.csv','r') as reader: if retStr in reader: retStr='' except: pass for item in data["data"]["bikes"]: retStr+=str(item['lat'])+','+str(item['lon'])+','+str(item['is_disabled'])+','+str(dateTimeStr)+'\n' with open('outputDataUpdated.csv', 'a+') as writer: writer.writelines(retStr) return True url = ["https://mds.bird.co/gbfs/los-angeles/free_bikes","https://s3.amazonaws.com/lyft-lastmile-production-iad/lbs/lax/free_bike_status.json","https://la-gbfs.getwheelsapp.com/free_bike_status.json"] for i in url: jsonReaderScooter(i)
hjames034/scooterRecordLA
parseScooter.py
parseScooter.py
py
941
python
en
code
0
github-code
6
40187735381
from luigi.contrib.postgres import CopyToTable from src.utils.general import read_yaml_file from src.utils.utils import load_df from src.pipeline.LuigiBiasFairnessTaskRDS import BiasFairnessTask #from src.pipeline.ingesta_almacenamiento import get_s3_client from datetime import date from time import gmtime, strftime import src.utils.constants as cte import pandas as pd import luigi import psycopg2 import yaml #import pickle import marbles.core import marbles.mixins class BiasFairnessTest(marbles.core.TestCase, marbles.mixins.DateTimeMixins): def __init__(self, my_date, data): super(BiasFairnessTest, self).__init__() self.date = my_date self.data = data def test_get_date_validation(self): self.assertDateTimesPast( sequence = [self.date], strict = True, msg = "La fecha solicitada debe ser menor a la fecha de hoy" ) return True def test_get_nrow_file_validation(self): data = self.data nrow = data.shape[0] self.assertGreater(nrow, 1, note = "El archivo debe de tener al menos 2 registros") return True class BiasFairnessTestTask(CopyToTable): path_cred = luigi.Parameter(default = 'credentials.yaml') initial = luigi.BoolParameter(default=True, parsing = luigi.BoolParameter.EXPLICIT_PARSING) limit = luigi.IntParameter(default = 300000) date = luigi.DateParameter(default = None) initial_date = luigi.DateParameter(default = None) bucket_path = luigi.Parameter(default = cte.BUCKET) exercise = luigi.BoolParameter(default=True, parsing = luigi.BoolParameter.EXPLICIT_PARSING) with open(cte.CREDENTIALS, 'r') as f: config = yaml.safe_load(f) credentials = config['db'] user = credentials['user'] password = credentials['pass'] database = credentials['database'] host = credentials['host'] port = credentials['port'] table = 'metadata.test_bias_fairness' columns = [("file_name", "VARCHAR"), ("data_date", "DATE"), ("processing_date", "TIMESTAMPTZ"), ("test_name", "VARCHAR"), ("result", "BOOLEAN") ] def requires(self): return BiasFairnessTask( self.path_cred, self.initial, self.limit, self.date, self.initial_date, self.bucket_path, self.exercise ) def input(self): with open(cte.CREDENTIALS, 'r') as f: config = yaml.safe_load(f) credentials = config['db'] user = credentials['user'] password = credentials['pass'] database = credentials['database'] host = credentials['host'] conn = psycopg2.connect( dbname=database, user=user, host=host, password=password ) cur = conn.cursor() cur.execute( """ SELECT * FROM sesgo.bias_fairness """ ) rows = cur.fetchall() data = pd.DataFrame(rows) data.columns = [desc[0] for desc in cur.description] return data def rows(self): file_name = "bias-fairness-" + self.date.strftime('%Y-%m-%d') test = BiasFairnessTest(data = self.input(), my_date = self.date) print("Realizando prueba unitaria: Validación de Fecha") test_val = test.test_get_date_validation() print("Prueba uitaria aprobada") print("Realizando prueba unitaria: Validación de número de renglones") test_nrow = test.test_get_nrow_file_validation() print("Prueba uitaria aprobada") date_time = strftime("%Y-%m-%d %H:%M:%S", gmtime()) data_test = { "file_name": [file_name, file_name], "data_date": [self.date, self.date], "processing_date": [date_time, date_time], "test_name": ["test_get_date_validation", "test_get_nrow_file_validation"], "result": [test_val, test_nrow] } data_test = pd.DataFrame(data_test) records = data_test.to_records(index=False) r = list(records) for element in r: yield element
Acturio/DPA-Project
src/pipeline/LuigiBiasFairnessTestTask.py
LuigiBiasFairnessTestTask.py
py
3,890
python
en
code
0
github-code
6
28792513287
MENU = { "espresso": { "ingredients": { "water": 50, "coffee": 18, }, "cost": 1.5, }, "latte": { "ingredients": { "water": 200, "milk": 150, "coffee": 24, }, "cost": 2.5, }, "cappuccino": { "ingredients": { "water": 250, "milk": 100, "coffee": 24, }, "cost": 3.0, } } profit = 0 resources = { "water": 300, "milk": 200, "coffee": 100, } def make_coffee(user_order, order_ingredients): global resources for item in order_ingredients: resources[item] -= order_ingredients[item] print(f"Here is your {user_order} ☕️. Enjoy!") def is_resource_sufficient(user_order): for item in MENU[user_order]["ingredients"]: if MENU[user_order]["ingredients"][item] > resources[item]: return False return True def process_coins(): """Returns the total calculated from coins inserted.""" print("Please insert coins.") total = int(input("how many quarters?: ")) * 0.25 total += int(input("how many dimes?: ")) * 0.1 total += int(input("how many nickels?: ")) * 0.05 total += int(input("how many pennies?: ")) * 0.01 return total def is_transaction_successful(money_received, drink_cost): """Return True when the payment is accepted, or False if money is insufficient.""" if money_received >= drink_cost: change = round(money_received - drink_cost, 2) print(f"Here is ${change} in change.") global profit profit += drink_cost return True else: print("Sorry, that's not enough money. Money refunded.") return False def resource_report(): """function to print remaining resources""" print(f""" Water: {resources['water']}ml Milk: {resources['milk']}ml Coffee: {resources['coffee']}g Money: ${profit} """) is_on = True while is_on: def what_to_do(user_order): global is_on if user_order == "off": is_on = False elif user_order in MENU: if is_resource_sufficient(user_order): print(f"The cost of {user_order} is ${MENU[user_order]['cost']}.") money_received = process_coins() if is_transaction_successful(money_received, MENU[user_order]['cost']): make_coffee(user_order, MENU[user_order]['ingredients']) else: print(f"Sorry, not enough resources for {user_order}.") elif user_order == "report": resource_report() else: print("You entered an invalid choice.") user_input = input("What would you like? (espresso/latte/cappuccino): ").lower() what_to_do(user_input)
Mohamed-Rirash/100-days-python-challenge
day15/coffee_machine.py
coffee_machine.py
py
2,823
python
en
code
0
github-code
6
650134167
#! /usr/bin/python import os import sys import json import luigi import numpy as np import vigra import nifty.ufd as nufd import cluster_tools.utils.volume_utils as vu import cluster_tools.utils.function_utils as fu from cluster_tools.cluster_tasks import SlurmTask, LocalTask, LSFTask # # Find Labeling Tasks # class MergeAssignmentsBase(luigi.Task): """ MergeAssignments base class """ task_name = "merge_assignments" src_file = os.path.abspath(__file__) allow_retry = False output_path = luigi.Parameter() output_key = luigi.Parameter() shape = luigi.ListParameter() # task that is required before running this task dependency = luigi.TaskParameter() def requires(self): return self.dependency def run_impl(self): shebang, block_shape, roi_begin, roi_end = self.global_config_values() self.init(shebang) block_list = vu.blocks_in_volume(self.shape, block_shape, roi_begin, roi_end) n_jobs = min(len(block_list), self.max_jobs) config = self.get_task_config() config.update({"output_path": self.output_path, "output_key": self.output_key, "tmp_folder": self.tmp_folder, "n_jobs": n_jobs, "block_list": block_list}) # we only have a single job to find the labeling self.prepare_jobs(1, None, config) self.submit_jobs(1) # wait till jobs finish and check for job success self.wait_for_jobs() # log the save-path again self.check_jobs(1) class MergeAssignmentsLocal(MergeAssignmentsBase, LocalTask): """ MergeAssignments on local machine """ pass class MergeAssignmentsSlurm(MergeAssignmentsBase, SlurmTask): """ MergeAssignments on slurm cluster """ pass class MergeAssignmentsLSF(MergeAssignmentsBase, LSFTask): """ MergeAssignments on lsf cluster """ pass def merge_assignments(job_id, config_path): fu.log("start processing job %i" % job_id) fu.log("reading config from %s" % config_path) with open(config_path, "r") as f: config = json.load(f) output_path = config["output_path"] output_key = config["output_key"] tmp_folder = config["tmp_folder"] n_jobs = config["n_jobs"] block_list = config["block_list"] id_prefix = "ids" assignment_prefix = "cc_assignments" # load labels label_paths = [os.path.join(tmp_folder, f"{id_prefix}_{block_id}.npy") for block_id in block_list] labels = [np.load(pp) if os.path.exists(pp) else [0] for pp in label_paths] labels = np.unique(np.concatenate(labels)) # load assignments assignment_paths = [os.path.join(tmp_folder, f"{assignment_prefix}_{job_id}.npy") for job_id in range(n_jobs)] assignments = [np.load(pp) for pp in assignment_paths if os.path.exists(pp)] if assignments: assignments = np.concatenate(assignments, axis=0) assignments = np.unique(assignments, axis=0) assert assignments.shape[1] == 2 fu.log("have %i pairs of node assignments" % len(assignments)) have_assignments = True else: fu.log("did not find any node assignments and will not merge any components") have_assignments = False if have_assignments: ufd = nufd.boost_ufd(labels) ufd.merge(assignments) label_assignments = ufd.find(labels) else: label_assignemnts = labels.copy() n_labels = len(labels) label_assignemnts, max_id, _ = vigra.analysis.relabelConsecutive(label_assignments, keep_zeros=True, start_label=1) assert len(label_assignments) == n_labels fu.log("reducing the number of labels from %i to %i" % (n_labels, max_id + 1)) label_assignments = np.concatenate([labels[:, None], label_assignments[:, None]], axis=1).astype("uint64") chunks = (min(65334, n_labels), 2) with vu.file_reader(output_path) as f: f.create_dataset(output_key, data=label_assignments, compression="gzip", chunks=chunks) fu.log_job_success(job_id) if __name__ == "__main__": path = sys.argv[1] assert os.path.exists(path), path job_id = int(os.path.split(path)[1].split(".")[0].split("_")[-1]) merge_assignments(job_id, path)
constantinpape/cluster_tools
cluster_tools/connected_components/merge_assignments.py
merge_assignments.py
py
4,231
python
en
code
32
github-code
6
42758646277
#!/usr/bin/env python import sys, os from cavan_adb import AdbManager class AndroidManager(AdbManager): def __init__(self, verbose = True): buildTop = self.getEnv("ANDROID_BUILD_TOP") productOut = self.getEnv("ANDROID_PRODUCT_OUT") if not buildTop or not productOut: self.doRaise("please run 'source build/envsetup.sh && lunch'") self.mBuildTop = os.path.realpath(buildTop) self.mProductOut = os.path.realpath(productOut) self.mProductOutLen = len(self.mProductOut) self.mPathSystem = os.path.join(self.mProductOut, "system") AdbManager.__init__(self, self.mBuildTop, verbose) if self.mVerbose: self.prStdInfo("mBuildTop = " + self.mBuildTop) self.prStdInfo("mProductOut = " + self.mProductOut) def getHostPath(self, pathname): if not os.path.exists(pathname): if os.path.isabs(pathname): self.doRaise("file %s is not exists" % pathname) else: if pathname.startswith("out"): dirname = self.mBuildTop else: dirname = self.mProductOut newPath = os.path.join(dirname, pathname) if os.path.exists(newPath): pathname = newPath elif not os.path.dirname(pathname): if self.mVerbose: self.prStdInfo("Try find from: ", self.mPathSystem) files = self.doFindFile(self.mPathSystem, pathname) if not files: self.doRaise("file %s is not exists" % pathname) elif len(files) > 1: for fn in files: self.prRedInfo("pathname = " + fn) self.doRaise("too much file named %s" % pathname) else: pathname = files[0] else: self.doRaise("file %s is not exists" % pathname) return os.path.realpath(pathname) def getDevicePath(self, pathname): if pathname.startswith(self.mProductOut): return pathname[self.mProductOutLen:] return pathname def push(self, listFile): if not self.doRemount(): return False lastDir = None for pathname in listFile: hostPath = self.getHostPath(pathname) if not os.path.exists(hostPath) and lastDir != None: hostPath = os.path.join(lastDir, pathname) devPath = self.getDevicePath(hostPath) if not self.doPush(hostPath, devPath): return False self.doSymlink(hostPath) lastDir = os.path.dirname(hostPath) return True
FuangCao/cavan-20150921
script/python/cavan_android.py
cavan_android.py
py
2,230
python
en
code
0
github-code
6
41550930434
import contextlib, os, signal from . import log, pid_context SIGNAL_NUMBERS = {k: v for k, v in signal.__dict__.items() if k.startswith('SIG') and '_' not in k} SIGNAL_NAMES = {v: k for k, v in SIGNAL_NUMBERS.items()} STOP_SIGNALS = 'SIGINT', 'SIGTERM' RESTART_SIGNALS = 'SIGHUP', HANDLED_SIGNALS = STOP_SIGNALS + RESTART_SIGNALS @contextlib.contextmanager def context(**handlers): signals = {} def handler(signum, frame): signame = SIGNAL_NAMES[signum] signals[signame] = True handler = handlers[signame] handler() def set_all(handler): for signame in handlers: if signame in SIGNAL_NUMBERS: # Windows doesn't have all signals signal.signal(SIGNAL_NUMBERS[signame], handler) set_all(handler) try: yield signals finally: set_all(signal.SIG_DFL) def send_signal(sig, pid_filename=None): sig = SIGNAL_NUMBERS.get(sig, sig) if sig not in SIGNAL_NAMES: log.error('No signal %s', sig) return -1 try: pid = pid_context.get_pid(pid_filename) except: log.error('No bp process running') log.debug('Could not find file %s', pid_filename) return -1 try: os.kill(pid, sig) except: log.error('Failed to send signal %s to bp process %s', sig, pid) return -1 log.info('%s sent to bp process %s', sig, pid) return 0 def run(filename, stopper, stop_signals=STOP_SIGNALS, restart_signals=RESTART_SIGNALS): signal_dict = {s: stopper for s in stop_signals + restart_signals} with pid_context.pid_context(filename): with context(**signal_dict) as signals: running = True while running: yield if not signals: return log.info('Received signal %s', ' '.join(signals)) running = all(s in restart_signals for s in signals) signals.clear() def make_command(default_signal, help=''): # Handle legacy commands restart, kill, shutdown def add_arguments(parser): parser.add_argument( 'signal', nargs='?', default=default_signal, choices=sorted(SIGNAL_NUMBERS), help='Signal to send.' + help) pid_context.add_arguments(parser) def run(args): return send_signal(args.signal, args.pid_filename) return add_arguments, run
ManiacalLabs/BiblioPixel
bibliopixel/util/signal_handler.py
signal_handler.py
py
2,465
python
en
code
263
github-code
6
30917930824
import os import shutil import sys import pandas as pd import numpy as np l_sys = sys.path l_path = l_sys[['tests' in i for i in l_sys].index(True)] l_path = l_path.replace("tests", '') l_path = l_path + "/tnbs/"#BTC_03_QPE/" sys.path.append(l_path) sys.path.append(l_path+"BTC_04_PH") from BTC_04_PH.my_benchmark_execution import KERNEL_BENCHMARK def create_folder(folder_name): """ Check if folder exist. If not the function creates it Parameters ---------- folder_name : str Name of the folder Returns ---------- folder_name : str Name of the folder """ # Check if the folder already exists if not os.path.exists(folder_name): # If it does not exist, create the folder os.mkdir(folder_name) print(f"Folder '{folder_name}' created.") else: print(f"Folder '{folder_name}' already exists.") if folder_name.endswith('/') != True: folder_name = folder_name + "/" return folder_name def test_ph(): #Anstaz depth = [3] qpu_ph = "c" nb_shots = 0 truncation = None kernel_configuration = { #Ansatz "conf_files_folder": "tnbs/BTC_04_PH/configuration_files", "depth": depth, "t_inv": True, # Ground State Energy "qpu_ph" : qpu_ph, "nb_shots" : nb_shots, "truncation": truncation, # Saving "save": True, "folder": None, # Errors for confidence level "gse_error" : None, "time_error": None, } list_of_qbits = [3] benchmark_arguments = { #Pre benchmark sttuff "pre_benchmark": True, "pre_samples": None, "pre_save": True, #Saving stuff "save_append" : True, "saving_folder": "./Results/", "benchmark_times": "kernel_times_benchmark.csv", "csv_results": "kernel_benchmark.csv", "summary_results": "kernel_SummaryResults.csv", #Computing Repetitions stuff "alpha": None, "min_meas": None, "max_meas": None, #List number of qubits tested "list_of_qbits": list_of_qbits, } #Configuration for the benchmark kernel benchmark_arguments.update({"kernel_configuration": kernel_configuration}) folder = create_folder(benchmark_arguments["saving_folder"]) kernel_bench = KERNEL_BENCHMARK(**benchmark_arguments) kernel_bench.exe() filename = "./Results/kernel_SummaryResults.csv" index_columns = [0, 1, 2, 3, 4, 5] a = pd.read_csv(filename, header=[0, 1], index_col=index_columns) a = a.reset_index() assert(np.abs(a["gse"]["mean"][0]) < 0.01) #assert((a[a['angle_method']=="exact"]['fidelity']['mean'] > 0.999).all()) #assert((a[a['angle_method']=="random"]['KS']['mean'] < 0.05).all()) shutil.rmtree(folder) test_ph()
NEASQC/WP3_Benchmark
tests/test_btc_04_ph.py
test_btc_04_ph.py
py
2,857
python
en
code
0
github-code
6
10057572506
def unionofList(list1,list2): list1.extend(list2) unionList=set(list1) print(unionList) def intersection(list1,list2): size1=len(list1) size2=len(list2) if(size1<size2): size1,size2=size2,size1 for i in list1: if i not in m: m[i]=1 else: m[i]+=1 intersectionList=[] for i in list2: if i in m and m[i]: m[i]-=1 intersectionList.append(i) print(intersectionList) n=int(input("Enter the size of the first array:")) list1=[] print("Enter array elements: ") while(n>0): number=int(input()) list1.append(number) n-=1 m=int(input("Enter the size of the second array:")) list2=[] print("Enter array elements: ") while(m>0): number=int(input()) list2.append(number) m-=1 unionofList(list1,list2) intersection(list1,list2)
FarhanTahmid/Problem-Solving
Array Problems - Geeks For Geeks/Level 1/problem10.py
problem10.py
py
858
python
en
code
0
github-code
6
13865138503
import argparse import datetime import json import os from itertools import zip_longest from pathlib import Path from typing import List, Optional, Tuple import gpxpy from rich import box from hiking.import_export import JSON_IMPORT_EXAMPLE from hiking.models import Hike from hiking.utils import DATA_HOME, DEFAULT_BOX_STYLE, SlimDateRange # TODO: find a way to auto-detect this from rich BOX_FORMATS = [ "ASCII", "ASCII2", "ASCII_DOUBLE_HEAD", "SQUARE", "SQUARE_DOUBLE_HEAD", "MINIMAL", "MINIMAL_HEAVY_HEAD", "MINIMAL_DOUBLE_HEAD", "SIMPLE", "SIMPLE_HEAD", "SIMPLE_HEAVY", "HORIZONTALS", "ROUNDED", "HEAVY", "HEAVY_EDGE", "HEAVY_HEAD", "DOUBLE", "DOUBLE_EDGE", "MARKDOWN", ] def get_valid_fields_for_args(exclude: Optional[List] = None): exclude = exclude or [] return [ field.info["name"] for field in Hike.FIELDS if field.info["data_view"] and field.info["name"] not in exclude ] class DateRangeType: description = ( "Only include hikes contained in provided daterange (default: all hikes)" ) examples = ( "Valid examples:\n" "1970-01-01\n" "1970-01-01/1970-02-01\n" "1970-01-01/ (all hikes from start date)\n" "/1970-01-01 (all hikes until end date)" ) help = f"{description}\n{examples}" def __call__(self, raw: str, *args, **kwargs): start = end = raw splitted = raw.split("/") if len(splitted) == 2 and all(splitted): start, end = splitted elif start.endswith("/"): start = start.rstrip("/") end = None elif end.startswith("/"): end = end.lstrip("/") start = None try: start = ( datetime.datetime.strptime(start, "%Y-%m-%d").date() if start else datetime.date.min ) end = ( datetime.datetime.strptime(end, "%Y-%m-%d").date() if end else datetime.date.max ) except ValueError as e: raise argparse.ArgumentTypeError(f"{e.args[0]}\n{self.examples}") return SlimDateRange(start, end) class WritableDirPathType: def __call__(self, raw: str, *args, **kwargs): directory = Path(raw) if ( not directory.exists() or not directory.is_dir() or not os.access(directory, os.W_OK) ): raise argparse.ArgumentTypeError( f'Cannot write to directory: "{directory.absolute()}". ' f"Make sure it exists and is writable." ) return directory class GPXFileType(argparse.FileType): def __call__(self, *args, **kwargs): file = super().__call__(*args, **kwargs) try: gpx_xml = file.read() gpxpy.parse(gpx_xml) except Exception as e: raise argparse.ArgumentTypeError(f"Cannot read *.gpx file: {str(e)}") return gpx_xml class JsonFileType(argparse.FileType): def __call__(self, *args, **kwargs): file = super().__call__(*args, **kwargs) try: data = json.load(file) except Exception as e: raise argparse.ArgumentTypeError(f"Cannot read *.json file: {str(e)}") return data def validate_order_key(value: str) -> Tuple[str, bool]: reverse = False if value.startswith("-"): reverse = True value = value.lstrip("-") if value not in get_valid_fields_for_args(): raise argparse.ArgumentTypeError("Invalid order_key") return value, reverse def validate_plot(value: str) -> Tuple[str, str]: try: x, y = tuple(value.split(",")) for i in x, y: assert i in get_valid_fields_for_args(["name"]) return x, y except (ValueError, AssertionError): raise argparse.ArgumentTypeError("plot") def validate_table_style(value: str) -> Tuple[str, str]: try: box_style = getattr(box, value.upper()) except AttributeError: raise argparse.ArgumentTypeError("Invalid table-style") return box_style def set_default_subparser( parser: argparse.ArgumentParser, default_subcommand: str, raw_args: List[str] ): subparser_found = False for arg in raw_args: if arg in ["-h", "--help"]: # pragma: no cover break else: for x in parser._subparsers._actions: if not isinstance(x, argparse._SubParsersAction): continue for sp_name in x._name_parser_map.keys(): if sp_name in raw_args: subparser_found = True if not subparser_found: raw_args.insert(0, default_subcommand) def parse_arguments(raw_args: List[str]) -> argparse.Namespace: """ Parse all arguments. """ def format_list(data: List[str]): data.sort() col_1 = data[: int(round(len(data) / 2))] col_2 = data[int(round(len(data) / 2)) :] table_data = list(zip_longest(col_1, col_2, fillvalue="")) longest = 0 for i in table_data: if len(i[0]) > longest: longest = len(i[0]) result = [f"{i[0].ljust(longest)}{' ' * 5}{i[1]}" for i in table_data] return "\n".join(result) parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter, prog="hiking" ) debug_arg_dict = { "help": "Show debug information (log queries)", "action": "store_true", } subparsers = parser.add_subparsers(dest="command") show = subparsers.add_parser( "show", help="Show hike(s) (default)", description="Show hike(s) (default)", formatter_class=argparse.RawTextHelpFormatter, ) show.add_argument( "ids", metavar="ID", help="Hike ID", nargs="*", type=int, ) show.add_argument( "-d", "--daterange", help=DateRangeType.help, type=DateRangeType(), default=SlimDateRange(datetime.date.min, datetime.date.max), ) show.add_argument( "-s", "--search", help="Search for text in name and body (case insensitive)", type=str, ) show.add_argument( "-t", "--table-style", help=( "Table format style (default: simple)\n" f"Available options:\n{format_list(BOX_FORMATS)}" ), default=DEFAULT_BOX_STYLE, type=validate_table_style, ) show.add_argument( "-o", "--order-key", help=( 'Key to use for hike sorting. To reverse, prepend with "-".\n' "Available options:\n" f"{format_list(get_valid_fields_for_args())}" ), default=("date", False), type=validate_order_key, ) show.add_argument( "--plot", help=( "Fields to plot in a graph.\n" "*experimental*\n" "Example:\n" '"date,distance"\n' "Available options:\n" f"{format_list(get_valid_fields_for_args(exclude=['name']))}" ), default=(), type=validate_plot, ) show.add_argument("--debug", **debug_arg_dict) create = subparsers.add_parser( "create", help="Create a new record", description="Create a new record.", formatter_class=argparse.RawTextHelpFormatter, ) create.add_argument( "--gpx", metavar="GPX_FILE", type=GPXFileType("r"), help="Import from *.gpx-file", ) create.add_argument("--debug", **debug_arg_dict) edit = subparsers.add_parser( "edit", help="Edit a record", description="Edit a record.", formatter_class=argparse.RawTextHelpFormatter, ) edit.add_argument( "id", metavar="ID", help="Hike ID", type=int, ) edit.add_argument( "--gpx", metavar="GPX_FILE", type=GPXFileType("r"), help="Import from *.gpx-file", ) edit.add_argument("--debug", **debug_arg_dict) delete = subparsers.add_parser( "delete", help="Delete records by ID", description="Delete records by ID.", formatter_class=argparse.RawTextHelpFormatter, ) delete.add_argument( "-f", "--force", help="Do not ask before deletion", action="store_true", ) delete.add_argument( "-q", "--quiet", help="Do not display hikes before deletion", action="store_true", ) delete.add_argument( "-a", "--all", help="Delete all hikes", action="store_true", ) delete.add_argument( "ids", metavar="ID", help="Hike ID", nargs="*", type=int, ) delete.add_argument("--debug", **debug_arg_dict) _import = subparsers.add_parser( "import", help="Import records from JSON", description=f"Import records from JSON.\nFormat:\n{JSON_IMPORT_EXAMPLE}", formatter_class=argparse.RawTextHelpFormatter, ) _import.add_argument( "json_data", metavar="JSON_FILE", help="Path to JSON file", type=JsonFileType("r"), ) _import.add_argument("--debug", **debug_arg_dict) export = subparsers.add_parser( "export", help="Export records as JSON and GPX", description="Export records as JSON and GPX.", formatter_class=argparse.RawTextHelpFormatter, ) export.add_argument( "export_dir", metavar="EXPORT_DIR", help="Path to export directory", type=WritableDirPathType(), ) export.add_argument( "ids", metavar="ID", help="Hike ID", nargs="*", type=int, ) export.add_argument( "-d", "--daterange", help=DateRangeType.help, type=DateRangeType(), default=SlimDateRange(datetime.date.min, datetime.date.max), ) export.add_argument( "-i", "--include-ids", help='Include IDs in export. Needed for "update", must be omitted for "create"', action="store_true", ) export.add_argument("--debug", **debug_arg_dict) set_default_subparser(parser, "show", raw_args) args = parser.parse_args(raw_args) if args.command == "delete" and not args.ids and not args.all: raise parser.error("IDs or --all must be provided") elif args.command == "delete" and args.ids and args.all: raise parser.error("Ambiguous argument: IDs and --all provided") try: WritableDirPathType()(DATA_HOME.parent) except argparse.ArgumentTypeError: raise parser.error(f"Cannot write to user data director: {DATA_HOME.parent}") return args
open-dynaMIX/hiking
hiking/arg_parsing.py
arg_parsing.py
py
10,991
python
en
code
0
github-code
6
41708182518
from model.siamese.config import cfg import tensorflow as tf import numpy as np import math from abc import ABC import os def create_model(trainable=True): input_shape = (cfg.NN.INPUT_SIZE, cfg.NN.INPUT_SIZE, 3) input_tensor = tf.keras.layers.Input(shape=input_shape) base = tf.keras.applications.MobileNetV2(input_shape=input_shape, alpha=cfg.NN.ALPHA, weights='imagenet', include_top=False) for layer in base.layers: layer.trainable = trainable x = input_tensor x = base(x) x = tf.keras.layers.Flatten()(x) x = tf.keras.layers.Dropout(0.5)(x) x = tf.keras.layers.Dense(512, activation='tanh')(x) x = tf.keras.layers.Lambda(lambda tensor: tf.math.l2_normalize( tensor, axis=1), name='embedding')(x) x = tf.keras.layers.Dense(16, activation='linear')(x) model = tf.keras.Model(inputs=input_tensor, outputs=x) return model def create_embedding_model(classif_model): return tf.keras.Model(classif_model.input, classif_model.get_layer('embedding').output) dirname = os.path.dirname(__file__) default_weights = os.path.join( dirname, cfg.MODEL.WEIGHTS_PATH, 'classif-model-6_0.2701_1.4515.h5') class ClassificationModel(ABC): """ Model based on classificator with last layer removed. It wraps TF model and provides easier to understand API. """ def __init__(self, weights_path=default_weights, trainable=True): super().__init__() self.net = create_model(trainable) self.net.load_weights(weights_path) # Remove last layer self.net = create_embedding_model(self.net) def predict(self, images: list): """ Calculate embeddings for each input image Args: images: List<Tensor>, list of images to process Returns: List List of embeddings """ images = list(map(lambda x: tf.image.resize(x, size=( cfg.NN.INPUT_SIZE, cfg.NN.INPUT_SIZE)), images)) boxes_tensors = tf.stack(images) boxes_tensors = tf.keras.applications.mobilenet.preprocess_input(boxes_tensors) predictions = self.net(boxes_tensors).numpy() return predictions
burnpiro/farm-animal-tracking
model/siamese/classification_model.py
classification_model.py
py
2,228
python
en
code
24
github-code
6
38735062705
import itertools import math from time import sleep def posible_sums(num): posibilities = [] divisor = 1 while divisor < num: current = num / divisor while not current.is_integer(): divisor += 1 current = num / divisor divisor += 1 posibilities.append(int(current)) return posibilities def to_exponent(base, exp): result = 1 results = [] current = 1 while True: rest = exp return results # print(to_exponent(2,12)) print(posible_sums(12))
acalasanzs/pyeuler
250/250.py
250.py
py
580
python
en
code
0
github-code
6
16132746633
''' mobile monkey ''' import time from typing import List from threading import Thread import config_reader as config import emulator_manager import api_commands from telnet_connector import TelnetAdb from telnet_connector import GsmProfile from telnet_connector import NetworkDelay from telnet_connector import NetworkStatus from emulator import Emulator from fuzz_context import Fuzzer from adb_settings import Airplane, KeyboardEvent, UserRotation # import adb_settings as AdbSettings import util from adb_monkey import AdbMonkey from apk import Apk from adb_logcat import Logcat, TestType, FatalWatcher from log_analyzer import Analyzer PRINT_FLAG = True TIME_PRINT_FLAG = True emulator_model = config.EMULATOR_NAME emulator_port = config.EMULATOR_PORT contextual_events = 0 WILL_MONKEY = True def start_emulator() -> bool: ''' starts emulator ''' global emulator_model if emulator_manager.adb_instances_manager(): util.debug_print('already emulators are running.', flag=PRINT_FLAG) return True else: util.debug_print( str.format("No emulator instance running. starting {} at port {}", emulator_model, emulator_port), flag=PRINT_FLAG) api_commands.adb_start_server_safe() emulator_manager.emulator_start_avd(emulator_port, emulator_model) # subprocess.Popen([command, # '-port', str(emulator_port), '-avd', # emulator_name, '-use-system-libs'], # stdout=subprocess.PIPE) emulator_manager.check_avd_booted_completely(emulator_port) return True def threads_to_run(emulator: Emulator, apk: Apk, fuzz: Fuzzer, will_monkey: bool) -> List: ''' runs the threads after checking permissions. ''' threads = [] global contextual_events util.debug_print(apk.permissions, flag=PRINT_FLAG) emulator_name = 'emulator-' + str(emulator.port) if "android.permission.INTERNET" in apk.permissions or \ "android.permission.ACCESS_NETWORK_STATE" in apk.permissions: util.debug_print("Internet permission detected", flag=PRINT_FLAG) network_delay_interval_events = fuzz.generate_step_interval_event( NetworkDelay) # print(network_delay_interval_events) contextual_events += len(network_delay_interval_events) threads.append(Thread(target=fuzz.random_network_delay, args=( config.LOCALHOST, emulator, network_delay_interval_events))) network_speed_interval_event = fuzz.generate_step_interval_event( NetworkStatus) # print(network_speed_interval_event) contextual_events += len(network_speed_interval_event) threads.append(Thread(target=fuzz.random_network_speed, args=( config.LOCALHOST, emulator, network_speed_interval_event))) airplane_mode_interval_events = fuzz.generate_step_interval_event( Airplane) # print(airplane_mode_interval_events) contextual_events += len(airplane_mode_interval_events) threads.append(Thread( target=fuzz.random_airplane_mode_call, args=(emulator_name, airplane_mode_interval_events))) if "android.permission.ACCESS_NETWORK_STATE" in apk.permissions: util.debug_print("access_network_state detected", flag=PRINT_FLAG) gsm_profile_interval_events = fuzz.generate_step_uniforminterval_event( GsmProfile) contextual_events += len(gsm_profile_interval_events) threads.append(Thread(target=fuzz.random_gsm_profile, args=( config.LOCALHOST, emulator, config.UNIFORM_INTERVAL, gsm_profile_interval_events))) user_rotation_interval_events = fuzz.generate_step_interval_event( UserRotation) contextual_events += len(user_rotation_interval_events) threads.append(Thread( target=fuzz.random_rotation, args=((emulator_name, user_rotation_interval_events)))) key_event_interval_events = fuzz.generate_step_interval_event( KeyboardEvent) contextual_events += len(key_event_interval_events) threads.append(Thread( target=fuzz.random_key_event, args=((emulator_name, key_event_interval_events)))) if will_monkey: monkey = AdbMonkey(emulator, apk, config.SEED, config.DURATION) thread_monkey = Thread(target=monkey.start_monkey) threads.append(thread_monkey) return threads def run(apk: Apk, emulator_name: str, emulator_port: int): ''' runs things ''' to_kill = False to_test = True to_full_run = True wipe_after_finish = False # test_time_seconds = 30 if not start_emulator(): return emulator = emulator_manager.get_adb_instance_from_emulators(emulator_name) # emulator_name = 'emulator-' + emulator.port telnet_connector = TelnetAdb(config.LOCALHOST, emulator.port) # apk = Apk(config.APK_FULL_PATH) # api_commands.adb_uninstall_apk(emulator, apk) # api_commands.adb_install_apk(emulator, apk) # api_commands.adb_start_launcher_of_apk(emulator, apk) log = Logcat(emulator, apk, TestType.MobileMonkey) # api_commands.adb_pidof_app(emulator, apk) if to_kill: telnet_connector.kill_avd() quit() if not to_test: return log.start_logcat() fuzz = Fuzzer(config.MINIMUM_INTERVAL, config.MAXIMUM_INTERVAL, config.SEED, config.DURATION, FatalWatcher(log.file_address)) # log.experimental_start_logcat(fuzz) # fuzz.print_intervals_events() threads = threads_to_run(emulator, apk, fuzz, WILL_MONKEY) # log_thread = Thread(target=log.start, args=(fuzz,)) global contextual_events print("Total contextual events: " + str(contextual_events)) # print(threads) # return # device = AdbSettings.AdbSettings('emulator-' + adb_instance.port) # triggers = [fuzz.set_continue_network_speed, # fuzz.set_continue_gsm_profile, # fuzz.set_continue_network_delay] # thread_test = Thread(target=time_to_test, args=[ # test_time_seconds, triggers, ]) # thread_fuzz_delay = Thread(target=fuzz.random_network_delay, args=( # config.LOCALHOST, emulator.port,)) # thread_fuzz_profile = Thread(target=fuzz.random_gsm_profile, args=( # config.LOCALHOST, emulator.port, 12,)) # thread_fuzz_speed = Thread(target=fuzz.random_network_speed, args=( # config.LOCALHOST, emulator.port,)) # thread_fuzz_rotation = Thread( # target=fuzz.random_rotation, args=((emulator_name,))) # thread_fuzz_airplane = Thread( # target=fuzz.random_airplane_mode_call, args=(emulator_name,)) # monkey = AdbMonkey(emulator, config.APP_PACKAGE_NAME, # config.SEED, config.DURATION) # thread_monkey = Thread(target=monkey.start_monkey) if to_full_run: util.debug_print( "started testing at {}".format(time.ctime()), flag=TIME_PRINT_FLAG) [thread.start() for thread in threads] # log_thread.start() [thread.join() for thread in threads] # log.log_process.kill() # log.stop_logcat() # log_thread.join() # thread_monkey.start() # thread_fuzz_rotation.start() # thread_fuzz_delay.start() # thread_fuzz_profile.start() # thread_fuzz_speed.start() # thread_fuzz_airplane.start() # thread_test.start() # thread_test.join() # thread_fuzz_delay.join() # thread_fuzz_profile.join() # thread_fuzz_speed.join() # thread_fuzz_rotation.join() # thread_fuzz_airplane.join() # thread_monkey.join() # telnet_connector.kill_avd() api_commands.adb_stop_activity_of_apk(emulator, apk) log.stop_logcat() api_commands.adb_uninstall_apk(emulator, apk) util.debug_print( 'Finished testing and uninstalling app at {}'.format(time.ctime()), flag=TIME_PRINT_FLAG) print(Analyzer(log.file_address)) if wipe_after_finish: print("successfully completed testing app. Closing emulator") telnet_connector.kill_avd() emulator_manager.emulator_wipe_data(emulator) if __name__ == '__main__': import os dir = os.path.dirname(__file__) StopFlagWatcher = os.path.join(dir, 'test/StopFlagWatcher') file = open(StopFlagWatcher, 'w') file.truncate() file.close() run(Apk(config.APK_FULL_PATH), config.EMULATOR_NAME, config.EMULATOR_PORT)
LordAmit/mobile-monkey
mobile_monkey.py
mobile_monkey.py
py
8,654
python
en
code
4
github-code
6
43344834943
import unittest import mock import time from copy import deepcopy from gorynych.common.domain import events from gorynych.common.exceptions import DomainError from gorynych.info.domain.test.helpers import create_contest from gorynych.info.domain import contest, person, race from gorynych.common.domain.types import Address, Name, Country from gorynych.info.domain.ids import PersonID, RaceID, TrackerID, TransportID class MockedPersonRepository(mock.Mock): ''' Necessary only for tracker assignment. ''' def get_by_id(self, key): person = mock.Mock() person.name = Name('name', 'surname') person.country = Country('RU') if key == 'person1': person.tracker = 'tracker1' elif key == 'person2': person.tracker = 'tracker2' elif key == 'person3': person.tracker = None return person class ContestFactoryTest(unittest.TestCase): def test_contestid_successfull_contest_creation(self): cont = create_contest(1, 2) self.assertIsInstance(cont.address, Address) self.assertEqual(cont.title, 'Hello world') self.assertEqual(cont.country, 'RU') self.assertEqual(cont.timezone, 'Europe/Moscow') self.assertEqual(cont.place, 'Yrupinsk') self.assertEquals((cont.start_time, cont.end_time), (1, 2)) self.assertIsInstance(cont.id, contest.ContestID) self.assertIsNone(cont._id) cont2 = create_contest(3, 4) self.assertNotEqual(cont.id, cont2.id, "Contest with the same id has been created.") def test_str_successfull_contest_creation(self): cont = create_contest(1, 3, id='cnts-130422-12345') self.assertEqual(cont.end_time, 3) self.assertEqual(cont.start_time, 1) self.assertEqual(cont.id, 'cnts-130422-12345') def test_unsuccessfull_contest_creation(self): self.assertRaises(ValueError, create_contest, 3, 1, "Contest can be created with wrong times.") class EventsApplyingTest(unittest.TestCase): def test_ContestRaceCreated(self): cont = create_contest(1, 2) rid = RaceID() ev = events.ContestRaceCreated(cont.id, rid) self.assertRaises(AssertionError, cont.apply, ev) cont.apply([ev]) self.assertEqual(len(cont.race_ids), 1) cont.apply([ev]) self.assertEqual(len(cont.race_ids), 1) rid = RaceID() ev = events.ContestRaceCreated(cont.id, rid) cont.apply([ev]) self.assertEqual(len(cont.race_ids), 2) class ContestTest(unittest.TestCase): @mock.patch('gorynych.common.infrastructure.persistence.event_store') def test_register_paraglider(self, patched): event_store = mock.Mock() patched.return_value = event_store cont = create_contest(1, 2) p1 = person.PersonID() c = cont.register_paraglider(p1, 'mantrA 9', '747') self.assertIsInstance(c, contest.Contest) self.assertEqual(len(cont._participants), 1) self.assertEqual(len(cont.paragliders), 1) self.assertIsInstance(cont.paragliders, dict, "It must be dict.") self.assertEqual(cont._participants[p1]['role'], 'paraglider') self.assertEqual(cont._participants[p1]['glider'], 'mantra') self.assertEqual(cont._participants[p1]['contest_number'], 747) p2 = person.PersonID() cont.register_paraglider(p2, 'mantrA 9', '757') self.assertEqual(len(cont._participants), 2) self.assertEqual(cont._participants[p2]['role'], 'paraglider') self.assertEqual(cont._participants[p2]['glider'], 'mantra') self.assertEqual(cont._participants[p2]['contest_number'], 757) # Check contest numbers uniqueness. self.assertRaises(ValueError, cont.register_paraglider, 'person3', 'mantrA 9', '757') mock_calls = event_store.mock_calls self.assertEqual(len(mock_calls), 2) self.assertEqual(mock_calls[-1], mock.call.persist( events.ParagliderRegisteredOnContest(p2, cont.id))) self.assertEqual(mock_calls[-2], mock.call.persist( events.ParagliderRegisteredOnContest(p1, cont.id))) def test_times_changing(self): cont = create_contest(1, '15') cont.start_time = '2' self.assertEqual(cont.start_time, 2) cont.end_time = '8' self.assertEqual(cont.end_time, 8) self.assertRaises(ValueError, setattr, cont, 'start_time', 8) self.assertRaises(ValueError, setattr, cont, 'start_time', 9) self.assertRaises(ValueError, setattr, cont, 'end_time', 2) self.assertRaises(ValueError, setattr, cont, 'end_time', 1) cont.change_times('10', '16') self.assertEqual((cont.start_time, cont.end_time), (10, 16)) self.assertRaises(ValueError, cont.change_times, '10', '8') def test_change_title(self): cont = create_contest(1, '15') cont.title = ' hello moOn ' self.assertEqual(cont.title, 'hello moOn') def test_change_address(self): cont = create_contest(1, '15') cont.place = 'Severodvinsk' self.assertEqual(cont.place, 'Severodvinsk') cont.country = 'tw' self.assertEqual(cont.country, 'TW') cont.hq_coords = (15, 0) self.assertEqual(cont.hq_coords, (15, 0)) class ContestTestWithRegisteredParagliders(unittest.TestCase): def setUp(self): self.p1_id = person.PersonID() self.p2_id = person.PersonID() self.p3_id = person.PersonID() @mock.patch('gorynych.common.infrastructure.persistence.event_store') def fixture(patched): patched.return_value = mock.Mock() cont = create_contest(1, 15) cont.register_paraglider(self.p2_id, 'mantrA 9', '757') cont.register_paraglider(self.p1_id, 'gIn 9', '747') person1 = cont._participants[self.p1_id] person2 = cont._participants[self.p2_id] return cont, person1, person2 try: self.cont, self.person1, self.person2 = fixture() except: raise unittest.SkipTest("ERROR: need contest with paragliders " "for test.") def tearDown(self): del self.cont del self.person1 del self.person2 def test_correct_change_participant_data(self): self.cont.change_participant_data(self.p1_id, glider='ajAx ', contest_number='0') self.assertEqual(self.person1['glider'], 'ajax') self.assertEqual(self.person1['contest_number'], 0) def test_no_data(self): self.assertRaises(ValueError, self.cont.change_participant_data, 'person2') def test_wrong_parameters(self): self.assertRaises(ValueError, self.cont.change_participant_data, 'person3', contest_number=9, glider='ajax') self.cont.change_participant_data(self.p1_id, cotest_number=9, glider='aJax') self.assertEqual(self.person1['contest_number'], 747) self.assertEqual(self.person1['glider'], 'ajax') def test_violate_invariants(self): self.assertRaises(ValueError, self.cont.change_participant_data, 'person1', contest_number='757') class ParagliderTest(unittest.TestCase): def test_success_creation(self): p_id = PersonID() t_id = TrackerID(TrackerID.device_types[0], '123456789012345') p = race.Paraglider(p_id, Name('Vasya', 'Pupkin'), Country('RU'), 'Mantra 9', 15, t_id) self.assertEqual(p.person_id, p_id) self.assertEqual(p.glider, 'mantra') self.assertEqual(p.contest_number, 15) self.assertEqual(p.tracker_id, t_id) @mock.patch('gorynych.common.infrastructure.persistence.event_store') class ContestServiceTest(unittest.TestCase): def setUp(self): self.cont = create_contest(time.time(), time.time() + 3600) def test_register_paraglider(self, patched): event_store = mock.Mock() patched.return_value = event_store alone_cont = deepcopy(self.cont) pid = PersonID() populated_cont = self.cont.register_paraglider(pid, 'glider', 11) self.assertFalse(alone_cont.paragliders) self.assertTrue(populated_cont.paragliders) pgl = populated_cont.paragliders self.assertEquals(pgl.keys()[0], pid) self.assertEquals(pgl[pid]['role'], 'paraglider') self.assertEquals(pgl[pid]['glider'], 'glider') self.assertEquals(pgl[pid]['contest_number'], 11) def test_add_transport(self, patched): event_store = mock.Mock() patched.return_value = event_store alone_cont = deepcopy(self.cont) tid = TransportID() populated_cont = self.cont.add_transport(tid) self.assertFalse(alone_cont.transport) self.assertIn(tid, populated_cont.transport) def test_change_paraglider(self, patched): event_store = mock.Mock() patched.return_value = event_store pid = PersonID() cont = self.cont.register_paraglider(pid, 'glider', 11) changed_cont = contest.change_participant(cont, dict(glider='noglider', contest_number=21, person_id=pid)) pgl = changed_cont.paragliders self.assertEquals(pgl.keys()[0], pid) self.assertEquals(pgl[pid]['glider'], 'noglider') self.assertEquals(pgl[pid]['contest_number'], 21) def test_add_winddummy(self, patched): event_store = mock.Mock() patched.return_value = event_store pid = PersonID() cont = self.cont.add_winddummy(pid) wdms = cont.winddummies self.assertEquals(wdms, [pid]) def test_get_winddummy(self, patched): event_store = mock.Mock() patched.return_value = event_store pid = PersonID() cont = self.cont.add_winddummy(pid) self.assertEquals(cont.get_winddummy(pid), pid) pid2 = PersonID() self.assertRaises(DomainError, cont.get_winddummy, pid2)
DmitryLoki/gorynych
gorynych/info/domain/test/test_contest.py
test_contest.py
py
10,466
python
en
code
3
github-code
6
11735874338
import sys import enum from sqlalchemy import Column, DateTime, Integer, String, ForeignKey, Table from sqlalchemy.orm import relationship, backref from rhinventory.extensions import db class SimpleAssetAttribute(): name: str def __str__(self) -> str: return f"{self.name}" def asset_n_to_n_table(other_table: db.Model) -> Table: other_name = other_table.__name__.lower() return Table( f"asset_{other_name}", db.Model.metadata, Column("asset_id", ForeignKey("assets.id")), Column(f"{other_name}_id", ForeignKey(other_table.id)), ) class Platform(db.Model, SimpleAssetAttribute): __tablename__ = 'platforms' id: int = Column(Integer, primary_key=True) # type: ignore slug: str = Column(String, nullable=False) # type: ignore name: str = Column(String, nullable=False) # type: ignore last_used = Column(DateTime, nullable=True) asset_platform_table = asset_n_to_n_table(Platform) class AssetTag(db.Model, SimpleAssetAttribute): __tablename__ = 'tags' id: int = Column(Integer, primary_key=True) # type: ignore name: str = Column(String, nullable=False) # type: ignore description: str = Column(String, nullable=False) # type: ignore last_used = Column(DateTime, nullable=True) asset_tag_table = asset_n_to_n_table(AssetTag) class Packaging(db.Model, SimpleAssetAttribute): __tablename__ = 'packagings' id: int = Column(Integer, primary_key=True) # type: ignore name: str = Column(String, nullable=False) # type: ignore last_used = Column(DateTime, nullable=True) # An asset can have a single packaging multiple times so we need a middle table class AssetPackaging(db.Model): __tablename__ = 'asset_packaging' id: int = Column(Integer, primary_key=True) # type: ignore asset_id: int = Column(Integer, ForeignKey('assets.id')) # type: ignore packaging_id: int = Column(Integer, ForeignKey(Packaging.id)) # type: ignore #asset = relationship("Asset") #packaging = relationship(Packaging) class Medium(db.Model, SimpleAssetAttribute): __tablename__ = 'media' id: int = Column(Integer, primary_key=True) # type: ignore name: str = Column(String, nullable=False) # type: ignore last_used = Column(DateTime, nullable=True) class AssetMedium(db.Model): __tablename__ = 'asset_mediums' id: int = Column(Integer, primary_key=True) # type: ignore asset_id: int = Column(Integer, ForeignKey('assets.id')) # type: ignore medium_id: int = Column(Integer, ForeignKey(Medium.id)) # type: ignore #asset = relationship("Asset") #medium = relationship(Medium) class Company(db.Model, SimpleAssetAttribute): __tablename__ = 'companies' id: int = Column(Integer, primary_key=True) # type: ignore name: str = Column(String, nullable=False) # type: ignore last_used = Column(DateTime, nullable=True) class CompanyAlias(db.Model): __tablename__ = 'company_aliases' id: int = Column(Integer, primary_key=True) # type: ignore alias: str = Column(String, nullable=False) # type: ignore company_id = Column(Integer, ForeignKey(Company.id), nullable=False) company = relationship(Company, backref="aliases") asset_company_table = asset_n_to_n_table(Company)
retroherna/rhinventory
rhinventory/models/asset_attributes.py
asset_attributes.py
py
3,448
python
en
code
1
github-code
6
45636612723
import pytest from page_objects.sign_in_page_object import SignInPage from utils.read_excel import ExcelReader @pytest.mark.usefixtures("setup") class TestRegistration(): @pytest.mark.parametrize("reg_data", ExcelReader.get_reg_data()) def test_registration_initial_form(self, reg_data): sign_in_page = SignInPage(self.driver) sign_in_page.open_sign_in_page() sign_in_page.open_registration_form(reg_data.email) assert sign_in_page.is_register_button() # def test_registration_main_form(self):
mcwilk/Selenium_automation
tests/registration_test.py
registration_test.py
py
544
python
en
code
0
github-code
6
5461750614
#Gets the longitude and latittude for an address using the Google Maps API import json import time import pandas as pd import urllib.error import urllib.parse import urllib.request #Gets api key from txt file with open(r".txt","r") as file: API_KEY = r"&key=" + file.readline() GEO_URL = r"https://maps.googleapis.com/maps/api/geocode/json?&address=" #Creates dataframe of all addresses from csv file specified df = pd.read_csv(r".csv") # df = pd.read_csv(r"-test.csv") #Removes duplicate addresses unique_search_address = df['SearchAddress'].unique() headers = ['SearchAddress','LAT','LON'] lat_lon = [] row = 1 for addr in unique_search_address: #formats address to be able to use in api f_addr = addr.replace(",", "").replace(" ", "%20") url = GEO_URL + f_addr + API_KEY try: result = json.load(urllib.request.urlopen(url)) lat_lon.append(( addr, result['results'][0]['geometry']['location']['lat'], result['results'][0]['geometry']['location']['lng'])) except: lat_lon.append((addr, None, None)) #Lets user know what row is being searched and prints to console, helpful in knowing script is running successfully but otherwise not necessary print(row) row = row + 1 #Converts list of address, lat, & lon tuples to a datafram df_join = pd.DataFrame(lat_lon, columns=headers) #Adds lat and lon to original dataframe using a left join df = df.merge(df_join, how='left', on='SearchAddress') df.to_csv(r".csv", index=False) # df.to_csv(r"test-results.csv", index=False)
randr000/MyPythonScripts
get_lat_lon_Google.py
get_lat_lon_Google.py
py
1,674
python
en
code
0
github-code
6
2028366431
#Aiswarya Sankar #8/5/2015 import webapp2 import jinja2 import os import logging import hashlib import hmac import re import string import random import time import math import urllib2 import json from google.appengine.ext import db from google.appengine.api import urlfetch from google.appengine.api import memcache template_dir = os.path.join(os.path.dirname(__file__), 'templates') jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape=True) USER_RE = re.compile(r"^[a-zA-Z0-9_-]{3,20}$") PASS_RE = re.compile(r"^.{3,20}$") DAYS_OF_WEEK = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] EVENT_TYPE = ['Competition', 'Meeting notice', 'Resource', 'Reminder', 'Survey'] ALL_INTERESTS = { 'Mathematics':'http://www.todayifoundout.com/wp-content/uploads/2014/11/mathematics-symbols.jpg', 'Biology': 'http://www.ccny.cuny.edu/biology/images/biologybanner.jpg', 'Chemistry': 'http://www.learnin4livin.com/wp-content/uploads/2014/07/acl2.jpg', 'Physics': 'http://callidolearning.com/wp-content/uploads/2015/07/physics.jpeg', 'Earth Science': 'http://science.nasa.gov/media/medialibrary/2011/03/01/small_earth.jpg', 'History': 'http://xemlasuong.org/wp-content/uploads/2015/01/ebola-virus-history.jpg', 'Computer Science Theory': 'https://upload.wikimedia.org/wikipedia/en/6/64/Theoretical_computer_science.svg', 'Computer Programming' : 'http://static.topyaps.com/wp-content/uploads/2012/12/computer-programming.jpg', 'Law' :'http://nagps.org/wordpress/wp-content/uploads/2014/02/law.jpg', 'Business' : 'http://globe-views.com/dcim/dreams/business/business-01.jpg', 'Economics' : 'http://www.stlawu.edu/sites/default/files/page-images/1economics_1.jpg', 'Finance' : 'http://intraweb.stockton.edu/eyos/hshs/content/images/2013%20Pics/finance.jpg', 'Marketing' : 'http://2z15ag3nu0eh3p41p2jsw3l1.wpengine.netdna-cdn.com/wp-content/uploads/2015/06/Marketing1.jpg', 'Arts' : 'http://bcaarts.org/images/Paint.jpg', 'Medicine' : 'http://ufatum.com/data_images/medicine/medicine5.jpg', 'Theater' : 'http://princetonfestival.org/wp-content/uploads/2015/03/LectureConvo.jpg', 'Dance' : 'http://static.wixstatic.com/media/11c679_bd0d108824a847729f998a7d4cd903de.gif', 'Health' : 'http://www.pacific.edu/Images/administration/finance/hr/healthy-heart.jpg', 'Food' : 'http://www.changefood.org/wp-content/uploads/2013/09/feel-healthier-bodymind-fresh-food-better-than-canned_32.jpg', 'Foreign Language' : 'http://www.scps.nyu.edu/content/scps/academics/departments/foreign-languages/_jcr_content/main_content/component_carousel/image_with_overlay_1.img.jpg/1406040703759.jpg', 'Literature' : 'http://c.tadst.com/gfx/600x400/galician-literature-day-spain.jpg?1', 'Design' : 'http://www.fotosefotos.com/admin/foto_img/foto_big/vetor_em_alta_qualidade_ee11960a4ece46ad67babac86517de82_vetor%20em%20alta%20qualidade.jpg', 'Service' : 'http://www.ycdsb.ca/assets/images/christian-community-service.jpg', 'Engineering' : 'http://cdn1.tnwcdn.com/wp-content/blogs.dir/1/files/2014/03/engineering-blueprint.jpg', 'Environmental Science' : 'http://www.ccny.cuny.edu/enveng/images/essbanner.jpg', 'Speech' : 'http://trullsenglish.weebly.com/uploads/2/5/1/9/25194894/1190544_orig.jpg' } urlfetch.set_default_fetch_deadline(240) secret = 'changetheworld' def render_str(template, **params): t = jinja_env.get_template(template) return t.render(params) def valid_username(username): return username and USER_RE.match(username) def valid_password(password): return password and PASS_RE.match(password) def memcacheClub(): #x = memcache.get('clubs') if x is None: clubQuery = Club.all() if clubQuery is not None: x = clubQuery else: x = [] x.append(a) memcache.set('clubs', x) def memcacheClublist(): y = memcache.get('CLUB_LIST') if y is None: clubNameQuery = db.GqlQuery('Select name from Club') if clubNameQuery is not None: y = clubNameQuery else: y= [] y.append(n) memcache.set('CLUB_LIST', y) #password salting functions def make_salt(): return ''.join(random.choice(string.letters) for x in xrange(5)) def create_salt_pass(name, password, salt=''): if salt == '': salt = make_salt() h = str(hashlib.sha256(name+password+salt).hexdigest()) return '%s,%s' %(salt, h) def check_salt_pass(name, password, h): salt = h.split(',')[0] if h == create_salt_pass(name, password, salt): return True #cookie hashing functions def create_cookie_hash(val): return '%s|%s' %(val, hmac.new(secret, val).hexdigest()) def check_cookie_hash(h): val = h.split('|')[0] if h == create_cookie_hash(val): return val # def topics(): # x = urllib2.urlopen('https://api.coursera.org/api/catalog.v1/categories').read() # j = json.loads(x) # topics = [] # for x in range(0, len(j['elements'])): # topics.append(j['elements'][x]['name']) # memcache.set('topics', topics) # def urls(): # start = 'http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=' # urlQueries = [] # temp = [] # topics = memcache.get('topics') # logging.info(topics) # for a in topics: # m = a.split(' ') # urlQueries.append('%s%s' % (start, '%20'.join(m))) # for url in urlQueries: # x = urllib2.urlopen(url).read() # j = json.loads(x) # logging.info(j['responseData']['results'][0]['url']) # temp.append( j['responseData']['results'][0]['url']) # memcache.set('urls', temp) ######## # 4 entity kinds here User, Club, Interest and Post ######## class User(db.Model): name = db.StringProperty(required=True) username = db.StringProperty(required=True) idNum = db.StringProperty(required=True) password = db.StringProperty(required=True) interests = db.StringListProperty() class Club(db.Model): name = db.StringProperty(required=True) officers = db.StringListProperty() interests = db.StringListProperty() location = db.StringProperty() days = db.StringListProperty() time = db.StringProperty() #brunch, lunch, after school adviser = db.StringProperty() picUrl = db.StringProperty() def render_new_post(self): global EVENT_TYPE return render_str('newPost.html', eventType = EVENT_TYPE) class Post(db.Model): title = db.StringProperty() content = db.TextProperty() created_time = db.DateTimeProperty(auto_now_add = True) interest = db.StringListProperty() inputter = db.StringProperty() picUrl = db.StringProperty() eventType = db.StringProperty() def render_post(self): return render_str('post.html', p = self) class Interest(db.Model): name = db.StringProperty() picUrl = db.StringProperty() # def members (self): # return Interest.gql("where user = :n", n=self.key()) # def render(self, num=0, int_list=[]): # return render_str("interestTable.html", int_list=int_list, num= num) class Handler(webapp2.RequestHandler): def write(self, *a, **kw): self.response.write(*a, **kw) def render_str(self, template, **params): t = jinja_env.get_template(template) return t.render(params) def render(self, template, **kw): self.write(self.render_str(template, **kw)) def login(self, u): self.set_cookie(val=u.idNum) #cookie functions def set_club_cookie(self, name='', val=''): cookie_hash = str(create_cookie_hash(val)) self.response.headers['Content-Type'] = 'text/plain' self.response.headers.add_header('set-cookie','club_id=%s;Path=/' % cookie_hash) self.response.headers['Content-Type'] = 'text/html' def set_cookie(self, name='', val=''): cookie_hash = str(create_cookie_hash(val)) self.response.headers['Content-Type'] = 'text/plain' self.response.headers.add_header('set-cookie','user_id=%s;Path=/' % cookie_hash) def get_cookie(self, name=''): cookie = self.request.cookies.get(name) if cookie: return check_cookie_hash(cookie) def initialize(self, *a, **kw): webapp2.RequestHandler.initialize(self, *a, **kw) idNum = self.get_cookie('user_id') clubNum = self.get_cookie('club_id') if idNum: self.user = User.get_by_key_name(idNum) else: self.user=None if clubNum: self.club = Club.get_by_id(int(clubNum)) else: self.club=None class LoginHandler(Handler): def get(self): self.render('login.html') def post(self): username= self.request.get('username') password = self.request.get('password') u = User.gql('where username = :n', n=username).get() if u and check_salt_pass(username, password, u.password): self.login(u) self.redirect('/home') else: err1 = 'Please check your username.' self.render('login.html', err1=err1) class EditClubHandler(Handler): def get(self): # top = memcache.get('topics') # if top is None: # topics() # top = memcache.get('topics') top=ALL_INTERESTS.keys() club_id = self.get_cookie('club_id') user_id = self.get_cookie('user_id') if club_id and user_id: cl = Club.get_by_id(int(club_id)) self.render('createClub.html', week=DAYS_OF_WEEK, topic_list= top, name=cl.name, location=cl.location, time=cl.time, days=cl.days, interests=cl.interests, officers=cl.officers, picUrl=cl.picUrl, adviser=cl.adviser) def post(self): n = self.request.get('name') a = self.request.get('adviser') l = self.request.get('location') t = self.request.get('time') d = self.request.get_all('days') i = self.request.get_all('interests') o = self.request.get_all('officers') picUrl = self.request.get('picUrl') if self.club: self.club.name=n self.club.adviser=a self.club.location=l self.club.time=t self.club.days=d for x in self.request.get_all('interests'): if x not in self.club.interests: self.club.interests.append(x) self.club.officers=o self.club.picUrl=picUrl self.club.put() if self.get_cookie('user_id'): self.redirect('/clubHome/%s' % self.get_cookie('club_id')) class ClubHandler(Handler): def get(self): # top = memcache.get('topics') # if top is None: # topics() # top = memcache.get('topics') top=ALL_INTERESTS.keys() club_id = self.get_cookie('club_id') user_id = self.get_cookie('user_id') # if club_id and user_id: # cl = Club.get_by_id(int(club_id)) # self.render('createClub.html', week=DAYS_OF_WEEK, topic_list= top, # name=cl.name, location=cl.location, time=cl.time, days=cl.days, # interests=cl.interests, officers=cl.officers, picUrl=cl.picUrl, # adviser=cl.adviser) # else: self.render('createClub.html', week=DAYS_OF_WEEK, topic_list= top) def post(self): n = self.request.get('name') a = self.request.get('adviser') l = self.request.get('location') t = self.request.get('time') d = self.request.get_all('days') i = self.request.get_all('interests') o = self.request.get_all('officers') picUrl = self.request.get('picUrl') # if self.club: # self.club.name=n # self.club.adviser=a # self.club.location=l # self.club.time=t # self.club.days=d # for x in self.request.get_all('interests'): # if x not in self.club.interests: # self.club.interests.append(x) # self.club.officers=o # self.club.picUrl=picUrl # self.club.put() # logging.info(self.club.location) # else: a = Club(name=n, location=l, time=t, days=d, interests=i, officers=o, picUrl=picUrl, adviser=a) a.put() if self.get_cookie('user_id'): self.redirect('/clubHome/%s' % self.get_cookie('club_id')) elif 'Club' or 'club' in n: self.render('extra.html', name=n, x=True, thanks=True) else: self.render('extra.html', name=n, x=False, thanks=True) class SignUpHandler(Handler): def register(self, u, p, n, i): m = User.gql('where idNum= :n', n=i).get() s = User.gql('where username = :n', n = u).get() if m: self.render('signup.html', err_user = "Student id %s already has an account" %i) elif s: self.render('signup.html', err_user = "That username already exists. Please choose another.") else: password=str(create_salt_pass(u, p)) a = User(key_name= i, username=u, password=password, name=n, idNum=i) a.put() self.set_cookie(name='user_id', val = i) self.redirect('/interest') def get(self): self.render('signup.html') def post(self): logging.info('in post') have_error=False username= self.request.get('username') password = self.request.get('password') name = self.request.get('name') idNum = self.request.get('idNum') params = dict(username = username) if not valid_username(username): params['err_user'] = "That's not a valid username." have_error = True if not valid_password(password): params['err_pass'] = "That's not a valid password." have_error = True if not name: params['err_name'] = "Please enter your name." have_error=True if not idNum: params['err_id'] = "Please enter your id Number." have_error=True if have_error: self.render('signup.html', **params) else: self.register(u=username, p=password, n=name, i=idNum) class InterestHandler(Handler): def get(self): if self.user: global ALL_INTERESTS # vtop = memcache.get('topics') # vurls = memcache.get('urls') # if vtop or vurls is None: # topics() # urls() # vtop = memcache.get('topics') # vurls = memcache.get('urls') # int_list = memcache.get('int_list') # l = [] # if int_list is None: # for x in range(0, len(vtop)): # a = Interest(name=vtop[x], picUrl=vurls[x]) # a.put() # l.append(a) # memcache.set('int_list', l) # int_list = memcache.get('int_list') # length = len(int_list) # self.render('interest.html', int_list = int_list, length=length) self.render('interest.html', ALL_INTERESTS = ALL_INTERESTS) else: self.redirect('/logout') def post(self): for x in self.request.get_all('interests'): if x not in self.user.interests: self.user.interests.append(x) else: logging.info(x) self.user.put() self.redirect('/home') class HomeHandler(Handler): def render_page(self, user): m = [] posts = [] postIds = [] CLUB_LIST= [] clubs = Club.all() for x in clubs: CLUB_LIST.append(x.name) clubIds = [] if clubs: for x in clubs: clubIds.append(str(x.key().id())) length = len(clubIds) for a in user.interests: m.append(a) w = Post.gql("where interest = :c order by created_time desc", c = a) for e in w: if e.key().id() not in postIds: posts.append(e) postIds.append(e.key().id()) self.render('userHome.html', account=True, isClub=False, length = length, clubIds = clubIds, clubs=CLUB_LIST, user=user, posts=posts, intList=m) def get(self): if self.user: self.render_page(self.user) else: self.redirect('/logout') def post(self): clubName = self.request.get('club') clu = Club.gql('where name = :n', n=clubName).get() if clu: idNum = clu.key().id() logging.info('idNum = %s' %idNum) self.redirect('/clubHome/%s' %idNum) class ClubHomeHandler(Handler): def checkOfficers(self, club): vari = self.get_cookie(name='user_id') if vari in club.officers: return True def render_page(self, post_id): userId = self.get_cookie('user_id') if userId: account = True else: account = False CLUB_LIST= [] clubs = Club.all() for x in clubs: CLUB_LIST.append(x.name) club = Club.get_by_id(int(post_id)) clubIds = [] if clubs: for x in clubs: clubIds.append(str(x.key().id())) if club: isOfficer = self.checkOfficers(club) posts = Post.gql("where inputter = :c order by created_time desc", c = post_id) offNames = [] for x in club.officers: if x != '' and User.get_by_key_name(x): offNames.append(User.get_by_key_name(x).name) self.render('clubHome.html', account = account, isClub=True, length=len(clubIds), clubIds = clubIds, clubs=CLUB_LIST, offNames = offNames, club=club, isOfficer=isOfficer, posts=posts) else: self.render('extra.html', thanks=False) def get(self, post_id): #if self.user: self.set_club_cookie(name='club_id', val=post_id) self.render_page(post_id=post_id) #else: # self.redirect('/') def post(self, post_id): if self.request.get('form_name') == 'search': clubName = self.request.get('club') clu = Club.gql('where name = :n', n=clubName).get() if clu: idNum = clu.key().id() logging.info('idNum = %s' %idNum) self.redirect('/clubHome/%s' %idNum) else: club = Club.get_by_id(int(post_id)) content = self.request.get("content") eventType =self.request.get("eventType") interest = club.interests title = "%s posted a %s" % (club.name, eventType) picUrl = club.picUrl inputter = post_id p = Post(eventType=eventType, picUrl = picUrl, title=title, content=content, interest=interest, inputter=inputter) p.put() time.sleep(0.5) self.render_page(post_id=post_id) class LogoutHandler(Handler): def get(self): self.response.headers['Content-Type'] = 'text/plain' var = '' self.response.headers.add_header('set-cookie', 'user_id=%s;Path=/' % var) self.response.headers.add_header('set-cookie', 'club_id=%s;Path=/' % var) self.redirect('/') def post(self): pass class AllClubsHandler(Handler): def get(self): #clubs = memcache.get('clubs') clubs = Club.all() clubIds=[] if clubs: for x in clubs: clubIds.append(str(x.key().id())) if clubs: length = len(clubIds) self.render('allClubs.html', clubIds=clubIds, clubs= clubs, length=length) else: self.response.write("No clubs have been added yet") app = webapp2.WSGIApplication([ ('/login', LoginHandler), ('/createClub', ClubHandler), ('/', SignUpHandler), ('/allClubs', AllClubsHandler), ('/interest', InterestHandler), ('/home', HomeHandler), ('/clubHome/(\w+)', ClubHomeHandler), ('/editClub', EditClubHandler), ('/logout', LogoutHandler) ], debug=True)
aiswaryasankar/mock2
main.py
main.py
py
17,647
python
en
code
0
github-code
6
26806868269
# -*- coding: utf-8 -*- """ Created on Wed Jan 23 17:29:26 2019 @author: dell """ from selenium import webdriver from time import sleep from bs4 import BeautifulSoup as bs url = "https://www.google.com/" browser = webdriver.Chrome("E:\\Study\\Project_4_Web_Scrapping\\chromedriver.exe") browser.get(url) sleep(2) search = browser.find_element_by_xpath('//*[@id="tsf"]/div[2]/div/div[1]/div/div[1]/input') search.click() type_search = "wikipedia" search.send_keys(type_search) sleep(2) search1 = browser.find_element_by_xpath('//*[@id="tsf"]/div[2]/div/div[2]/div[2]/div/center/input[1]') search1.click() sleep(5) browser.quit()
lavish71/Forsk_2019
Project_4_Web_Scrapping/Project_4_2/Project_4_2_2.py
Project_4_2_2.py
py
665
python
en
code
0
github-code
6
25135340045
from flask import Flask, request, render_template from chatXYZ import run, run_test import logging # API Key from config import openai_api_key log_handler = logging.StreamHandler() log_formatter = logging.Formatter("%(asctime)s - %(message)s") log_handler.setFormatter(log_formatter) logger = logging.getLogger() logger.setLevel(logging.INFO) logger.addHandler(log_handler) app = Flask(__name__) api_key_mode = "system" # "user"" or "system" SHOW_API_KEY_BOX = True if api_key_mode == "user" else False @app.route("/", methods=["GET", "POST"]) def index(): if request.method == "POST": query = request.form["query"] # Get answer or error message try: if api_key_mode == "user": api_key = request.form["api_key"].strip() if api_key == "": # API key is not provided in user mode; show error result = f"Please enter your OpenAI API Key!" elif api_key != "": # If API key provided in user mode; use it result = run_test(query, api_key=api_key, victim="Oppie") elif api_key_mode == "system": # API key is not required in system mode; use system key api_key = openai_api_key["OPENAI_API_KEY"] result = run_test(query, api_key=api_key, victim="Oppie") logger.info(f"User input: {query}") # Using logger else: raise NotImplementedError("Please set api_key_mode to either 'user' or 'system'.") except Exception as e: result = f"Ah, it seems something terrible has happened. Perhaps too many people are trying to ask me questions at the moment, or the test has gone wrong. Error: {e}" return render_template("index.html", result=result, query=query, show_api_key_box=SHOW_API_KEY_BOX) else: return render_template("index.html", show_api_key_box=SHOW_API_KEY_BOX) @app.route("/") def home(): return render_template("index.html", show_api_key_box=SHOW_API_KEY_BOX) if __name__ == "__main__": app.run(host="127.0.0.1", port=8080, debug=True)
rikab/ChatXYZ
main.py
main.py
py
2,111
python
en
code
null
github-code
6
72274308029
import datetime import inspect import json import logging from typing import Callable, Dict, List, Union _JSON_INDENT = 4 _JSON_SEPERATORS = (",", ": ") _DEPTH_RECURSION_DEFAULT = 1 _DEPTH_RECURSION_GET_LOGGER = 2 _DEPTH_RECURSION_JSON_LOGGER = 3 _LOGGING_LEVEL = logging.INFO if not __debug__ else logging.DEBUG _FORMATTER_STR_DETAILED = ( "%(asctime)s (PID:%(process)d) %(levelname)s %(name)s: %(message)s" ) # _FORMATTER_STR_SIMPLE = "%(name)s %(message)s" _FORMATTER_STR = _FORMATTER_STR_DETAILED def get_method_name( module_name: str = None, class_name: str = None, depth_recursion: int = _DEPTH_RECURSION_DEFAULT, ) -> str: """Retrieves a method name with a module name and class name. :param module_name: Module name :type module_name: str :param class_name: Class name :type class_name: str :param depth_recursion: Depth of recursive call for call stacks (>=1) :type depth_recursion: int :return: Method name :rtype: str """ if depth_recursion < 1: raise ValueError(f"depth_recursion is not natural number. - {depth_recursion}") # Gets an appropriate frame stack where the logger is called. f_stack = inspect.currentframe() for _ in range(depth_recursion): f_stack = f_stack.f_back if f_stack is None: raise ValueError("Reached the call stack limit.") method_name = f_stack.f_code.co_name if module_name is None and class_name is None: return method_name elif module_name is None: return f"{class_name}.{method_name}" elif class_name is None: return f"{module_name}.{method_name}" else: return f"{module_name}.{class_name}.{method_name}" def _logging_base_decorator(func_logging_decorator: Callable) -> Callable: """Decorator Function with Parameters. :param func_logging_system: Function object for Decoration :type func_logging_system: Function object :return: Wrapper function's object :rtype: Callable """ def wrapper(*args, **kwargs): def wrapper_logging_decorator(func_get_logger): return func_logging_decorator(func_get_logger, *args, **kwargs) return wrapper_logging_decorator return wrapper @_logging_base_decorator def _logging_decorator( func_get_logger: Callable, level: int = _LOGGING_LEVEL, is_propagate: bool = False ) -> Callable: """Decorator Function for Python Logging. :param func_get_logger: Function object for Decoration :type func_get_logger: function :param level: Logging Level :type level: int :param is_propagate: Need Propagation or not (False: Not propagate / True: Propagate) :type is_propagate: bool :return Wrapper function's object :rtype: Callable """ handler = logging.StreamHandler() handler.setLevel(level) formatter = logging.Formatter(_FORMATTER_STR) handler.setFormatter(formatter) def wrapper(name): logger = func_get_logger(name) if handler is not None: logger.addHandler(handler) logger.setLevel(level) logger.propagate = is_propagate return logger return wrapper @_logging_decorator() def get_logger(name: str) -> logging.Logger: """Gets a logger with the name. :param name: Name of the logger :type name: str :return Logger :rtype: logging.Logger """ return logging.getLogger(name=name) def get_default_logger() -> logging.Logger: """Gets a logger with the method name. :return Logger :rtype: logging.Logger """ return get_logger(name=get_method_name(depth_recursion=_DEPTH_RECURSION_GET_LOGGER)) def get_class_default_logger( class_name: str, module_name: str = None ) -> logging.Logger: """Gets a logger with the class name. :param class_name: Class name. :type class_name: str :param class_name: (optional) Module name. :type class_name: str :return Logger :rtype: logging.Logger """ return get_logger( name=get_method_name( module_name=module_name, class_name=class_name, depth_recursion=_DEPTH_RECURSION_GET_LOGGER, ) ) def _json_serialize(obj: object) -> str: """Serializes the given object :param obj: obj :type obj: object :return iso-formatted obj :rtype: str """ if isinstance(obj, (datetime.datetime, datetime.date)): return obj.isoformat() raise TypeError(f"Type {type(obj)} not serializable") def _json_dumps(json_items: Union[List[object], Dict[object, object]]) -> str: """Dumps as a JSON format. :param json_items: Items to be converted to a JSON format. :type json_items: list or dict :return JSON formatted items. :rtype: str """ return json.dumps( json_items, indent=_JSON_INDENT, ensure_ascii=False, sort_keys=True, separators=_JSON_SEPERATORS, default=_json_serialize, ) def json_logger( level: int, json_items: Union[List[object], Dict[object, object]], module_name: str = None, class_name: str = None, depth_recursion: int = 2, msg: str = None, ) -> None: """Logs the given json string. :param level: Logging level. :type level: int :param json_items: Items to be converted to a JSON format. :type json_items: list or dict :param module_name: Module name. :type module_name: str :param class_name: Class name. :type class_name: str :param depth_recursion: Depth recursion. :type depth_recursion: int :param msg: Logging message. :type msg: str """ get_logger( get_method_name( module_name=module_name, class_name=class_name, depth_recursion=depth_recursion, ) ).log(level=level, msg=msg) get_logger( get_method_name( module_name=module_name, class_name=class_name, depth_recursion=depth_recursion, ) ).log(level=level, msg=_json_dumps(json_items)) def json_logger_debug( json_items: Union[List[object], Dict[object, object]], module_name: str = None, class_name: str = None, msg: str = None, ) -> None: """Logs the given json string as DEBUG. :param json_items: Items to be converted to a JSON format. :type json_items: list or dict :param module_name: Module name. :type module_name: str :param class_name: Class name. :type class_name: str :param msg: Logging message. :type msg: str """ json_logger( level=logging.DEBUG, json_items=json_items, module_name=module_name, class_name=class_name, depth_recursion=_DEPTH_RECURSION_JSON_LOGGER, msg=msg, ) def json_logger_info( json_items: Union[List[object], Dict[object, object]], module_name: str = None, class_name: str = None, msg: str = None, ) -> None: """Logs the given json string as INFO. :param json_items: Items to be converted to a JSON format. :type json_items: list or dict :param module_name: Module name. :type module_name: str :param class_name: Class name. :type class_name: str :param msg: Logging message. :type msg: str """ json_logger( level=logging.INFO, json_items=json_items, module_name=module_name, class_name=class_name, depth_recursion=_DEPTH_RECURSION_JSON_LOGGER, msg=msg, ) def json_logger_warning( json_items: Union[List[object], Dict[object, object]], module_name: str = None, class_name: str = None, msg: str = None, ) -> None: """Logs the given json string as WARNING. :param json_items: Items to be converted to a JSON format. :type json_items: list or dict :param module_name: Module name. :type module_name: str :param class_name: Class name. :type class_name: str :param msg: Logging message. :type msg: str """ json_logger( level=logging.WARNING, json_items=json_items, module_name=module_name, class_name=class_name, depth_recursion=_DEPTH_RECURSION_JSON_LOGGER, msg=msg, ) def json_logger_error( json_items: Union[List[object], Dict[object, object]], module_name: str = None, class_name: str = None, msg: str = None, ) -> None: """Logs the given json string as ERROR. :param json_items: Items to be converted to a JSON format. :type json_items: list or dict :param module_name: Module name. :type module_name: str :param class_name: Class name. :type class_name: str :param msg: Logging message. :type msg: str """ json_logger( level=logging.ERROR, json_items=json_items, module_name=module_name, class_name=class_name, depth_recursion=_DEPTH_RECURSION_JSON_LOGGER, msg=msg, ) def json_logger_critical( json_items: Union[List[object], Dict[object, object]], module_name: str = None, class_name: str = None, msg: str = None, ) -> None: """Logs the given json string as CRITICAL. :param json_items: Items to be converted to a JSON format. :type json_items: list or dict :param module_name: Module name. :type module_name: str :param class_name: Class name. :type class_name: str :param msg: Logging message. :type msg: str """ json_logger( level=logging.CRITICAL, json_items=json_items, module_name=module_name, class_name=class_name, depth_recursion=_DEPTH_RECURSION_JSON_LOGGER, msg=msg, )
novus-inc/pylogger
pylogger/pylogger.py
pylogger.py
py
9,703
python
en
code
0
github-code
6
27265911454
import time import json from scrape_linkedin.utils import AnyEC from scrape_linkedin.Profile import Profile from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException, NoSuchElementException class ProfileScraper: """ Scraper for Personal LinkedIn Profiles. See inherited Scraper class for details about the constructor. """ MAIN_SELECTOR = '.core-rail' ERROR_SELECTOR = '.profile-unavailable' def __init__(self, driver): self.timeout = 10 self.driver = driver self.scroll_pause = 0.1 self.scroll_increment = 300 def scrape_by_email(self, email): self.load_profile_page( 'https://www.linkedin.com/sales/gmail/profile/proxy/{}'.format(email)) return self.get_profile() def scrape(self, url='', user=None): self.load_profile_page(url, user) return self.get_profile() def load_profile_page(self, url='', user=None): """Load profile page and all async content Params: - url {str}: url of the profile to be loaded Raises: ValueError: If link doesn't match a typical profile url """ if user: url = 'http://www.linkedin.com/in/' + user if 'com/in/' not in url and 'sales/gmail/profile/proxy/' not in url: raise ValueError( "Url must look like... .com/in/NAME or... '.com/sales/gmail/profile/proxy/EMAIL") self.driver.get(url) # Wait for page to load dynamically via javascript try: myElem = WebDriverWait(self.driver, self.timeout).until(AnyEC( EC.presence_of_element_located( (By.CSS_SELECTOR, self.MAIN_SELECTOR)), EC.presence_of_element_located( (By.CSS_SELECTOR, self.ERROR_SELECTOR)) )) except TimeoutException as e: raise ValueError( """Took too long to load profile. Common problems/solutions: 1. Invalid LI_AT value: ensure that yours is correct (they update frequently) 2. Slow Internet: increase the time out parameter in the Scraper constructor 3. Invalid e-mail address (or user does not allow e-mail scrapes) on scrape_by_email call """) # Check if we got the 'profile unavailable' page try: self.driver.find_element_by_css_selector(self.MAIN_SELECTOR) except: raise ValueError( 'Profile Unavailable: Profile link does not match any current Linkedin Profiles') # Scroll to the bottom of the page incrementally to load any lazy-loaded content self.scroll_to_bottom() def get_profile(self): try: profile = self.driver.find_element_by_css_selector( self.MAIN_SELECTOR).get_attribute("outerHTML") except: raise Exception( "Could not find profile wrapper html. This sometimes happens for exceptionally long profiles. Try decreasing scroll-increment.") contact_info = self.get_contact_info() return Profile(profile + contact_info) def get_contact_info(self): try: # Scroll to top to put clickable button in view self.driver.execute_script("window.scrollTo(0, 0);") button = self.driver.find_element_by_css_selector( 'a[data-control-name="contact_see_more"]') button.click() contact_info = self.wait_for_el('.pv-contact-info') return contact_info.get_attribute('outerHTML') except Exception as e: print(e) return "" def scroll_to_bottom(self): """Scroll to the bottom of the page Params: - scroll_pause_time {float}: time to wait (s) between page scroll increments - scroll_increment {int}: increment size of page scrolls (pixels) """ expandable_button_selectors = [ 'button[aria-expanded="false"].pv-skills-section__additional-skills', 'button[aria-expanded="false"].pv-profile-section__see-more-inline', 'button[aria-expanded="false"].pv-top-card-section__summary-toggle-button', 'button[data-control-name="contact_see_more"]' ] current_height = 0 while True: for name in expandable_button_selectors: try: self.driver.find_element_by_css_selector(name).click() except: pass # Use JQuery to click on invisible expandable 'see more...' elements self.driver.execute_script( 'document.querySelectorAll(".lt-line-clamp__ellipsis:not(.lt-line-clamp__ellipsis--dummy) .lt-line-clamp__more").forEach(el => el.click())') # Scroll down to bottom new_height = self.driver.execute_script( "return Math.min({}, document.body.scrollHeight)".format(current_height + self.scroll_increment)) if (new_height == current_height): break self.driver.execute_script( "window.scrollTo(0, Math.min({}, document.body.scrollHeight));".format(new_height)) current_height = new_height # Wait to load page time.sleep(self.scroll_pause) def wait(self, condition): return WebDriverWait(self.driver, self.timeout).until(condition) def wait_for_el(self, selector): return self.wait(EC.presence_of_element_located(( By.CSS_SELECTOR, selector )))
DumbMachine/linkedin
person.py
person.py
py
5,813
python
en
code
0
github-code
6
2732586952
#-_- coding: utf-8 -_- from signature import settings from control.middleware.config import RET_DATA, apple_url from control.middleware.common import get_random_s import re import json import logging import datetime import requests import random import time import jwt logger = logging.getLogger('django') class AppStoreConnectApi(object): ''' 苹果开发者商店 接口 ''' def __init__(self, account, p8, iss, kid): ''' 初始化 个人开发者账号信息 ''' self.__account = account self.__p8 = p8 self.__iss = iss self.__kid = kid self.__ret_data = RET_DATA.copy() self.__timeout = 15 self.__verify = False self.__token = self._get_token() def _get_token(self): ''' 利用 jwt 获取token ''' # 苹果采用的 ES256 编码方式,key是需要分段(\n)的,密钥头尾的"—BEGIN PRIVATE KEY—"也是必须的。之前我一直直接复制privatekey以文本的形式输入,在HS256下正常但是ES256会报错ValueError: Could not deserialize key data。 private_key = "-----BEGIN PRIVATE KEY-----" + self.__p8.replace("-----BEGIN PRIVATE KEY-----", "").replace("-----END PRIVATE KEY-----", "").replace(" ", "\n") + "-----END PRIVATE KEY-----" # payload token_dict = { "exp": time.time() + 20*60, # 时间戳, token 有效时间 20分钟 "iss": self.__iss, "aud": "appstoreconnect-v1" } # headers headers = { "alg": "ES256", # 声明所使用的算法。 "kid": self.__kid, "typ": "JWT", } try: # 使用jwt 获取苹果开发者 接口token jwt_token = jwt.encode(token_dict, private_key, algorithm="ES256", headers=headers) token = str(jwt_token, encoding='utf-8') logger.info(f"{self.__account} : {token}") return token except Exception as e: logger.error(f"获取苹果开发者 {self.__account} 接口token 错误: {str(e)}") return None def create_profile(self, bundleIds, cer_id, device_id): ''' 创建profile ''' # 初始化 req 参数 self.__content = "创建profile" self.__method = "POST" self.__url = f"{apple_url}/profiles" self.__data = { "data": { "type": "profiles", "attributes": { "name": get_random_s(16), "profileType": "IOS_APP_ADHOC" }, "relationships": { "bundleId": { "data": { "id": bundleIds, "type": "bundleIds" } }, "certificates": { "data": [{ "id": cer_id, "type": "certificates" }] }, "devices": { "data": [{ "id": device_id, "type": "devices" }] } } } } self.__headers = {"Content-Type": "application/json"} # 获取接口结果 return self._send_req() def create_devices(self, udid): ''' 创建devices ''' # 初始化 req 参数 self.__content = "创建devices" self.__method = "POST" self.__url = f"{apple_url}/devices" self.__data = { "data": { "type": "devices", "attributes": { "udid": udid, "name": udid, "platform": "IOS", } } } self.__headers = {"Content-Type": "application/json"} # 获取接口结果 return self._send_req() def create_bundleIds(self, bundleId): ''' 创建bundleIds: ''' # 初始化 req 参数 self.__content = "创建bundleIds" self.__method = "POST" self.__url = f"{apple_url}/bundleIds" self.__data = { "data": { "type": "bundleIds", "attributes": { "identifier": bundleId, "name": "AppBundleId", "platform": "IOS", } } } self.__headers = {"Content-Type": "application/json"} # 获取接口结果 return self._send_req() def delete_bundleIds(self, bundleIds): ''' 删除bundleIds ''' # 初始化 req 参数 self.__content = "删除bundleIds" self.__method = "DELETE" self.__url = f"{apple_url}/bundleIds/{bundleIds}" self.__data = {} self.__headers = {"Content-Type": "application/json"} # 获取接口结果 return self._send_req() def get_bundleIds(self): ''' 获取bundleIds ''' # 初始化 req 参数 self.__content = "获取bundleIds" self.__method = "GET" self.__url = f"{apple_url}/bundleIds?limit=200" self.__data = { "platform": "IOS" } self.__headers = {"Content-Type": "application/json"} # 获取接口结果 return self._send_req() def create_cer(self, csr): ''' 创建证书: { "certificateType": "IOS_DISTRIBUTION" } ''' # 初始化 req 参数 self.__content = "创建证书" self.__method = "POST" self.__url = f"{apple_url}/certificates" self.__data = { "data": { "type": "certificates", "attributes": { "csrContent": csr, "certificateType": "IOS_DISTRIBUTION" } } } self.__headers = {"Content-Type": "application/json"} # 获取接口结果 return self._send_req() def delete_cer(self, cer_id): ''' 删除证书: { "certificateType": "IOS_DISTRIBUTION" } ''' # 初始化 req 参数 self.__content = "删除证书" self.__method = "DELETE" self.__url = f"{apple_url}/certificates/{cer_id}" self.__data = {} self.__headers = {"Content-Type": "application/json"} # 获取接口结果 return self._send_req() def get_cer(self): ''' 获取证书: { "certificateType": "IOS_DISTRIBUTION" } ''' # 初始化 req 参数 self.__content = "获取证书" self.__method = "GET" self.__url = f"{apple_url}/certificates?limit=200" self.__data = { "certificateType": "IOS_DISTRIBUTION" # 这个筛选参数是不生效的,filter[certificateType] 这个不清楚怎么加入到参数里进行请求 } self.__headers = {"Content-Type": "application/json"} # 获取接口结果 return self._send_req() def get_devices(self): ''' 获取开发者账号上的已注册设备 GET https://api.appstoreconnect.apple.com/v1/devices ''' # 初始化 req 参数 self.__content = "获取已注册设备信息" self.__method = "GET" self.__url = f"{apple_url}/devices?limit=200" self.__data = {} self.__headers = {"Content-Type": "application/json"} # 获取接口结果 return self._send_req() def _send_req(self): ''' 发送 requests 请求 ''' token = self.__token if not token: # 获取token 失败 self.__ret_data['msg'] = "获取 苹果账号token 失败" self.__ret_data['code'] = 500 return self.__ret_data self.__headers["Authorization"] = f"Bearer {token}" self.__req_id = ''.join(str(random.choice(range(10))) for _ in range(10)) # 对每一次请求,指定一个随机的10位数 logger.info(f"""{self.__content}: # 记录请求参数 req_id: {self.__req_id} method: {self.__method} url: {self.__url} data: {self.__data} headers: {self.__headers} """) s = requests.Session() req = requests.Request(self.__method, self.__url, data=json.dumps(self.__data), headers=self.__headers ) prepped = s.prepare_request(req) try: ret = s.send(prepped, verify=self.__verify, timeout=self.__timeout) # 发起请求 self.__ret_data['code'] = 0 if ret.status_code == 204: # 状态码 204,返回内容为空,例如 DELETE 证书的请求 self.__ret_data['data'] = f"{self.__account}: {self.__content} 成功" logger.info(f"req_id: {self.__req_id} {self.__ret_data['data']}") else: app_ret = ret.json() self.__ret_data['data'] = app_ret self.__ret_data['msg'] = f"{self.__account}: {self.__content} 成功" if "errors" in app_ret.keys(): self.__ret_data['msg'] = f"{self.__account}: {self.__content} 失败" self.__ret_data['code'] = 500 logger.error(f"req_id: {self.__req_id} {self.__ret_data['msg']}: {self.__url} :{str(app_ret)}") else: logger.info(f"req_id: {self.__req_id} {self.__ret_data['msg']}: {self.__url} :{str(app_ret)}") except Exception as e: self.__ret_data['msg'] = f"{self.__account}: {self.__content} 失败: {ret.text}" self.__ret_data['code'] = 500 logger.error(f"req_id: {self.__req_id} {self.__account}: {self.__content} 失败: {self.__url} : {str(e)}。返回错误: {ret.text}") return self.__ret_data def test_connect(self): ''' 测试账号能够正常通过 苹果API 来连接 ''' # 初始化 req 参数 self.__content = "测试连接" self.__method = "GET" self.__url = f"{apple_url}/apps" self.__data = {} self.__headers = {"Content-Type": "application/json"} # 获取接口结果 return self._send_req()
lessknownisland/signature
apple/middleware/api.py
api.py
py
10,781
python
en
code
0
github-code
6
19670935871
from konlpy.tag import Kkma, Okt from pandas import DataFrame as df from gensim.models.word2vec import Word2Vec import pandas as pd import logging import time import re import os import matplotlib as mpl from sklearn.manifold import TSNE import matplotlib.pyplot as plt from sklearn.cluster import KMeans from sklearn.cluster import DBSCAN start = time.time() logging.basicConfig( format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) kkma = Kkma() mc = Okt() def word2vec(): word_list = [] path_dir = "C:\\Users\\gusals\\Desktop\\현민\\딥러닝 특론\\리포트 2013~2015 pkl" file_list = os.listdir(path_dir) file_list.sort() print(file_list) for i in file_list: df = pd.read_pickle("C:\\Users\\gusals\\Desktop\\현민\\딥러닝 특론\\리포트 2013~2015 pkl\\%s" % i) for j in df['sentences']: if len(j) > 1: #print(j) word_list.append(j) print(len(word_list)) #print(word_list) embedding_model = Word2Vec(word_list, size=200, window=10, min_count=5, iter=500, sg=1, sample=1e-3, hs=0) # embedding_model2 = Word2Vec.load('C:\\Users\\gusals\\Desktop\\현민\\딥러닝 특론\\word2vec_model\\stock_summary_model_01.model') # embedding_model2.wv.save_word2vec_format("C:\\Users\\gusals\\Desktop\\현민\\딥러닝 특론\\word2vec_model\\word_vector_sample.bin", binary=True) # model2 = Word2Vec.load('C:\\Users\\gusals\\Desktop\\현민\\딥러닝 특론\\word2vec_model\\2013~2015_report_size20_win10_min5_iter500_hs0_intersect_ko2') # model2.wv.save_word2vec_format("C:\\Users\\gusals\\Desktop\\현민\\딥러닝 특론\\word2vec_model\\ko\\2013~2015_report_size20_win10_min5_iter500_hs0_intersect_ko2.bin", binary=True) # # prev_model = 'C:\\Users\\gusals\\Desktop\\현민\\딥러닝 특론\\word2vec_model\\ko\\2013~2015_report_size20_win10_min5_iter500_hs0_intersect_ko2.bin' # embedding_model.intersect_word2vec_format(fname=prev_model, lockf=1.0, binary=True) model_name = "2013~2015_report_size200_win10_min5_iter500_hs0" embedding_model.save('C:\\Users\\gusals\\Desktop\\현민\\딥러닝 특론\\word2vec_model\\%s' % model_name) word_vector = embedding_model.wv def tsne_plot(model): labels = [] tokens = [] mpl.rcParams['axes.unicode_minus'] = False plt.rc('font', family='NanumGothic') for word in model.wv.vocab: tokens.append(model[word]) labels.append(word) print(labels) print(len(labels)) tsne_model = TSNE(perplexity=40, n_components=2, init='pca', n_iter=2500, random_state=23) new_values = tsne_model.fit_transform(tokens) x = [] y = [] for value in new_values[:300]: x.append(value[0]) y.append(value[1]) plt.figure(figsize=(16, 16)) for i in range(len(x)): plt.scatter(x[i], y[i]) plt.annotate(labels[i], xy=(x[i], y[i]), xytext=(5, 2), textcoords='offset points', ha='right', va='bottom') plt.show() def cluster(model, file, model_name): result = model.wv # 어휘의 feature vector topic = pd.read_pickle('C:\\Users\\gusals\\Desktop\\현민\\딥러닝 특론\\토픽 모델링 결과\\%s' % file) #print(result.vocab.keys()) #vocabs = result.vocab.keys() vocabs = [] for i in topic['sentences']: for j in i: vocabs.append(j) print(len(vocabs)) # clean_file = open('C:\\Users\\gusals\\Desktop\\현민\\딥러닝 특론\\클러스터전처리.txt', 'r') # lines = clean_file.readlines() # clean_file.close() # remove_list = lines[0].split(', ') remove_list = [] word_vectors = [] clean_vocabs = [] for i in vocabs: for remove in remove_list: i = re.sub(remove, '', i) if len(i) > 1: clean_vocabs.append(i) for v in clean_vocabs: try: word_vectors.append(result[v]) except: print(v) clean_vocabs.remove(v) num_clusters = 50 # int(len(clean_vocabs) / 5) # int(word_vectors.shape[0]/50) # 어휘 크기의 1/5나 평균 5단어 print(num_clusters) num_clusters = int(num_clusters) kmeans_clustering = KMeans(n_clusters=num_clusters) idx = kmeans_clustering.fit_predict(word_vectors) #idx = DBSCAN(eps=1000, min_samples=2).fit(word_vectors) print(id) idx = list(idx) print(len(vocabs)) print(len(idx)) names = clean_vocabs print(names) word_centroid_map = {names[i]: idx[i] for i in range(len(idx))} dfIndustry = pd.DataFrame(columns=["cluster", "keyword"]) for c in range(num_clusters): # 클러스터 번호를 출력 print("\ncluster {}".format(c)) words = [] cluster_values = list(word_centroid_map.values()) for i in range(len(cluster_values)): if (cluster_values[i] == c): words.append(list(word_centroid_map.keys())[i]) if len(words) == 1: print(words) rowIndustry = [c, words] dfIndustry.loc[len(dfIndustry)] = rowIndustry print(dfIndustry) clean_file = open('C:\\Users\\gusals\\Desktop\\현민\\딥러닝 특론\\클러스터전처리.txt', 'r') lines = clean_file.readlines() clean_file.close() remove_list = lines[0].split(', ') count = 0 for i in dfIndustry['keyword']: clean_v = [] for j in i: print(j) for remove in remove_list: j = re.sub(remove, '', j) if len(j) > 1: clean_v.append(j) dfIndustry['keyword'][count] = clean_v count += 1 print(dfIndustry) print("time: ", time.time() - start) dfIndustry.to_pickle("C:\\Users\\gusals\\Desktop\\현민\\딥러닝 특론\\클러스터링최종\\군집_%s.pkl" % (model_name)) word2vec() #tsne_plot(model) # path_dir = "C:\\Users\\gusals\\Desktop\\현민\\딥러닝 특론\\토픽 모델링 결과" # file_list = os.listdir(path_dir) # file_list.sort() # print(file_list) # # for file in file_list: # cluster(model, file) # model_name = '2013~2015_report_size20_win20_min5_iter1000_hs0' # model = Word2Vec.load('C:\\Users\\gusals\\Desktop\\현민\\딥러닝 특론\\word2vec_model\\%s' % model_name) # file = '3년.pkl' # # cluster(model, file, model_name) #sim(['기계', '펄프'], model)
gusals6804/TopicModelling
Word2Vec.py
Word2Vec.py
py
6,481
python
en
code
0
github-code
6
3508415121
#!/usr/bin/env python3 import sys if __name__ == "__main__": repl = {} poly = {} for l in open(sys.argv[1] if len(sys.argv) > 1 else '14-input'): l = l.strip() if '->' in l: a, b = l.split(' -> ') repl[a] = b elif l: for i in range(0, len(l) - 1): T = l[i:i + 2] poly.setdefault(T, 0) poly[T] += 1 for i in range(40): npoly = {} for T in poly: N = T[0] + repl[T] npoly[N] = npoly.get(N, 0) + poly[T] N = repl[T] + T[1] npoly[N] = npoly.get(N, 0) + poly[T] poly = npoly if i == 9: part1 = poly.copy() if i == 39: part2 = poly.copy() def result(r: dict) -> int: total = {v: 0 for v in repl.values()} for p, c in r.items(): total[p[0]] += c total[p[1]] += c return int((max(total.values()) - min(total.values())) / 2 + 0.5) print('part1', result(part1)) print('part2', result(part2))
pboettch/advent-of-code
2021/14.py
14.py
py
1,087
python
en
code
1
github-code
6
30763374181
# -*- coding: utf-8 -*- """ Created on Mon Dec 26 15:42:17 2016 @author: Shahidur Rahman """ import explorers import stringRecorder import pandas from sqlalchemy import create_engine import random from mmh3 import hash128 #from sklearn.datasets import load_iris import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) engine = create_engine('mysql+pymysql://root:shahidur_123@localhost:3306/mwt') j=0 #Data generation import numpy as np #import pdb;pdb.set_trace() mu, sigma = 0, 1 actionValue = np.random.normal(mu, sigma, 200000) #type(actionValue) minVal = np.amin(actionValue) maxVal = np.amax(actionValue) trainData = np.random.normal(mu, sigma, 200000) testValue = np.random.normal(mu, sigma, 200000) #s1 = np.empty(2000, dtype=np.int) for i in range(0,200000): #reward generation trainData[i] = int(round(0 + (trainData[i]-minVal)*(1-0)/(maxVal-minVal),0)) #action generation actionValue[i] = int(round(1 + (actionValue[i]-minVal)*(10-1)/(maxVal-minVal),0)) #testData testValue[i] = int(round(1 + (testValue[i]-minVal)*(10-0)/(maxVal-minVal),0)) X = [0] * 200000 Y = [0] * 200000 X1 = [0] * 200000 y1 = [0] * 200000 from random import randint for i in range(0,200000): X[i] = [randint(0,9), randint(0,9), randint(0,9), randint(0,9), randint(0,9), randint(0,9), actionValue[i]] Y[i] = [randint(0,9), randint(0,9), randint(0,9), randint(0,9), randint(0,9), randint(0,9)] #train data set up actionValue for i in range(0,200000): X1[i], y1[i] = [np.asarray(X[i])[0], np.asarray(X[i])[1], np.asarray(X[i])[2], np.asarray(X[i])[3], np.asarray(X[i])[4], np.asarray(X[i])[5]], actionValue[i] #train data setup rewardValue X2, y2 = X, trainData #model action selection from sklearn import svm clf = svm.SVC(kernel='rbf') modelActionSelection = clf.fit(X1, y1) #model reward allocation clf = svm.SVC(kernel='rbf') modelRewardAllocation = clf.fit(X2, y2) for i in range(0,200000): #epsilon epsilon = round(random.random(),3) #unique number generator unique_key =hash128('my string of doom ', seed=1234) ##of actions noOfActions = 10 print(i) #policy decision policyDecision = modelActionSelection.predict(Y[i]) #print("predict["+str(i)+"] is "+str(predict)) for x in policyDecision: policyDecision = int(x) #scores scores = [.2,.5,.3] callExplorer = explorers.explorers(epsilon,noOfActions,policyDecision,scores) storeValues = callExplorer.algoSelection() #reward check dataset rewardCheckData = [np.asarray(Y[i])[0], np.asarray(Y[i])[1], np.asarray(Y[i])[2], np.asarray(Y[i])[3], np.asarray(Y[i])[4], np.asarray(Y[i])[5], storeValues['actionID']] rewardValue = int(modelRewardAllocation.predict(rewardCheckData)) record = stringRecorder.stringRecorder(str(Y[i]), str(storeValues['actionID']),str(storeValues['actionProbability']), str(unique_key), str(storeValues['isExplore']), str(epsilon), str(noOfActions),str(policyDecision),str(storeValues['explorerAlgo']), str(rewardValue)) record = record.sewStrings() #print('record : '+str(record)) colList="context,actionID,actionProbability,unique_key,isExplore,epsilon,noOfActions,policyDecision,explorerAlgo,rewardValue".split(',') #c1=['col1'] df = pandas.DataFrame(data=record,index=colList) #transpose the data df=df.T #print("printing panda df here") #print(df) #push data in sql #rf = pandas.DataFrame(data=['10',1,2,'62019057582468709482189373788949966293',4,5,6,7,'8'],index=colList) #rf=rf.T #rf.to_sql(con=engine, name='stringrecord', if_exists='append', index=False) df.to_sql(con=engine, name='stringrecord', if_exists='append', index=False) df.to_sql(con=engine, name='stringrecord_test', if_exists='append', index=False)
skshahidur/nlp_paper_implementation
Word-Embedding/mwt_v1.py
mwt_v1.py
py
4,021
python
en
code
0
github-code
6
33371549713
#---!/usr/bin/env python #--- -*- coding: utf-8 -*- # Librerias import re import sys import json import string import random import operator import unicodedata sys.stdout.encoding 'UTF-8' # Libreria NLTK import nltk nltk.download('punkt') nltk.download('stopwords') from nltk.tokenize.toktok import ToktokTokenizer from nltk.metrics.distance import edit_distance from nltk.stem.snowball import SnowballStemmer from nltk.corpus import stopwords # Libreria para Grafo import matplotlib.pyplot as plt import networkx as nx import random # Variables miniparams = [] parametros = [] nombreArchivo = "wikipedia_es_abstracts.txt" # "OWesA.txt" # Stemmer en Español stemmer = SnowballStemmer("spanish") # Recorrer parametros for i in range(len(sys.argv)): # Validar if 0 < i: # Recuperar paramtros parm = str(sys.argv[i].strip().lower()) # Validar asignación if parm not in parametros: # Asignar parametro parametros.append(parm) miniparams.append(stemmer.stem(parm)) # Iniciar Tokenizador toktok = ToktokTokenizer() # Crear Tokenizar de oraciones esTokenizarOraciones = nltk.data.load("tokenizers/punkt/spanish.pickle") # Generar lista de palabras funcionales listPalabrasfuns = stopwords.words("spanish") listPuntuaciones = list(string.punctuation) listPuntuaciones.append("¿") listPuntuaciones.append("¡") listPuntuaciones.append("ja") listPuntuaciones.append("yme") listPuntuaciones.append("yczna") listPuntuaciones.append("así") # Función de tokenización def leer_archivo (archivo, params): # Variables documento = {} # Leer documento with open(archivo, 'r', encoding="utf-8") as myFile: # open(archivo, encoding="latin-1") # Recuperar lineas del texto lins_arch = myFile.readlines() list_temp_parr = [] contador = 0 # Recorrer parrafos del archivo for parrafo in lins_arch: # Dividir por \t list_segmentos = parrafo.split("\t") # Validar tamaño if 2 <= len(list_segmentos): # Variable textoObjetivo = "" # Titulo divido por : list_titulo = list_segmentos[0].split(":") titulo = "" # Validar titulo if 2 <= len(list_titulo): titulo = list_titulo[1].lower() # Titulo divido por \n list_parrafo = list_segmentos[1].split("\n") # Validar parrafo textoObjetivo = "" if 1 <= len(list_parrafo): textoObjetivo = list_parrafo[0].lower() # Validar asginación de parrafo bandera = False for prm in params: if textoObjetivo.find(prm) >= 0: bandera = True # Validar asignación de parrafo if bandera and textoObjetivo not in list_temp_parr: # Agregar el parrafo a la variable documento documento[contador] = { "T": titulo, "P": textoObjetivo} list_temp_parr.append(textoObjetivo) contador = contador + 1 # Cerrar archivo myFile.close() # Regresar json de documentos return documento # Leer archivo listParrafos = leer_archivo(nombreArchivo, miniparams) # Función para buscar palabras objetivo conforme un patron def buscar_coincidencias(list_pals_funs, list_punts, texto, one_pos, final_star_pos, expresion, dicc_de_rel = None): # Validar existencia de diccionario if dicc_de_rel == None: dicc_de_rel = {} # Crear patron patron_exp = re.compile(expresion) # Buscar coincidencias del patron en el texto list_matches = patron_exp.findall(texto) # Recorrer maches for mi_match in list_matches: # Lista de palabras de interes temporal list_of_temp_words = [] # Recorrer palabras de match for temp_i in range(len(mi_match)): # Validar match if (temp_i == one_pos) or (temp_i >= final_star_pos): # Recuperar palabra relacionada temp_word = mi_match[temp_i] temp_word = re.sub(', ', '', temp_word) temp_word = re.sub('y ', '', temp_word) temp_word = temp_word.strip() # Validar resguardo if temp_word != '' and temp_word not in list_pals_funs and temp_word not in list_punts and temp_word not in list_of_temp_words: # Resguardar palabra relacionada list_of_temp_words.append(temp_word) if len(list_of_temp_words) > 1: # Recorrer palabras temporales my_temp_w = list_of_temp_words[0] # Validar existencia de parametro en diccionario if my_temp_w not in dicc_de_rel: # Lista de palabras de interes temporal dicc_de_rel[my_temp_w] = [] # SubRecorrido de palabras temporales for m_sbtmp_w in list_of_temp_words: # Validar existencia en diccionario if m_sbtmp_w not in dicc_de_rel[my_temp_w]: # Guardar palabra temporal dicc_de_rel[my_temp_w].append(m_sbtmp_w) # Regresar resultados return dicc_de_rel # Variable diccionario de relaciones diccDeRel = {} # Recorrer parrafos en diccionario for key,value in listParrafos.items(): # Revisar patrones y actualizar diccionario diccDeRel = buscar_coincidencias(listPalabrasfuns, listPuntuaciones, value["P"], 1, 3, '(las|la|los|el)*(\s*\w+) (son un|son una|es un|es una|fueron un|fueron una|fue un|fue una){1} (\w+)', diccDeRel) diccDeRel = buscar_coincidencias(listPalabrasfuns, listPuntuaciones, value["P"], 0, 2, '(\w+) (tal como|así tambien|así como|como por|por ejemplo|tambien conocida como|tambien conocido como|tal como:|como:|como){1} (\w+)*(,\s*\w+)*(\s*y\s*\w+)*', diccDeRel) diccDeRel = buscar_coincidencias(listPalabrasfuns, listPuntuaciones, value["P"], 0, 4, '(\w+) (es|forma|forman|son){1} (parte){1} (del|de las|de los|de el|de una|de un|de){1} (\w+)', diccDeRel) diccDeRel = buscar_coincidencias(listPalabrasfuns, listPuntuaciones, value["P"], 0, 5, '(\w+)(\s*le|\s*es|\s*son)* (perteneciente(s)*|pertenecen|pertenece|a){1} (la|al|a)* (\w+)', diccDeRel) diccDeRel = buscar_coincidencias(listPalabrasfuns, listPuntuaciones, value["P"], 0, 1, '(\w+)(,\s*\w+)*(\s*y\s*\w+)', diccDeRel) # Variables list_nodos = [] list_aristas = [] # Recorrer diccionario de relaciones for key,arry in diccDeRel.items(): # Validar si agregar nodo if key not in list_nodos: # Agregar nodo list_nodos.append(key) # Recorrer relaciones de la llave for value in arry: # Generar tupla tempTupla = (key, value) # Validar si agregar tupla if tempTupla not in list_aristas: # Agregar nodo list_aristas.append(tempTupla) # Validar si agregar nodo if value not in list_nodos: # Agregar nodo list_nodos.append(value) # Crea grafica Grafico = nx.DiGraph() # Vertices Grafico.add_nodes_from(list_nodos) # Aristas Grafico.add_edges_from(list_aristas) posicion = nx.spring_layout(Grafico) nx.draw_networkx_labels(Grafico, posicion, labels=dict([(nodo, nodo) for nodo in list_nodos])) # Dibuja la gráfica nx.draw(Grafico, posicion) # Muestra en pantalla lo dibujado plt.show()
SoraGefroren/Practicas_relacionadas_al_NLP_utilizando_Python
Práctica_04-Wiki/relaciones.py
relaciones.py
py
6,622
python
es
code
0
github-code
6
27146623453
from UserSimulator.User import User from UserSimulator.user_behavior import calculate_session_length, Devices, load_spotify, playback_decision from datetime import datetime from datetime import timedelta import random import time from json import load import pickle import json import csv import requests from DataPreprocessor.build_user_track_dict import TrainTripletParser from DataPreprocessor.normalize_play_counts import SongRatingNormalizer from DataPreprocessor.create_blc_input import SparseMatGenerator from DataPreprocessor.filter_sparse_songs import SparseSongFilter from DataPreprocessor.build_song_dict import SongDictBuilder from DataPreprocessor.get_top_user_artists import TopUserBuilder from ResultProcessor.process_P import PProcessor from ResultProcessor.build_nym_ratings import NymRatingBuilder from ResultProcessor.get_top_nym_songs import SongListBuilder from ResultProcessor.get_unique_nym_artists import UniqueNymArtistFilter from ResultProcessor.get_nym_artist_variance import ArtistVarianceCalculator from ResultProcessor.NymRatingFormatter import NymRatingFormatter from spotify import SpotifyWrapper from os import path REQ = "https://ec2-52-50-185-176.eu-west-1.compute.amazonaws.com:4400/ratings/update" RATINGS_REQ = "http://localhost:4000/ratings/{}/spotify.com" # pre-selected users just for convenience # contains tuples in the form (nym, user_number) USER_LIST = [ (0,234384), (0,234384), (0,402687), (0,462404), (0,669980), (0,991089), (1,679065), (1,723268), (1,889236), (1,954125), (1,964856), (10,12383), (10,222379), (10,241854), (10,332593), (10,436898), (12,179532), (12,351979), (12,473021), (12,811920), (12,94387), (13,190513), (13,272213), (13,372156), (13,745999), (13,752718), (14,152776), (14,291748), (14,555065), (14,880214), (14,948598), (2,202368), (2,8028), (2,869250), (2,957121), (2,975702), (3,329210), (3,491540), (3,622692), (3,819217), (3,835998), (4,143096), (4,411888), (4,470913), (4,669115), (4,792160), (5,169059), (5,472503), (5,502502), (5,599726), (5,883355), (6,151851), (6,269475), (6,427642), (6,483795), (6,864712), (7,117436), (7,471509), (7,542147), (7,605562), (7,66213), (8,355770), (8,400013), (8,689580), (8,74987), (8,824276), (9,189979), (9,396445), (9,513441), (9,543235), (9,753614) ] config = load(open('config.json')) def make_rating(nym_id, domain, item, score, num_v,): return { "nymRating" : { "numVotes" : num_v, "score": score }, "domain": domain, "item": item, "nym_id": nym_id } def manual_update(details): _, nym, domain, item, rating, num_votes = details new_rating = make_rating(nym, domain, item, rating, num_votes+1) headers = { "content-type": "application/json"} resp = requests.put(REQ, data=json.dumps({'rating' : new_rating}), headers=headers, verify=False) return resp def load_user_nym_pairs(): nym_users_dict = {} user_nym_pairs = [] path_to_P_with_ids = path.join(config["nym_data"]["base"], config["nym_data"]["P_with_ids"]) with open(path_to_P_with_ids) as input_file: for line in input_file: user_nym_pairs.append(map(int, line.split(","))) # Convert list to dict for user, nym in user_nym_pairs: if nym not in nym_users_dict: nym_users_dict[nym] = [] nym_users_dict[nym].append(user) return nym_users_dict def load_user_song_map(): with open(path.join(config["user_data"]["base"], config["user_data"]["user_songs_map"]), 'rb') as input_pickle: return pickle.load(input_pickle) print("Done") def havent_played_song(user,song_id): song = user.song_to_id_dict[song_id] user_songs_map = load_user_song_map() nym_users_dict = load_user_nym_pairs() result = [] for nym, users in nym_users_dict.items(): # print("Building ratings for nym {}".format(nym)) # Iterate through each user in a Nym for user in sorted(users): # For each user get every song they listened to and their play counts found = False for user_song, _ in user_songs_map[user]: if user_song == song: found = True break if not found: result.append((nym, user)) return sorted(result, key=lambda x: x[0]) def update_data(): # Normalize play counts print("Normalizing play counts") song_rating_normalizer = SongRatingNormalizer(config) song_rating_normalizer.load_user_songs_dict() song_rating_normalizer.normalize_data() song_rating_normalizer.write_data_to_disk() print("Done") del song_rating_normalizer # Generate sparse matrix for BLC print("Generating Sparse Matrix") sparse_mat_generator = SparseMatGenerator(config, num_users=40000) sparse_mat_generator.load_data() sparse_mat_generator.generate_sparse_mat() sparse_mat_generator.write_user_data() print("Done") del sparse_mat_generator # Filter sparse songs from matrix print("Filtering Sparse Songs from matrix") sparse_song_filter = SparseSongFilter(config) sparse_song_filter.parse_sparse_mat_files() sparse_song_filter.filter_sparse_songs() sparse_song_filter.write_filtered_matrix() print("Done") del sparse_song_filter # Build dict of song IDs to artist-song tuples print("Building dict of songs") song_dict_builder = SongDictBuilder(config) song_dict_builder.load_track_list() song_dict_builder.write_song_details_to_file() print("Done") del song_dict_builder # Build the top users for dataset print("Outputting top users") top_user_builder = TopUserBuilder(config) top_user_builder.load_data() top_user_builder.get_top_songs() top_user_builder.dump_top_users() del top_user_builder def gen_db_data(): # Map row numbers to users in raw P file print("Processing P") p_processor = PProcessor(config) p_processor.generate_row_user_map() p_processor.map_rows_to_users() del p_processor # Build ratings for nym and write out to nym_ratings directory print("Generating Nym Ratings") nym_rating_builder = NymRatingBuilder(config) nym_rating_builder.load_data() nym_rating_builder.delete_old_ratings() nym_rating_builder.build_ratings() nym_rating_builder.dump_nym_users_map() del nym_rating_builder # Get Top Nym songs based on ratings print("Generating Song Lists") song_list_builder = SongListBuilder(config) song_list_builder.load_data() song_list_builder.load_ratings() song_list_builder.delete_old_songs() song_list_builder.build_song_lists() del song_list_builder # Get artists unique to each nym print("Generating artists unique to each nym") unique_nym_artist_filter = UniqueNymArtistFilter(config) unique_nym_artist_filter.load_songs() unique_nym_artist_filter.delete_old_artists() unique_nym_artist_filter.build_top_nym_artists() unique_nym_artist_filter.filter_unique_artists() del unique_nym_artist_filter print("Calculating Artist Variances") artist_variance_calculator = ArtistVarianceCalculator(config) artist_variance_calculator.load_data() artist_variance_calculator.calculate_variance() del artist_variance_calculator print("Generating ratings for db") nym_rating_formatter = NymRatingFormatter(config) nym_rating_formatter.load_data() nym_rating_formatter.parse_song_rankings() nym_rating_formatter.generate_db_input() del nym_rating_formatter def load_previous_ratings(nym): result = {} with open('Data/DB_Data/ratings-1.csv', 'r') as input_file: ratings = csv.reader(input_file, delimiter=',') for _,nym_r,domain, item,rating,num_v in ratings: if nym_r != "nym" and int(nym_r) == nym: result[item] = [domain,rating,num_v] # sort by item return result def load_new_ratings(nym): result = {} with open('Data/DB_Data/ratings.csv', 'r') as input_file: ratings = csv.reader(input_file, delimiter=',') for _,nym_r,domain, item,rating,num_v in ratings: if nym_r != "nym" and int(nym_r) == nym: result[item] = [domain,rating,num_v] # sort by item return result # Send new ratings to the server def update_server(nym): #ratings_resp = requests.get(RATINGS_REQ.format(nym), verify=False) #current_ratings = ratings_resp.content[:len(ratings_resp.content) - int(ratings_resp.headers["padding-len"])] old_ratings = load_previous_ratings(nym) new_ratings = load_new_ratings(nym) resp = None for k, v in new_ratings.items(): if (not k in old_ratings) or old_ratings[k] != v: domain, rating, num_v = v print("item:{} , rating:{}, num votes:{}".format(k, rating, num_v)) new_rating = { "nymRating" : { "numVotes" : int(num_v), "score": float(rating) }, "domain": domain, "item": k, "nym_id": nym } headers = { "content-type": "application/json"} resp = requests.put(REQ, data=json.dumps({'rating' : new_rating}), headers=headers, verify=False) return resp def listen_to_playlist(nym, user_num): prev_sess = None user = User(nym, user_num, config) start = datetime.now() sess_length = float(calculate_session_length(start, Devices.Mobile)) end = timedelta(seconds=(sess_length * 60)) spotify_obj = load_spotify() decision = 'appload' while sess_length > 0: while datetime.now() < start + end: print("Got here") try: id, nym, domain, uri, rating, num_votes = user.get_next_recommendation() resp = None decision = playback_decision(spotify_obj, uri, decision) if decision == 'trackdone': print("Updating") resp = manual_update([id, nym, domain, uri, rating, int(num_votes)]) elif decision == "clickrow": user.set_recommendation(random.randint(0, len(user.recommendations))) if resp: to_be_added = False print(resp.status_code) print(resp.headers["padding-len"]) while resp.status_code != 200 and not to_be_added: rating = resp.content[:len(resp.content) - int(resp.headers["padding-len"])].decode('utf8') rating = load(rating) if int(rating["nymRating"]["numVotes"]) == 0: to_be_added = True else: num_votes = float(rating["nymRating"]["score"]) num_votes = int(rating["nymRating"]["numVotes"]) resp = manual_update([id, nym, domain, uri, rating, num_votes]) except Exception as e: print(e) prev_sess = sess_length sess_length = calculate_session_length(start, Devices.Mobile, prev_session=prev_sess) print("Session length is {}".format(sess_length)) end = timedelta(seconds=(int(sess_length) * 60)) start = datetime.now() if __name__ == "__main__": start = datetime.now() period = timedelta(hours=3) for _ in range(1): index = random.randint(0, len(USER_LIST) - 1) nym, user_num = USER_LIST[index] print("nym:{}, user:{}".format(0, user_num)) current_hour = datetime.now().hour played = False pick_time = random.uniform(current_hour, current_hour + 1) % 24 print("Picked time is {}".format(pick_time)) while datetime.now() < start + period: if not played and datetime.now().minute >= (pick_time % 1) * 60: listen_to_playlist(nym, user_num) print("finished iteration") played = True if current_hour < datetime.now().hour: current_hour = datetime.now().hour played = False pick_time = random.uniform(current_hour, current_hour + 1) % 24 print("Picked time is {}".format(pick_time))
dyllew3/Timing-Attacks-Against-Opennym
MillionSongDataset/simulate_user.py
simulate_user.py
py
12,732
python
en
code
0
github-code
6
38058129584
from lib.processors import findFaceGetPulse import networkx as nx """ Simple tool to visualize the design of the real-time image analysis Everything needed to produce the graph already exists in an instance of the assembly. """ #get the component/data dependancy graph (depgraph) of the assembly assembly = findFaceGetPulse() graph = assembly._depgraph._graph #prune a few unconnected nodes not related to the actual analysis graph.remove_node("@xin") graph.remove_node("@xout") graph.remove_node("driver") #plot the graph to disc as a png image ag = nx.to_agraph(graph) ag.layout('dot') ag.draw('design.png')
noahcse/webcam_pulse_detect
make_design_graph.py
make_design_graph.py
py
615
python
en
code
1
github-code
6
28541533714
import aes_new import os import sys def encrypt_img(input, key, aes, iv, mode): #input = [255, 255, 255, 255, 5, 6, 7, 7, 7, 7, 11, 12, 13, 254, 15, 240] if mode == 'ECB' or mode == 'CBC': plaintext = [0, 0, 0, 0] i = 0 max = (len(input)//16) ciphertext_arr = [ ] for i in range(0, max): plaintext[0] = (input[16*i] << 24) | (input[16*i+1] << 16) | (input[16*i+2] << 8) | input[16*i+3] for j in range(1, 4): plaintext[j] = (input[4*j+16*i] << 24) | (input[4*j+16*i+1] << 16) | (input[4*j+16*i+2] << 8) | input[4*j+16*i+3] ciphertext = aes.encrypt(plaintext) for m in range(0, 16): ciphertext_arr.append(ciphertext[m]) # decrypted = [aes.decrypt(ciphertext(i))] return ciphertext_arr elif mode == 'CFB' or 'OFB' or 'CTR': ciphertext = list(aes.encrypt(input)) return ciphertext # Since there is no state stored in this mode of operation, it # is not necessary to create a new aes object for decryption. #aes = pyaes.AESModeOfOperationECB(key) # True # print ('decrypted ', decrypted) # print (decrypted == plaintext)
ilshatKam/aes-image-encrypt
test_image.py
test_image.py
py
1,192
python
en
code
0
github-code
6
2279356920
import gtk import mailanie class Preferences(gtk.Dialog): def __init__(self): super(Preferences, self).__init__( _("Mailanie Preferences"), buttons=(gtk.STOCK_APPLY, gtk.RESPONSE_APPLY, gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)) self.set_has_separator(False) self.connect("response", self._response) self.options = [] self.notebook = gtk.Notebook() self.vbox.add(self.notebook) vbox = VBox() self.notebook.append_page(vbox, gtk.Label(_("Folders"))) frame = vbox.add(_("Mail")) frame.add( FileChooserBox( _("Mailbox"), ("path", "mailbox"), self.options)) frame = vbox.add(_("Address Book")) frame.add( FileChooserBox( _("Address book"), ("path", "addressbook"), self.options)) frame = vbox.add(_("Cache")) frame.add( FileChooserBox( _("Folders"), ("path", "folder"), self.options)) frame.add( FileChooserBox( _("Attached files"), ("path", "part"), self.options)) vbox = VBox() self.notebook.append_page(vbox, gtk.Label(_("Mailboxes"))) # TODO: update combo_list when maildir is updated combo_list = [(_("None"), "none")] combo_list.extend((box.label, box.path) for box in mailanie.mailbox.list_boxes()) frame = vbox.add(_("Default Mailboxes")) frame.add( ComboTextBox( _("Draft"), combo_list, ("mailbox", "draft"), self.options)) frame.add( ComboTextBox( _("Sent Mail"), combo_list, ("mailbox", "sent"), self.options)) vbox = VBox() self.notebook.append_page(vbox, gtk.Label(_("SMTP Server"))) # TODO: update combo_list when maildir is updated frame = vbox.add(_("Server")) frame.add( EntryBox( _("Server"), ("smtp", "server"), self.options)) frame.add( EntryBox( _("Port"), ("smtp", "port"), self.options)) frame.add( CheckBox( _("Use SSL"), ("smtp", "ssl"), self.options)) frame = vbox.add(_("User")) frame.add( EntryBox( _("Login"), ("smtp", "login"), self.options)) frame.add( EntryBox( _("Password"), ("smtp", "password"), self.options, password=True)) frame.add( EntryBox( _("Sender Name"), ("smtp", "name"), self.options)) frame.add( EntryBox( _("Sender Address"), ("smtp", "address"), self.options)) self._set_config_options() def _set_config_options(self): for option in self.options: try: option.set_value(option.type(option.path[0], option.path[1])) except ValueError: pass def _response(self, dialog, response): if response in (gtk.RESPONSE_ACCEPT, gtk.RESPONSE_APPLY): for option in self.options: mailanie.config.set(option.path[0], option.path[1], str(option.get_value())) mailanie.config.write() else: self._set_config_options() class VBox(gtk.VBox): def __init__(self): super(VBox, self).__init__() def add(self, title): frame = Frame(title) self.pack_start(frame, expand=False, fill=False) return frame class Frame(gtk.Frame): def __init__(self, title): super(Frame, self).__init__() self.set_border_width(5) self.set_shadow_type(gtk.SHADOW_NONE) self.set_label("<b>%s</b>" % title) self.get_label_widget().set_use_markup(True) self.vbox = gtk.VBox() gtk.Frame.add(self, self.vbox) def add(self, child): self.vbox.add(child) class ComboTextBox(gtk.HBox): def __init__(self, title, combo_list, path, options): super(ComboTextBox, self).__init__() self.set_border_width(5) self.set_spacing(10) self.label = gtk.Label(title) self.label.set_alignment(0, 0.5) self.pack_start(self.label, expand=True, fill=True) self.combo = gtk.combo_box_new_text() for action in combo_list: self.combo.append_text(action[0]) self.pack_end(self.combo, expand=False) self.path = path self.get_value = lambda: combo_list[self.combo.get_active()][1] self.set_value = lambda x: self.combo.set_active( [action[1] for action in combo_list].index(x)) self.type = mailanie.config.get options.append(self) class FileChooserBox(gtk.HBox): def __init__(self, title, path, options): super(FileChooserBox, self).__init__() self.set_border_width(5) self.set_spacing(10) self.label = gtk.Label(title) self.label.set_alignment(0, 0.5) self.pack_start(self.label, expand=True, fill=True) self.button = gtk.FileChooserButton(_("Select Your Folder")) self.button.set_local_only(False) self.button.set_action(gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER) self.pack_end(self.button, expand=False) self.path = path self.get_value = self.button.get_current_folder_uri self.set_value = self.button.set_current_folder_uri self.type = mailanie.config.get options.append(self) class CheckBox(gtk.CheckButton): def __init__(self, title, path, options): super(CheckBox, self).__init__(title) self.set_border_width(5) self.path = path self.get_value = self.get_active self.set_value = self.set_active self.type = mailanie.config.getboolean options.append(self) class EntryBox(gtk.HBox): def __init__(self, title, path, options, password=False): super(EntryBox, self).__init__() self.set_border_width(5) self.set_spacing(10) self.label = gtk.Label(title) self.label.set_alignment(0, 0.5) self.pack_start(self.label, expand=True, fill=True) self.entry = gtk.Entry() self.entry.set_visibility(not password) self.pack_end(self.entry, expand=False) self.path = path self.get_value = self.entry.get_text self.set_value = self.entry.set_text self.type = mailanie.config.get options.append(self)
liZe/Mailanie
mailanie/ui/preferences.py
preferences.py
py
6,586
python
en
code
5
github-code
6
14810439425
import os, sys from os.path import join as ospj import torch import numpy as np from PIL import Image import torch.utils.data as data import kornia import argparse from logger import Logger class PairedImageDataset(data.Dataset): def __init__(self, lr_img_path, lr_filelist_path, hr_img_path, hr_filelist_path, args): self.args=args self.lr_img_path = lr_img_path self.hr_img_path = hr_img_path self.lr_filelist_path = lr_filelist_path self.hr_filelist_path = hr_filelist_path self.lr_img_list = [x.strip() for x in open(self.lr_filelist_path).readlines()] self.hr_img_list = [x.strip() for x in open(self.hr_filelist_path).readlines()] # -85.61112_30.197733_28cm.tif -> -85.61112_30.197733_50cm.png self.paired_lr_img_list = [x.replace("28cm.tif", "50cm.png") for x in self.hr_img_list] def __getitem__(self, item): lr_img_name = self.paired_lr_img_list[item] hr_img_name = self.hr_img_list[item] lr_img = Image.open(ospj(self.lr_img_path, lr_img_name)).convert('RGB') hr_img = Image.open(ospj(self.hr_img_path, hr_img_name)).convert('RGB') lr_img = np.asarray(lr_img) / 255.0 hr_img = np.asarray(hr_img) / 255.0 lr_img = kornia.image_to_tensor(lr_img).squeeze() hr_img = kornia.image_to_tensor(hr_img).squeeze() return lr_img, hr_img def __len__(self): return len(self.hr_img_list) class TVDenoise(torch.nn.Module): def __init__(self, args): super(TVDenoise, self).__init__() self.l2_term = torch.nn.MSELoss(reduction='mean') self.l1_term = torch.nn.L1Loss(reduction='mean') self.psnr = kornia.losses.PSNRLoss(max_val=1.0) self.ssim=kornia.losses.SSIM(5, reduction='mean') self.regularization_term = kornia.losses.TotalVariation() self.args=args self.xyxy = torch.nn.Parameter(data=torch.tensor([[0.], [0.], [713], [713]]), requires_grad=True) self.mem = torch.nn.Parameter(data=torch.tensor( [[1., 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 0, 1]]), requires_grad=False) def forward(self, src_img, dst_img): new_image = self.get_new_image(src_img, dst_img) return new_image def get_new_image(self, src_img, dst_img): self.boxes=torch.matmul(self.mem, self.xyxy).reshape(1, 4, 2) return kornia.crop_and_resize((src_img), self.boxes, dst_img.shape[-2:]) def train(epoch_i, data_loader, network, optimizer, args): num_iters = len(data_loader) loss_list=[] l1loss_list=[] l2loss_list=[] for i, input_tuple in enumerate(data_loader): optimizer.zero_grad() lr_img, hr_img = input_tuple resized_img = network(hr_img, lr_img) l1loss = network.l1_term(resized_img, lr_img) l2loss = network.l2_term(resized_img, lr_img) if args.use_l2_loss: loss = l2loss else: loss = l1loss loss.backward() optimizer.step() loss_list.append(loss.detach().numpy()) l1loss_list.append(l1loss.item()) l2loss_list.append(l2loss.item()) if i % 20 == 0: print("[{:2d}] [{:3d}/{:3d}]: loss {:.5f} l1:{:.5f} l2:{:.5f}". format(epoch_i, i, num_iters, loss.item(), l1loss.item(), l2loss.item()), "crop", network.xyxy.detach().numpy().flatten()) print("Averge loss: %.5f\tl1: %.5f\tl2: %.5f"%(np.mean(loss_list), np.mean(l1loss_list), np.mean(l2loss_list))) def main(): parser = argparse.ArgumentParser(description="Learnable Cropping Images") parser.add_argument('--use_l2_loss', action='store_true') parser.add_argument('--batch_size', type=int, default=32) parser.add_argument('--shuffle', action='store_true') parser.add_argument('--workers', type=int, default=2) parser.add_argument('--not_pin_memory', action='store_true') parser.add_argument('--lr_img_path', type=str, default="../../dataset/satellite_images/") parser.add_argument('--lr_filelist_path', type=str, default="data/satellite_images_filelist.txt") parser.add_argument('--hr_img_path', type=str, default="../../dataset/aerial_images/") parser.add_argument('--hr_filelist_path', type=str, default="data/aerial_images_filelist.txt") parser.add_argument('--num_epochs', type=int, default=25) parser.add_argument('--learning_rate', type=float, default=100.0) parser.add_argument('--exp_name', type=str, default="learncrop") args = parser.parse_args() logger = Logger() exp_dir = ospj("exps", args.exp_name+logger._timestr) os.makedirs(exp_dir, exist_ok=True) logger.create_log(exp_dir) sys.stdout = logger if args.use_l2_loss: print("use l2 loss") else: print("use l1 loss") dataset = PairedImageDataset(args.lr_img_path, args.lr_filelist_path, args.hr_img_path, args.hr_filelist_path, args) data_loader = torch.utils.data.DataLoader(dataset, batch_size=args.batch_size, shuffle=args.shuffle, num_workers=args.workers, pin_memory=not args.not_pin_memory, sampler=None, drop_last=False) network = TVDenoise(args) optimizer = torch.optim.SGD(network.parameters(), lr=args.learning_rate, momentum=0.9) for epoch_i in range(args.num_epochs): train(epoch_i, data_loader, network, optimizer, args) if __name__ == "__main__": main()
mengyuest/satellite2aerial
learn_crop.py
learn_crop.py
py
5,572
python
en
code
0
github-code
6
11045109174
def interfaces(interface_list): header = "{:<12} {:<16} {:<7} {:<4} {:<12} {:<12}".format('Interface', 'IP Address', 'Method', 'OK?', 'Connected', 'Operational') header += '\n-----------------------------------------------------------------------------\n' entries = '' for interface in interface_list: int_co = "False" if interface.get_is_connected(): int_co = "True" int_ok = "NO" if interface.get_is_operational(): int_ok = "YES" int_op = "Up" + ' ' * 19 if interface.get_administratively_down(): int_op = "Administratively Down" ipv4 = interface.get_ipv4_address() if not ipv4: ipv4 = " ----" method = interface.get_ip_assignment_method() entries += "{:<12} {:<16} {:<7} {:<4} {:<12} {:<12}".format(interface.get_shortened_name(), ipv4, method, int_ok, int_co, int_op + '\n') for sub_intf in interface.get_sub_interfaces(): entries += '--> ' + ("{:<12} {:<15}".format(sub_intf.get_shortened_name(), sub_intf.get_ipv4_address()) + '\n') return header + entries def routing_table(rt_table): header = "{:<10} {:<20} {:<15}".format('Type', 'Destination Network', 'Next Hop/Exit Interface') header += '\n--------------------------------------------------------\n' entries = '' for route in rt_table: flag = True for i in rt_table[route]: if flag: entries += "{:<10} {:<20} {:<15}".format(i[0], i[1], i[2]) flag = False else: entries += "{:<10} {:<20} {:<15}".format(i[0], i[1], i[2]) entries += "\n" return header + entries def arp_table(table): header = "{:<25} {:<25} {:<15}".format('Internet Address', 'Physical Address', 'Type') header += '\n-----------------------------------------------------------\n' entries = '' for ip in table: entries += "{:<25} {:<25} {:<15}".format(ip, table[ip][0], table[ip][1]) entries += "\n" return header + entries
KarimKabbara00/Network-Simulator
network/show_commands/RouterShowCommands.py
RouterShowCommands.py
py
2,160
python
en
code
0
github-code
6
75136491707
from dialogic.adapters import VkAdapter from dialogic.dialog import Response def test_keyboard_squeeze(): resp = Response(text='не важно', suggests=[ 'удалить направление', 'Агропромышленный комплекс', 'Вооружение и военная техника', 'Естественные науки', 'Инженерные науки и технологии', 'Искусство и гуманитарные науки', 'Компьютерные науки', 'Медицина и здравоохранение', 'Педагогические науки', 'Социально-экономические науки', 'вакансии', 'мой регион', 'мои направления', 'главное меню' ]) adapter = VkAdapter(suggest_cols='auto') result = adapter.make_response(resp) keyboard = result['keyboard']['buttons'] assert len(keyboard) == 10 assert sum(len(row) for row in keyboard) == len(resp.suggests) assert max(len(row) for row in keyboard) <= 5
avidale/dialogic
tests/test_adapters/test_vk_adapter.py
test_vk_adapter.py
py
1,089
python
ru
code
22
github-code
6
7807067398
from metagame_balance.cool_game import BotType import numpy as np class CoolGameMetaData: def __init__(self): self._winrates = np.zeros((len(BotType), len(BotType))) # in the ERG formulation, this is a table that you take the entropy of # in the policy entropy case, you learn a utility function from stats onto pick slate self._policy = None @property def winrates(self): return self._winrates @staticmethod def get_init_win_probs(): win_probs = np.zeros((len(BotType), len(BotType))) # ERG design matrix: cycle. win_probs[BotType.SAW][BotType.TORCH] = 0.7 win_probs[BotType.NAIL][BotType.SAW] = 0.7 win_probs[BotType.TORCH][BotType.NAIL] = 0.7 win_probs = win_probs + -win_probs.T return win_probs
nianticlabs/metagame-balance
src/metagame_balance/cool_game/metadata.py
metadata.py
py
823
python
en
code
3
github-code
6
42411316279
# -*- coding: utf-8 -*- # # File: BPDParticipante.py # # Copyright (c) 2011 by Conselleria de Infraestructuras y Transporte de la # Generalidad Valenciana # # GNU General Public License (GPL) # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. # # __author__ = """Conselleria de Infraestructuras y Transporte de la Generalidad Valenciana <[email protected]>, Model Driven Development sl <[email protected]>, Antonio Carrasco Valero <[email protected]>""" __docformat__ = 'plaintext' from AccessControl import ClassSecurityInfo from Products.Archetypes.atapi import * from Products.gvSIGbpd.BPDArquetipoConAdopcion import BPDArquetipoConAdopcion from Products.Relations.field import RelationField from Products.gvSIGbpd.config import * # additional imports from tagged value 'import' from Products.ATReferenceBrowserWidget.ATReferenceBrowserWidget import ReferenceBrowserWidget ##code-section module-header #fill in your manual code here ##/code-section module-header schema = Schema(( StringField( name='abreviatura', widget=StringWidget( label="Abreviatura", label2="Abbreviation", description="Para identificacion rapida de los Perfiles o Unidades Organizacionales mas significativos.", description2="For inmediate identification of participant Profiles and Organisational Units.", label_msgid='gvSIGbpd_BPDParticipante_attr_abreviatura_label', description_msgid='gvSIGbpd_BPDParticipante_attr_abreviatura_help', i18n_domain='gvSIGbpd', ), description="Para identificacion rapida de los Perfiles o Unidades Organizacionales mas significativos.", searchable=1, duplicates="0", label2="Abbreviation", ea_localid="245", derived="0", precision=0, collection="false", styleex="volatile=0;", description2="For inmediate identification of participant Profiles and Organisational Units.", ea_guid="{32115567-9FBE-406b-968F-C98308EB0C45}", write_permission='Modify portal content', scale="0", label="Abreviatura", length="0", containment="Not Specified", position="0", owner_class_name="BPDParticipante" ), RelationField( name='destinatarioDeEnvios', inverse_relation_label="Destinatarios", additional_columns=['abreviatura',], inverse_relation_description="Perfiles o Unidades Organizacionales a los que se destina el Envio.", description="Envios que se destinan a este Perfil o Unidad Organizacional.", relationship='BPDDestinatarioDeEnvios', inverse_relation_field_name='destinatarios', sourcestyle="Union=0;Derived=0;AllowDuplicates=0;Owned=0;Navigable=Unspecified;", inverse_relation_label2="Receivers", label2="Receiver of Send steps", inverse_relation_description2="Participant Profiles or Organisational Units to whom this is Sent", widget=ReferenceBrowserWidget( label="Destinatario de Envios", label2="Receiver of Send steps", description="Envios que se destinan a este Perfil o Unidad Organizacional.", description2="Send process steps addressed to this participant Profile or Organisational Unit.", label_msgid='gvSIGbpd_BPDParticipante_rel_destinatarioDeEnvios_label', description_msgid='gvSIGbpd_BPDParticipante_rel_destinatarioDeEnvios_help', i18n_domain='gvSIGbpd', ), label="Destinatario de Envios", description2="Send process steps addressed to this participant Profile or Organisational Unit.", multiValued=1, containment="Unspecified", inverse_relationship='BPDDestinatarios', dependency_supplier=True ), RelationField( name='pasosEjecutados', inverse_relation_label="Ejecutores", inverse_relation_description="Perfiles y Unidades Organizacionales a cargo de ejecutar el Paso.", description="Pasos de Negocio que se encarga de ejecutar el Perfil o Unidad Organizacional", relationship='BPDPasosEjecutados', label2="Performed Business Process Steps", widget=ReferenceBrowserWidget( label="Pasos Ejecutados", label2="Performed Business Process Steps", description="Pasos de Negocio que se encarga de ejecutar el Perfil o Unidad Organizacional", description2="Business Process Steps performed by the participant Profile or Organisational Unit.", label_msgid='gvSIGbpd_BPDParticipante_rel_pasosEjecutados_label', description_msgid='gvSIGbpd_BPDParticipante_rel_pasosEjecutados_help', i18n_domain='gvSIGbpd', ), description2="Business Process Steps performed by the participant Profile or Organisational Unit.", sourcestyle="Owned=0;Navigable=Unspecified;Union=0;Derived=0;AllowDuplicates=0;", inverse_relation_label2="Performers", dependency_supplier=True, inverse_relation_field_name='ejecutores', inverse_relation_description2="Participant Profiles and Organisational Units allowed to execute the Step.", additional_columns=['abreviatura',], write_permission='Modify portal content', label="Pasos Ejecutados", multiValued=1, containment="Unspecified", inverse_relationship='BPDEjecutoresDelPaso' ), RelationField( name='procesosEjecutados', inverse_relation_label="Ejecutores del Proceso", inverse_relation_description="Los Perfiles o Unidades Organizacionales a cargo de ejecutar el Proceso de Negocio.", description="Procesos de Negocio que se encarga de ejecutar el Perfil o Unidad Organizacional.", relationship='BPDProcesosEjecutados', label2="Performed Business Processes", widget=ReferenceBrowserWidget( label="Procesos Ejecutados", label2="Performed Business Processes", description="Procesos de Negocio que se encarga de ejecutar el Perfil o Unidad Organizacional.", description2="Business Process that can be executed by the participant Profile or Organisational Unit.", label_msgid='gvSIGbpd_BPDParticipante_rel_procesosEjecutados_label', description_msgid='gvSIGbpd_BPDParticipante_rel_procesosEjecutados_help', i18n_domain='gvSIGbpd', ), description2="Business Process that can be executed by the participant Profile or Organisational Unit.", sourcestyle="Owned=0;Navigable=Unspecified;Union=0;Derived=0;AllowDuplicates=0;", inverse_relation_label2="Performers", dependency_supplier=True, inverse_relation_field_name='ejecutores', inverse_relation_description2="Participant Profiles and Organisational Units allowed to execute the Business Process.", additional_columns=['abreviatura',], write_permission='Modify portal content', label="Procesos Ejecutados", multiValued=1, containment="Unspecified", inverse_relationship='BPDEjecutoresDelProceso' ), RelationField( name='reglasDeNegocioDirigentes', inverse_relation_label="Participantes dirigidos", containment="Unspecified", inverse_relation_description="Perfiles y Unidades Organizacionales que aplican la Regla de Negocio durante su labor.", description="Las Reglas de Negocio que dirigen la labor de el Perfil o Unidad Organizacional.", relationship='BPDAfectadoPorReglasDeNegocio', inverse_relation_field_name='participantesDirigidos', sourcestyle="Union=0;Derived=0;AllowDuplicates=0;Owned=0;Navigable=Unspecified;", label2="Directing Business Rules", inverse_relation_description2="Participant Profiles and Organisational Units that apply the Business Rule.", widget=ReferenceBrowserWidget( label="Reglas de Negocio dirigentes", label2="Directing Business Rules", description="Las Reglas de Negocio que dirigen la labor de el Perfil o Unidad Organizacional.", description2="Business Rule affecting the participant Profile or Organisational Unit", label_msgid='gvSIGbpd_BPDParticipante_rel_reglasDeNegocioDirigentes_label', description_msgid='gvSIGbpd_BPDParticipante_rel_reglasDeNegocioDirigentes_help', i18n_domain='gvSIGbpd', ), label="Reglas de Negocio dirigentes", description2="Business Rule affecting the participant Profile or Organisational Unit", multiValued=1, inverse_relation_label2="Directed Participant Profiles and Organisational Units", inverse_relationship='BPDParticipantesDirigidos', write_permission='Modify portal content', additional_columns=['abreviatura',] ), RelationField( name='politicasDeNegocioGobernantes', inverse_relation_label="Participantes gobernados", containment="Unspecified", inverse_relation_description="Perfiles y Unidades Organizacionales que aplican la Politica de Negocio durante su labor.", description="Las Politicas de Negocio que afectan a la labor del Perfil o Unidad Organizacional", relationship='BPDAfectadoPorPoliticasDeNegocio', inverse_relation_field_name='participantesGobernados', sourcestyle="Union=0;Derived=0;AllowDuplicates=0;Owned=0;Navigable=Unspecified;", label2="Governing Business Policies", inverse_relation_description2="Participant Profiles and Organisational Units that must endeavour to apply the Business Policy.", widget=ReferenceBrowserWidget( label="Politicas de Negocio gobernantes", label2="Governing Business Policies", description="Las Politicas de Negocio que afectan a la labor del Perfil o Unidad Organizacional", description2="Business Policies governing the participant Profile or Organisational Unit.", label_msgid='gvSIGbpd_BPDParticipante_rel_politicasDeNegocioGobernantes_label', description_msgid='gvSIGbpd_BPDParticipante_rel_politicasDeNegocioGobernantes_help', i18n_domain='gvSIGbpd', ), label="Politicas de Negocio gobernantes", description2="Business Policies governing the participant Profile or Organisational Unit.", multiValued=1, inverse_relation_label2="Governed participant Profiles and Organisational Units", inverse_relationship='BPDParticipantesGobernados', write_permission='Modify portal content', additional_columns=['abreviatura',] ), RelationField( name='remitenteDeRecepciones', inverse_relation_label="Remitente", additional_columns=['abreviatura',], inverse_relation_description="El Perfil o Unidad Organizacional que originan la Recepcion.", description="Recepciones originadas en este Perfil o Unidad Organizacional.", relationship='BPDRemitenteDeRecepciones', inverse_relation_field_name='remitente', sourcestyle="Union=0;Derived=0;AllowDuplicates=0;Owned=0;Navigable=Unspecified;", inverse_relation_label2="Sender", label2="Sender of Reception steps", inverse_relation_description2="Participant Profiles or Organisational Units originating this Reception.", widget=ReferenceBrowserWidget( label="Remitente de Recepciones", label2="Sender of Reception steps", description="Recepciones originadas en este Perfil o Unidad Organizacional.", description2="Business Process Reception Steps originated by the participant Profile or Organisational Units.", label_msgid='gvSIGbpd_BPDParticipante_rel_remitenteDeRecepciones_label', description_msgid='gvSIGbpd_BPDParticipante_rel_remitenteDeRecepciones_help', i18n_domain='gvSIGbpd', ), label="Remitente de Recepciones", description2="Business Process Reception Steps originated by the participant Profile or Organisational Units.", multiValued=1, containment="Unspecified", inverse_relationship='BPDRemitente', dependency_supplier=True ), TextField( name='responsabilidadesClave', widget=TextAreaWidget( label="Responsabilidades Clave", label2="Key Responsibilities", description="Los Participantes, en general, se haran cargo principalmente de las responsabilidades especificadas.", description2="The participant Profile or Organisational Unit shall be generally responsible of these subject areas.", label_msgid='gvSIGbpd_BPDParticipante_attr_responsabilidadesClave_label', description_msgid='gvSIGbpd_BPDParticipante_attr_responsabilidadesClave_help', i18n_domain='gvSIGbpd', ), description="Los Participantes, en general, se haran cargo principalmente de las responsabilidades especificadas.", searchable=1, duplicates="0", label2="Key Responsibilities", ea_localid="246", derived="0", precision=0, collection="false", styleex="volatile=0;", description2="The participant Profile or Organisational Unit shall be generally responsible of these subject areas.", ea_guid="{DC8EFEB8-D377-47ff-B13F-A719BDA70D04}", write_permission='Modify portal content', scale="0", label="Responsabilidades Clave", length="0", containment="Not Specified", position="1", owner_class_name="BPDParticipante" ), RelationField( name='responsableDeArtefactos', inverse_relation_label="Responsables", containment="Unspecified", inverse_relation_description="Perfiles o Unidades Organizacionales a cargo de los Artefactos de este tipo.", description="Artefactos que estan a cargo del Perfil o Unidad Organizacional.", relationship='BPDArtefactosACargo', inverse_relation_field_name='responsablesDeArtefacto', sourcestyle="Navigable=Unspecified;Union=0;Derived=0;AllowDuplicates=0;Owned=0;", label2="In charge of Artefacts", inverse_relation_description2="Participant Profiles or Organisational Units generally in charge of Artefacts of this type.", widget=ReferenceBrowserWidget( label="Artefactos a su cargo", label2="In charge of Artefacts", description="Artefactos que estan a cargo del Perfil o Unidad Organizacional.", description2="Artefacts for which the the participant Profile or Organisational Unit is generally responsible for.", label_msgid='gvSIGbpd_BPDParticipante_rel_responsableDeArtefactos_label', description_msgid='gvSIGbpd_BPDParticipante_rel_responsableDeArtefactos_help', i18n_domain='gvSIGbpd', ), label="Artefactos a su cargo", description2="Artefacts for which the the participant Profile or Organisational Unit is generally responsible for.", multiValued=1, inverse_relation_label2="Responsible Profiles or Organisational Units", inverse_relationship='BPDResponsablesDeArtefacto', write_permission='Modify portal content', additional_columns=['abreviatura',] ), RelationField( name='responsableDeHerramientas', inverse_relation_label="Responsables", containment="Unspecified", inverse_relation_description="Perfiles o Unidades Organizacionales a cargo de asistir a la organizacion en su manejo de esta Herramienta.", description="Herramientas que estan a cargo de el Perfil o Unidad Organizacional", relationship='BPDHerramientasACargo', inverse_relation_field_name='responsablesDeHerramienta', sourcestyle="Union=0;Derived=0;AllowDuplicates=0;Owned=0;Navigable=Unspecified;", label2="In charge of Tools", inverse_relation_description2="Participant Profiles or Organisational Units generally in charge of handling, administering or assisting the Teams in their usage of the Tool.", widget=ReferenceBrowserWidget( label="Herramientas a su Cargo", label2="In charge of Tools", description="Herramientas que estan a cargo de el Perfil o Unidad Organizacional", description2="Tools for which the the participant Profile or Organisational Unit is generally responsible for.", label_msgid='gvSIGbpd_BPDParticipante_rel_responsableDeHerramientas_label', description_msgid='gvSIGbpd_BPDParticipante_rel_responsableDeHerramientas_help', i18n_domain='gvSIGbpd', ), label="Herramientas a su Cargo", description2="Tools for which the the participant Profile or Organisational Unit is generally responsible for.", multiValued=1, inverse_relation_label2="Profiles or Organisational Units Responsible for the Tool", inverse_relationship='BPDResponsablesDeHerramienta', write_permission='Modify portal content', additional_columns=['abreviatura',] ), RelationField( name='procesosSupervisados', inverse_relation_label="Supervisor", inverse_relation_description="El Perfil o Unidad Organizacional a cargo de velar por que el cumplimiento del Proceso de Negocio se realize de acuerdo con la regulacion aplicable.", description="Procesos de Negocio que se encarga de supervisar el Perfil o Unidad Organizacional.", relationship='BPDProcesosSupervisados', label2="Supervised Business Processes", widget=ReferenceBrowserWidget( label="Procesos Supervisados", label2="Supervised Business Processes", description="Procesos de Negocio que se encarga de supervisar el Perfil o Unidad Organizacional.", description2="Business Process under supervision of the participant Profile or Organisational Unit.", label_msgid='gvSIGbpd_BPDParticipante_rel_procesosSupervisados_label', description_msgid='gvSIGbpd_BPDParticipante_rel_procesosSupervisados_help', i18n_domain='gvSIGbpd', ), description2="Business Process under supervision of the participant Profile or Organisational Unit.", sourcestyle="Union=0;Derived=0;AllowDuplicates=0;Owned=0;Navigable=Unspecified;", inverse_relation_label2="Supervisor", dependency_supplier=True, inverse_relation_field_name='supervisor', inverse_relation_description2="The participant Profile or Organisational Unit is responsible to ensure the compliance of the Business Process execution with applicable directives.", additional_columns=['abreviatura',], write_permission='Modify portal content', label="Procesos Supervisados", multiValued=1, containment="Unspecified", inverse_relationship='BPDSupervisor' ), ), ) ##code-section after-local-schema #fill in your manual code here ##/code-section after-local-schema BPDParticipante_schema = getattr(BPDArquetipoConAdopcion, 'schema', Schema(())).copy() + \ schema.copy() ##code-section after-schema #fill in your manual code here ##/code-section after-schema class BPDParticipante(OrderedBaseFolder, BPDArquetipoConAdopcion): """ """ security = ClassSecurityInfo() __implements__ = (getattr(OrderedBaseFolder,'__implements__',()),) + (getattr(BPDArquetipoConAdopcion,'__implements__',()),) # Change Audit fields creation_date_field = 'fechaCreacion' creation_user_field = 'usuarioCreador' modification_date_field = 'fechaModificacion' modification_user_field = 'usuarioModificador' deletion_date_field = 'fechaEliminacion' deletion_user_field = 'usuarioEliminador' is_inactive_field = 'estaInactivo' change_counter_field = 'contadorCambios' sources_counters_field = 'contadoresDeFuentes' change_log_field = 'registroDeCambios' # Versioning and Translation fields inter_version_field = 'uidInterVersionesInterno' version_field = 'versionInterna' version_storage_field = 'versionInternaAlmacenada' version_comment_field = 'comentarioVersionInterna' version_comment_storage_field = 'comentarioVersionInternaAlmacenada' inter_translation_field = 'uidInterTraduccionesInterno' language_field = 'codigoIdiomaInterno' fields_pending_translation_field = 'camposPendientesTraduccionInterna' fields_pending_revision_field = 'camposPendientesRevisionInterna' allowed_content_types = [] + list(getattr(BPDArquetipoConAdopcion, 'allowed_content_types', [])) actions = ( {'action': "string:$object_url/content_status_history", 'category': "object", 'id': 'content_status_history', 'name': 'State', 'permissions': ("View",), 'condition': """python:0""" }, {'action': "string:${object_url}/MDDInspectClipboard", 'category': "object_buttons", 'id': 'inspectclipboard', 'name': 'Clipboard', 'permissions': ("View",), 'condition': """python:object.fAllowRead()""" }, {'action': "string:${object_url}/Editar", 'category': "object", 'id': 'edit', 'name': 'Edit', 'permissions': ("Modify portal content",), 'condition': """python:object.fAllowWrite()""" }, {'action': "string:${object_url}/MDDOrdenar", 'category': "object_buttons", 'id': 'reorder', 'name': 'Reorder', 'permissions': ("Modify portal content",), 'condition': """python:object.fAllowWrite()""" }, {'action': "string:${object_url}/MDDExport", 'category': "object_buttons", 'id': 'mddexport', 'name': 'Export', 'permissions': ("View",), 'condition': """python:object.fAllowExport()""" }, {'action': "string:${object_url}/MDDImport", 'category': "object_buttons", 'id': 'mddimport', 'name': 'Import', 'permissions': ("Modify portal content",), 'condition': """python:object.fAllowImport()""" }, {'action': "string:${object_url}/sharing", 'category': "object", 'id': 'local_roles', 'name': 'Sharing', 'permissions': ("Manage properties",), 'condition': """python:1""" }, {'action': "string:${object_url}/", 'category': "object", 'id': 'view', 'name': 'View', 'permissions': ("View",), 'condition': """python:1""" }, {'action': "string:${object_url}/MDDChanges", 'category': "object_buttons", 'id': 'mddchanges', 'name': 'Changes', 'permissions': ("View",), 'condition': """python:1""" }, {'action': "string:${object_url}/MDDVersions", 'category': "object_buttons", 'id': 'mddversions', 'name': 'Versions', 'permissions': ("View",), 'condition': """python:1""" }, {'action': "string:${object_url}/MDDCacheStatus/", 'category': "object_buttons", 'id': 'mddcachestatus', 'name': 'Cache', 'permissions': ("View",), 'condition': """python:1""" }, {'action': "string:${object_url}/TextualRest", 'category': "object_buttons", 'id': 'textual_rest', 'name': 'TextualRest', 'permissions': ("View",), 'condition': """python:1""" }, ) _at_rename_after_creation = True schema = BPDParticipante_schema ##code-section class-header #fill in your manual code here ##/code-section class-header # Methods # end of class BPDParticipante ##code-section module-footer #fill in your manual code here ##/code-section module-footer
carrascoMDD/gvSIG-bpd
gvSIGbpd/BPDParticipante.py
BPDParticipante.py
py
25,254
python
en
code
0
github-code
6
43269447803
""" Django settings for msca_provisioner project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) MSCA_MANAGER_SUPPORT_GROUP = 'u_acadev_msca_support' MSCA_MANAGER_ADMIN_GROUP = MSCA_MANAGER_SUPPORT_GROUP RESTCLIENTS_ADMIN_GROUP = MSCA_MANAGER_ADMIN_GROUP USERSERVICE_ADMIN_GROUP = MSCA_MANAGER_ADMIN_GROUP AUTHZ_GROUP_BACKEND = 'authz_group.authz_implementation.uw_group_service.UWGroupService' # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ['DJANGO_SECRET_KEY'] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = int(os.environ['DJANGO_DEBUG']) TEMPLATE_DEBUG = True ALLOWED_HOSTS = [ os.getenv('DJANGO_ALLOWED_HOSTS', '*') ] SUPPORTTOOLS_PARENT_APP = 'Office 365' SUPPORTTOOLS_PARENT_APP_URL = 'https://outlook.office.com' # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'templatetag_handlebars', 'supporttools', 'userservice', 'authz_group', 'compressor', 'restclients', 'provisioner', 'events', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django_mobileesp.middleware.UserAgentDetectionMiddleware', 'userservice.user.UserServiceMiddleware', ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.core.context_processors.request', 'django.core.context_processors.static', 'django.core.context_processors.tz', 'django.contrib.messages.context_processors.messages', 'supporttools.context_processors.supportools_globals', 'supporttools.context_processors.has_less_compiled', ) AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.RemoteUserBackend', ) from django_mobileesp.detector import agent DETECT_USER_AGENTS = { 'is_tablet': agent.detectTierTablet, 'is_mobile': agent.detectMobileQuick, } ROOT_URLCONF = 'msca_provisioner.urls' WSGI_APPLICATION = 'msca_provisioner.wsgi.application' # Database # https://docs.djangoproject.com/en/1.7/ref/settings/#databases try: DB_DEFAULT = { 'ENGINE': 'sql_server.pyodbc', 'NAME': os.environ['DJANGO_DB_NAME'], 'USER': os.environ['DJANGO_DB_USER'], 'PASSWORD': os.environ['DJANGO_DB_PASSWORD'], 'HOST': os.environ['DJANGO_DB_HOST'], 'PORT': os.environ['DJANGO_DB_PORT'], 'OPTIONS': { 'driver': 'SQL Server Native Client 11.0', } } except KeyError: DB_DEFAULT = { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'db.sqlite3' } DATABASES = { 'default': DB_DEFAULT } # Internationalization # https://docs.djangoproject.com/en/1.7/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.7/howto/static-files/ STATIC_URL = '/static/' # Set Static file path PROJECT_ROOT = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static').replace('\\','/') from socket import gethostname # Logging LOG_LEVEL = 'INFO' LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt' : "%d/%b/%Y %H:%M:%S" }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(os.getenv('LOGPATH', '.'), 'provisioner-%s.log' % gethostname()), 'formatter': 'verbose' }, }, 'loggers': { 'django.db.backends': { 'handlers':['file'], 'propagate': False, 'level': 'INFO' }, 'django': { 'handlers':['file'], 'propagate': True, 'level': LOG_LEVEL }, 'aws_message': { 'handlers':['file'], 'propagate': True, 'level': LOG_LEVEL }, 'provisioner': { 'handlers': ['file'], 'propagate': True, 'level': LOG_LEVEL }, 'events': { 'handlers': ['file'], 'propagate': True, 'level': LOG_LEVEL }, } } #COMPRESSOR SETTINGS COMPRESS_ENABLED = False COMPRESS_OFFLINE = False RESTCLIENTS_GWS_DAO_CLASS = 'restclients.dao_implementation.gws.Live' RESTCLIENTS_GWS_HOST='https://groups.uw.edu' RESTCLIENTS_GWS_KEY_FILE=os.environ['UWNETID_KEY_FILE'] RESTCLIENTS_GWS_CERT_FILE=os.environ['UWNETID_CERT_FILE'] # UW NetId Web Service settings RESTCLIENTS_UWNETID_DAO_CLASS = 'restclients.dao_implementation.uwnetid.Live' RESTCLIENTS_UWNETID_HOST=os.environ['UWNETID_HOST'] RESTCLIENTS_UWNETID_KEY_FILE=os.environ['UWNETID_KEY_FILE'] RESTCLIENTS_UWNETID_CERT_FILE=os.environ['UWNETID_CERT_FILE'] # Office 365 settings RESTCLIENTS_O365_DAO_CLASS = 'restclients.dao_implementation.o365.Live' RESTCLIENTS_O365_PRINCIPLE_DOMAIAN=os.environ['O365_PRINCIPLE_DOMAIN'] RESTCLIENTS_O365_TENANT=os.environ['O365_TENANT'] RESTCLIENTS_O365_CLIENT_ID=os.environ['O365_CLIENT_ID'] RESTCLIENTS_O365_CLIENT_SECRET=os.environ['O365_CLIENT_SECRET'] # Dictionary mapping subscription codes to Office 365 licenses. # Each subscription code is a dictionary of license SKU Part # Numbers that contain a list of disabled service plans within # the license. O365_LICENSES = { 'O365_TEST_LICENSE_MAP': { 234: { # UW Office 365 Education (Dogfood)' 'STANDARDWOFFPACK_IW_FACULTY': [] #'STANDARDWOFFPACK_FACULTY': [] }, 236 : { # UW Office 365 ProPlus (Dogfood)' 'OFFICESUBSCRIPTION_FACULTY': [] }, 238: { # UW Project Server Online user access (Dogfood)' 'PROJECTONLINE_PLAN_1_FACULTY': [] }, 240: { # UW Power BI (Dogfood)' 'POWER_BI_STANDARD': [] } }, 'O365_PRODUCTION_LICENSE_MAP': { 233: { # UW Office 365 Education' 'STANDARDWOFFPACK_FACULTY': [] }, 235: { # UW Office 365 ProPlus' 'OFFICESUBSCRIPTION_FACULTY': [] }, 237: { # UW Project Server Online user access' 'PROJECTONLINE_PLAN_1_FACULTY': [] }, 239: { # UW Power BI' 'POWER_BI_STANDARD': [] } } } O365_LICENSE_MAP = O365_LICENSES[os.environ['LICENSE_MAP']] O365_LIMITS = { 'process' : { 'default': 250 }, 'monitor' : { 'default': 250 } } RESTCLIENTS_CA_BUNDLE = os.environ['CA_BUNDLE'] RESTCLIENTS_TIMEOUT = None AWS_CA_BUNDLE = os.environ['CA_BUNDLE'] AWS_SQS = { 'SUBSCRIPTION' : { 'TOPIC_ARN' : os.environ['SQS_SUBSCRIPTION_TOPIC_ARN'], 'QUEUE': os.environ['SQS_SUBSCRIPTION_QUEUE'], 'KEY_ID': os.environ['SQS_SUBSCRIPTION_KEY_ID'], 'KEY': os.environ['SQS_SUBSCRIPTION_KEY'], 'VISIBILITY_TIMEOUT': 60, 'MESSAGE_GATHER_SIZE': 100, 'VALIDATE_SNS_SIGNATURE': True, 'VALIDATE_MSG_SIGNATURE': True, 'EVENT_COUNT_PRUNE_AFTER_DAY': 2, 'PAYLOAD_SETTINGS': { 'SUBSCRIPTIONS': O365_LICENSES[os.environ['LICENSE_MAP']] } } } API_CONSUMERS = {} try: API_CONSUMERS[os.environ['API_KEY_1']] = os.environ['API_SECRET_1'] except: pass # admin app settings ADMIN_EVENT_GRAPH_FREQ = 10 ADMIN_SUBSCRIPTION_STATUS_FREQ = 30
uw-it-aca/msca-provisioner
msca_provisioner/settings.py
settings.py
py
8,632
python
en
code
1
github-code
6
5035337247
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('authentication_module', '0004_auto_20160801_2318'), ] operations = [ migrations.AddField( model_name='customuser', name='tipo_cuenta', field=models.CharField(default=b'C', max_length=1, choices=[(b'C', b'COMERCIANTE'), (b'M', b'MUNICIPIO')]), ), ]
DirectorioTurismoComercio/BackEnd
authentication_module/migrations/0005_customuser_tipo_cuenta.py
0005_customuser_tipo_cuenta.py
py
492
python
en
code
0
github-code
6
25068902425
import unittest from unittest.mock import patch import purplship from purplship.core.utils import DP from purplship.core.models import RateRequest from tests.dhl_poland.fixture import gateway class TestDHLPolandRating(unittest.TestCase): def setUp(self): self.maxDiff = None self.RateRequest = RateRequest(**rate_request_data) def test_parse_rate_response(self): parsed_response = ( purplship.Rating.fetch(self.RateRequest).from_(gateway).parse() ) self.assertListEqual(DP.to_dict(parsed_response), ParsedRateResponse) if __name__ == "__main__": unittest.main() rate_request_data = { "shipper": {"postal_code": "00909", "country_code": "PL"}, "recipient": {"postal_code": "00001", "country_code": "PL"}, "parcels": [ { "height": 3.0, "length": 5.0, "width": 3.0, "weight": 4.0, "dimension_unit": "IN", "weight_unit": "LB", } ], "services": [], } ParsedRateResponse = [ [ { "base_charge": 0.0, "carrier_id": "dhl_poland", "carrier_name": "dhl_poland", "currency": "USD", "meta": {"service_name": "DHL Poland Premium"}, "service": "dhl_poland_premium", "total_charge": 0.0, }, { "base_charge": 0.0, "carrier_id": "dhl_poland", "carrier_name": "dhl_poland", "currency": "USD", "meta": {"service_name": "DHL Poland Polska"}, "service": "dhl_poland_polska", "total_charge": 0.0, }, { "base_charge": 0.0, "carrier_id": "dhl_poland", "carrier_name": "dhl_poland", "currency": "USD", "meta": {"service_name": "DHL Poland 09"}, "service": "dhl_poland_09", "total_charge": 0.0, }, { "base_charge": 0.0, "carrier_id": "dhl_poland", "carrier_name": "dhl_poland", "currency": "USD", "meta": {"service_name": "DHL Poland 12"}, "service": "dhl_poland_12", "total_charge": 0.0, }, ], [], ]
danh91/purplship
sdk/extensions/dhl_poland/tests/dhl_poland/rate.py
rate.py
py
2,268
python
en
code
null
github-code
6
21052465999
from pylib.android.log import log import re import pylib.basic.re_exp.re_exp as re_exp class EventLog(log.Log): def __init__(self, path=None): log.Log.__init__(self, path) if self.logs is not None: self.logs['file'] = 'evnet' def _match_pids(self, log): pat = None if log.tag == 'am_proc_start': # am_proc_start: [0,1617,10021,com.android.deskclock,broadcast,com.android.deskclock/.AlarmInitReceiver] pat = re_exp.re_exp(r'[%d,%d,%d,%s,%s,%s/%s]') elif log.tag == 'am_proc_died': # am_proc_died: [0,1042,com.android.printspooler] pat = re_exp.re_exp(r'[%d,%d,%s]') elif log.tag == 'am_kill': # am_kill : [0,1078,com.android.provision,15,empty #17] pat = re_exp.re_exp(r'[%d,%d,%s,%d,%s') if pat is not None: pat = re.compile(pat) m = pat.match(log.msg) return m.groups() return None def _to_value(self, log): if log.msg[0] == '[' and log.msg[-1] == ']': value = log.msg[1:-1].split(',') else: value = log.msg return value def get_pids(self): df = self.find( lambda log: log.tag == 'am_proc_start' or log.tag == 'am_proc_died' or log.tag == 'am_kill', self._to_value ) pids = {} for _, log in df.iterrows(): if log.tag == 'am_proc_start': # am_proc_start: [0,1617,10021,com.android.deskclock,broadcast,com.android.deskclock/.AlarmInitReceiver] pid = log.match[1] package = log.match[3] time = log.datetime reason = log.match[4] + '(' + log.match[5] + ')' pids[pid] = { 'pid': pid, 'package': package, 'start_reason': reason, 'start_time': time } elif log.tag == 'am_kill': # am_kill : [0,1078,com.android.provision,15,empty #17] pid = log.match[1] package = log.match[2] reason = log.match[4] if not pid in pids: pids[pid] = { 'pid': pid } pids[pid]['package'] = package pids[pid]['die_reason'] = reason elif log.tag == 'am_proc_died': pid = log.match[1] package = log.match[2] time = log.datetime if not pid in pids: pids[pid] = { 'pid': pid } pids[pid]['package'] = package pids[pid]['die_time'] = time # am_proc_died: [0,1042,com.android.printspooler] return pids
cttmayi/pylib
pylib/android/log/event_log.py
event_log.py
py
2,702
python
en
code
0
github-code
6
16701006334
import os import sys from xml.etree import ElementTree def isPlaylistUpdated(cmusPlaylistFile, jellyfinMusicPathArray) : cmusMusicPathArray = open(cmusPlaylistFile, 'r').read().splitlines() if len(cmusMusicPathArray) != len(jellyfinMusicPathArray) : return True length = len(cmusMusicPathArray) for i in range(0, length) : if cmusMusicPathArray[i] != jellyfinMusicPathArray[i].text : return True return False def updateFile(cmusPlaylistFile, musicPathArray) : print('updating or creating ' + cmusPlaylistFile) string = '' for path in musicPathArray : string += path.text + '\n' with open(cmusPlaylistFile, 'w') as sw : sw.write(string) JELLYFIN_PLAYLIST_PATH = sys.argv[1] CMUS_PLAYLIST_PATH = sys.argv[2] for playlist in os.listdir(JELLYFIN_PLAYLIST_PATH) : playlistFile = os.path.join(JELLYFIN_PLAYLIST_PATH, playlist) playlistFile = os.path.join(playlistFile, 'playlist.xml') if os.path.isfile(playlistFile) : dom = ElementTree.parse(playlistFile) paths = dom.findall('PlaylistItems/PlaylistItem/Path') cmusPlaylistFile = os.path.join(CMUS_PLAYLIST_PATH, playlist) if (not os.path.isfile(cmusPlaylistFile)) or isPlaylistUpdated(cmusPlaylistFile, paths) : updateFile(cmusPlaylistFile, paths) # checkIfPlaylistUpdated('/home/nate/.config/cmus/playlists/test', None)
nate-1/playlist-jellyfin-cmus-interface
main.py
main.py
py
1,427
python
en
code
0
github-code
6
28377193501
import numpy as np from keras.models import Sequential from keras.layers import Dense, Flatten from keras.datasets import mnist from keras.utils import to_categorical import matplotlib.pyplot as plt # 载入MNIST数据集 (x_train, y_train), (x_test, y_test) = mnist.load_data() # 将像素值标准化到 0 到 1 之间 x_train, x_test = x_train / 255.0, x_test / 255.0 # 对标签进行独热编码 y_train = to_categorical(y_train, 10) y_test = to_categorical(y_test, 10) # 显示第一张图片 plt.imshow(x_train[0], cmap='gray') plt.title(f"Label: {np.argmax(y_train[0])}") # 显示标签 plt.show() # 构建模型 model = Sequential() model.add(Flatten(input_shape=(28, 28))) # 将 28x28 的图像展平成一维数组 model.add(Dense(128, activation='relu')) # 具有128个神经元和ReLU激活函数的隐藏层 model.add(Dense(10, activation='softmax')) # 具有10个神经元(用于10个类别)和softmax激活函数的输出层 # 编译模型 model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) # 训练模型 model.fit(x_train, y_train, epochs=5, validation_data=(x_test, y_test)) # 在测试集上评估模型 test_loss, test_acc = model.evaluate(x_test, y_test) print(f'测试准确率:{test_acc}')
Ldh88/112-LiDingHui-ShangHai
112-李鼎辉-上海/第八周作业/cv_tensorflow_keras.py
cv_tensorflow_keras.py
py
1,333
python
en
code
null
github-code
6
35940096218
import pygame import random from typing import Callable from pygame import Vector2, Rect, Color, Surface pygame.init() class Signal: def __init__(self): self.handlers = [] def connect(self, handler: callable) -> None: self.handlers.append(handler) def disconnect(self, handler: callable) -> None: self.handlers.remove(handler) def disconnect_all(self) -> None: self.handlers.clear() def emit(self, *args, **kwargs) -> None: for handler in self.handlers: handler(*args, **kwargs) class Buff: def __init__(self): self.name = "Buff" self.desc = "" def __str__(self) -> str: return f"{self.name}({self.desc})" def use(self, player: "Player") -> None: pass class HealthBuff(Buff): def __init__(self, value: int): super().__init__() self.name = "勇往直前" self.desc = f"恢复{value}点生命值." self.value = value def use(self, player: "Player") -> None: player.health += self.value class BulletDamage(Buff): def __init__(self, value: int): super().__init__() self.name = "血脉觉醒" self.desc = f"每颗子弹增加{value}点伤害." self.value = value def use(self, player: "Player") -> None: player.gun.bullet_damage += self.value class BulletSpeed(Buff): def __init__(self, value: int): super().__init__() self.name = "速战速决" self.desc = f"子弹速度增加{value}点." self.value = value def use(self, player: "Player") -> None: player.gun.bullet_speed += self.value class FireRateBuff(Buff): def __init__(self, value: int): super().__init__() self.name = "唯快不破" self.desc = f"枪的射速增加{value}点." self.value = value def use(self, player: "Player") -> None: player.gun.firing_rate += self.value class FireBulletCountBuff(Buff): def __init__(self, value: int): super().__init__() self.name = "火力覆盖" self.desc = f"发射子弹的颗数增加{value}颗." self.value = value def use(self, player: "Player") -> None: player.gun.fire_bullet_count += self.value class BulletKnockbackForce(Buff): def __init__(self, value: int): super().__init__() self.name = "大力出奇迹" self.desc = f"击退力度增加{value}点." self.value = value def use(self, player: "Player") -> None: player.gun.bullet_knockback_force += self.value Buffs = [ (HealthBuff, 5, 15), (BulletDamage, 1, 30), (BulletSpeed, 20, 100), (FireRateBuff, 1, 2), (FireBulletCountBuff, 1, 2), (BulletKnockbackForce, 1, 5) ] class Node2D: def __init__(self, parent: "Node2D", pos: Vector2, size: Vector2, z_index: int = 0): self.parent = parent self.pos = pos self.size = size self.collision_rect = Rect(pos, size) self.z_index = z_index self.visible = True self.can_paused = True self.children = [] self.can_collide = False self.has_collided_signal = Signal() self.set_parent(parent) def update(self, delta: float) -> None: pass def draw(self, surface: Surface) -> None: if not self.visible: return def set_parent(self, parent: "Node2D") -> None: self.parent = parent if parent is None: return if not self in parent.children: parent.children.append(self) def add_child(self, child: "Node2D") -> None: self.children.append(child) child.set_parent(self) def remove_child(self, child: "Node2D") -> None: if child not in self.children: return self.children.remove(child) child.set_parent(None) def remove_all_children(self) -> None: for child in self.children[:]: self.children.remove(child) child.set_parent(None) def remove(self) -> None: if self.parent is None: return self.parent.remove_child(self) self.parent = None def get_all_children(self) -> list: all_children = [] for child in self.children: all_children.append(child) all_children.extend(child.get_all_children()) return all_children def get_root(self) -> "Root": if isinstance(self, Root): return self if isinstance(self.parent, Root): return self.parent return self.parent.get_root() def get_rect(self) -> Rect: return Rect(self.pos, self.size) def add_in_group(self, name: str) -> None: root = self.get_root() if root is None: return group = root.groups.get(name) if group is None: group = [] root.groups[name] = group group.append(self) class Root(Node2D): instance = None def __new__(cls, *args, **kwargs): if cls.instance is None: cls.instance = super().__new__(cls) return cls.instance def __init__(self): super().__init__(None, Vector2(0, 0), Vector2(pygame.display.get_surface().get_size())) self.groups = {} self.delta = 0.0 self.clear_color = Color(0, 0, 0) self.mouse_pos = Vector2(0, 0) self.__pause_time = 0 self.__pause_duration = 0 self.__is_paused = False def update(self, delta: float) -> None: self.delta = delta self.mouse_pos = pygame.mouse.get_pos() def get_nodes_in_group(self, name: str) -> list: group = self.groups.get(name) if group is None: return [] return group def get_first_node_in_group(self, name: str) -> Node2D: group = self.groups.get(name) if group is None: return None return group[0] def pause(self, value: bool) -> None: self.__is_paused = value if value: self.__pause_time = pygame.time.get_ticks() else: self.__pause_duration += pygame.time.get_ticks() - self.__pause_time def is_paused(self) -> bool: return self.__is_paused def get_ticks(self, offset: int = 0) -> int: return pygame.time.get_ticks() - self.__pause_duration + offset class Sprite2D(Node2D): def __init__(self, parent: Node2D, pos: Vector2, image: Surface): super().__init__(parent, pos, Vector2(image.get_size())) self.image = image self.size = Vector2(image.get_size()) def draw(self, surface: Surface) -> None: super().draw(surface) surface.blit(self.image, self.pos) class HealthBar(Sprite2D): def __init__(self, parent: Node2D, max_health: int, pos: Vector2, size: Vector2, border: int = 1): super().__init__(parent, pos, Surface(size)) self.max_health = max_health self.health = max_health self.border = border self.border_color = Color(255, 255, 255) self.value_color = Color(255, 0, 0) self.z_index = 5 self.image.set_colorkey((0, 0, 0)) def draw(self, surface: Surface) -> None: self.image.fill((0, 0, 0)) pygame.draw.rect(self.image, self.border_color, (0, 0, self.size.x, self.size.y), self.border) pygame.draw.rect(self.image, self.value_color, (self.border, self.border, (self.size.x - self.border * 2) * self.health * 1.0 / self.max_health, self.size.y - self.border * 2)) super().draw(surface) class Bullet(Sprite2D): def __init__(self, parent: Node2D, pos: Vector2, direction: Vector2): super().__init__(parent, pos, Surface((10, 10))) self.speed = 800 self.damage = 5 self.knockback_force = 5 self.can_penetrate = False self.direction = direction self.z_index = 2 self.image.set_colorkey((0, 0, 0)) self.can_collide = True self.pos -= self.size / 2 def update(self, delta: float) -> None: self.pos += self.speed * self.direction * delta self.collision_rect.topleft = self.pos rect = pygame.display.get_surface().get_rect() if self.pos.x < 0 or self.pos.x > rect.width or self.pos.y < 0 or self.pos.y > rect.height: self.remove() def draw(self, surface: Surface) -> None: pygame.draw.circle(self.image, (0, 255, 0), self.size / 2, self.size.x / 2) super().draw(surface) class Gun(Node2D): def __init__(self, parent: Node2D): super().__init__(parent, Vector2(parent.get_rect().center), Vector2()) self.z_index = 3 self.__laste_fire_time = 0 self.firing_rate = 3 self.bullet_damage = 5 self.bullet_speed = 800 self.bullet_knockback_force = 5 self.bullet_can_penetrate = False self.fire_bullet_count = 1 def _create_bullet(self, direction: Vector2) -> None: bullet = Bullet(self, self.pos.copy(), direction) bullet.can_penetrate = self.bullet_can_penetrate bullet.damage = self.bullet_damage bullet.speed = self.bullet_speed bullet.knockback_force = self.bullet_knockback_force def _create_multiple_bullets(self, count: int, base_direction: Vector2, rotate_angle: float) -> None: for i in range(1, count + 1): angle = base_direction if self.fire_bullet_count % 2 == 0: if i == 1: angle = base_direction.rotate(rotate_angle / 2) else: angle = base_direction.rotate((i-1) * rotate_angle + rotate_angle / 2) else: angle = base_direction.rotate(i * rotate_angle) self._create_bullet(angle) def fire(self, direction: Vector2) -> None: if self.get_root().get_ticks() - self.__laste_fire_time < 1000.0 / self.firing_rate: return half = self.fire_bullet_count // 2 self._create_multiple_bullets(half, direction, 5) if not self.fire_bullet_count % 2 == 0: self._create_bullet(direction) self._create_multiple_bullets(half, direction, -5) self.__laste_fire_time = self.get_root().get_ticks() class Player(Sprite2D): def __init__(self, parent: Node2D, pos: Vector2): super().__init__(parent, pos, Surface(Vector2(60, 60))) self.speed = 500 self.z_index = 1 self.can_collide = True self.image.fill((255, 0, 0)) self.limit_rect = Rect(pygame.display.get_surface().get_rect()) self.died_signal = Signal() self.max_health = 100 self.health = self.max_health self.score = 0 self.kill_count = 0 self.add_in_group("player") self.gun = Gun(self) self.gun.bullet_damage = 50 self.gun.firing_rate = 5 self.gun.bullet_speed = 650 self.gun.bullet_knockback_force = 5 self.gun.fire_bullet_count = 1 # self.gun.bullet_can_penetrate = True self._init_data = self._get_init_data() def __str__(self) -> str: return f"""Player( bullet_damage: {self.gun.bullet_damage}, firing_rate: {self.gun.firing_rate}, bullet_speed: {self.gun.bullet_speed}, bullet_knockback_force: {self.gun.bullet_knockback_force}, fire_bullet_count: {self.gun.fire_bullet_count}, health: {self.health}, )""" def update(self, delta: float) -> None: keys = pygame.key.get_pressed() direction = Vector2() if keys[pygame.K_w]: direction.y = -1 if keys[pygame.K_s]: direction.y = 1 if keys[pygame.K_a]: direction.x = -1 if keys[pygame.K_d]: direction.x = 1 pos = self.pos direction = direction.normalize() if direction.length() != 0 else direction pos += direction * self.speed * delta if pos.x < self.limit_rect.left: pos.x = self.limit_rect.left if pos.x > self.limit_rect.right - self.size.x: pos.x = self.limit_rect.right - self.size.x if pos.y < self.limit_rect.top: pos.y = self.limit_rect.top if pos.y > self.limit_rect.bottom - self.size.y: pos.y = self.limit_rect.bottom - self.size.y self.pos = pos self.collision_rect.topleft = self.pos self.gun.pos = Vector2(self.get_rect().center) shoot_direction = Vector2(pygame.mouse.get_pos()) - self.get_rect().center shoot_direction = shoot_direction.normalize() if shoot_direction.length()!= 0 else shoot_direction # if pygame.mouse.get_pressed()[0]: self.gun.fire(shoot_direction) def set_health(self, health: int) -> None: self.health = pygame.math.clamp(health, 0, self.max_health) if self.health <= 0: self.died_signal.emit() def _get_init_data(self) -> dict: return { "pos": self.pos.copy(), "speed": self.speed, "health": self.health, "score": self.score, "kill_count": self.kill_count, "max_health": self.max_health, "bullet_can_penetrate": self.gun.bullet_can_penetrate, "bullet_damage": self.gun.bullet_damage, "firing_rate": self.gun.firing_rate, "bullet_speed": self.gun.bullet_speed, "bullet_knockback_force": self.gun.bullet_knockback_force, "fire_bullet_count": self.gun.fire_bullet_count, } def restore_init_data(self) -> None: self.pos = self._init_data["pos"] self.speed = self._init_data["speed"] self.health = self._init_data["health"] self.score = self._init_data["score"] self.kill_count = self._init_data["kill_count"] self.max_health = self._init_data["max_health"] self.gun.bullet_can_penetrate = self._init_data["bullet_can_penetrate"] self.gun.bullet_damage = self._init_data["bullet_damage"] self.gun.firing_rate = self._init_data["firing_rate"] self.gun.bullet_speed = self._init_data["bullet_speed"] self.gun.bullet_knockback_force = self._init_data["bullet_knockback_force"] self.gun.fire_bullet_count = self._init_data["fire_bullet_count"] class Cursor(Sprite2D): def __init__(self, parent: Node2D): super().__init__(parent, Vector2(0, 0), Surface((12, 12))) self.z_index = 9999 self.thickness = 2 self.color = Color((0, 255, 0)) self.image.set_colorkey((0, 0, 0)) self.can_paused = False pygame.mouse.set_visible(False) def update(self, delta: float) -> None: self.pos = pygame.mouse.get_pos() def draw(self, surface: Surface) -> None: pygame.draw.line(self.image, self.color, Vector2(self.size.x / 2 - self.thickness / 2, 0), Vector2(self.size.x / 2 - self.thickness / 2, self.size.y), self.thickness) pygame.draw.line(self.image, self.color, Vector2(0, self.size.y / 2 - self.thickness / 2), Vector2(self.size.x, self.size.y / 2 - self.thickness / 2), self.thickness) super().draw(surface) class Enemy(Sprite2D): init_data = {} def __init__(self, parent: Node2D, pos: Vector2): super().__init__(parent, pos, Surface((30, 30))) self.speed = 80 self.z_index = 0 self.image.fill((255, 255, 255)) self.can_collide = True self.player = self.get_root().get_first_node_in_group("player") self.max_health = 500 self.health = self.max_health Enemy.init_data = self._get_init_data() self.health_bar = HealthBar(self, self.max_health, Vector2(self.pos.x, self.pos.y - 15), Vector2(self.size.x, 8), 2) self.has_collided_signal.connect(self._on_has_collided_signal) def update(self, delta: float) -> None: self.collision_rect.topleft = self.pos self.health_bar.pos = Vector2(self.pos.x, self.pos.y - 15) direction = Vector2(self.player.get_rect().center) - Vector2(self.get_rect().center) if direction.length()!= 0: direction = direction.normalize() self.pos += direction * self.speed * delta def draw(self, surface: Surface) -> None: pygame.draw.circle(self.image, (255, 0, 0), self.size / 2, 7.5) super().draw(surface) def _get_init_data(self) -> dict: return { "speed": self.speed, "health": self.health, "max_health": self.max_health, } def _on_has_collided_signal(self, node: Node2D) -> None: if isinstance(node, Bullet): self.health -= node.damage self.health_bar.health = self.health self.pos += node.direction * node.knockback_force if self.health <= 0: self.player.score += 5 self.player.kill_count += 1 self.remove() if not node.can_penetrate: node.remove() if isinstance(node, Player): self.player.score -= 10 self.player.set_health(self.player.health - 10) self.player.kill_count += 1 self.remove() class Lable(Node2D): def __init__(self, parent: Node2D, pos: Vector2, text: str = ""): super().__init__(parent, pos, Vector2()) self.font = pygame.font.SysFont("SimHei", 30) self.font_color = Color(255, 255, 255) self.text_surfaces = [] self.__text = text self.set_text(text) def update(self, delta: float) -> None: self.text_surfaces.clear() lines = self.__text.split("\n") line_height = self.font.get_linesize() y = self.pos.y max_width = 0 for line in lines: text_surface = self.font.render(line, True, self.font_color) self.text_surfaces.append((text_surface, Vector2(self.pos.x, y))) y += line_height if text_surface.get_width() > max_width: max_width = text_surface.get_width() self.size = Vector2(max_width, len(lines) * line_height) def draw(self, surface: Surface) -> None: for text_surface, pos in self.text_surfaces: surface.blit(text_surface, pos) def set_text(self, text: str) -> None: self.__text = text # self.text_surfaces.clear() # lines = self.__text.split("\n") # line_height = self.font.get_linesize() # y = self.pos.y # max_width = 0 # for line in lines: # text_surface = self.font.render(line, True, self.font_color) # self.text_surfaces.append((text_surface, Vector2(self.pos.x, y))) # y += line_height # if text_surface.get_width() > max_width: # max_width = text_surface.get_width() # self.size = Vector2(max_width, len(lines) * line_height) def get_text(self) -> str: return self.__text class Button(Node2D): def __init__(self, parent: Node2D, pos: Vector2, text: str): super().__init__(parent, pos, Vector2()) self.padding = Vector2(10) self.is_pressed = False self.text_lbl = Lable(self, pos + self.padding, text) self.bg_color = Color(0, 0, 0) self.border_color = Color(255, 255, 255) self.border_width = 3 self.hot_keys = [] self.hot_key_pressed = False self.set_text(text) self.pressed_singal = Signal() def update(self, delta: float) -> None: self.size = Vector2(self.text_lbl.size) + self.padding * 2 self.text_lbl.pos = self.pos + self.padding self.text_lbl.z_index = self.z_index self.text_lbl.can_paused = self.can_paused self.text_lbl.visible = self.visible if self.visible: if pygame.mouse.get_pressed()[0] and self.get_rect().collidepoint(pygame.mouse.get_pos()) and not self.is_pressed: self.pressed_singal.emit() self.is_pressed = True if not pygame.mouse.get_pressed()[0]: self.is_pressed = False keys = pygame.key.get_pressed() for key in self.hot_keys: if keys[key]: if self.hot_key_pressed: break self.pressed_singal.emit() self.hot_key_pressed = True break else: self.hot_key_pressed = False def draw(self, surface: Surface) -> None: pygame.draw.rect(surface, self.bg_color, Rect(self.pos.x, self.pos.y, self.size.x, self.size.y)) pygame.draw.rect(surface, self.border_color, Rect(self.pos.x, self.pos.y, self.size.x, self.size.y), self.border_width) def set_text(self, text: str) -> None: self.text_lbl.set_text(text) self.size = Vector2(self.text_lbl.size) + self.padding * 2 def get_text(self) -> str: return self.text_lbl.get_text() class BuffPanel(Sprite2D): def __init__(self, parent: Node2D): super().__init__(parent, Vector2(0, 0), Surface(pygame.display.get_surface().get_size(), pygame.SRCALPHA)) self.image.fill(Color(0, 0, 0, 100)) self.buff_btns = [] self.buff_btn1 = Button(self, Vector2(10, 10), "buff1") self.buff_btn2 = Button(self, Vector2(120, 10), "buff2") self.buff_btn3 = Button(self, Vector2(230, 10), "buff3") self.buff_btns.append(self.buff_btn1) self.buff_btns.append(self.buff_btn2) self.buff_btns.append(self.buff_btn3) self.player = self.get_root().get_first_node_in_group("player") self.visible = False self.can_paused = False for btn in self.buff_btns: btn.can_paused = self.can_paused def update(self, delta: float) -> None: width = 0 max_height = 0 for btn in self.buff_btns: btn.z_index = self.z_index width += btn.size.x if btn.size.y > max_height: max_height = btn.size.y pos = Vector2((self.size.x - width - 2 * 20) / 2, (self.size.y - max_height) / 2) for btn in self.buff_btns: btn.pos = pos.copy() pos.x += btn.size.x + 20 btn.visible = self.visible def draw(self, surface: Surface) -> None: super().draw(surface) def _on_buff_btn_pressed(self, buff: Buff) -> None: buff.use(self.player) self.visible = False self.get_root().pause(not self.get_root().is_paused()) def _bind_buff(self, btn: Button) -> None: b = random.choice(Buffs) buff = b[0](random.randint(b[1], b[2])) btn.set_text(f"{buff.name}\n{buff.desc}") btn.pressed_singal.disconnect_all() btn.pressed_singal.connect(lambda: self._on_buff_btn_pressed(buff)) def display(self) -> None: for btn in self.buff_btns: self._bind_buff(btn) self.visible = True class GameOverPanel(Sprite2D): def __init__(self, parent: Node2D): super().__init__(parent, Vector2(0, 0), Surface(pygame.display.get_surface().get_size(), pygame.SRCALPHA)) self.image.fill(Color(0, 0, 0, 100)) self.z_index = 99 self.can_paused = False self.visible = False self.lbl = Lable(self, Vector2(), "游戏结束") self.lbl.font_color = Color(255, 0, 0) self.lbl.font = pygame.font.SysFont("SimHei", 50) self.lbl.can_paused = False self.restart_bnt = Button(self, Vector2(10, 10), "重新开始") self.restart_bnt.can_paused = False def update(self, delta: float) -> None: self.lbl.visible = self.visible self.restart_bnt.visible = self.visible self.lbl.z_index = self.z_index self.restart_bnt.z_index = self.z_index self.lbl.pos = (self.size - self.lbl.size) / 2 self.lbl.pos.y -= 100 self.restart_bnt.pos = (self.size - self.restart_bnt.size) / 2 self.restart_bnt.pos.y += self.lbl.size.y class TopUI(Node2D): def __init__(self, parent: Node2D): super().__init__(parent, Vector2(0, 0), Vector2(pygame.display.get_surface().get_size())) self.z_index = 99 self.add_in_group("top_ui") self.player = self.get_root().get_first_node_in_group("player") self.player_health_bar = HealthBar(self, self.player.max_health, Vector2(), Vector2(400, 20), 3) self.player_health_bar.z_index = self.z_index self.player_health_bar.pos.x = (self.size.x - self.player_health_bar.size.x) / 2 self.player_health_bar.pos.y = self.size.y - self.player_health_bar.size.y - 10 self.player_health_lbl = Lable(self, Vector2(10, 10)) self.player_health_lbl.z_index = self.z_index self.player_health_lbl.pos.y = self.player_health_bar.pos.y - self.player_health_lbl.size.y - 5 self.score_lbl = Lable(self, Vector2(10, 10)) self.score_lbl.z_index = self.z_index self.timer_lbl = Lable(self, Vector2(10, 10)) self.timer_lbl.z_index = self.z_index self.kill_count_lbl = Lable(self, Vector2(10, 10)) self.kill_count_lbl.z_index = self.z_index self.buff_panel = BuffPanel(self) self.buff_panel.z_index = self.z_index + 1 self.buff_panel.visible = False pause_btn = Button(self, Vector2(10, 10), "暂停") pause_btn.visible = False pause_btn.can_paused = False pause_btn.hot_keys.append(pygame.K_ESCAPE) def _on_pause_btn_pressed(): if self.over_panel.visible: return if self.buff_panel.visible: return self.get_root().pause(not self.get_root().is_paused()) pause_btn.pressed_singal.connect(_on_pause_btn_pressed) self.over_panel = GameOverPanel(self) self.over_panel.z_index = self.z_index + 1 def update(self, delta: float) -> None: self.player_health_bar.health = self.player.health lbl_text = f"{self.player.health}/{self.player.max_health}" self.player_health_lbl.set_text(lbl_text) self.player_health_lbl.pos.x = (self.size.x - self.player_health_lbl.size.x) / 2 self.score_lbl.set_text(f"分数: {self.player.score}") self.timer_lbl.pos.x = (self.size.x - self.timer_lbl.size.x) / 2 self.kill_count_lbl.pos.x = self.size.x - self.kill_count_lbl.size.x - 10 self.kill_count_lbl.set_text(f"击杀: {self.player.kill_count}") def _convert_time(self, time: int) -> str: minutes = time // 60 seconds = time % 60 return f"{minutes:02}:{seconds:02}" def update_timer_lbl(self, offset: int) -> None: self.timer_lbl.set_text(f"{self._convert_time(int(self.get_root().get_ticks(offset) / 1000))}") class MainScene(Node2D): def __init__(self, root: Root): super().__init__(root, Vector2(0, 0), Vector2(pygame.display.get_surface().get_size())) self.z_index = 0 self.max_enemy_count = 10 self.create_enemies_range = 100 self.update_buff_time = 10 self.enemy_health = 500 self.enemy_speed = 80 Cursor(self) self.player = Player(self, self.size / 2) self.enemies = Node2D(self, Vector2(0, 0), Vector2(0, 0)) self.top_ui = TopUI(self) self.player.died_signal.connect(self.game_over) self.top_ui.over_panel.restart_bnt.pressed_singal.connect(self._on_game_over_btn_pressed) self.start_time = self.get_root().get_ticks() self.over_time = 0 def update(self, delta: float) -> None: self.top_ui.update_timer_lbl(-self.over_time) if len(self.enemies.children) < self.max_enemy_count: pos = Vector2() flag = random.randrange(0, 4) if flag == 0: pos = Vector2(random.randint(0, self.size.x), random.randint(-self.create_enemies_range, 0)) elif flag == 1: pos = Vector2(random.randint(0, self.size.x), random.randint(self.size.y, self.size.y + self.create_enemies_range)) elif flag == 2: pos = Vector2(random.randint(-self.create_enemies_range, 0), random.randint(0, self.size.y)) else: pos = Vector2(random.randint(self.size.x, self.size.x + self.create_enemies_range), random.randint(0, self.size.y)) enemy = Enemy(self.enemies, pos) enemy.max_health = self.enemy_health enemy.health = self.enemy_health enemy.speed = self.enemy_speed for enemy in self.enemies.children[:]: if enemy.health <= 0: self.enemies.remove_child(enemy) if self.get_root().get_ticks() - self.start_time >= self.update_buff_time * 1000: if int((self.get_root().get_ticks() - self.start_time) / 1000) % self.update_buff_time == 0: self.get_root().pause(True) self.top_ui.buff_panel.display() self.enemy_health += 100 self.enemy_speed += 5 self.start_time = self.get_root().get_ticks() def game_over(self) -> None: self.get_root().pause(True) self.top_ui.over_panel.visible = True self.over_time = self.get_root().get_ticks() def _on_game_over_btn_pressed(self) -> None: self.get_root().pause(False) self.player.restore_init_data() self.enemy_health = Enemy.init_data["health"] self.enemy_speed = Enemy.init_data["speed"] self.enemies.remove_all_children() self.player.gun.remove_all_children() self.top_ui.over_panel.visible = False self.start_time = self.get_root().get_ticks() class Game: def __init__(self): self.screen = pygame.display.set_mode((1280, 720)) self.clock = pygame.time.Clock() self.running = True self.root = Root() self.root.clear_color = Color(47, 47, 47) MainScene(self.root) def run(self) -> None: while self.running: self.clock.tick(120) for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False self.screen.fill(self.root.clear_color) delta = self.clock.get_time() / 1000 self.root.update(delta) for node in sorted(self.root.get_all_children(), key=lambda node: node.z_index): if self.root.is_paused() and node.can_paused: if node.visible: node.draw(self.screen) continue node.update(delta) if node.visible: node.draw(self.screen) if isinstance(node, Bullet): for other_node in self.root.get_all_children(): if node.parent == other_node: continue if not isinstance(other_node, Enemy): continue if node.collision_rect.colliderect(other_node.collision_rect): other_node.has_collided_signal.emit(node) if not node.can_penetrate: break if isinstance(node, Player): for other_node in self.root.get_all_children(): if not isinstance(other_node, Enemy): continue if node.collision_rect.colliderect(other_node.collision_rect): other_node.has_collided_signal.emit(node) pygame.display.flip() pygame.quit() Game().run()
cliegc/simple-roguelike-game
main.py
main.py
py
32,075
python
en
code
0
github-code
6
35912386575
#coding=utf-8 """ imgcv """ from setuptools import setup from setuptools import find_packages install_requires = [ ] setup( name = "imgcv", version = "1.0.0", description = 'image computer visior', author='Hyxbiao', author_email="[email protected]", packages = find_packages(), entry_points={ 'console_scripts': [ 'imgcv = imgcv.tools.imgcv:main', 'imgbrowser = imgcv.tools.imgbrowser:main', ] }, install_requires = install_requires, zip_safe = False, )
hyxbiao/imgcv
setup.py
setup.py
py
537
python
en
code
0
github-code
6
16294942824
import functools import os import re import requests import csv import sys from datetime import time, timedelta import argparse #print(response.json()) class event_type: GOAL = 0 PENALTY = 1 ASSIST = 2 class game_event: def toPeriod(self, int_period): int_period = int(int_period) if int_period == 1: return str(int_period) + 'st' elif int_period == 2: return str(int_period) + 'nd' elif int_period == 3: return str(int_period) + 'rd' else: return str(int_period) + 'th' def __init__(self, id, name, start_time, end_time, period, participant, partNumber, event_type, penalty_duration = 0, event_subtype = ''): self.id = id self.name = name self.participant = participant self.partNumber = partNumber self.start_time = start_time self.end_time = end_time self.period = self.toPeriod(period) self.event_type = event_type self.event_subtype = event_subtype self.penalty_duration = penalty_duration def score_sort(item1, item2): if(item1.period < item2.period or (item1.period == item2.period and item1.start_time >= item2.start_time)): return -1 else: return 1 class score_track: def __init__(self): self.scores_ = [] def add_score(self, score): self.scores_.append(score) self.scores_ = sorted(self.scores_, key=functools.cmp_to_key(score_sort)) def score_str(self, period, time, team1, team2): dict = {team1: 0, team2: 0} for score in filter(lambda x: x.event_type == event_type.GOAL, self.scores_): if score.period > period or (score.period == period and score.start_time < time): continue dict[score.name] += 1 vals = list(dict.values()) return '' + str(vals[0]) + ' -- ' + str(vals[1]) def collectGameTime(dateObj): return timedelta(minutes=int(dateObj['minutes']), seconds=int(dateObj['seconds'])) def computePenalty(start, dur): if start.seconds <= dur.seconds: return timedelta(minutes=0, seconds=0) return start - dur def obtainGoalCode(dict): if dict['isPowerplay']: return 'PPG' elif dict['isShorthanded']: return 'SHG' elif dict['isEmptyNet']: return 'ENG' elif dict['isPenaltyShot']: return 'PSG' else: return 'REG' def writeGameToFile(hockey_csv, response, date): rj = response.json() idTeamName = {} out_writer = csv.writer(hockey_csv) for team in rj['teams']: idTeamName[team['id']] = team['name'] teamNames = list(idTeamName.values()) scores = score_track() for goal in rj['goals']: scores.add_score(game_event(goal['teamId'], idTeamName[goal['teamId']], collectGameTime(goal['gameTime']), collectGameTime(goal['gameTime']), goal['gameTime']['period'], goal['participant']['fullName'], goal['participant']['number'], event_type.GOAL, 0, obtainGoalCode(goal))) for assist in goal['assists']: scores.add_score(game_event(goal['teamId'], idTeamName[goal['teamId']], collectGameTime(goal['gameTime']), collectGameTime(goal['gameTime']), goal['gameTime']['period'], assist['fullName'], assist['number'], event_type.ASSIST, 0, obtainGoalCode(goal))) for pen in rj['penalties']: pen_period = int(pen['gameTime']['period']) pen_starttime = collectGameTime(pen['gameTime']) pen_endtime = pen_starttime pen_duration = 0 if 'description' in pen['duration']: pen_duration = int(re.findall("\d+", pen['duration']['description'])[0]) pen_endtime = computePenalty(collectGameTime(pen['gameTime']), timedelta(minutes=pen_duration)) scores.add_score(game_event(pen['teamId'], idTeamName[pen['teamId']], pen_starttime, pen_endtime , pen_period, pen['participant']['fullName'], pen['participant']['number'], event_type.PENALTY, pen_duration, pen['infraction'])) if pen_starttime.total_seconds() < pen_duration * 60 and pen_period < 3: carryover_start = timedelta(minutes=20, seconds=0) carryover_duration = timedelta(minutes=pen_duration) - pen_starttime carryover_endtime = carryover_start - carryover_duration scores.add_score(game_event(pen['teamId'], idTeamName[pen['teamId']], carryover_start, carryover_endtime, pen_period + 1, pen['participant']['fullName'], pen['participant']['number'], event_type.PENALTY, pen_duration, pen['infraction'])) for score in scores.scores_: if score.event_type == event_type.GOAL: out_writer.writerow([teamNames[0], teamNames[1], date, 'GOAL', score.event_subtype, score.participant, score.partNumber, score.name, score.start_time, score.end_time, score.period, 0, scores.score_str(score.period, score.start_time, teamNames[0], teamNames[1])]) if score.event_type == event_type.ASSIST: out_writer.writerow([teamNames[0], teamNames[1], date, 'ASSIST', score.event_subtype, score.participant, score.partNumber, score.name, score.start_time, score.end_time, score.period, 0, scores.score_str(score.period, score.start_time, teamNames[0], teamNames[1])]) if score.event_type == event_type.PENALTY: out_writer.writerow([teamNames[0], teamNames[1], date, 'PENALTY', score.event_subtype, score.participant, score.partNumber, score.name, score.start_time, score.end_time, score.period, score.penalty_duration, scores.score_str(score.period, score.start_time, teamNames[0], teamNames[1])]) def main(): parser = argparse.ArgumentParser('Collect data from VIAHA webpage and dump to csv spreadsheets.') parser.add_argument('-s','--separate', dest='separate', action='store_const', const=True, default=False, help='If enabled, games will be split into separate files.') parser.add_argument('scheduleId', type=int, nargs='?', help='Provide the ID of the schedule for the games you want to collect.') parser.add_argument('teamId', type=int, nargs='?', help='Provide the team you are interested in from the provided schedule') args=parser.parse_args() if args.scheduleId is None or args.teamId is None: raise Exception('Cannot run script without a schedule and team ID') gameId = sys.argv[1] scheduleUrl = 'https://api.hisports.app/api/games' paramStr = '?filter={{"where":{{"and":[{{"scheduleId":{}}},{{"or":[{{"homeTeamId":{}}},{{"awayTeamId":{}}}]}}]}},"include":["arena","schedule","group","teamStats"],"order":["startTime ASC","id DESC"],"limit":null,"skip":null}}'.format(args.scheduleId, args.teamId, args.teamId) headers = {'authorization' : 'API-Key f75fa549e81421f19dc929bc91f88820b6d09421'} sess = requests.Session() req = requests.Request('GET', scheduleUrl, headers=headers) prep = req.prepare() prep.url += paramStr resp = sess.send(prep) collectfilename = 'games-season-{}-{}-{}.csv'.format(resp.json()[0]['seasonId'], args.scheduleId, args.teamId) if args.separate == False: if os.path.isfile(collectfilename): os.remove(collectfilename) with open(collectfilename, 'a') as file: out_writer = csv.writer(file) out_writer.writerow(['Home Team', 'Away Team', 'Date', 'Event', 'Event Type', 'Player Name', 'Player Number', 'Player Team', 'Start Time', 'End Time', 'Period', 'Penalty Mins', 'Score']) for game in resp.json(): gameUrl = 'https://api.hisports.app/api/games/{}/boxScore'.format(game['id']) req = requests.Request('GET', gameUrl, headers=headers) resp = sess.send(req.prepare()) if args.separate: with open('game-{}-{}-{}.csv'.format(game['date'], args.scheduleId, args.teamId), 'w+') as file: out_writer = csv.writer(file) out_writer.writerow(['Home Team', 'Away Team', 'Date', 'Event', 'Event Type', 'Player Name', 'Player Number', 'Player Team', 'Start Time', 'End Time', 'Period', 'Penalty Mins', 'Score']) writeGameToFile(file, resp, game['date']) else: with open(collectfilename, 'a') as file: writeGameToFile(file, resp, game['date']) if __name__ == '__main__': main()
SolidSnackDrive/hockepy_viaha
hockey.py
hockey.py
py
8,307
python
en
code
0
github-code
6
856594294
from __future__ import division from vistrails.db.domain import DBPEFunction, DBPEParameter from vistrails.core.paramexplore.param import PEParam import copy import unittest from vistrails.db.domain import IdScope ################################################################################ class PEFunction(DBPEFunction): """ Stores a function for a parameter exploration """ ########################################################################## # Constructors and copy def __init__(self, *args, **kwargs): DBPEFunction.__init__(self, *args, **kwargs) if self.id is None: self.id = -1 if self.module_id is None: self.module_id = -1 if self.port_name is None: self.port_name = "" if self.is_alias is None: self.is_alias = 0 self.set_defaults() def set_defaults(self, other=None): pass def __copy__(self): """ __copy__() -> ModuleFunction - Returns a clone of itself """ return PEFunction.do_copy(self) def do_copy(self, new_ids=False, id_scope=None, id_remap=None): cp = DBPEFunction.do_copy(self, new_ids, id_scope, id_remap) cp.__class__ = PEFunction cp.set_defaults(self) return cp @staticmethod def convert(_function): if _function.__class__ == PEFunction: return _function.__class__ = PEFunction for _parameter in _function.db_get_parameters(): PEParam.convert(_parameter) _function.set_defaults() ########################################################################## # Properties id = DBPEFunction.db_id module_id = DBPEFunction.db_module_id port_name = DBPEFunction.db_port_name is_alias = DBPEFunction.db_is_alias def _get_params(self): self.db_parameters.sort(key=lambda x: x.db_pos) return self.db_parameters def _set_params(self, params): self.db_parameters = params parameters = property(_get_params, _set_params) params = property(_get_params, _set_params) def add_parameter(self, param): self.db_add_parameter(param) addParameter = add_parameter def add_parameters(self, params): for p in params: self.db_add_parameter(p) ########################################################################## # Operators def __str__(self): """ __str__() -> str - Returns a string representation of itself """ return ("<PEFunction id=%s module_id=%s port_name='%s' is_alias=%s params=%s)@%X" % (self.id, self.module_id, self.port_name, self.is_alias, [str(p) for p in self.params], id(self))) def __eq__(self, other): """ __eq__(other: ModuleFunction) -> boolean Returns True if self and other have the same attributes. Used by == operator. """ if type(self) != type(other): return False if self.port_name != other.port_name: return False if self.module_id != other.module_id: return False if self.is_alias != other.is_alias: return False if len(self.params) != len(other.params): return False for p,q in zip(self.params, other.params): if p != q: return False return True def __ne__(self, other): """ __ne__(other: ModuleFunction) -> boolean Returns True if self and other don't have the same attributes. Used by != operator. """ return not self.__eq__(other) ################################################################################ # Testing class TestModuleFunction(unittest.TestCase): def create_function(self, id_scope=IdScope()): param = PEParam(id=id_scope.getNewId(PEParam.vtType), pos=2, interpolator='Stepper', dimension=4, value='[1, 2]') function = PEFunction(id=id_scope.getNewId(PEFunction.vtType), module_id=7, port_name='value', is_alias=0, parameters=[param]) return function def test_copy(self): id_scope = IdScope() f1 = self.create_function(id_scope) f2 = copy.copy(f1) self.assertEquals(f1, f2) self.assertEquals(f1.id, f2.id) f3 = f1.do_copy(True, id_scope, {}) self.assertEquals(f1, f3) self.assertNotEquals(f1.id, f3.id) def testComparisonOperators(self): f = self.create_function() g = self.create_function() self.assertEqual(f, g) g.module_id = 1 self.assertNotEqual(f, g) g.module_id = 7 g.port_name = "val" self.assertNotEqual(f, g) g.port_name = "value" g.is_alias = 1 self.assertNotEqual(f, g) def test_str(self): str(self.create_function()) if __name__ == '__main__': unittest.main()
VisTrails/VisTrails
vistrails/core/paramexplore/function.py
function.py
py
5,283
python
en
code
100
github-code
6
2056234872
import tensorflow as tf def accuracy(output, target, top_k=(1,)): """ output : [10, 6] target: [10] """ max_k = max(top_k) batch_size = target.shape[0] pred = tf.math.top_k(output, max_k).indices # [10, 6] pred = tf.transpose(pred, perm=[1, 0]) # [6, 10] to compare top_1, top_2,... between pred and target target = tf.broadcast_to(target, pred.shape) correct = tf.equal(pred, target) res = [] for k in top_k: correct_k = tf.cast(tf.reshape(correct[:k], [-1]), dtype=tf.float32) correct_k = tf.reduce_sum(correct_k) acc = float(correct_k * (100 / batch_size)) res.append(acc) return res output = tf.random.normal([10, 6]) output = tf.math.softmax(output, axis=1) target = tf.random.uniform([10], maxval=6, dtype=tf.int32) acc = accuracy(output, target, top_k=(1,2,3,4,5,6))
lykhahaha/Mine
Tf-tutorial/lesson16_topk.py
lesson16_topk.py
py
863
python
en
code
0
github-code
6
7811594670
from qiskit import * from qiskit.visualization import plot_histogram from qiskit.visualization import plot_state_city, plot_bloch_multivector from qiskit.visualization import plot_state_paulivec, plot_state_hinton from qiskit.visualization import plot_state_qsphere # quantum circuit to make a Bell state bell = QuantumCircuit(2, 2) bell.h(0) bell.cx(0, 1) meas = QuantumCircuit(2, 2) meas.measure([0,1], [0,1]) # execute the quantum circuit backend = BasicAer.get_backend('qasm_simulator') # the device to run on circ = bell.compose(meas) result = backend.run(transpile(circ, backend), shots=1000).result() counts = result.get_counts(circ) print(counts) #히스토그램 plot_histogram(counts) #히스토그램 그래프 옵션 # Execute 2-qubit Bell state again second_result = backend.run(transpile(circ, backend), shots=1000).result()#트랜스파일: 서킷(cric)을 벡엔드로 소스코드를 변환한다. second_counts = second_result.get_counts(circ) # Plot results with legend legend = ['First execution', 'Second execution']#히스토그램에 레이블 지정 plot_histogram([counts, second_counts], legend=legend, figsize=(15,12), color=['red', 'blue'], bar_labels=False)#figsize :그래프 사이즈 설정 #마치 건물처럼 표현하는 그래프 backend = BasicAer.get_backend('statevector_simulator') # the device to run on result = backend.run(transpile(bell, backend)).result() psi = result.get_statevector(bell) plot_state_city(psi) #힌튼 plot_state_hinton(psi) #qsphere 상태 벡터의 진폭과 위상이 구체에 그려지는 양자 상태 plot_state_qsphere(psi) #블로흐 구면 plot_bloch_multivector(psi)
xhaeng06x/quantum_computing
codingproject/whatsyoureta/ETA_3Qiskit 시각화하기/ETA-3 여러가지 시각화 도구main.py
ETA-3 여러가지 시각화 도구main.py
py
1,705
python
en
code
0
github-code
6
22525757483
""" Author: Matthew Smith (45326242) Date: 15/04/2021 Title: AERO4450 Design Report Progress Check """ import numpy as np import matplotlib.pyplot as plt import math import scipy.sparse as sps import scipy.sparse.linalg as splinalg # Parameters M_N2 = 28 # g/mol M_F2 = 44 # g/mol M_O2 = 32 # g/mol mdot_a = 900 # g/s mdot_f = 30 # g/s T_in = 800 # K T_act = 40000 # K A = 5*10**11 # (1/s) T_ref = 298.15 # K # Thermodynamic Properties (formation enthalpy,Cp) P = {'F2': (0,2000), 'FO2': (-12,2200), 'O2': (0,1090), 'N2': (0,1170) } # Preliminaries # Task 1 b = (0.77*M_O2)/(0.23*M_N2) m_air = 2*M_O2/0.23 Zst = M_F2/(M_F2 + m_air) AFst = m_air/M_F2 Zavg = mdot_f/(mdot_a + mdot_f) AFavg = mdot_a/mdot_f print("Zst =",Zst) print("AFst =",AFst) print("Zavg =",Zavg) print("AFavg =",AFavg) # Task 2 Y_pc_max = 2*(M_F2/2 + M_O2)/(2*b*M_N2 + 2*(M_F2/2 + M_O2)) # Define the piecewise function Ypc(Z) def Y_pc(Z): if Z <= Zst: grad = Y_pc_max/Zst c = 0 Y = grad*Z + c if Z > Zst: grad = -Y_pc_max/(1-Zst) c = -grad Y = grad*Z + c return Y # Plot Y_pc(Z) plt.figure(figsize=(10,8)) plt.plot([0,Zst],[0,Y_pc_max],'b-') plt.plot([Zst,1],[Y_pc_max,0],'b-') plt.plot([0,Zst],[Y_pc_max,Y_pc_max],'r--') plt.plot([Zst,Zst],[0,Y_pc_max],'r--') plt.xticks([0.0,0.137,0.2,0.4,0.6,0.8,1.0]) plt.yticks([0.0,0.2,0.335,0.4,0.6,0.8,1.0]) plt.xlabel("Mixture Fraction (Z)") plt.ylabel("Mass Fraction (Y)") plt.title("Mass Fraction of FO2 vs. Mixture Fraction") plt.xlim(0,1) plt.ylim(0,1) plt.show() print("Ymax =",Y_pc_max) # Task 4 # Find ao and af ao = M_O2/(M_F2/2 + M_O2) af = 0.5*M_F2/(M_F2/2 + M_O2) print("ao =",ao) print("af =",af) def Y_O2(Z,Y_FO2): Y = 0.23*(1-Z) - ao*Y_FO2 # Ensure that Y is non-negative if Y < 0: return 0 else: return Y def Y_F2(Z,Y_FO2): Y = Z - af*Y_FO2 # Ensure that Y is non-negative if Y < 0: return 0 else: return Y # YN2 is a conserved scalar def Y_N2(Z): return 0.77*(1-Z) # Sum of all Y's should be 1 def Y_Total(Z,Y_FO2): return Y_O2(Z,Y_FO2) + Y_N2(Z) + Y_F2(Z,Y_FO2) + Y_FO2 # Create lists for all mass fractions Zs = np.linspace(0,1,200) O2 = [Y_O2(Z,Y_pc(Z)) for Z in Zs] F2 = [Y_F2(Z,Y_pc(Z)) for Z in Zs] N2 = [Y_N2(Z) for Z in Zs] FO2 = [Y_pc(Z) for Z in Zs] Total = [Y_Total(Z,Y_pc(Z)) for Z in Zs] # Plot the mass fractions vs. Z plt.figure(figsize=(10,8)) plt.plot(Zs,O2,'c-',label='O2') plt.plot(Zs,F2,'m-',label='F2') plt.plot(Zs,N2,'g-',label='N2') plt.plot(Zs,Total,'k-',label='Sum') plt.plot(Zs,FO2,'b-',label='FO2') plt.plot([Zst,Zst],[0,1],'r--',label='Zst') plt.xlabel("Mixture Fraction (Z)") plt.ylabel("Mass Fraction (Y)") plt.xlim(0,1) plt.ylim(0,1.1) plt.yticks([0.0,0.2,0.23,0.4,0.6,0.77,0.8,1.0]) plt.legend() plt.show() # Task 5 def phi(prop,Z,c): # Y_FO2 depends on combustion progress Y_FO2 = c*Y_pc(Z) # Define formation enthalpy if prop == 'h_f': val = (P['F2'][0]*Y_F2(Z,Y_FO2) + P['FO2'][0]*Y_FO2 + P['O2'][0]*Y_O2(Z,Y_FO2) + P['N2'][0]*Y_N2(Z))*10**6 # Define heat capacity if prop == 'Cp': val = (P['F2'][1]*Y_F2(Z,Y_FO2) + P['FO2'][1]*Y_FO2 + P['O2'][1]*Y_O2(Z,Y_FO2) + P['N2'][1]*Y_N2(Z)) # Define total enthalpy if prop == 'h': val = phi('h_f',Z,c)*Y_FO2 + (T_in - T_ref)*phi('Cp',Z,c) return val # Task 6 # TotaL enthalpy is a conserved scalar def h(Z,c): return phi('h',0,c) + Z*(phi('h',1,c) - phi('h',0,c)) def T(Z,c): return T_ref + (h(Z,c) - phi('h_f',Z,c))/phi('Cp',Z,c) def W(Z,c): Y_FO2 = c*Y_pc(Z) return Y_F2(Z,Y_FO2)*Y_O2(Z,Y_FO2)*A*np.exp(-T_act/T(Z,c)) # Task 7 Zs = np.linspace(0,1,500) # Plot the temperature vs. Z for different combustion progresses plot1 = [] plot2 = [] plot3 = [] plot4 = [] for z in Zs: for c in [0,1/3,2/3,1]: if c == 1/3: plot1.append(T(z,c)) if c == 2/3: plot2.append(T(z,c)) if c == 0: plot3.append(T(z,c)) if c == 1: plot4.append(T(z,c)) plt.figure(figsize=(10,8)) plt.plot(Zs,plot1,'r-',label='c = 1/3') plt.plot(Zs,plot2,'b-',label='c = 2/3') plt.plot(Zs,plot3,'g-',label='c = 0') plt.plot(Zs,plot4,'m-',label='c = 1') plt.title('Temperature vs. Z for Different c Values') plt.xlabel('Mixture Fraction (Z)') plt.ylabel('Temperature (K)') plt.xlim(0,1) plt.ylim(500,3500) plt.yticks([500,800,1000,1500,2000,2500,3000,3500]) plt.legend() plt.show() # Plot the reaction rate vs. Z for different combustion progresses plot1 = [] plot2 = [] for z in Zs: for c in [1/3,2/3]: if c == 1/3: plot1.append(W(z,c)) if c == 2/3: plot2.append(W(z,c)) plt.figure(figsize=(10,8)) plt.plot(Zs,plot1,'r-',label='c = 1/3') plt.plot(Zs,plot2,'b-',label='c = 2/3') plt.title('Reaction Rate vs. Z for Different c Values') plt.xlabel('Mixture Fraction (Z)') plt.ylabel('W (1/s)') plt.xlim(0,1) plt.legend() plt.show() # Flamelet Model # Task 1 nZ = 101 dZ = 1/(nZ-1) Z_values = np.linspace(0,1,nZ) # Define flamelet model that output the steady-state mass fractions for a given # Nst def flamelet_model(Nst): W_max = 500 # Set time-step and CFL number dt = 0.01/W_max CFL = dt*Nst/(dZ**2) t = 0 # Initial conditions current_Y = np.array([Y_pc(z) for z in Z_values]) # Initial reaction rates current_W = np.zeros(nZ) for i in range(1,nZ-1): c = current_Y[i]/Y_pc(i*dZ) current_W[i] = W(i*dZ,c) # Define implicit coefficient matrix implicit_matrix = ((1+2*CFL) * sps.eye(nZ, k=0) -CFL * sps.eye(nZ, k=-1) -CFL * sps.eye(nZ, k=+1)) # Dirichlet boundary conditions B = implicit_matrix.tolil() B[0,:], B[nZ-1,:] = 0, 0 B[0,0], B[nZ-1,nZ-1] = 1, 1 implicit_matrix = B.tocsr() # Begin general updates until steady-state solution is achieved or FO2 goes # extinct previous_Y = np.zeros(nZ) while abs(np.amax(current_Y) - np.amax(previous_Y)) > 1*10**-7: t += dt previous_Y = current_Y.copy() # Use sparse matrix solver current_Y = splinalg.spsolve(implicit_matrix,(previous_Y+current_W*dt)) # Update reaction rates for i in range(1,nZ-1): c = current_Y[i]/Y_pc(i*dZ) current_W[i] = W(i*dZ,c) print('Number of time steps used =', t/dt) return current_Y # Task 2 # Show steady-state solution for Nst = 30 (subcritical) Y_ss = flamelet_model(30) Ypc = [Y_pc(Z) for Z in Z_values] plt.figure(figsize=(10,8)) plt.plot(Z_values,Y_ss,'b-',label='Steady-State Solution') plt.plot(Z_values,Ypc,'r--',label='Y_pc(Z)') plt.title('Mass Fraction of FO2 vs. Mixture Fraction for Nst = 30') plt.xlabel('Mixture Fraction (Z)') plt.ylabel('Mass Fraction (Y)') plt.xlim(0,1) plt.ylim(0,0.4) plt.legend() plt.show() # Task 3 # Golden ratio gr = (math.sqrt(5) + 1) / 2 # Define Golden-Section Search function def gss(f, a, b, tol=0.01): # Find initial c and d values c = b - (b - a) / gr d = a + (b - a) / gr while abs(b - a) > tol: # If f(c) goes to extinction, return 100 if np.amax(f(c)) < 10**-3: x = 100 # If f(c) reaches steady-state, return max Y_FO2 else: x = np.amax(f(c)) # If f(d) goes to extinction, return 100 if np.amax(f(d)) < 10**-3: y = 100 # If f(d) reaches steady-state, return max Y_FO2 else: y = np.amax(f(d)) # When f(c) and f(d) go to extinction, a = a, b = c if x and y == 100: b = c c = b - (b - a) / gr d = a + (b - a) / gr continue # When f(c) and f(d) both have a steady solution, a = d, b = b if x and y > 10**-3: a = d c = b - (b - a) / gr d = a + (b - a) / gr continue # If f(c) < f(d), b = d, a = a if x < y: b = d else: a = c c = b - (b - a) / gr d = a + (b - a) / gr return (b + a) / 2 #print(gss(flamelet_model,50.5,51,tol=0.01)) # ^^ uncomment this if you want to see the golden search result # It takes roughly 5 mins to run though # Critical value found form golden search Ncr = 50.64387 print('Ncr =',Ncr) # Plot critical solution Y_ss = flamelet_model(Ncr) Ypc = [Y_pc(Z) for Z in Z_values] plt.figure(figsize=(10,8)) plt.plot(Z_values,Y_ss,'b-',label='Steady-State Solution') plt.plot(Z_values,Ypc,'r--',label='Y_pc(Z)') plt.title('Mass Fration of FO2 vs. Mixture Fraction for Ncr') plt.xlabel('Mixture Fraction (Z)') plt.ylabel('Mass Fraction (Y)') plt.xlim(0,1) plt.ylim(0,0.4) plt.legend() plt.show() # Plot critical temperatures Temps = np.zeros(nZ) Temps[0] = T(0,0) Temps[nZ-1] = T(1,0) for i in range(1,nZ-1): c = Y_ss[i]/Y_pc(i*dZ) Temps[i] = T(i*dZ,c) T_a = np.amax(Temps) plt.figure(figsize=(10,8)) plt.plot(Z_values,Temps,'b-') plt.plot([0,1],[T_a,T_a],'r--') plt.title('Temperature vs. Mixture Fraction') plt.xlabel('Mixture Fraction (Z)') plt.ylabel('Temperature (K)') plt.xlim(0,1) plt.ylim(750,3000) plt.yticks([750,1000,1250,1500,1750,2000,2250,2500,2750,2812.34,3000]) plt.show() print('Adiabatic Temp =',T_a) # Task 4 # Find residence time t_res = (Zavg - Zavg**2)/(2*Ncr) print('Residence Time =',t_res)
msmit677/AERO4450
AERO4450_Combustion_Modelling.py
AERO4450_Combustion_Modelling.py
py
9,866
python
en
code
0
github-code
6
17509582783
from treenode import TreeNode from tree_builder import build_tree, get_node class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': """use dfs to build path between root and given node""" def traverse(v, w, a): a.append(w) if v is w: return True if w.left and traverse(v, w.left, a): return True if w.right and traverse(v, w.right, a): return True a.pop() return False a = [] b = [] traverse(p,root,a) traverse(q,root,b) for u,v in zip(a,b): if u is v: res = u else: break return res.val tree = build_tree([3,5,1,6,2,0,8,None,None,7,4]) pp,qq=5,1 pp=get_node(tree,pp) qq=get_node(tree,qq) assert Solution().lowestCommonAncestor(tree,pp,qq) == 3 # pp,qq=5,4 # pp=get_node(tree,pp) # qq=get_node(tree,qq) # assert Solution().lowestCommonAncestor(tree,pp,qq) == 5
soji-omiwade/cs
dsa/before_rubrik/lowest_common_ancestor.py
lowest_common_ancestor.py
py
1,079
python
en
code
0
github-code
6
38649606721
import threading import time # 使用线程来执行类的成员函数,则类必须定义run方法,并且必须继承threading类 # 调用start的时候,自动调用run方法,run方法结束了,那么线程也结束了 class MyThread(threading.Thread): def run(seft): for i in range(3): time.sleep(1) msg = "I'm " + seft.name + ' @ ' + str(i) print(msg) if __name__ == "__main__": t = MyThread() t.start()
Vieran/network_programming
multi_process_or_thread/thread/demo3.py
demo3.py
py
475
python
zh
code
0
github-code
6
7143818426
from player import * from gameMap import * from creature import * from item import * from treasure import * import random as r fullMap = [] newMap = gameMap(20,20, fullMap) newPlayer = Player(2, 9, 9, 20, 5, "P") running = True numCreatures = 10 numTreasure = 30 numLocked = r.randint(0, numTreasure) numOpen = numTreasure - numLocked atkItem = r.randint(0, numTreasure) hpItem = numTreasure - atkItem hostCreatures = r.randint(0, numCreatures) passiveCreatures = numCreatures - hostCreatures creatures = [] treasures = [] items = [] for i in range(hostCreatures): creatures.append(Creature(r.randint(0,19), r.randint(0,19), r.randint(2,15), r.randint(1,10), True, "C")) for i in range(passiveCreatures): creatures.append(Creature(r.randint(0,19), r.randint(0,19), r.randint(2,15), r.randint(1,10), False, "C")) for i in range(atkItem): items.append(attackMod(r.randint(-3, 3))) for i in range(hpItem): items.append(healthMod(r.randint(-10, 10))) for i in range(numLocked): treasures.append(Treasure(r.randint(0,19), r.randint(0,19), r.randint(2,15), True, "T", items[0])) items.pop(0) for i in range(numOpen): treasures.append(Treasure(r.randint(0,19), r.randint(0,19), r.randint(2,15), False, "T", items[0])) items.pop(0) def checkMapItems(creatureList, treasureList): for a in creatureList: for b in treasureList: if a.x == b.x and a.y == b.y: a.x += 1 def playerPosition(mapList, player): posy = mapList.map[player.y] posy[player.x] = player.symbol def creaturePosition(mapList, player, creatureList): for i in creatureList: if i.alive == True: if i.x == player.x: if i.y == player.y: i.x += 1 posy = mapList.map[i.y] posy[i.x] = i.symbol if i.alive == False: creatureList.remove(i) def treasurePosition(mapList, player, treasureList): for i in treasureList: if i.open == False: if i.x == player.x: if i.y == player.y: i.x += 1 posy = mapList.map[i.y] posy[i.x] = i.symbol if i.open == True: i.giveItem(newPlayer) treasureList.remove(i) newMap.createMap() print("Welcome to this short interaction game") input("Input anything to start!: ") def update(): while running == True: newMap.clearOld() checkMapItems(creatures, treasures) playerPosition(newMap, newPlayer) creaturePosition(newMap, newPlayer, creatures) treasurePosition(newMap, newPlayer, treasures) newMap.showMap() print("P = Player, C = Creature, T = Treasure") print("Health: " + str(newPlayer.health)) print("Damage: " + str(newPlayer.damage)) print("Input Left, Right, Up or Down to move") print("Input anything else to skip") movement = input("Input: ") if movement.upper() == "LEFT": newPlayer.x -= 1 if movement.upper() == "RIGHT": newPlayer.x += 1 if movement.upper() == "UP": newPlayer.y -= 1 if movement.upper() == "DOWN": newPlayer.y += 1 else: pass print("Input Attack or Interact") action = input("Input: ") print("Input Direction (Left, Right, Up or Down)") direction = input("Direction: ") if action.upper() == "ATTACK": if direction.upper() == "LEFT": for i in creatures: if i.x == newPlayer.x - 1 and i.y == newPlayer.y: i.health -= newPlayer.damage print("Creature Health Remaining:" + str(i.health)) i.update() for i in treasures: if i.x == newPlayer.x - 1 and i.y == newPlayer.y: i.health -= newPlayer.damage print("Treasure Health Remaining:" + str(i.health)) i.update() if direction.upper() == "RIGHT": for i in creatures: if i.x == newPlayer.x + 1 and i.y == newPlayer.y: i.health -= newPlayer.damage print("Creature Health Remaining:" + str(i.health)) i.update() for i in treasures: if i.x == newPlayer.x + 1 and i.y == newPlayer.y: i.health -= newPlayer.damage print("Treasure Health Remaining:" + str(i.health)) i.update() if direction.upper() == "UP": for i in creatures: if i.x == newPlayer.x and i.y == newPlayer.y - 1: i.health -= newPlayer.damage print("Creature Health Remaining:" + str(i.health)) i.update() for i in treasures: if i.x == newPlayer.x and i.y == newPlayer.y - 1: i.health -= newPlayer.damage print("Treasure Health Remaining:" + str(i.health)) i.update() if direction.upper() == "DOWN": for i in creatures: if i.x == newPlayer.x and i.y == newPlayer.y + 1: i.health -= newPlayer.damage print("Creature Health Remaining:" + str(i.health)) i.update() for i in treasures: if i.x == newPlayer.x and i.y == newPlayer.y + 1: i.health -= newPlayer.damage print("Treasure Health Remaining:" + str(i.health)) i.update() if action.upper() == "INTERACT": if direction.upper() == "LEFT": for i in creatures: if i.x == newPlayer.x - 1 and i.y == newPlayer.y: i.interact(newPlayer) for i in treasures: if i.x == newPlayer.x - 1 and i.y == newPlayer.y: i.tryOpen() i.update() i.giveItem(newPlayer) if direction.upper() == "RIGHT": for i in creatures: if i.x == newPlayer.x + 1 and i.y == newPlayer.y: i.interact(newPlayer) for i in treasures: if i.x == newPlayer.x + 1 and i.y == newPlayer.y: i.tryOpen() i.update() i.giveItem(newPlayer) if direction.upper() == "UP": for i in creatures: if i.x == newPlayer.x and i.y == newPlayer.y - 1: i.interact(newPlayer) for i in treasures: if i.x == newPlayer.x and i.y == newPlayer.y - 1: i.tryOpen() i.update() i.giveItem(newPlayer) if direction.upper() == "DOWN": for i in creatures: if i.x == newPlayer.x and i.y == newPlayer.y + 1: i.interact(newPlayer) for i in treasures: if i.x == newPlayer.x and i.y == newPlayer.y + 1: i.tryOpen() i.update() i.giveItem(newPlayer) else: pass update() #def (target, posx, posy)
HydraHYD/OOP-Final
application.py
application.py
py
7,659
python
en
code
0
github-code
6
33042404005
"""Helpers for tests.""" import json import pytest from .common import MQTTMessage from tests.async_mock import patch from tests.common import load_fixture @pytest.fixture(name="generic_data", scope="session") def generic_data_fixture(): """Load generic MQTT data and return it.""" return load_fixture("ozw/generic_network_dump.csv") @pytest.fixture(name="light_data", scope="session") def light_data_fixture(): """Load light dimmer MQTT data and return it.""" return load_fixture("ozw/light_network_dump.csv") @pytest.fixture(name="sent_messages") def sent_messages_fixture(): """Fixture to capture sent messages.""" sent_messages = [] with patch( "homeassistant.components.mqtt.async_publish", side_effect=lambda hass, topic, payload: sent_messages.append( {"topic": topic, "payload": json.loads(payload)} ), ): yield sent_messages @pytest.fixture(name="light_msg") async def light_msg_fixture(hass): """Return a mock MQTT msg with a light actuator message.""" light_json = json.loads( await hass.async_add_executor_job(load_fixture, "ozw/light.json") ) message = MQTTMessage(topic=light_json["topic"], payload=light_json["payload"]) message.encode() return message @pytest.fixture(name="switch_msg") async def switch_msg_fixture(hass): """Return a mock MQTT msg with a switch actuator message.""" switch_json = json.loads( await hass.async_add_executor_job(load_fixture, "ozw/switch.json") ) message = MQTTMessage(topic=switch_json["topic"], payload=switch_json["payload"]) message.encode() return message @pytest.fixture(name="sensor_msg") async def sensor_msg_fixture(hass): """Return a mock MQTT msg with a sensor change message.""" sensor_json = json.loads( await hass.async_add_executor_job(load_fixture, "ozw/sensor.json") ) message = MQTTMessage(topic=sensor_json["topic"], payload=sensor_json["payload"]) message.encode() return message @pytest.fixture(name="binary_sensor_msg") async def binary_sensor_msg_fixture(hass): """Return a mock MQTT msg with a binary_sensor change message.""" sensor_json = json.loads( await hass.async_add_executor_job(load_fixture, "ozw/binary_sensor.json") ) message = MQTTMessage(topic=sensor_json["topic"], payload=sensor_json["payload"]) message.encode() return message @pytest.fixture(name="binary_sensor_alt_msg") async def binary_sensor_alt_msg_fixture(hass): """Return a mock MQTT msg with a binary_sensor change message.""" sensor_json = json.loads( await hass.async_add_executor_job(load_fixture, "ozw/binary_sensor_alt.json") ) message = MQTTMessage(topic=sensor_json["topic"], payload=sensor_json["payload"]) message.encode() return message
84KaliPleXon3/home-assistant-core
tests/components/ozw/conftest.py
conftest.py
py
2,850
python
en
code
1
github-code
6
5309163060
# 투포인터 def trap(heights): if not heights: return 0 volume = 0 left, right = 0, len(heights)-1 left_max, right_max = heights[left], heights[right] while left <= right: left_max, right_max = max(heights[left], left_max), max( heights[right], right_max) # 더 높은쪽으로 이동 if left_max <= right_max: volume += left_max - heights[left] left += 1 else: volume += right_max - heights[right] right -= 1 return volume # 스택 def trap2(heights): stack = [] # 인덱스 추가 volume = 0 for i in range(len(heights)): # 변곡점 만나는 경우 while stack and heights[i] > heights[stack[-1]]: # 스택에서 꺼내기 top = stack.pop() # 스택이 없으면 종료 if not len(stack): break # 이전과의 차이만큼 물높이 처리 distance = i - stack[-1] - 1 waters = min(heights[i], heights[stack[-1]]) - heights[top] volume += distance * waters stack.append(i) return volume
louisuss/Algorithms-Code-Upload
Python/Tips/questions/trapping_rain+.py
trapping_rain+.py
py
1,182
python
ko
code
0
github-code
6
34608382125
import sys import pygame from setting import Settings from setting import Ship import game_functions as gf def run_game(): # Initialize game and create a screen object. pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) ship = Ship(screen) pygame.display.set_caption("Andy and Mr. Umair's Rocket game") bg_color = (30,67,78) # Start the main loop for the game. while True: gf.check_events(ship) ship.update() # Watch for keyboard and mouse events. # Make the most recently drawn screen visible. gf.update_screen(ai_settings, screen, ship) run_game()
andy-miao-gu/preply_by_umair
old/okbruhpygame.py
okbruhpygame.py
py
749
python
en
code
0
github-code
6
20859673703
import pymunk import pymunk.pygame_util import pygame from classes.ammo.ammo_box import AmmoBox from classes.coin.coin import Coin import os import random import math from functions.math import get_xys, get_distance class Enemy: def __init__(self, game, space, radius, pos): self.game = game self.body = pymunk.Body() self.body.position = pos self.radius = 20 self.image = pygame.transform.scale(self.original_image, (radius * 2, radius * 2)) self.rect = self.image.get_rect() self.shape = pymunk.Circle(self.body, radius) self.shape.collision_type = game.collision_types["ENEMY"] self.shape.elasticity = 0.8 self.shape.friction = 1 self.shape.mass = radius / 10 self.shape.color = self.color space.add(self.body, self.shape) self.health_bar = pygame.surface.Surface((120, 30)) self.health_bar_size = (120, 30) self.s = 3 # IMPLEMENTING PATH FINDING # self.graph = graph self.game.graph.A_star( self.game.graph.map[round(self.body.position[0] // self.game.TILE_SIZE)][ round(self.body.position[1] // self.game.TILE_SIZE)], self.game.graph.map[round(self.game.player.body.position[0] // self.game.TILE_SIZE)][ round(self.game.player.body.position[1] // self.game.TILE_SIZE)] ) # print(self.game.graph.A_star( # self.game.graph.map[round(self.body.position[0] // self.game.TILE_SIZE)][ # round(self.body.position[1] // self.game.TILE_SIZE)], # self.game.graph.map[round(self.game.player.body.position[0] // self.game.TILE_SIZE)][ # round(self.game.player.body.position[1] // self.game.TILE_SIZE)] # )[self.game.graph.map[round(self.body.position[0] // self.game.TILE_SIZE)][ # round(self.body.position[1] // self.game.TILE_SIZE)]]) self.path = [] self.create_path() # print(len(self.path)) def create_path(self): routes = self.game.graph.A_star( self.game.graph.map[round(self.body.position[0] // self.game.TILE_SIZE)][ round(self.body.position[1] // self.game.TILE_SIZE)], self.game.graph.map[round(self.game.player.body.position[0] // self.game.TILE_SIZE)][ round(self.game.player.body.position[1] // self.game.TILE_SIZE)] ) node = routes[self.game.graph.map[round(self.game.player.body.position[0] // self.game.TILE_SIZE)][ round(self.game.player.body.position[1] // self.game.TILE_SIZE)]] while node is not None: self.path.append(node) node = routes[node] self.path.pop() def move(self): # for item in self.path: # x,y = self.game.get_position_by_player((item.x * self.game.TILE_SIZE, # item.y * self.game.TILE_SIZE)) # pygame.draw.rect(self.game.window, (0, 255, 0), # (round(x), round(y), self.game.TILE_SIZE, self.game.TILE_SIZE)) self.create_path() if len(self.path) <= 0: return xy = (self.path[-1].x * self.game.TILE_SIZE + self.game.TILE_SIZE / 2, self.path[-1].y * self.game.TILE_SIZE + self.game.TILE_SIZE / 2) xs, ys = get_xys(self.body.position, xy) self.body.position = (self.body.position.x + xs * self.s, self.body.position.y + ys * self.s) if get_distance(self.body.position, xy) < self.radius: self.path.pop() def update(self, game): self.rect.center = game.get_position_by_player(self.body.position) new_rect = self.image.get_rect(center=self.rect.center) game.window.blit(self.image, new_rect) def show_hp(self, game): pygame.draw.rect(self.health_bar, (0, 0, 0), (0, 0, self.health_bar_size[0], self.health_bar_size[1])) pygame.draw.rect(self.health_bar, (35, 189, 26), (2, 2, (self.health_bar_size[0] - 4) * (self.hp / self.max_hp), self.health_bar_size[1] - 4)) x, y = game.get_position_by_player(self.body.position) game.window.blit(self.health_bar, (x - 60, y - self.radius * 2 - 10)) # Call on delete def __del__(self): if random.random() > 0.6: ammo_type = ["light", "medium"][random.randrange(2)] self.game.ground_items.append(AmmoBox(self.game, self.body.position, ammo_type, random.randrange(1, 6))) for i in range(2): self.game.coins.append(Coin(self.game, (self.body.position.x + 100 * (random.random() - 0.5), self.body.position.y + (100 * random.random() * 0.5)))) self.game.space.remove(self.body, self.shape) def special_attack(self): pass class BasicEnemy(Enemy): color = (255, 250, 0, 100) original_image = pygame.image.load(os.path.join("imgs", "basic.png")) collision_damage = 5 spawn_cost = 2 def __init__(self, game, space, radius, pos): super().__init__(game, space, radius, pos) self.max_hp = 15 self.hp = 15
matej-kotrba/python-survival-game
classes/enemies/basic.py
basic.py
py
5,383
python
en
code
3
github-code
6
9771781643
#Brownian Motion Simulator #Simulate first on $R^1$ import numpy as np import numpy import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib.pyplot as plt def graph(points): data = np.array(points) fig = plt.figure() ax = fig.add_subplot(111) ax.scatter(data[:,0],data[:,1]) ax.set_xlabel("X") ax.set_ylabel("Y") plt.axis('scaled') plt.show() return def run1d(n): function = BMinterval(n) pointlist = convert(function) graph(pointlist) return def grapher(func): a = convert(func) graph(a) return def convert(func): a = [] for term in func: a.append([term, func[term]]) return a def BMinterval(n,startpos,starttime): #creates a 1-d Brownian motion on $[0,1]$ with $D_n$ dyadic level. B = {} i = 1 B[starttime] = startpos B[starttime + 1] = startpos + np.random.randn() while i < n: k = 0 while 2*k + 1 <= np.power(2,i): diadic = float(np.power(2,i)) d = (2*k + 1) / diadic B[starttime + d] = startpos + .5 * ( B[starttime + (d - 1 / diadic)] + B[starttime + (d + 1 / diadic)] - 2*startpos) + .5 * np.random.randn()/ diadic k = k + 1 i = i + 1 return B def BM(n,t): #creates a depth n brownian motion on [0,t], where t is an integer: i = 1 B = BMinterval(n,0,0) while i < t: B = dict(B.items() + BMinterval(n, B[i], i).items()) i = i + 1 return B def BM2d(n,t): B1 = BM(n,t) B2 = BM(n,t) list = [] for term in B1: list.append([B1[term],B2[term]]) return list def fracpart(number): return number - np.floor(number) def inbox(points): ##Returns percentage of in points that are (up to ZxZ) in a the box, [0,1/2]x[0,1/2] c = 0 for term in points: if (fracpart(term[0]) <= .5) and (fracpart(term[1]) <= .5): c = c + 1 return c / float(len(points)) def fold(points): new = [] for term in points: new.append([fracpart(term[0]),fracpart(term[1])]) return new def inint(points,k): c = 0 for term in points: if (fracpart(points[term])) <= k: c = c + 1 return c / float(len(points)) def fold2(points): new = [] for term in points: new.append([fracpart(points[term])]) return new
ElleNajt/TinyProjects
BrownianMotionSimulator.py
BrownianMotionSimulator.py
py
2,129
python
en
code
4
github-code
6
44137255205
#pip3 install wikiepdia-api #pip3 install elasticsearch #pip3 install nltk #pip3 install gensim #pip3 install pandas #pip3 install tabulate import pickle import wikipediaapi from model.WikiPage import WikiPage from elasticsearch import Elasticsearch import json from time import sleep import gensim from gensim import corpora, models import nltk from nltk.stem import WordNetLemmatizer, SnowballStemmer import pandas as pd from tabulate import tabulate nltk.download('stopwords') nltk.download('wordnet') wiki = wikipediaapi.Wikipedia('en', extract_format=wikipediaapi.ExtractFormat.WIKI) index = "ir_project" es = Elasticsearch() ################################################# PAGES DOWNLOAD AND INDEXING ########################################## def getPagesfromCategory(category, limit): pages = [] count = 0 for el in wiki.page(category).categorymembers.values(): if el.namespace == wikipediaapi.Namespace.MAIN: pages.append(WikiPage(el)) count += 1 print("{}) {} ".format(count, el)) if count >= limit: break print(category + ": download DONE") return pages def setNormalizedCitations(pages): numbers = [] for page in pages: numbers.append(page.citations) maximum = max(numbers) for page in pages: page.setCitationsNorm( round((page.citations - 0) / (maximum - 0), 4) ) return pages def getAllPages(limit): actors = getPagesfromCategory("Category:Golden Globe Award-winning producers", limit) guitar_companies = getPagesfromCategory("Category:Guitar manufacturing companies of the United States", limit) bands = getPagesfromCategory("Category:Grammy Lifetime Achievement Award winners", limit) pages = setNormalizedCitations(actors + guitar_companies + bands) # write collection to files pages_json = [] for page in pages: pages_json.append(dict(page)) with open('pages.json', 'w') as f: json.dump(pages_json, f, indent=4) def createIndex(data): # read index config from json file with open('index-config.json') as f: client_body = json.load(f) # wipe and create index if es.indices.exists(index): es.indices.delete(index=index) es.indices.create(index=index, ignore=400, body=client_body) for page in data: es.index(index=index, id=page["url"].replace(" ", "_"), body=page) ############################################## TOPIC MODELING ########################################################## def lemmatize_stemming(text): stemmer = SnowballStemmer('english') return stemmer.stem(WordNetLemmatizer().lemmatize(text, pos='v')) def preprocess(text): result = [] for token in gensim.utils.simple_preprocess(text): if token not in gensim.parsing.preprocessing.STOPWORDS and len(token) > 3: result.append(lemmatize_stemming(token)) return result def getTopics(recalculate): with open("pages.json", "r") as read_file: data = json.load(read_file) corpus = [] # list of strings: list of docs for page in data: corpus.append(page["abstract"]) processed_docs = [] # list of lists: list of tokenized docs for doc in corpus: processed_docs.append(preprocess(doc)) dictionary = gensim.corpora.Dictionary(processed_docs) dictionary.filter_extremes(no_below=5, keep_n=100000) if recalculate: print("Recalculating topics...") bow_corpus = [dictionary.doc2bow(doc) for doc in processed_docs] lda_model = gensim.models.LdaMulticore(bow_corpus, num_topics=3, id2word=dictionary, passes=2, workers=2) with open("lda_model.pk", 'wb') as pickle_file: pickle.dump(lda_model, pickle_file) else: with open("lda_model.pk", 'rb') as pickle_file: lda_model = pickle.load(pickle_file) # calculates topic for each document final_docs = [] for page in data: document = dictionary.doc2bow(preprocess(page["abstract"])) index, score = sorted(lda_model[document], key=lambda tup: -1 * tup[1])[0] page["topic"] = index final_docs.append(page) return(lda_model, final_docs) ################################################## SEARCH ################################################################ def print_results(results): df = pd.DataFrame(columns=['score', 'title', "citations", "citations_norm", "topic", "url"]) for hit in results['hits']['hits']: df.loc[len(df)] =[hit['_score'], hit['_source']['title'], hit['_source']['citations'],hit['_source']['citations_norm'], hit['_source']['topic'], hit['_source']['url']] print(tabulate(df, headers='keys', tablefmt='psql', showindex=False)) def search(query=None): results = es.search(index=index, body={ "from" : 0, "size" : 12, "query": {"match": query}}) print_results(results) def search_phrase(query=None): results = es.search(index=index, body={"query": {"match_phrase": query}}) print_results(results) def search_fuzzy(query): results = es.search(index=index, body={"query": {"fuzzy": query}}) print_results(results) def search_boolean(query): results = es.search(index=index, body={"query": {"bool": query}}) print_results(results) def search_with_topic(query, topic): results = es.search(index=index, body={"query": {"bool": {"must": { "match": query }, "filter": {"term": {"topic": topic}}}}}) print_results(results) def queries_samples(): print("\nquery: {query: {match: {abstract:is an american pianist}}}") print("Notes: it returns both alive and dead pianists (is/was) due to the analyzer") search(query={"abstract":"is an american pianist"}) print("\n\nquery: {query: {match_phrase: {text:was an american pianist}}}") print("Notes: it returns only dead pianist") search_phrase(query={"text":"was an american pianist"}) print("\n\nquery: {query: {match_phrase: {text:is an american pianist}}}") print("Notes: it returns only alive pianist") search_phrase(query={"text":"is an american pianist"}) print("\n\nquery: {query: {fuzzy: {title: {value: batles}}}}") print("Notes: it returns \"The Beatles\" despite the misspelling ") search_fuzzy(query={"title": {"value": "batles"}}) print("\n\nquery: {query: {bool: {must: {match: {abstract: guitarist}},must_not: [{match: {abstract: company}}, {match: {abstract: manufacturer}}],must: {range: {citations_norm: {gt: 0.500}}}}}}") print("Notes: it return only guitarists that have a lot of citations in wikiepdia") search_boolean(query={"must": {"match": {"abstract": "guitarist"}}, "must_not": [{"match": {"abstract": "company"}}, {"match": {"abstract": "manufacturer"}}], "must": {"range": {"citations_norm": {"gt": "0.500"}}} } ) print("\n\nquery: {query: {bool: {must: {match: {abstract: guitarist}},must: {match: {text: drugs}}}}}") print("Notes: it returns all the guitarists that have a relation with drugs") search_boolean(query={"must": {"match": {"abstract": "guitarist"}}, "must": {"match": {"text": "drugs"}} } ) print("\n\nquery: { query: {match: {abstract: philanthropist}}}") print("Notes: it returns all the philantropist from the corpus. They are all producers") search(query={"abstract": "philanthropist"}) print("\n\nquery: {query: {match_phrase: {text: philanthropist}}}") print("Notes: Since i intentionally declare \"philanthropist\" as synonym of \"rock\" in the text_analyzer filter, this query returns rock stars ") search_phrase(query={"text": "philanthropist"}) print("\n\n") def menu(): while True: for idx, topic in model.print_topics(-1): print('Topic {}: {}'.format(idx, topic)) print("\ninsert a keyword") q = input() print("insert topic id") topic = input() search_with_topic(query={"abstract": q}, topic=topic) print("\n\n") if __name__ == '__main__': # getAllPages(100) print("please wait for indexing...") model, docs = getTopics(False) createIndex(docs) sleep(5) queries_samples() menu()
rAlvaPrincipe/wikipedia-search-engine
Wiki.py
Wiki.py
py
8,334
python
en
code
0
github-code
6
20634168426
from .utils import get_colors def show_help_mess(error: bool = False) -> None: """Usage: pytrash <param> [param[, param ...]] {0}-h, --help{1} Print this help message and exit. {0}-d, --del <path> [path[ path ...]]{1} Move files/dirs to trash (~/.local/share/Trash/). {0}-f, --find <pattern>{1} Search for files and directories in the trash. {0}-r, --restore [pattern]{1} Print list of files/dirs on trash with the possibility of their recovery. If the pattern is specified, then only matches with this pattern are displayed. {0}-c, --clear{1} Clear trash. {0}-s, --size{1} Show the size of the trash. """ colors = get_colors() if error: print(('{0}Wrong parameters.{1} ' '\'pytrash --help\'{2} for help').format(colors['red'], colors['cyan'], colors['reset'])) raise SystemExit # show usage print(str(show_help_mess.__doc__).format(colors['cyan'], colors['reset']))
MyRequiem/pytrash
src/helpmess.py
helpmess.py
py
1,128
python
en
code
1
github-code
6
13067456622
class TrainedAI: def __init__(self): self.playerBase = set() self.cheaterLobbies = set() self.cheatedPlayers = set() self.CheaterData = set() self.PlayerData = set() class NaturalSelectionAI: def __init__(self): self.Data = set() self.Iterations = set() class Player: def __init__(self): self.MatchData = set() self.Username = "" self.Password = "" def CheckPlayerForCheats(player, selection): if player.MatchData == selection.Data: return True else: return False
MyCodingSpace5/Dual-Symbosis-Model
concept.py
concept.py
py
583
python
en
code
0
github-code
6
74149674427
import os import argparse import cv2 import numpy as np from glob import glob from PIL import Image def img2video(video_name): filelist = [] root_dir = video_name for (root, dirs, files) in os.walk(root_dir): print("root : " + root) if len(files) > 0: for file_dir in files: file_root = root + '/' + file_dir #print("file root :" + file_root) filelist.append(file_root) return filelist def dataLoader_img(video_name,locateframe): filelist = [] root_dir = video_name for (root, dirs, files) in os.walk(root_dir): if len(dirs) > 0: for dir_name in dirs: if dir_name == 'images' : file = root +'/'+dir_name + '/' + locateframe +'.png' #print(" root : " + file) filelist.append(file) return filelist def dataLoader_focal(video_name,locateframe): filelist = [] root_dir = video_name for (root, dirs, files) in os.walk(root_dir): #print(" root : " + root) if len(dirs) > 0: for dir_name in dirs: #print(" root : " + dir_name) if dir_name == 'focal' : file = root +'/'+dir_name + '/' + locateframe +'.png' #print(" root : " + file) filelist.append(file) return filelist if __name__ == "__main__": video_name = '../siamfc-pytorch/tools/data/NonVideo4_tiny' locateframe ='005' #dataLoader(locateframe) print(dataLoader_img(video_name,locateframe))
khw11044/PlenOpticVot_Siamfc_2020
vot_siamfc_2D/dataloader.py
dataloader.py
py
1,602
python
en
code
0
github-code
6
13543441403
import pandas as pd import numpy as np import scipy.stats as stats import pylab as pl import re import seaborn as sns pd.set_option('display.max_columns', 15) pd.set_option('display.max_rows', 40) column_types = { 'Account Number':'int32', 'Assessment Year': 'int16', 'Neighbourhood': 'category', 'Assessed Value':'object' } columns = ['Account Number','Assessment Year','Neighbourhood','Assessed Value'] filepath = '\\Coding\\DataAnalystInterview\\AssessmentData.csv' '''Reduces size from 255mb to ~30mb by converting datatypes and dropping columns''' Data = pd.read_csv(filepath, usecols = columns, dtype = column_types, header = 0, sep = ',') Data.rename(columns = {'Assessed Value':'Assessed_Value'}, inplace=True) Data['Assessed_Value'] = Data.Assessed_Value.str.replace(',','').astype('float').astype('int32') '''Pivot Table - Neighborhood vs sum of assessments by year''' NeighbourhoodTable = pd.pivot_table(Data, index = "Neighbourhood", columns = "Assessment Year", values = "Assessed_Value", aggfunc = [np.sum], fill_value = 0) ''' RenamedNeighbourhoods = new or renamed neighborhoods with no assessments in any year from 2012 - 2018''' RenamedNeighbourhoods = (NeighbourhoodTable[NeighbourhoodTable['sum'].all(axis=1) != True]) NeighbourhoodTable = (NeighbourhoodTable[NeighbourhoodTable['sum'].all(axis=1) != False]) #Reviewed Renamed Neighbourhoods to determine areas that would affect results. These are renamed areas that have high impact missing data '''Magrath Heights Area - 254848500 in 2012 to Magrath Heights''' '''Terwillegar South - 1145614500 to 2012 to South Terwillegar''' NeighbourhoodTable.loc['MAGRATH HEIGHTS', ('sum', 2012)] += 254848500 NeighbourhoodTable.loc['SOUTH TERWILLEGAR', ('sum', 2012)] += 1145614500 '''Table by Percentage Change''' NeighbourhoodTableChange = NeighbourhoodTable.pct_change(axis=1) NeighbourhoodTableChange.columns = NeighbourhoodTableChange.columns.droplevel() del NeighbourhoodTableChange.index.name del NeighbourhoodTableChange[2012] NeighbourhoodTableChange.columns = ['2012-2013','2013-2014', '2014-2015', '2015-2016', '2016-2017', '2017-2018'] '''Changes to Neighbourhood Table''' NeighbourhoodTable = NeighbourhoodTable.xs('sum', axis = 1) del NeighbourhoodTable.index.name del NeighbourhoodTable.columns.name #Sum the Total % Change. Decided not to take the absolute value of change because 5 years increasing steadily is #very different from 5 years increasing and decreasing but ending in the same place. Check for variation at the end NeighbourhoodTableChange['Total % Change'] = NeighbourhoodTableChange.sum(axis=1) NeighbourhoodTableChange = NeighbourhoodTableChange.sort_values(by='Total % Change') Neighbourhoods = NeighbourhoodTable.mean(axis=1).astype(int) #NeighbourhoodTable: Table with Raw Assessment Values and Sum of all Assessment Values for Neighbourhoods with data from 2012-2018 NeighbourhoodTable.to_csv(r'\\Coding\\DataAnalystInterview\\NeighbourhoodAssessments.csv') #RenamedNeighbourhoodsL: Table with Raw Assessment Values of Neighbourhoods with missing 2012 - 2018 data RenamedNeighbourhoods.to_csv(r'\\Coding\\DataAnalystInterview\\RenamedNeighbourhoods.csv') #NeighbourhoodTableChange: Table with %Change in all years with data and Standard Deviation NeighbourhoodTableChange.to_csv(r'\\Coding\\DataAnalystInterview\\NeighbourhoodTableChange.csv') #Neighbourhoods: Table with Average Assessments from 2012-2018 in each Neighborhood to segment the analysis Neighbourhoods.to_csv(r'\\Coding\\DataAnalystInterview\\Neighbourhoods.csv') '''print (NeighbourhoodTable.info())''' '''print (NeighbourhoodTable)''' '''print (NeighbourhoodTable.std(axis=1))''' '''print (Data.loc[Data['Neighbourhood'] == 'MACTAGGART AREA'])''' '''print (set(Data['Neighbourhood']))''' '''RenamedNeighbourhoods = (NeighbourhoodTable['sum'][:] != 0).all(axis=1).dropna()''' #NeighbourhoodTable.to_csv(r'C:\Users\aviel\Desktop\Coding\Data Analyst Interview\NeighbourhoodAssessments.csv') #RenamedNeighbourhoods.to_csv(r'C:\Users\aviel\Desktop\Coding\Data Analyst Interview\RenamedNeighbourhoods.csv')
avielchow/Property-Assessment-Analysis
CleanData.py
CleanData.py
py
4,195
python
en
code
0
github-code
6